Skip to content

Instantly share code, notes, and snippets.

@mnbi
Created November 1, 2010 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnbi/657951 to your computer and use it in GitHub Desktop.
Save mnbi/657951 to your computer and use it in GitHub Desktop.
a LIFO ring buffer
class RequestHistory(object):
def __init__(self, size=10):
self.size = size
self.modulus = self.size + 1
self.history = [''] * (self.modulus)
self.base = 0
self.top = 1
def is_empty(self):
return self.base == self.decrement(self.top)
def peek(self):
if self.is_empty():
return None
else:
return self.history[self.decrement(self.top)]
def push(self, request):
self.history[self.top] = request
if self.top == self.base:
self.base = self.increment(self.base)
self.top = self.increment(self.top)
def pop(self):
index = self.decrement(self.top)
if self.is_empty():
return None
self.top = index
return self.history[self.top]
def export_history(self):
h = []
i = self.increment(self.base)
while i != self.top:
h.append(self.history[i])
i = self.increment(i)
h.append(self.history[i])
return h
def import_history(self, history):
for request in history:
self.push(request)
def increment(self, number):
return (number + 1) % self.modulus
def decrement(self, number):
return (number - 1) % self.modulus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment