From: Christian Herdtweck Date: Tue, 12 Jan 2016 12:25:29 +0000 (+0100) Subject: more renaming and testing to make clear CircularBuffer is not just for log text X-Git-Tag: v1.2~85 X-Git-Url: http://developer.intra2net.com/git/?a=commitdiff_plain;h=e14eed4a563ff34b46db0da657fa18859fd92adb;p=pyi2ncommon more renaming and testing to make clear CircularBuffer is not just for log text --- diff --git a/buffers.py b/buffers.py index 96e065d..bda7d80 100644 --- a/buffers.py +++ b/buffers.py @@ -29,36 +29,52 @@ Featuring:: """ class CircularBuffer: - """ circular buffer for text lines; saves last N lines + """ circular buffer for data; saves last N sets - can output them afterwards in correct order + can return or run func on them afterwards in correct order - public attributes (please read only!): buffer_size, n_lines + public attributes (please read only!): buffer_size, n_items """ buffer_size = None _buffer = None _buff_idx = None - n_lines = None + n_items = None - def __init__(self, size): + def __init__(self, size, empty_element=None): """ initialize with N = size """ + if size < 1: + raise ValueError('size must be positive!') self.buffer_size = size - self._buffer = ['[no output]' for line_idx in range(size)] + self._buffer = [empty_element for idx in range(size)] self._buff_idx = 0 - self.n_lines = 0 + self.n_items = 0 - def add(self, line): - """ add a line to buffer -- might replace the oldest line """ - self._buffer[self._buff_idx] = line + def add(self, new_item): + """ add a new item to buffer -- might replace the oldest item """ + oldest_item = self._buffer[self._buff_idx] + self._buffer[self._buff_idx] = new_item self._buff_idx = (self._buff_idx + 1) % self.buffer_size - self.n_lines += 1 + self.n_items += 1 + return oldest_item - def output(self, output_func): - """ run output_func(line) on last saved lines """ - if self.n_lines >= self.buffer_size: + def run_func(self, some_func): + """ run some_func(item) on last saved items in correct order """ + if self.n_items >= self.buffer_size: for idx in range(self._buff_idx, self.buffer_size): - output_func(self._buffer[idx]) + some_func(self._buffer[idx]) for idx in range(0, self._buff_idx): - output_func(self._buffer[idx]) + some_func(self._buffer[idx]) + + def get_all(self): + """ return the buffered contents in correct order """ + result = [] + if self.n_items >= self.buffer_size: + for idx in range(self._buff_idx, self.buffer_size): + result.append(self._buffer[idx]) + + for idx in range(0, self._buff_idx): + result.append(self._buffer[idx]) + + return result