Skip to content

Commit

Permalink
feat(corelib): range IndexView
Browse files Browse the repository at this point in the history
  • Loading branch information
cairoIover committed Jan 4, 2025
1 parent 4e834eb commit fa338af
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
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());
}

0 comments on commit fa338af

Please sign in to comment.