Skip to content
Merged
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
11 changes: 11 additions & 0 deletions pottery/deque.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,17 @@ def rotate(self, n: int = 1) -> None:
# Rotating an empty RedisDeque is a no-op.
return

# Rotating more than the length wraps around, like
# collections.deque.rotate(). Rotate the shorter way to
# minimize the number of elements pushed.
length = len(self)
n %= length
if n > length // 2:
n -= length
if n == 0:
# A whole number of turns is a no-op.
return

push_method_name = 'lpush' if n > 0 else 'rpush' # Available since Redis 1.0.0
values = self[-n:][::-1] if n > 0 else self[:-n]
encoded_values = (self._encode(value) for value in values)
Expand Down
16 changes: 16 additions & 0 deletions tests/test_deque.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,22 @@ def test_rotate_left(redis: Redis) -> None:
assert d == collections.deque([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])


@pytest.mark.parametrize('steps, expected', (
(4, [3, 1, 2]),
(-4, [2, 3, 1]),
(7, [3, 1, 2]),
(-7, [2, 3, 1]),
(6, [1, 2, 3]),
(-6, [1, 2, 3]),
))
def test_rotate_more_than_length(redis: Redis, steps: int, expected: list) -> None:
# Rotating more than the length wraps around, like
# collections.deque.rotate().
d = RedisDeque([1, 2, 3], redis=redis)
d.rotate(steps)
assert d == collections.deque(expected)


def test_moving_average(redis: Redis) -> None:
'Test RedisDeque-based moving average'

Expand Down
Loading