Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions numpy_ringbuffer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,10 @@ def __len__(self):
def __getitem__(self, item):
# handle simple (b[1]) and basic (b[np.array([1, 2, 3])]) fancy indexing specially
if not isinstance(item, tuple):
if isinstance(item, int) and item < 0:
# ringbuf[-<n>]
item = (item + self._right_index) % self._capacity
return self._arr[item]
item_arr = np.asarray(item)
if issubclass(item_arr.dtype.type, np.integer):
item_arr = (item_arr + self._left_index) % self._capacity

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just:

item_arr = ((item_arr % len(self)) + self._left_index) % self._capacity

instead of lines 167-170? :)

Expand Down
14 changes: 14 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,20 @@ def test_getitem(self):
ii = [0, 4, 3, 1, 2]
np.testing.assert_equal(r[ii], expected[ii])

def test_getitem_from_right(self):
r = RingBuffer(5, dtype=int)
r.append(1)
for num in range(2, 5):
r.append(num)
self.assertEqual(r[-1], num)
for num in range(5, 13):
r.append(num)
self.assertEqual(r[-1], num)
self.assertEqual(r[-2], num - 1)
self.assertEqual(r[-5], num - 4)
np.testing.assert_equal(r[-4:], [9, 10, 11, 12])
np.testing.assert_equal(r[-5:-2], [8, 9, 10])

def test_appendleft(self):
r = RingBuffer(5)

Expand Down