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

feat(corelib): range IndexView #6971

Open
wants to merge 1 commit into
base: main
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
17 changes: 17 additions & 0 deletions corelib/src/array.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,14 @@ impl ArrayIndex<T> of IndexView<Array<T>, usize, @T> {
}
}

impl ArraySliceIndex<T> of core::ops::IndexView<Array<T>, core::ops::Range<usize>> {
type Target = Span<T>;

fn index(self: @Array<T>, index: core::ops::Range<usize>) -> Span<T> {
self.span()[index]
}
}

impl ArraySerde<T, +Serde<T>, +Drop<T>> of Serde<Array<T>> {
/// Serializes an `Array<T>` into an `Array<felt252>`.
///
Expand Down Expand Up @@ -635,6 +643,15 @@ pub impl SpanIndex<T> of IndexView<Span<T>, usize, @T> {
}
}

impl SpanSliceIndex<T> of core::ops::IndexView<Span<T>, core::ops::Range<usize>> {
type Target = Span<T>;

#[inline]
fn index(self: @Span<T>, index: core::ops::Range<usize>) -> Span<T> {
(*self).slice(index.start, index.end - index.start)
}
}

/// `ToSpanTrait` converts a data structure into a span of its data.
pub trait ToSpanTrait<C, T> {
/// Returns a span pointing to the data in the input.
Expand Down
17 changes: 15 additions & 2 deletions corelib/src/test/array_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ fn test_array() {
#[should_panic]
fn test_array_out_of_bound_1() {
let arr = array![10, 11, 12];
arr[3];
arr[3_usize];
}

#[test]
#[should_panic]
fn test_array_out_of_bound_2() {
let arr = array![10, 11, 12];
arr[11];
arr[11_usize];
}

#[test]
Expand Down Expand Up @@ -215,6 +215,7 @@ fn test_array_snap_into_span() {
fn test_span_into_array_snap() {
assert_eq!(@array![1, 2, 3], array![1, 2, 3].span().into());
}

#[test]
fn nested_for_loop() {
let mat = array![array![1, 2], array![3, 4], array![5, 6]];
Expand All @@ -226,3 +227,15 @@ fn nested_for_loop() {
};
assert_eq!(result, 21);
}

#[test]
fn test_array_slice_index() {
let arr = array![1, 2, 3, 4, 5];
assert!(arr[2_usize..4] == [3, 4].span());
}

#[test]
fn test_span_slice_index() {
let span = [1, 2, 3, 4, 5].span();
assert!(span[2_usize..4] == [3, 4].span());
}