diff --git a/ethereum/circuits/lib/src/misc.nr b/ethereum/circuits/lib/src/misc.nr index de329756..13564237 100644 --- a/ethereum/circuits/lib/src/misc.nr +++ b/ethereum/circuits/lib/src/misc.nr @@ -11,3 +11,4 @@ mod types; mod option; mod bytes32; mod bytes32_test; +mod iterator; diff --git a/ethereum/circuits/lib/src/misc/bounded_vecs.nr b/ethereum/circuits/lib/src/misc/bounded_vecs.nr index 1ca98f6a..ffd7a81b 100644 --- a/ethereum/circuits/lib/src/misc/bounded_vecs.nr +++ b/ethereum/circuits/lib/src/misc/bounded_vecs.nr @@ -1,3 +1,5 @@ +use crate::misc::iterator::Iterator; + pub fn bounded_vec_from_array(array: [T; N]) -> BoundedVec { assert(N <= M, "Array size exceeds bounded vector size"); let mut vec = BoundedVec::new(); @@ -10,11 +12,18 @@ pub fn bounded_vec_map( bounded_vec: BoundedVec , f: fn[Env](T) -> U ) -> BoundedVec { - let mut result: BoundedVec = BoundedVec::new(); - for i in 0..N { - if (i < bounded_vec.len) { - result.push(f(bounded_vec.get(i))); + let result: &mut BoundedVec = &mut BoundedVec::new(); + bounded_vec.for_each(|x| result.push(f(x))); + + *result +} + +impl Iterator for BoundedVec { + fn for_each(self, f: fn[Env](T) -> ()) { + for i in 0..N { + if i < self.len { + f(self.get(i)); + } } } - result } diff --git a/ethereum/circuits/lib/src/misc/fragment.nr b/ethereum/circuits/lib/src/misc/fragment.nr index 8439bd97..5806bfea 100644 --- a/ethereum/circuits/lib/src/misc/fragment.nr +++ b/ethereum/circuits/lib/src/misc/fragment.nr @@ -1,4 +1,4 @@ -use crate::misc::arrays::{memcpy_up_to_length, resize}; +use crate::misc::{arrays::{memcpy_up_to_length, resize}, iterator::Iterator}; use dep::std::unsafe::zeroed; struct Fragment { @@ -38,13 +38,10 @@ impl Fragment { pub fn to_bounded_vec(self) -> BoundedVec { assert(self.length <= N, "Fragment length exceeds BoundedVec max length"); - let mut bounded_vec: BoundedVec = BoundedVec::new(); - for i in 0..N { - if (i < self.length) { - bounded_vec.push(self.at(i)); - } - } - bounded_vec + let bounded_vec: &mut BoundedVec = &mut BoundedVec::new(); + self.for_each(|x| bounded_vec.push(x)); + + *bounded_vec } pub fn from_vec(vec: BoundedVec) -> Fragment { @@ -150,3 +147,13 @@ impl Eq for Fragment where T: Eq { res } } + +impl Iterator for Fragment { + fn for_each(self, f: fn[Env](T) -> ()) { + for i in 0..MAX_DATA_LEN { + if i < self.length { + f(self.at(i)); + } + } + } +} diff --git a/ethereum/circuits/lib/src/misc/iterator.nr b/ethereum/circuits/lib/src/misc/iterator.nr new file mode 100644 index 00000000..244cdeb7 --- /dev/null +++ b/ethereum/circuits/lib/src/misc/iterator.nr @@ -0,0 +1,3 @@ +trait Iterator { + fn for_each(self, f: fn[Env](T) -> ()); +}