Skip to content

feat: array concat method #7199

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

Merged
merged 11 commits into from
Mar 7, 2025
Merged
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
31 changes: 31 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 = [self[0]; N + M];
for i in 1..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,12 @@ 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]);
}
}
Loading