Skip to content

Commit

Permalink
implement From<Vec> and FromIterator for LazyIndexMap
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelcolvin committed Sep 9, 2024
1 parent dd25fd0 commit c2c3b45
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions crates/jiter/src/lazy_index_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,27 @@ impl<K: PartialEq, V: PartialEq> PartialEq for LazyIndexMap<K, V> {
}
}

impl<K, V> FromIterator<(K, V)> for LazyIndexMap<K, V> {
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
let vec = iter.into_iter().collect();
Self {
vec,
map: OnceLock::new(),
last_find: AtomicUsize::new(0),
}
}

Check warning on line 160 in crates/jiter/src/lazy_index_map.rs

View check run for this annotation

Codecov / codecov/patch

crates/jiter/src/lazy_index_map.rs#L153-L160

Added lines #L153 - L160 were not covered by tests
}

impl<K, V> From<Vec<(K, V)>> for LazyIndexMap<K, V> {
fn from(vec: Vec<(K, V)>) -> Self {
Self {
vec: vec.into(),
map: OnceLock::new(),
last_find: AtomicUsize::new(0),
}
}

Check warning on line 170 in crates/jiter/src/lazy_index_map.rs

View check run for this annotation

Codecov / codecov/patch

crates/jiter/src/lazy_index_map.rs#L164-L170

Added lines #L164 - L170 were not covered by tests
}

struct IterUnique<'a, K, V> {
vec: &'a SmallVec<[(K, V); 8]>,
map: &'a AHashMap<K, usize>,
Expand All @@ -172,3 +193,32 @@ impl<'a, K: Hash + Eq, V> Iterator for IterUnique<'a, K, V> {
None
}
}

#[cfg(test)]
mod test {
use super::*;
use crate::JsonValue;

#[test]
fn test_lazy_index_map_collect() {
let pairs: Vec<(Cow<'static, str>, JsonValue<'static>)> = vec![
("foo".into(), JsonValue::Null),
("bar".into(), JsonValue::Bool(true)),
("spam".into(), JsonValue::Int(123)),
];
let map: LazyIndexMap<_, _> = pairs.into_iter().collect();
assert_eq!(map.len(), 3);
assert_eq!(map.keys().collect::<Vec<_>>(), ["foo", "bar", "spam"]);
assert_eq!(map.get("bar"), Some(&JsonValue::Bool(true)));
}

#[test]
fn test_lazy_index_map_from_vec() {
let pairs: Vec<(Cow<'static, str>, JsonValue<'static>)> =
vec![("foo".into(), JsonValue::Null), ("bar".into(), JsonValue::Bool(true))];
let map: LazyIndexMap<_, _> = pairs.into();
assert_eq!(map.len(), 2);
assert_eq!(map.keys().collect::<Vec<_>>(), ["foo", "bar"]);
assert_eq!(map.get("bar"), Some(&JsonValue::Bool(true)));
}
}

0 comments on commit c2c3b45

Please sign in to comment.