Skip to content

Commit

Permalink
feat: array concat method (#7199)
Browse files Browse the repository at this point in the history
Co-authored-by: Tom French <15848336+TomAFrench@users.noreply.github.com>
Co-authored-by: Ary Borenszweig <asterite@gmail.com>
  • Loading branch information
3 people authored Mar 7, 2025
1 parent 37be49f commit 5b725bb
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"combinators",
"compinit",
"comptime",
"concat",
"cpus",
"cranelift",
"critesjosh",
Expand Down
17 changes: 17 additions & 0 deletions docs/docs/noir/concepts/data_types/arrays.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,23 @@ fn main() {
}
```

### concat

Concatenates this array with another array.

```rust
fn concat<let M: u32>(self, array2: [T; M]) -> [T; N + M]
```

```rust
fn main() {
let arr1 = [1, 2, 3, 4];
let arr2 = [6, 7, 8, 9, 10, 11];
let concatenated_arr = arr1.concat(arr2);
assert(concatenated_arr == [1, 2, 3, 4, 6, 7, 8, 9, 10, 11]);
}
```

### as_str_unchecked

Converts a byte array of type `[u8; N]` to a string. Note that this performs no UTF-8 validation -
Expand Down
55 changes: 55 additions & 0 deletions noir_stdlib/src/array/mod.nr
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,29 @@ impl<T, let N: u32> [T; N] {
}
ret
}

/// Concatenates this array with another array.
///
/// Example:
///
/// ```noir
/// fn main() {
/// let arr1 = [1, 2, 3, 4];
/// let arr2 = [6, 7, 8, 9, 10, 11];
/// let concatenated_arr = arr1.concat(arr2);
/// assert(concatenated_arr == [1, 2, 3, 4, 6, 7, 8, 9, 10, 11]);
/// }
/// ```
pub fn concat<let M: u32>(self, array2: [T; M]) -> [T; N + M] {
let mut result = [crate::mem::zeroed(); N + M];
for i in 0..N {
result[i] = self[i];
}
for i in 0..M {
result[i + N] = array2[i];
}
result
}
}

impl<T, let N: u32> [T; N]
Expand Down Expand Up @@ -232,4 +255,36 @@ mod test {
fn map_empty() {
assert_eq([].map(|x| x + 1), []);
}

#[test]
fn concat() {
let arr1 = [1, 2, 3, 4];
let arr2 = [6, 7, 8, 9, 10, 11];
let concatenated_arr = arr1.concat(arr2);
assert_eq(concatenated_arr, [1, 2, 3, 4, 6, 7, 8, 9, 10, 11]);
}

#[test]
fn concat_zero_length_with_something() {
let arr1 = [];
let arr2 = [1];
let concatenated_arr = arr1.concat(arr2);
assert_eq(concatenated_arr, [1]);
}

#[test]
fn concat_something_with_zero_length() {
let arr1 = [1];
let arr2 = [];
let concatenated_arr = arr1.concat(arr2);
assert_eq(concatenated_arr, [1]);
}

#[test]
fn concat_zero_lengths() {
let arr1: [Field; 0] = [];
let arr2: [Field; 0] = [];
let concatenated_arr = arr1.concat(arr2);
assert_eq(concatenated_arr, []);
}
}

0 comments on commit 5b725bb

Please sign in to comment.