From 8a02635ef9825f38b5d2ce5a0cabb84dc548e4fc Mon Sep 17 00:00:00 2001 From: oleh Date: Wed, 23 Oct 2024 03:54:00 +0200 Subject: [PATCH] feat: array slice --- README.md | 12 +++++++++++- src/array.nr | 15 +++++++++++++++ src/lib.nr | 1 + 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cb1c07d..a08b697 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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. diff --git a/src/array.nr b/src/array.nr index 10c985f..215325c 100644 --- a/src/array.nr +++ b/src/array.nr @@ -1,4 +1,14 @@ impl crate::ArrayExtensions for [T; N] { + fn slice(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(self, other: [T; M]) -> [T; N + M] { let mut result = [self[0]; N + M]; for i in 0..N { @@ -30,6 +40,11 @@ impl crate::ArrayExtensions 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]); diff --git a/src/lib.nr b/src/lib.nr index 669f4ca..d795b63 100644 --- a/src/lib.nr +++ b/src/lib.nr @@ -8,6 +8,7 @@ pub use string::{to_hex_string_bytes, str_to_u64}; pub use math::{clamp, div_ceil, sqrt::sqrt}; trait ArrayExtensions { + fn slice(self, start: u32, end: u32) -> [T; M]; fn concat(self, other: [T; M]) -> [T; N + M]; fn pad_start(self, pad_value: T) -> [T; M]; fn pad_end(self, pad_value: T) -> [T; M];