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 3 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 dest_ptr = UnsafePointer[T].alloc(new_len)
i = 0
while start > end:
dest_ptr[i] = self._data[start]
start -= step
i += 1
return Span[T, lifetime](unsafe_ptr=dest_ptr, len=new_len)
Copy link
Contributor Author

@msaelices msaelices Oct 12, 2024

Choose a reason for hiding this comment

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

What's the best way to ensure the buffer allocated memory is destroyed when the span is deleted?

Copy link
Contributor

@martinvuyk martinvuyk Oct 12, 2024

Choose a reason for hiding this comment

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

Hmmm, not sure since I don't really understand lifetimes yet. But I think building a var items = List[T](unsafe_pointer=dest_ptr, size=new_len, capacity=new_len) and returning Span[T, lifetime](items^) will work?

Either way I think this should probably return an iterator in the future (once we have them), it doesn't make much sense to allocate for this since it is a read only view on the data.


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