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: impl Into for Span/Array pair #5650

Merged
merged 10 commits into from
Jun 6, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
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(mut 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());
}