Skip to content

Commit

Permalink
feat: array slice
Browse files Browse the repository at this point in the history
  • Loading branch information
olehmisar committed Oct 23, 2024
1 parent f51557a commit 8a02635
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Put this into your Nargo.toml.
If you are using Noir:

```toml
nodash = { git = "https://github.com/olehmisar/nodash/", tag = "v0.35.1" }
nodash = { git = "https://github.com/olehmisar/nodash/", tag = "v0.35.3" }
```

The version of nodash matches the version of Noir. The patch version may be different if a bugfix or a new feature is added for the same version of Noir. E.g., nodash@v0.35.0 and nodash@v0.35.1 are compatible with noir@v0.35.0.
Expand Down Expand Up @@ -98,6 +98,16 @@ assert(str_to_u64("02345678912345678912") == 02345678912345678912);

### `ArrayExtensions`

#### `slice`

Returns a slice of the array.

```rs
use nodash::ArrayExtensions;

assert([1, 2, 3, 4, 5].slice::<3>(1, 4) == [2, 3, 4]);
```

#### `concat`

Concatenates two arrays.
Expand Down
15 changes: 15 additions & 0 deletions src/array.nr
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
impl<T, let N: u32> crate::ArrayExtensions<T, N> for [T; N] {
fn slice<let M: u32>(self, start: u32, end: u32) -> [T; M] {
assert(start + M == end, "slice: invalid slice length");
assert(end <= N, "slice: slice end out of bounds");
let mut result = [self[0]; M];
for i in 0..M {
result[i] = self[start + i];
}
result
}

fn concat<let M: u32>(self, other: [T; M]) -> [T; N + M] {
let mut result = [self[0]; N + M];
for i in 0..N {
Expand Down Expand Up @@ -30,6 +40,11 @@ impl<T, let N: u32> crate::ArrayExtensions<T, N> for [T; N] {
}

mod tests {
#[test]
fn test_slice() {
assert([1, 2, 3, 4, 5].slice::<3>(1, 4) == [2, 3, 4]);
}

#[test]
fn test_simple() {
assert([1, 2, 3].concat([4, 5]) == [1, 2, 3, 4, 5]);
Expand Down
1 change: 1 addition & 0 deletions src/lib.nr
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub use string::{to_hex_string_bytes, str_to_u64};
pub use math::{clamp, div_ceil, sqrt::sqrt};

trait ArrayExtensions<T, let N: u32> {
fn slice<let M: u32>(self, start: u32, end: u32) -> [T; M];
fn concat<let M: u32>(self, other: [T; M]) -> [T; N + M];
fn pad_start<let M: u32>(self, pad_value: T) -> [T; M];
fn pad_end<let M: u32>(self, pad_value: T) -> [T; M];
Expand Down

0 comments on commit 8a02635

Please sign in to comment.