Skip to content

Commit

Permalink
Add Vec to Set helpers (#573)
Browse files Browse the repository at this point in the history
  • Loading branch information
accordeiro authored Sep 8, 2022
1 parent 9292b80 commit afcd1e5
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion soroban-sdk/src/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::iter::{UncheckedEnumerable, UncheckedIter};

use super::{
env::internal::Env as _, env::EnvObj, xdr::ScObjectType, ConversionError, Env, EnvVal, IntoVal,
Object, RawVal, TryFromVal, TryIntoVal,
Object, RawVal, Set, TryFromVal, TryIntoVal,
};

#[cfg(doc)]
Expand Down Expand Up @@ -271,6 +271,19 @@ where
}
}

impl<T> From<Vec<T>> for Set<T>
where
T: IntoVal<Env, RawVal> + TryFromVal<Env, RawVal>,
{
fn from(v: Vec<T>) -> Self {
let mut s: Set<T> = Set::new(v.env());
for i in v.into_iter().flatten() {
s.insert(i);
}
s
}
}

#[cfg(not(target_family = "wasm"))]
use super::xdr::ScVal;

Expand Down Expand Up @@ -762,6 +775,7 @@ where
#[cfg(test)]
mod test {
use super::*;
use crate::set;

#[test]
fn test_vec_macro() {
Expand Down Expand Up @@ -1013,4 +1027,17 @@ mod test {
let roundtrip = Vec::<i64>::try_from_val(&env, val).unwrap();
assert_eq!(v, roundtrip);
}

#[test]
fn test_vec_to_set() {
let env = Env::default();
let v = vec![&env, 1, 2, 3];
let s = Set::from(v);
assert_eq!(s, set![&env, 1, 2, 3]);

// Ensure this also deduplicates and sorts values
let v2 = vec![&env, 9, 9, 1, 5, 3, 7, 3, 5, 5];
let s2 = Set::from(v2);
assert_eq!(s2, set![&env, 1, 3, 5, 7, 9]);
}
}

0 comments on commit afcd1e5

Please sign in to comment.