Skip to content

Commit

Permalink
fix: improve perf of zero based range iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
sstadick committed Jan 8, 2025
1 parent 4af59db commit 8b2b7ed
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions stdlib/src/builtin/range.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@ fn _sign(x: Int) -> Int:

@register_passable("trivial")
struct _ZeroStartingRange(Sized, ReversibleRange, _IntIterable):
var curr: Int
var start: Int
var end: Int

@always_inline
@implicit
fn __init__(out self, end: Int):
self.curr = max(0, end)
self.start = 0
self.end = self.curr

@always_inline
Expand All @@ -61,26 +61,26 @@ struct _ZeroStartingRange(Sized, ReversibleRange, _IntIterable):

@always_inline
fn __next__(mut self) -> Int:
var curr = self.curr
self.curr -= 1
return self.end - curr
var start = self.start
self.start += 1
return start

@always_inline
fn __has_next__(self) -> Bool:
return self.__len__() > 0

@always_inline
fn __len__(self) -> Int:
return self.curr
return max(0, self.end - self.start)

@always_inline
fn __getitem__(self, idx: Int) -> Int:
debug_assert(idx < self.__len__(), "index out of range")
return index(idx)
return self.start + index(idx)

@always_inline
fn __reversed__(self) -> _StridedRange:
return range(self.end - 1, -1, -1)
return range(self.end - 1, self.start - 1, -1)


@value
Expand Down

0 comments on commit 8b2b7ed

Please sign in to comment.