From fa338af8b3ee4545dbecd9c29c4c113b6b1e0fc6 Mon Sep 17 00:00:00 2001 From: cairoIover <193099744+cairoIover@users.noreply.github.com> Date: Sat, 4 Jan 2025 03:01:49 +0100 Subject: [PATCH] feat(corelib): range IndexView --- corelib/src/array.cairo | 17 +++++++++++++++++ corelib/src/test/array_test.cairo | 17 +++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/corelib/src/array.cairo b/corelib/src/array.cairo index 4d83548fb8a..42b729079d3 100644 --- a/corelib/src/array.cairo +++ b/corelib/src/array.cairo @@ -300,6 +300,14 @@ impl ArrayIndex of IndexView, usize, @T> { } } +impl ArraySliceIndex of core::ops::IndexView, core::ops::Range> { + type Target = Span; + + fn index(self: @Array, index: core::ops::Range) -> Span { + self.span()[index] + } +} + impl ArraySerde, +Drop> of Serde> { /// Serializes an `Array` into an `Array`. /// @@ -635,6 +643,15 @@ pub impl SpanIndex of IndexView, usize, @T> { } } +impl SpanSliceIndex of core::ops::IndexView, core::ops::Range> { + type Target = Span; + + #[inline] + fn index(self: @Span, index: core::ops::Range) -> Span { + (*self).slice(index.start, index.end - index.start) + } +} + /// `ToSpanTrait` converts a data structure into a span of its data. pub trait ToSpanTrait { /// Returns a span pointing to the data in the input. diff --git a/corelib/src/test/array_test.cairo b/corelib/src/test/array_test.cairo index a72d0deb9d4..eee681a4abc 100644 --- a/corelib/src/test/array_test.cairo +++ b/corelib/src/test/array_test.cairo @@ -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] @@ -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]]; @@ -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()); +}