-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathring_buffer.py
More file actions
84 lines (67 loc) · 1.9 KB
/
ring_buffer.py
File metadata and controls
84 lines (67 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class RingBuffer(object):
def __init__(self, size):
'''
Initialise the buffer
'''
self.head = 0
self.tail = 0
self.max_size = size
self.buffer = [0 for i in range(0, size)]
self.full = False
self.empty = True
def push(self, element):
'''
Push an element into the buffer
'''
if (self.is_full()):
raise RuntimeError('Buffer is full!')
self.buffer[self.head] = element
self.head = (self.head + 1) % self.max_size
self.empty = False
if self.head == self.tail:
self.full = True
def pop(self):
'''
Pop an element from the buffer
'''
if(self.is_empty()):
raise RuntimeError('Buffer is empty!')
element = self.buffer[self.tail]
self.tail = (self.tail + 1) % self.max_size
self.full = False
if self.tail == self.head:
self.empty = True
return element
def get_capacity(self):
'''
Return buffer's capacity
'''
return self.max_size
def is_empty(self):
'''
Return true if buffer is empty else false
'''
return self.empty
def is_full(self):
'''
Return true is buffer is full else false
'''
return self.full
def get_buffer_fill(self):
'''
Return current buffer occupied size
'''
if self.head == self.tail:
return 0 if self.is_empty() else self.max_size
if self.head > self.tail:
return self.head - self.tail
return ((self.max_size - self.tail) + (self.head - 0))
def clear(self):
'''
Clear the buffer
'''
self.buffer = [0 for i in range(0, self.max_size)]
self.head = 0
self.tail = 0
self.full = False
self.empty = True