Skip to content

Commit e1570e3

Browse files
committed
implement From<Vec> and FromIterator for LazyIndexMap
1 parent b09b969 commit e1570e3

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

crates/jiter/src/lazy_index_map.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,27 @@ impl<K: PartialEq, V: PartialEq> PartialEq for LazyIndexMap<K, V> {
149149
}
150150
}
151151

152+
impl<K, V> FromIterator<(K, V)> for LazyIndexMap<K, V> {
153+
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
154+
let vec = iter.into_iter().collect();
155+
Self {
156+
vec,
157+
map: OnceLock::new(),
158+
last_find: AtomicUsize::new(0),
159+
}
160+
}
161+
}
162+
163+
impl<K, V> From<Vec<(K, V)>> for LazyIndexMap<K, V> {
164+
fn from(vec: Vec<(K, V)>) -> Self {
165+
Self {
166+
vec: vec.into(),
167+
map: OnceLock::new(),
168+
last_find: AtomicUsize::new(0),
169+
}
170+
}
171+
}
172+
152173
struct IterUnique<'a, K, V> {
153174
vec: &'a SmallVec<[(K, V); 8]>,
154175
map: &'a AHashMap<K, usize>,
@@ -172,3 +193,32 @@ impl<'a, K: Hash + Eq, V> Iterator for IterUnique<'a, K, V> {
172193
None
173194
}
174195
}
196+
197+
#[cfg(test)]
198+
mod test {
199+
use super::*;
200+
use crate::JsonValue;
201+
202+
#[test]
203+
fn test_lazy_index_map_collect() {
204+
let pairs: Vec<(Cow<'static, str>, JsonValue<'static>)> = vec![
205+
("foo".into(), JsonValue::Null),
206+
("bar".into(), JsonValue::Bool(true)),
207+
("spam".into(), JsonValue::Int(123)),
208+
];
209+
let map: LazyIndexMap<_, _> = pairs.into_iter().collect();
210+
assert_eq!(map.len(), 3);
211+
assert_eq!(map.keys().collect::<Vec<_>>(), ["foo", "bar", "spam"]);
212+
assert_eq!(map.get("bar"), Some(&JsonValue::Bool(true)));
213+
}
214+
215+
#[test]
216+
fn test_lazy_index_map_from_vec() {
217+
let pairs: Vec<(Cow<'static, str>, JsonValue<'static>)> =
218+
vec![("foo".into(), JsonValue::Null), ("bar".into(), JsonValue::Bool(true))];
219+
let map: LazyIndexMap<_, _> = pairs.into();
220+
assert_eq!(map.len(), 2);
221+
assert_eq!(map.keys().collect::<Vec<_>>(), ["foo", "bar"]);
222+
assert_eq!(map.get("bar"), Some(&JsonValue::Bool(true)));
223+
}
224+
}

0 commit comments

Comments
 (0)