From 5b2558ed2eaa0939491ad58e76b3cd776d6729a6 Mon Sep 17 00:00:00 2001 From: Leigh McCulloch <351529+leighmcculloch@users.noreply.github.com> Date: Wed, 11 Sep 2024 06:45:03 +1000 Subject: [PATCH] Add IntoIterator for &Vec<> (#1328) ### What Add IntoIterator for `&Vec<>`. ### Why To improve the ergonomics of using the `soroban_sdk::Vec` type. So that it is possible to do `for _ in &vec`. So it is possible to iterate a vec without moving it. Today if a developer would like to iterate a Vec without moving it, they need to write `for _ in vec.iter()`. This pattern is a little odd because ordinarily a developer just passes `&vec` to iterate without moving. Note that iterating `&vec` will still be somewhat different than it would be to iterate a ref of a `std::vec::Vec` from the Rust std library. This is because the Rust std library `Vec` when iterating a vec is iterating refs to items in the vec. When iterating a `soroban_sdk::Vec` there is no items in memory to ref, rather during iteration each item is communicated across the host-guest interface and must be passed by value as no one is holding onto its value. --- soroban-sdk/src/vec.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/soroban-sdk/src/vec.rs b/soroban-sdk/src/vec.rs index 70ed89b47..46f66bc9b 100644 --- a/soroban-sdk/src/vec.rs +++ b/soroban-sdk/src/vec.rs @@ -894,6 +894,18 @@ where } } +impl IntoIterator for &Vec +where + T: IntoVal + TryFromVal, +{ + type Item = T; + type IntoIter = UnwrappedIter, T, T::Error>; + + fn into_iter(self) -> Self::IntoIter { + self.clone().into_iter() + } +} + impl Vec where T: IntoVal + TryFromVal,