Last active
May 2, 2021 17:07
-
-
Save jcrubino/d27471263f30584630e44e976043c31c to your computer and use it in GitHub Desktop.
Circular Buffer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RingBuffer: | |
index = 0 | |
value = None | |
def __init__(self, length): | |
# create buffer using dequeue | |
self.buffer = deque([], length) | |
# establish end index number | |
self._eix = length-1 | |
# Populate Buffer Length With None | |
for n in range(length): | |
self.buffer.append(None) | |
def populate_buffer(self, value_array): | |
"Init Buffer with array of values" | |
rix = 0 | |
for item in value_array: | |
self.buffer[rix] = item | |
if rix == 0: | |
self.v = item | |
print(rix, item) | |
rix += 1 | |
def move_right(self): | |
if self.buffer == deque([]): | |
raise Exception("Ring.buffer is empty.") | |
# move index right by one | |
self.index += 1 | |
# if index is greater or equal to end index | |
# reset index to zero | |
if self.index > self._eix: | |
self.index = 0 | |
# pull value from buffer at new index | |
self.value = self.buffer[self.index] | |
# return index and value | |
return self.index, self.value | |
def peek_right(self, n=1): | |
if n == 0: | |
raise Exception("n must be > 0") | |
notional_index = self.index + n | |
length = self._eix + 1 | |
index = notional_index % length | |
return index, self.buffer[index] | |
def peek_left(self, n=1): | |
# Convert n to negative number | |
if n > 0: | |
n *= -1 | |
if n == 0: | |
raise Exception("abs(n) must be > 0") | |
notional_index = self.index+n | |
if notional_index > 0: | |
return notional_index, self.buffer[notional_index] | |
index = notional_value % _len | |
return index, self.buffer[index] | |
def move_left(self): | |
if self.buffer == deque([]): | |
raise Exception("Ring.buffer is empty.") | |
# Move index left | |
self.index -= 1 | |
# If index is less than zero | |
# reset index to end index | |
if self.index < 0: | |
self.index = self._eix | |
# pull value from buffer | |
self.value = self.buffer[self.index] | |
# return index and value | |
return self.index, self.value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment