diff --git a/elrond-wasm-debug/tests/managed_vec_test.rs b/elrond-wasm-debug/tests/managed_vec_test.rs index 6784f851a2..430df92ea4 100644 --- a/elrond-wasm-debug/tests/managed_vec_test.rs +++ b/elrond-wasm-debug/tests/managed_vec_test.rs @@ -27,6 +27,23 @@ fn test_managed_vec_iter_rev() { assert_eq!(reversed_numbers, expected_reversed_numbers); } +#[test] +fn test_managed_vec_from_iterator_trait() { + let _ = DebugApi::dummy(); + let mut managed_vec = ManagedVec::::new(); + for i in 1..=10 { + managed_vec.push(i); + } + let mut expected_vec = ManagedVec::::new(); + for i in 1..=5 { + expected_vec.push(i); + } + + let collected_vec = managed_vec.iter().filter(|x| x <= &5).collect::>(); + + assert_eq!(collected_vec, expected_vec); +} + #[test] fn test_managed_vec_iter_exact_size_trait() { let _ = DebugApi::dummy(); diff --git a/elrond-wasm/src/types/managed/wrapped/managed_vec.rs b/elrond-wasm/src/types/managed/wrapped/managed_vec.rs index 5dfee3fa5c..8cca40a64d 100644 --- a/elrond-wasm/src/types/managed/wrapped/managed_vec.rs +++ b/elrond-wasm/src/types/managed/wrapped/managed_vec.rs @@ -8,7 +8,7 @@ use crate::{ }, }; use alloc::vec::Vec; -use core::{borrow::Borrow, marker::PhantomData}; +use core::{borrow::Borrow, iter::FromIterator, marker::PhantomData}; use elrond_codec::{ DecodeErrorHandler, EncodeErrorHandler, NestedDecode, NestedDecodeInput, NestedEncode, NestedEncodeOutput, TopDecode, TopDecodeInput, TopEncode, TopEncodeMultiOutput, @@ -520,3 +520,15 @@ where Ok(()) } } + +impl FromIterator for ManagedVec +where + M: ManagedTypeApi, + V: ManagedVecItem, +{ + fn from_iter>(iter: T) -> Self { + let mut result: ManagedVec = ManagedVec::new(); + iter.into_iter().for_each(|f| result.push(f)); + result + } +}