Skip to content

Commit

Permalink
feat: impl Into for Span/Array pair (#5650)
Browse files Browse the repository at this point in the history
  • Loading branch information
tdelabro authored Jun 6, 2024
1 parent 86c3334 commit b363cd5
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
26 changes: 26 additions & 0 deletions corelib/src/array.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,26 @@ pub struct Span<T> {
impl SpanCopy<T> of Copy<Span<T>>;
impl SpanDrop<T> of Drop<Span<T>>;

impl ArrayIntoSpan<T, +Drop<T>> of Into<Array<T>, Span<T>> {
fn into(self: Array<T>) -> Span<T> {
self.span()
}
}

impl SpanIntoArray<T, +Drop<T>, +Clone<T>> of Into<Span<T>, Array<T>> {
fn into(self: Span<T>) -> Array<T> {
let mut arr = array![];
arr.append_span(self);
arr
}
}

impl SpanIntoArraySnap<T> of Into<Span<T>, @Array<T>> {
fn into(self: Span<T>) -> @Array<T> {
self.snapshot
}
}

impl SpanFelt252Serde of Serde<Span<felt252>> {
fn serialize(self: @Span<felt252>, ref output: Array<felt252>) {
(*self).len().serialize(ref output);
Expand Down Expand Up @@ -251,6 +271,12 @@ impl ArrayToSpan<T> of ToSpanTrait<Array<T>, T> {
}
}

impl SnapIntoSpanWhereToSpanTrait<C, T, +ToSpanTrait<C, T>> of Into<@C, Span<T>> {
fn into(self: @C) -> Span<T> {
self.span()
}
}

/// Returns a span from a box of struct of members of the same type.
/// The additional `+Copy<@T>` arg is to prevent later stages from propagating the `S` type Sierra
/// level, where it is deduced by the `T` type.
Expand Down
19 changes: 19 additions & 0 deletions corelib/src/test/array_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,22 @@ fn test_array_iterator() {
i += 1;
}
}

fn test_array_into_span() {
assert_eq!(array![1, 2, 3].span(), array![1, 2, 3].into())
}

#[test]
fn test_span_into_array() {
assert_eq!(array![1, 2, 3], array![1, 2, 3].span().into());
}

#[test]
fn test_array_snap_into_span() {
assert_eq!(array![1, 2, 3].span(), (@array![1, 2, 3]).into());
}

#[test]
fn test_span_into_array_snap() {
assert_eq!(@array![1, 2, 3], array![1, 2, 3].span().into());
}

0 comments on commit b363cd5

Please sign in to comment.