Skip to content

Commit

Permalink
refactor to _physical_index()
Browse files Browse the repository at this point in the history
  • Loading branch information
avitkauskas committed Oct 24, 2024
1 parent a080abd commit c96da75
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions stdlib/src/collections/deque.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ struct Deque[ElementType: CollectionElement](
fn __del__(owned self):
"""Destroys all elements in the deque and free its memory."""
for i in range(len(self)):
offset = (self._head + i) & (self._capacity - 1)
offset = self._physical_index(self._head + i)
(self._data + offset).destroy_pointee()
self._data.free()

Expand Down Expand Up @@ -248,7 +248,7 @@ struct Deque[ElementType: CollectionElement](
if normalized_idx < 0:
normalized_idx += len(self)

offset = (self._head + normalized_idx) & (self._capacity - 1)
offset = self._physical_index(self._head + normalized_idx)
return (self._data + offset)[]

# ===-------------------------------------------------------------------===#
Expand All @@ -263,10 +263,10 @@ struct Deque[ElementType: CollectionElement](
"""
if len(self) == self._maxlen:
(self._data + self._head).destroy_pointee()
self._head = (self._head + 1) & (self._capacity - 1)
self._head = self._physical_index(self._head + 1)

(self._data + self._tail).init_pointee_move(value^)
self._tail = (self._tail + 1) & (self._capacity - 1)
self._tail = self._physical_index(self._tail + 1)

if self._head == self._tail:
self._realloc(self._capacity << 1)
Expand All @@ -280,6 +280,20 @@ struct Deque[ElementType: CollectionElement](
for value in values:
self.append(value[])

@doc_private
@always_inline
fn _physical_index(self, logical_index: Int) -> Int:
"""Calculates the physical index in the circular buffer.
Args:
logical_index: The logical index, which may fall outside the physical bounds
of the buffer and needs to be wrapped around.
The size of the underlying buffer is always a power of two, allowing the use of
the more efficient bitwise `&` operation instead of the modulo `%` operator.
"""
return logical_index & (self._capacity - 1)

@doc_private
fn _realloc(inout self, new_capacity: Int):
"""Relocates data to a new storage buffer.
Expand Down

0 comments on commit c96da75

Please sign in to comment.