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: add BoundedVec::map #5250

Merged
merged 2 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
14 changes: 14 additions & 0 deletions docs/docs/noir/standard_library/containers/boundedvec.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,20 @@ Example:
let bounded_vec: BoundedVec<Field, 10> = BoundedVec::from_array([1, 2, 3])
```

### map

```rust
pub fn map<Env>(self, f: fn[Env](T) -> T) -> Self
nventuro marked this conversation as resolved.
Show resolved Hide resolved
```

Creates a new vector of equal size by calling a closure on each element in this vector.

Example:
```rust
let bounded_vec: BoundedVec<Field, 10> = BoundedVec::from_array([1, 2, 3])
let doubled = bounded_vec.map(|x| x * 2);
```
nventuro marked this conversation as resolved.
Show resolved Hide resolved

### any

```rust
Expand Down
34 changes: 34 additions & 0 deletions noir_stdlib/src/collections/bounded_vec.nr
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,17 @@ impl<T, MaxLen> BoundedVec<T, MaxLen> {
}
ret
}

pub fn map<Env>(self, f: fn[Env](T) -> T) -> Self {
nventuro marked this conversation as resolved.
Show resolved Hide resolved
let mut ret = BoundedVec::new();
ret.len = self.len();
for i in 0..MaxLen {
if i < self.len() {
ret.storage[i] = f(self.get_unchecked(i));
}
}
ret
}
}

impl<T, MaxLen> Eq for BoundedVec<T, MaxLen> where T: Eq {
Expand Down Expand Up @@ -195,6 +206,29 @@ mod bounded_vec_tests {
}
}

mod map {
use crate::collections::bounded_vec::BoundedVec;

#[test]
fn applies_function_correctly() {
let vec: BoundedVec<u32, 4> = BoundedVec::from_array([1, 2, 3, 4]);
let result = vec.map(|value| if value > 2 { value * 2 } else { value });
let expected = BoundedVec::from_array([1, 2, 6, 8]);

assert_eq(result, expected);
}

#[test]
fn does_not_apply_function_past_len() {
let vec: BoundedVec<u32, 3> = BoundedVec::from_array([0, 1]);
let result = vec.map(|value| if value == 0 { 5 } else { value });
let expected = BoundedVec::from_array([5, 1]);

assert_eq(result, expected);
assert_eq(result.storage()[2], 0);
}
}

mod from_array {
use crate::collections::bounded_vec::BoundedVec;

Expand Down
Loading