Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[stdlib] Span slicing with negative step #3650

Open
wants to merge 4 commits into
base: nightly
Choose a base branch
from
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
15 changes: 12 additions & 3 deletions stdlib/src/utils/span.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,18 @@ struct Span[
var end: Int
var step: Int
start, end, step = slc.indices(len(self))
debug_assert(
step == 1, "Slice must be within bounds and step must be 1"
)

if step < 0:
step = -step
var new_len = (start - end + step - 1) // step
var buff = UnsafePointer[T].alloc(new_len)
i = 0
while start > end:
buff[i] = self._data[start]
start -= step
i += 1
return Span[T, lifetime](unsafe_ptr=buff, len=new_len)

var res = Self(
unsafe_ptr=(self._data + start),
len=len(range(start, end, step)),
Expand Down
14 changes: 10 additions & 4 deletions stdlib/test/utils/test_span.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,16 @@ def test_span_slice():
assert_equal(res[0], 2)
assert_equal(res[1], 3)
assert_equal(res[2], 4)
# TODO: Fix Span slicing
# res = s[1::-1]
# assert_equal(res[0], 2)
# assert_equal(res[1], 1)
# Test slicing with negative step
res = s[1::-1]
assert_equal(res[0], 2)
assert_equal(res[1], 1)
res = s[2:1:-1]
assert_equal(res[0], 3)
assert_equal(len(res), 1)
res = s[5:1:-2]
assert_equal(res[0], 5)
assert_equal(res[1], 3)


def test_copy_from():
Expand Down
Loading