Skip to content

Commit

Permalink
Add IntoIterator for &Vec<> (#1328)
Browse files Browse the repository at this point in the history
### 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.
  • Loading branch information
leighmcculloch authored Sep 10, 2024
1 parent 0a86ece commit 5b2558e
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions soroban-sdk/src/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -894,6 +894,18 @@ where
}
}

impl<T> IntoIterator for &Vec<T>
where
T: IntoVal<Env, Val> + TryFromVal<Env, Val>,
{
type Item = T;
type IntoIter = UnwrappedIter<VecTryIter<T>, T, T::Error>;

fn into_iter(self) -> Self::IntoIter {
self.clone().into_iter()
}
}

impl<T> Vec<T>
where
T: IntoVal<Env, Val> + TryFromVal<Env, Val>,
Expand Down

0 comments on commit 5b2558e

Please sign in to comment.