iddqd/id_ord_map/imp.rs
1use super::{
2 Entry, IdOrdItem, IntoIter, Iter, IterMut, OccupiedEntry, RefMut,
3 VacantEntry, tables::IdOrdMapTables,
4};
5use crate::{
6 errors::DuplicateItem,
7 internal::{ValidateChaos, ValidateCompact, ValidationError},
8 support::{
9 alloc::{Global, global_alloc},
10 borrow::DormantMutRef,
11 item_set::ItemSet,
12 map_hash::MapHash,
13 },
14};
15use alloc::collections::BTreeSet;
16use core::{
17 fmt,
18 hash::{BuildHasher, Hash},
19};
20use equivalent::{Comparable, Equivalent};
21
22/// An ordered map where the keys are part of the values, based on a B-Tree.
23///
24/// The storage mechanism is a fast hash table of integer indexes to items, with
25/// the indexes stored in a B-Tree map.
26///
27/// # Examples
28///
29/// ```
30/// # #[cfg(feature = "default-hasher")] {
31/// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
32///
33/// // Define a struct with a key.
34/// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
35/// struct MyItem {
36/// id: String,
37/// value: u32,
38/// }
39///
40/// // Implement IdOrdItem for the struct.
41/// impl IdOrdItem for MyItem {
42/// // Keys can borrow from the item.
43/// type Key<'a> = &'a str;
44///
45/// fn key(&self) -> Self::Key<'_> {
46/// &self.id
47/// }
48///
49/// id_upcast!();
50/// }
51///
52/// // Create an IdOrdMap and insert items.
53/// let mut map = IdOrdMap::new();
54/// map.insert_unique(MyItem { id: "foo".to_string(), value: 42 }).unwrap();
55/// map.insert_unique(MyItem { id: "bar".to_string(), value: 20 }).unwrap();
56///
57/// // Look up items by their keys.
58/// assert_eq!(map.get("foo").unwrap().value, 42);
59/// assert_eq!(map.get("bar").unwrap().value, 20);
60/// assert!(map.get("baz").is_none());
61/// # }
62/// ```
63#[derive(Clone)]
64pub struct IdOrdMap<T> {
65 // We don't expose an allocator trait here because it isn't stable with
66 // std's BTreeMap.
67 pub(super) items: ItemSet<T, Global>,
68 // Invariant: the values (usize) in these tables are valid indexes into
69 // `items`, and are a 1:1 mapping.
70 pub(super) tables: IdOrdMapTables,
71}
72
73impl<T: IdOrdItem> Default for IdOrdMap<T> {
74 fn default() -> Self {
75 Self::new()
76 }
77}
78
79impl<T: IdOrdItem> IdOrdMap<T> {
80 /// Creates a new, empty `IdOrdMap`.
81 ///
82 /// # Examples
83 ///
84 /// ```
85 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
86 ///
87 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
88 /// struct Item {
89 /// id: String,
90 /// value: u32,
91 /// }
92 ///
93 /// impl IdOrdItem for Item {
94 /// type Key<'a> = &'a str;
95 ///
96 /// fn key(&self) -> Self::Key<'_> {
97 /// &self.id
98 /// }
99 ///
100 /// id_upcast!();
101 /// }
102 ///
103 /// let map: IdOrdMap<Item> = IdOrdMap::new();
104 /// assert!(map.is_empty());
105 /// assert_eq!(map.len(), 0);
106 /// ```
107 #[inline]
108 pub const fn new() -> Self {
109 Self { items: ItemSet::new(), tables: IdOrdMapTables::new() }
110 }
111
112 /// Creates a new `IdOrdMap` with the given capacity.
113 ///
114 /// The capacity will be used to initialize the underlying hash table.
115 ///
116 /// # Examples
117 ///
118 /// ```
119 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
120 ///
121 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
122 /// struct Item {
123 /// id: String,
124 /// value: u32,
125 /// }
126 ///
127 /// impl IdOrdItem for Item {
128 /// type Key<'a> = &'a str;
129 ///
130 /// fn key(&self) -> Self::Key<'_> {
131 /// &self.id
132 /// }
133 ///
134 /// id_upcast!();
135 /// }
136 ///
137 /// let map: IdOrdMap<Item> = IdOrdMap::with_capacity(10);
138 /// assert!(map.capacity() >= 10);
139 /// assert!(map.is_empty());
140 /// ```
141 pub fn with_capacity(capacity: usize) -> Self {
142 Self {
143 items: ItemSet::with_capacity_in(capacity, global_alloc()),
144 tables: IdOrdMapTables::new(),
145 }
146 }
147
148 /// Returns the currently allocated capacity of the map.
149 ///
150 /// # Examples
151 ///
152 /// ```
153 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
154 ///
155 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
156 /// struct Item {
157 /// id: String,
158 /// value: u32,
159 /// }
160 ///
161 /// impl IdOrdItem for Item {
162 /// type Key<'a> = &'a str;
163 ///
164 /// fn key(&self) -> Self::Key<'_> {
165 /// &self.id
166 /// }
167 ///
168 /// id_upcast!();
169 /// }
170 ///
171 /// let map: IdOrdMap<Item> = IdOrdMap::with_capacity(10);
172 /// assert!(map.capacity() >= 10);
173 /// ```
174 pub fn capacity(&self) -> usize {
175 // There's no self.tables.capacity.
176 self.items.capacity()
177 }
178
179 /// Constructs a new `IdOrdMap` from an iterator of values, rejecting
180 /// duplicates.
181 ///
182 /// To overwrite duplicates instead, use [`IdOrdMap::from_iter`].
183 ///
184 /// # Examples
185 ///
186 /// ```
187 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
188 ///
189 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
190 /// struct Item {
191 /// id: String,
192 /// value: u32,
193 /// }
194 ///
195 /// impl IdOrdItem for Item {
196 /// type Key<'a> = &'a str;
197 ///
198 /// fn key(&self) -> Self::Key<'_> {
199 /// &self.id
200 /// }
201 ///
202 /// id_upcast!();
203 /// }
204 ///
205 /// let items = vec![
206 /// Item { id: "foo".to_string(), value: 42 },
207 /// Item { id: "bar".to_string(), value: 99 },
208 /// ];
209 ///
210 /// // Successful creation with unique keys
211 /// let map = IdOrdMap::from_iter_unique(items).unwrap();
212 /// assert_eq!(map.len(), 2);
213 /// assert_eq!(map.get("foo").unwrap().value, 42);
214 ///
215 /// // Error with duplicate keys
216 /// let duplicate_items = vec![
217 /// Item { id: "foo".to_string(), value: 42 },
218 /// Item { id: "foo".to_string(), value: 99 },
219 /// ];
220 /// assert!(IdOrdMap::from_iter_unique(duplicate_items).is_err());
221 /// ```
222 pub fn from_iter_unique<I: IntoIterator<Item = T>>(
223 iter: I,
224 ) -> Result<Self, DuplicateItem<T>> {
225 let mut map = IdOrdMap::new();
226 for value in iter {
227 // It would be nice to use insert_overwrite here, but that would
228 // return a `DuplicateItem<T, &T>`, which can only be converted into
229 // an owned value if T: Clone. Doing this via the Entry API means we
230 // can return a `DuplicateItem<T>` without requiring T to be Clone.
231 match map.entry(value.key()) {
232 Entry::Occupied(entry) => {
233 let duplicate = entry.remove();
234 return Err(DuplicateItem::__internal_new(
235 value,
236 vec![duplicate],
237 ));
238 }
239 Entry::Vacant(entry) => {
240 entry.insert_ref(value);
241 }
242 }
243 }
244
245 Ok(map)
246 }
247
248 /// Returns true if the map is empty.
249 ///
250 /// # Examples
251 ///
252 /// ```
253 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
254 ///
255 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
256 /// struct Item {
257 /// id: String,
258 /// value: u32,
259 /// }
260 ///
261 /// impl IdOrdItem for Item {
262 /// type Key<'a> = &'a str;
263 ///
264 /// fn key(&self) -> Self::Key<'_> {
265 /// &self.id
266 /// }
267 ///
268 /// id_upcast!();
269 /// }
270 ///
271 /// let mut map = IdOrdMap::new();
272 /// assert!(map.is_empty());
273 ///
274 /// map.insert_unique(Item { id: "foo".to_string(), value: 42 }).unwrap();
275 /// assert!(!map.is_empty());
276 /// ```
277 #[inline]
278 pub fn is_empty(&self) -> bool {
279 self.items.is_empty()
280 }
281
282 /// Returns the number of items in the map.
283 ///
284 /// # Examples
285 ///
286 /// ```
287 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
288 ///
289 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
290 /// struct Item {
291 /// id: String,
292 /// value: u32,
293 /// }
294 ///
295 /// impl IdOrdItem for Item {
296 /// type Key<'a> = &'a str;
297 ///
298 /// fn key(&self) -> Self::Key<'_> {
299 /// &self.id
300 /// }
301 ///
302 /// id_upcast!();
303 /// }
304 ///
305 /// let mut map = IdOrdMap::new();
306 /// assert_eq!(map.len(), 0);
307 ///
308 /// map.insert_unique(Item { id: "foo".to_string(), value: 42 }).unwrap();
309 /// map.insert_unique(Item { id: "bar".to_string(), value: 99 }).unwrap();
310 /// assert_eq!(map.len(), 2);
311 /// ```
312 #[inline]
313 pub fn len(&self) -> usize {
314 self.items.len()
315 }
316
317 /// Clears the map, removing all items.
318 ///
319 /// # Examples
320 ///
321 /// ```
322 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
323 ///
324 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
325 /// struct Item {
326 /// id: String,
327 /// value: u32,
328 /// }
329 ///
330 /// impl IdOrdItem for Item {
331 /// type Key<'a> = &'a str;
332 ///
333 /// fn key(&self) -> Self::Key<'_> {
334 /// &self.id
335 /// }
336 ///
337 /// id_upcast!();
338 /// }
339 ///
340 /// let mut map = IdOrdMap::new();
341 /// map.insert_unique(Item { id: "foo".to_string(), value: 42 }).unwrap();
342 /// map.insert_unique(Item { id: "bar".to_string(), value: 99 }).unwrap();
343 /// assert_eq!(map.len(), 2);
344 ///
345 /// map.clear();
346 /// assert!(map.is_empty());
347 /// assert_eq!(map.len(), 0);
348 /// ```
349 pub fn clear(&mut self) {
350 self.items.clear();
351 self.tables.key_to_item.clear();
352 }
353
354 /// Iterates over the items in the map.
355 ///
356 /// Similar to [`BTreeMap`], the iteration is ordered by [`T::Key`].
357 ///
358 /// # Examples
359 ///
360 /// ```
361 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
362 ///
363 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
364 /// struct Item {
365 /// id: String,
366 /// value: u32,
367 /// }
368 ///
369 /// impl IdOrdItem for Item {
370 /// type Key<'a> = &'a str;
371 ///
372 /// fn key(&self) -> Self::Key<'_> {
373 /// &self.id
374 /// }
375 ///
376 /// id_upcast!();
377 /// }
378 ///
379 /// let mut map = IdOrdMap::new();
380 /// map.insert_unique(Item { id: "charlie".to_string(), value: 30 }).unwrap();
381 /// map.insert_unique(Item { id: "alice".to_string(), value: 42 }).unwrap();
382 /// map.insert_unique(Item { id: "bob".to_string(), value: 99 }).unwrap();
383 ///
384 /// // Iteration is ordered by key
385 /// let mut iter = map.iter();
386 /// let item = iter.next().unwrap();
387 /// assert_eq!(item.id, "alice");
388 /// let item = iter.next().unwrap();
389 /// assert_eq!(item.id, "bob");
390 /// let item = iter.next().unwrap();
391 /// assert_eq!(item.id, "charlie");
392 /// assert!(iter.next().is_none());
393 /// ```
394 ///
395 /// [`BTreeMap`]: std::collections::BTreeMap
396 /// [`T::Key`]: crate::IdOrdItem::Key
397 #[inline]
398 pub fn iter(&self) -> Iter<'_, T> {
399 Iter::new(&self.items, &self.tables)
400 }
401
402 /// Iterates over the items in the map, allowing for mutation.
403 ///
404 /// Similar to [`BTreeMap`], the iteration is ordered by [`T::Key`].
405 ///
406 /// # Examples
407 ///
408 /// ```
409 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
410 ///
411 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
412 /// struct Item {
413 /// id: String,
414 /// value: u32,
415 /// }
416 ///
417 /// impl IdOrdItem for Item {
418 /// type Key<'a> = &'a str;
419 ///
420 /// fn key(&self) -> Self::Key<'_> {
421 /// &self.id
422 /// }
423 ///
424 /// id_upcast!();
425 /// }
426 ///
427 /// let mut map = IdOrdMap::new();
428 /// map.insert_unique(Item { id: "foo".to_string(), value: 42 }).unwrap();
429 /// map.insert_unique(Item { id: "bar".to_string(), value: 99 }).unwrap();
430 ///
431 /// // Modify values through the mutable iterator
432 /// for mut item in map.iter_mut() {
433 /// item.value *= 2;
434 /// }
435 ///
436 /// assert_eq!(map.get("foo").unwrap().value, 84);
437 /// assert_eq!(map.get("bar").unwrap().value, 198);
438 /// ```
439 ///
440 /// [`BTreeMap`]: std::collections::BTreeMap
441 /// [`T::Key`]: crate::IdOrdItem::Key
442 #[inline]
443 pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T>
444 where
445 T::Key<'a>: Hash,
446 {
447 IterMut::new(&mut self.items, &self.tables)
448 }
449
450 /// Checks general invariants of the map.
451 ///
452 /// The code below always upholds these invariants, but it's useful to have
453 /// an explicit check for tests.
454 #[doc(hidden)]
455 pub fn validate(
456 &self,
457 compactness: ValidateCompact,
458 chaos: ValidateChaos,
459 ) -> Result<(), ValidationError>
460 where
461 T: fmt::Debug,
462 {
463 self.items.validate(compactness)?;
464 self.tables.validate(self.len(), compactness)?;
465
466 // Check that the indexes are all correct.
467
468 for (&ix, item) in self.items.iter() {
469 let key = item.key();
470 let ix1 = match chaos {
471 ValidateChaos::Yes => {
472 // Fall back to a linear search.
473 self.linear_search_index(&key)
474 }
475 ValidateChaos::No => {
476 // Use the B-Tree table to find the index.
477 self.find_index(&key)
478 }
479 };
480 let Some(ix1) = ix1 else {
481 return Err(ValidationError::general(format!(
482 "item at index {ix} has no key1 index"
483 )));
484 };
485
486 if ix1 != ix {
487 return Err(ValidationError::General(format!(
488 "item at index {ix} has mismatched indexes: ix1: {ix1}",
489 )));
490 }
491 }
492
493 Ok(())
494 }
495
496 /// Inserts a value into the set, returning an error if any duplicates were
497 /// added.
498 ///
499 /// # Examples
500 ///
501 /// ```
502 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
503 ///
504 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
505 /// struct Item {
506 /// id: String,
507 /// value: u32,
508 /// }
509 ///
510 /// impl IdOrdItem for Item {
511 /// type Key<'a> = &'a str;
512 ///
513 /// fn key(&self) -> Self::Key<'_> {
514 /// &self.id
515 /// }
516 ///
517 /// id_upcast!();
518 /// }
519 ///
520 /// let mut map = IdOrdMap::new();
521 ///
522 /// // Successful insertion
523 /// assert!(
524 /// map.insert_unique(Item { id: "foo".to_string(), value: 42 }).is_ok()
525 /// );
526 /// assert!(
527 /// map.insert_unique(Item { id: "bar".to_string(), value: 99 }).is_ok()
528 /// );
529 ///
530 /// // Duplicate key
531 /// assert!(
532 /// map.insert_unique(Item { id: "foo".to_string(), value: 100 }).is_err()
533 /// );
534 /// ```
535 pub fn insert_unique(
536 &mut self,
537 value: T,
538 ) -> Result<(), DuplicateItem<T, &T>> {
539 let _ = self.insert_unique_impl(value)?;
540 Ok(())
541 }
542
543 /// Inserts a value into the map, removing and returning the conflicting
544 /// item, if any.
545 ///
546 /// # Examples
547 ///
548 /// ```
549 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
550 ///
551 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
552 /// struct Item {
553 /// id: String,
554 /// value: u32,
555 /// }
556 ///
557 /// impl IdOrdItem for Item {
558 /// type Key<'a> = &'a str;
559 ///
560 /// fn key(&self) -> Self::Key<'_> {
561 /// &self.id
562 /// }
563 ///
564 /// id_upcast!();
565 /// }
566 ///
567 /// let mut map = IdOrdMap::new();
568 ///
569 /// // First insertion - no conflict
570 /// let old = map.insert_overwrite(Item { id: "foo".to_string(), value: 42 });
571 /// assert!(old.is_none());
572 ///
573 /// // Overwrite existing key - returns old value
574 /// let old = map.insert_overwrite(Item { id: "foo".to_string(), value: 99 });
575 /// assert!(old.is_some());
576 /// assert_eq!(old.unwrap().value, 42);
577 ///
578 /// // Verify new value is in the map
579 /// assert_eq!(map.get("foo").unwrap().value, 99);
580 /// ```
581 #[doc(alias = "insert")]
582 pub fn insert_overwrite(&mut self, value: T) -> Option<T> {
583 // Trying to write this function for maximal efficiency can get very
584 // tricky, requiring delicate handling of indexes. We follow a very
585 // simple approach instead:
586 //
587 // 1. Remove the item corresponding to the key that is already in the map.
588 // 2. Add the item to the map.
589
590 let duplicate = self.remove(&value.key());
591
592 if self.insert_unique(value).is_err() {
593 // We should never get here, because we just removed all the
594 // duplicates.
595 panic!("insert_unique failed after removing duplicates");
596 }
597
598 duplicate
599 }
600
601 /// Returns true if the map contains the given `key`.
602 ///
603 /// # Examples
604 ///
605 /// ```
606 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
607 ///
608 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
609 /// struct Item {
610 /// id: String,
611 /// value: u32,
612 /// }
613 ///
614 /// impl IdOrdItem for Item {
615 /// type Key<'a> = &'a str;
616 ///
617 /// fn key(&self) -> Self::Key<'_> {
618 /// &self.id
619 /// }
620 ///
621 /// id_upcast!();
622 /// }
623 ///
624 /// let mut map = IdOrdMap::new();
625 /// map.insert_unique(Item { id: "foo".to_string(), value: 42 }).unwrap();
626 ///
627 /// assert!(map.contains_key("foo"));
628 /// assert!(!map.contains_key("bar"));
629 /// ```
630 pub fn contains_key<'a, Q>(&'a self, key: &Q) -> bool
631 where
632 Q: ?Sized + Comparable<T::Key<'a>>,
633 {
634 self.find_index(key).is_some()
635 }
636
637 /// Gets a reference to the value associated with the given `key`.
638 ///
639 /// # Examples
640 ///
641 /// ```
642 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
643 ///
644 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
645 /// struct Item {
646 /// id: String,
647 /// value: u32,
648 /// }
649 ///
650 /// impl IdOrdItem for Item {
651 /// type Key<'a> = &'a str;
652 ///
653 /// fn key(&self) -> Self::Key<'_> {
654 /// &self.id
655 /// }
656 ///
657 /// id_upcast!();
658 /// }
659 ///
660 /// let mut map = IdOrdMap::new();
661 /// map.insert_unique(Item { id: "foo".to_string(), value: 42 }).unwrap();
662 ///
663 /// assert_eq!(map.get("foo").unwrap().value, 42);
664 /// assert!(map.get("bar").is_none());
665 /// ```
666 pub fn get<'a, Q>(&'a self, key: &Q) -> Option<&'a T>
667 where
668 Q: ?Sized + Comparable<T::Key<'a>>,
669 {
670 self.find(key)
671 }
672
673 /// Gets a mutable reference to the item associated with the given `key`.
674 ///
675 /// # Examples
676 ///
677 /// ```
678 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
679 ///
680 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
681 /// struct Item {
682 /// id: String,
683 /// value: u32,
684 /// }
685 ///
686 /// impl IdOrdItem for Item {
687 /// type Key<'a> = &'a str;
688 ///
689 /// fn key(&self) -> Self::Key<'_> {
690 /// &self.id
691 /// }
692 ///
693 /// id_upcast!();
694 /// }
695 ///
696 /// let mut map = IdOrdMap::new();
697 /// map.insert_unique(Item { id: "foo".to_string(), value: 42 }).unwrap();
698 ///
699 /// if let Some(mut item) = map.get_mut("foo") {
700 /// item.value = 99;
701 /// }
702 ///
703 /// assert_eq!(map.get("foo").unwrap().value, 99);
704 /// ```
705 pub fn get_mut<'a, Q>(&'a mut self, key: &Q) -> Option<RefMut<'a, T>>
706 where
707 Q: ?Sized + Comparable<T::Key<'a>>,
708 T::Key<'a>: Hash,
709 {
710 let (dormant_map, index) = {
711 let (map, dormant_map) = DormantMutRef::new(self);
712 let index = map.find_index(key)?;
713 (dormant_map, index)
714 };
715
716 // SAFETY: `map` is not used after this point.
717 let awakened_map = unsafe { dormant_map.awaken() };
718 let item = &mut awakened_map.items[index];
719 let state = awakened_map.tables.state().clone();
720 let (hash, dormant) = {
721 let (item, dormant) = DormantMutRef::new(item);
722 let hash = awakened_map.tables.make_hash(item);
723 (hash, dormant)
724 };
725
726 // SAFETY: the original item is not used after this point.
727 let item = unsafe { dormant.awaken() };
728 Some(RefMut::new(state, hash, item))
729 }
730
731 /// Removes an item from the map by its `key`.
732 ///
733 /// # Examples
734 ///
735 /// ```
736 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
737 ///
738 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
739 /// struct Item {
740 /// id: String,
741 /// value: u32,
742 /// }
743 ///
744 /// impl IdOrdItem for Item {
745 /// type Key<'a> = &'a str;
746 ///
747 /// fn key(&self) -> Self::Key<'_> {
748 /// &self.id
749 /// }
750 ///
751 /// id_upcast!();
752 /// }
753 ///
754 /// let mut map = IdOrdMap::new();
755 /// map.insert_unique(Item { id: "foo".to_string(), value: 42 }).unwrap();
756 ///
757 /// let removed = map.remove("foo");
758 /// assert!(removed.is_some());
759 /// assert_eq!(removed.unwrap().value, 42);
760 /// assert!(map.is_empty());
761 ///
762 /// // Removing a non-existent key returns None
763 /// assert!(map.remove("bar").is_none());
764 /// ```
765 pub fn remove<'a, Q>(&'a mut self, key: &Q) -> Option<T>
766 where
767 Q: ?Sized + Comparable<T::Key<'a>>,
768 {
769 let (dormant_map, remove_index) = {
770 let (map, dormant_map) = DormantMutRef::new(self);
771 let remove_index = map.find_index(key)?;
772 (dormant_map, remove_index)
773 };
774
775 // SAFETY: `map` is not used after this point.
776 let awakened_map = unsafe { dormant_map.awaken() };
777 awakened_map.remove_by_index(remove_index)
778 }
779
780 /// Retrieves an entry by its `key`.
781 ///
782 /// Due to borrow checker limitations, this always accepts an owned key rather
783 /// than a borrowed form.
784 ///
785 /// # Examples
786 ///
787 /// ```
788 /// use iddqd::{IdOrdItem, IdOrdMap, id_ord_map, id_upcast};
789 ///
790 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
791 /// struct Item {
792 /// id: String,
793 /// value: u32,
794 /// }
795 ///
796 /// impl IdOrdItem for Item {
797 /// type Key<'a> = &'a str;
798 ///
799 /// fn key(&self) -> Self::Key<'_> {
800 /// &self.id
801 /// }
802 ///
803 /// id_upcast!();
804 /// }
805 ///
806 /// let mut map = IdOrdMap::new();
807 ///
808 /// // Insert via vacant entry
809 /// match map.entry("foo") {
810 /// id_ord_map::Entry::Vacant(entry) => {
811 /// entry.insert(Item { id: "foo".to_string(), value: 42 });
812 /// }
813 /// id_ord_map::Entry::Occupied(_) => {}
814 /// }
815 ///
816 /// // Update via occupied entry
817 /// match map.entry("foo") {
818 /// id_ord_map::Entry::Occupied(mut entry) => {
819 /// entry.get_mut().value = 99;
820 /// }
821 /// id_ord_map::Entry::Vacant(_) => {}
822 /// }
823 ///
824 /// assert_eq!(map.get("foo").unwrap().value, 99);
825 /// ```
826 pub fn entry<'a>(&'a mut self, key: T::Key<'_>) -> Entry<'a, T> {
827 // Why does this always take an owned key? Well, it would seem like we
828 // should be able to pass in any Q that is equivalent. That results in
829 // *this* code compiling fine, but callers have trouble using it because
830 // the borrow checker believes the keys are borrowed for the full 'a
831 // rather than a shorter lifetime.
832 //
833 // By accepting owned keys, we can use the upcast functions to convert
834 // them to a shorter lifetime (so this function accepts T::Key<'_>
835 // rather than T::Key<'a>).
836 //
837 // Really, the solution here is to allow GATs to require covariant
838 // parameters. If that were allowed, the borrow checker should be able
839 // to figure out that keys don't need to be borrowed for the full 'a,
840 // just for some shorter lifetime.
841 let (map, dormant_map) = DormantMutRef::new(self);
842 let key = T::upcast_key(key);
843 {
844 // index is explicitly typed to show that it has a trivial Drop impl
845 // that doesn't capture anything from map.
846 let index: Option<usize> = map
847 .tables
848 .key_to_item
849 .find_index(&key, |index| map.items[index].key());
850 if let Some(index) = index {
851 drop(key);
852 return Entry::Occupied(
853 // SAFETY: `map` is not used after this point.
854 unsafe { OccupiedEntry::new(dormant_map, index) },
855 );
856 }
857 }
858 Entry::Vacant(
859 // SAFETY: `map` is not used after this point.
860 unsafe { VacantEntry::new(dormant_map) },
861 )
862 }
863
864 /// Returns the first item in the map. The key of this item is the minimum
865 /// key in the map.
866 ///
867 /// # Examples
868 ///
869 /// ```
870 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
871 ///
872 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
873 /// struct Item {
874 /// id: String,
875 /// value: u32,
876 /// }
877 ///
878 /// impl IdOrdItem for Item {
879 /// type Key<'a> = &'a str;
880 ///
881 /// fn key(&self) -> Self::Key<'_> {
882 /// &self.id
883 /// }
884 ///
885 /// id_upcast!();
886 /// }
887 ///
888 /// let mut map = IdOrdMap::new();
889 /// map.insert_unique(Item { id: "charlie".to_string(), value: 30 }).unwrap();
890 /// map.insert_unique(Item { id: "alice".to_string(), value: 42 }).unwrap();
891 /// map.insert_unique(Item { id: "bob".to_string(), value: 99 }).unwrap();
892 ///
893 /// // First item has the minimum key.
894 /// let first = map.first().unwrap();
895 /// assert_eq!(first.id, "alice");
896 /// assert_eq!(first.value, 42);
897 ///
898 /// // Empty map returns None.
899 /// let empty_map: IdOrdMap<Item> = IdOrdMap::new();
900 /// assert!(empty_map.first().is_none());
901 /// ```
902 #[inline]
903 pub fn first(&self) -> Option<&T> {
904 self.tables.key_to_item.first().map(|index| &self.items[index])
905 }
906
907 /// Returns the first entry in the map for in-place manipulation. The key of
908 /// this entry is the minimum key in the map.
909 ///
910 /// # Examples
911 ///
912 /// ```
913 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
914 ///
915 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
916 /// struct Item {
917 /// id: String,
918 /// value: u32,
919 /// }
920 ///
921 /// impl IdOrdItem for Item {
922 /// type Key<'a> = &'a str;
923 ///
924 /// fn key(&self) -> Self::Key<'_> {
925 /// &self.id
926 /// }
927 ///
928 /// id_upcast!();
929 /// }
930 ///
931 /// let mut map = IdOrdMap::new();
932 /// map.insert_unique(Item { id: "charlie".to_string(), value: 30 }).unwrap();
933 /// map.insert_unique(Item { id: "alice".to_string(), value: 42 }).unwrap();
934 /// map.insert_unique(Item { id: "bob".to_string(), value: 99 }).unwrap();
935 ///
936 /// // Modify the first entry.
937 /// if let Some(mut entry) = map.first_entry() {
938 /// entry.get_mut().value = 100;
939 /// }
940 ///
941 /// assert_eq!(map.get("alice").unwrap().value, 100);
942 /// ```
943 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, T>> {
944 let index = self.tables.key_to_item.first()?;
945 let (_, dormant_map) = DormantMutRef::new(self);
946 Some(
947 // SAFETY: `map` is dropped immediately while creating the
948 // DormantMutRef.
949 unsafe { OccupiedEntry::new(dormant_map, index) },
950 )
951 }
952
953 /// Removes and returns the first element in the map. The key of this
954 /// element is the minimum key in the map.
955 ///
956 /// # Examples
957 ///
958 /// ```
959 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
960 ///
961 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
962 /// struct Item {
963 /// id: String,
964 /// value: u32,
965 /// }
966 ///
967 /// impl IdOrdItem for Item {
968 /// type Key<'a> = &'a str;
969 ///
970 /// fn key(&self) -> Self::Key<'_> {
971 /// &self.id
972 /// }
973 ///
974 /// id_upcast!();
975 /// }
976 ///
977 /// let mut map = IdOrdMap::new();
978 /// map.insert_unique(Item { id: "charlie".to_string(), value: 30 }).unwrap();
979 /// map.insert_unique(Item { id: "alice".to_string(), value: 42 }).unwrap();
980 /// map.insert_unique(Item { id: "bob".to_string(), value: 99 }).unwrap();
981 ///
982 /// // Remove the first element.
983 /// let first = map.pop_first().unwrap();
984 /// assert_eq!(first.id, "alice");
985 /// assert_eq!(first.value, 42);
986 /// assert_eq!(map.len(), 2);
987 ///
988 /// // Remove the next element.
989 /// let first = map.pop_first().unwrap();
990 /// assert_eq!(first.id, "bob");
991 ///
992 /// // Empty map returns None.
993 /// map.pop_first();
994 /// assert!(map.pop_first().is_none());
995 /// ```
996 pub fn pop_first(&mut self) -> Option<T> {
997 let index = self.tables.key_to_item.first()?;
998 self.remove_by_index(index)
999 }
1000
1001 /// Returns the last item in the map. The key of this item is the maximum
1002 /// key in the map.
1003 ///
1004 /// # Examples
1005 ///
1006 /// ```
1007 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
1008 ///
1009 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
1010 /// struct Item {
1011 /// id: String,
1012 /// value: u32,
1013 /// }
1014 ///
1015 /// impl IdOrdItem for Item {
1016 /// type Key<'a> = &'a str;
1017 ///
1018 /// fn key(&self) -> Self::Key<'_> {
1019 /// &self.id
1020 /// }
1021 ///
1022 /// id_upcast!();
1023 /// }
1024 ///
1025 /// let mut map = IdOrdMap::new();
1026 /// map.insert_unique(Item { id: "charlie".to_string(), value: 30 }).unwrap();
1027 /// map.insert_unique(Item { id: "alice".to_string(), value: 42 }).unwrap();
1028 /// map.insert_unique(Item { id: "bob".to_string(), value: 99 }).unwrap();
1029 ///
1030 /// // Last item has the maximum key.
1031 /// let last = map.last().unwrap();
1032 /// assert_eq!(last.id, "charlie");
1033 /// assert_eq!(last.value, 30);
1034 ///
1035 /// // Empty map returns None.
1036 /// let empty_map: IdOrdMap<Item> = IdOrdMap::new();
1037 /// assert!(empty_map.last().is_none());
1038 /// ```
1039 #[inline]
1040 pub fn last(&self) -> Option<&T> {
1041 self.tables.key_to_item.last().map(|index| &self.items[index])
1042 }
1043
1044 /// Returns the last entry in the map for in-place manipulation. The key of
1045 /// this entry is the maximum key in the map.
1046 ///
1047 /// # Examples
1048 ///
1049 /// ```
1050 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
1051 ///
1052 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
1053 /// struct Item {
1054 /// id: String,
1055 /// value: u32,
1056 /// }
1057 ///
1058 /// impl IdOrdItem for Item {
1059 /// type Key<'a> = &'a str;
1060 ///
1061 /// fn key(&self) -> Self::Key<'_> {
1062 /// &self.id
1063 /// }
1064 ///
1065 /// id_upcast!();
1066 /// }
1067 ///
1068 /// let mut map = IdOrdMap::new();
1069 /// map.insert_unique(Item { id: "charlie".to_string(), value: 30 }).unwrap();
1070 /// map.insert_unique(Item { id: "alice".to_string(), value: 42 }).unwrap();
1071 /// map.insert_unique(Item { id: "bob".to_string(), value: 99 }).unwrap();
1072 ///
1073 /// // Modify the last entry.
1074 /// if let Some(mut entry) = map.last_entry() {
1075 /// entry.get_mut().value = 200;
1076 /// }
1077 ///
1078 /// assert_eq!(map.get("charlie").unwrap().value, 200);
1079 /// ```
1080 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, T>> {
1081 let index = self.tables.key_to_item.last()?;
1082 let (_, dormant_map) = DormantMutRef::new(self);
1083 Some(
1084 // SAFETY: `map` is dropped immediately while creating the
1085 // DormantMutRef.
1086 unsafe { OccupiedEntry::new(dormant_map, index) },
1087 )
1088 }
1089
1090 /// Removes and returns the last element in the map. The key of this
1091 /// element is the maximum key in the map.
1092 ///
1093 /// # Examples
1094 ///
1095 /// ```
1096 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
1097 ///
1098 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
1099 /// struct Item {
1100 /// id: String,
1101 /// value: u32,
1102 /// }
1103 ///
1104 /// impl IdOrdItem for Item {
1105 /// type Key<'a> = &'a str;
1106 ///
1107 /// fn key(&self) -> Self::Key<'_> {
1108 /// &self.id
1109 /// }
1110 ///
1111 /// id_upcast!();
1112 /// }
1113 ///
1114 /// let mut map = IdOrdMap::new();
1115 /// map.insert_unique(Item { id: "charlie".to_string(), value: 30 }).unwrap();
1116 /// map.insert_unique(Item { id: "alice".to_string(), value: 42 }).unwrap();
1117 /// map.insert_unique(Item { id: "bob".to_string(), value: 99 }).unwrap();
1118 ///
1119 /// // Remove the last element.
1120 /// let last = map.pop_last().unwrap();
1121 /// assert_eq!(last.id, "charlie");
1122 /// assert_eq!(last.value, 30);
1123 /// assert_eq!(map.len(), 2);
1124 ///
1125 /// // Remove the next element.
1126 /// let last = map.pop_last().unwrap();
1127 /// assert_eq!(last.id, "bob");
1128 ///
1129 /// // Empty map returns None.
1130 /// map.pop_last();
1131 /// assert!(map.pop_last().is_none());
1132 /// ```
1133 pub fn pop_last(&mut self) -> Option<T> {
1134 let index = self.tables.key_to_item.last()?;
1135 self.remove_by_index(index)
1136 }
1137
1138 /// Retains only the elements specified by the predicate.
1139 ///
1140 /// In other words, remove all items `T` for which `f(RefMut<T>)` returns
1141 /// false. The elements are visited in ascending key order.
1142 ///
1143 /// # Examples
1144 ///
1145 /// ```
1146 /// use iddqd::{IdOrdItem, IdOrdMap, id_upcast};
1147 ///
1148 /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
1149 /// struct Item {
1150 /// id: String,
1151 /// value: u32,
1152 /// }
1153 ///
1154 /// impl IdOrdItem for Item {
1155 /// type Key<'a> = &'a str;
1156 ///
1157 /// fn key(&self) -> Self::Key<'_> {
1158 /// &self.id
1159 /// }
1160 ///
1161 /// id_upcast!();
1162 /// }
1163 ///
1164 /// let mut map = IdOrdMap::new();
1165 /// map.insert_unique(Item { id: "foo".to_string(), value: 42 }).unwrap();
1166 /// map.insert_unique(Item { id: "bar".to_string(), value: 20 }).unwrap();
1167 /// map.insert_unique(Item { id: "baz".to_string(), value: 99 }).unwrap();
1168 ///
1169 /// // Retain only items where value is greater than 30
1170 /// map.retain(|item| item.value > 30);
1171 ///
1172 /// assert_eq!(map.len(), 2);
1173 /// assert_eq!(map.get("foo").unwrap().value, 42);
1174 /// assert_eq!(map.get("baz").unwrap().value, 99);
1175 /// assert!(map.get("bar").is_none());
1176 /// ```
1177 pub fn retain<'a, F>(&'a mut self, mut f: F)
1178 where
1179 F: FnMut(RefMut<'a, T>) -> bool,
1180 T::Key<'a>: Hash,
1181 {
1182 let hash_state = self.tables.state().clone();
1183 let (_, mut dormant_items) = DormantMutRef::new(&mut self.items);
1184
1185 self.tables.key_to_item.retain(|index| {
1186 let (item, dormant_items) = {
1187 // SAFETY: All uses of `items` ended in the previous iteration.
1188 let items = unsafe { dormant_items.reborrow() };
1189 let (items, dormant_items) = DormantMutRef::new(items);
1190 let item: &'a mut T = items
1191 .get_mut(index)
1192 .expect("all indexes are present in self.items");
1193 (item, dormant_items)
1194 };
1195
1196 let (hash, dormant_item) = {
1197 let (item, dormant_item): (&'a mut T, _) =
1198 DormantMutRef::new(item);
1199 // Use T::key(item) rather than item.key() to force the key
1200 // trait function to be called for T rather than &mut T.
1201 let key = T::key(item);
1202 let hash = hash_state.hash_one(key);
1203 (MapHash::new(hash), dormant_item)
1204 };
1205
1206 // SAFETY: The original items is no longer used after the first
1207 // block above.
1208 let items = unsafe { dormant_items.awaken() };
1209 // SAFETY: The original item is no longer used after the second
1210 // block above.
1211 let item = unsafe { dormant_item.awaken() };
1212
1213 let ref_mut = RefMut::new(hash_state.clone(), hash, item);
1214 if f(ref_mut) {
1215 true
1216 } else {
1217 items.remove(index);
1218 false
1219 }
1220 });
1221 }
1222
1223 fn find<'a, Q>(&'a self, k: &Q) -> Option<&'a T>
1224 where
1225 Q: ?Sized + Comparable<T::Key<'a>>,
1226 {
1227 self.find_index(k).map(|ix| &self.items[ix])
1228 }
1229
1230 fn linear_search_index<'a, Q>(&'a self, k: &Q) -> Option<usize>
1231 where
1232 Q: ?Sized + Ord + Equivalent<T::Key<'a>>,
1233 {
1234 self.items.iter().find_map(|(index, item)| {
1235 (k.equivalent(&item.key())).then_some(*index)
1236 })
1237 }
1238
1239 fn find_index<'a, Q>(&'a self, k: &Q) -> Option<usize>
1240 where
1241 Q: ?Sized + Comparable<T::Key<'a>>,
1242 {
1243 self.tables.key_to_item.find_index(k, |index| self.items[index].key())
1244 }
1245
1246 pub(super) fn get_by_index(&self, index: usize) -> Option<&T> {
1247 self.items.get(index)
1248 }
1249
1250 pub(super) fn get_by_index_mut<'a>(
1251 &'a mut self,
1252 index: usize,
1253 ) -> Option<RefMut<'a, T>>
1254 where
1255 T::Key<'a>: Hash,
1256 {
1257 let state = self.tables.state().clone();
1258 let (hash, dormant) = {
1259 let item: &'a mut T = self.items.get_mut(index)?;
1260 let (item, dormant) = DormantMutRef::new(item);
1261 let hash = self.tables.make_hash(item);
1262 (hash, dormant)
1263 };
1264
1265 // SAFETY: item is no longer used after the above point.
1266 let item = unsafe { dormant.awaken() };
1267 Some(RefMut::new(state, hash, item))
1268 }
1269
1270 pub(super) fn insert_unique_impl(
1271 &mut self,
1272 value: T,
1273 ) -> Result<usize, DuplicateItem<T, &T>> {
1274 let mut duplicates = BTreeSet::new();
1275
1276 // Check for duplicates *before* inserting the new item, because we
1277 // don't want to partially insert the new item and then have to roll
1278 // back.
1279 let key = value.key();
1280
1281 if let Some(index) = self
1282 .tables
1283 .key_to_item
1284 .find_index(&key, |index| self.items[index].key())
1285 {
1286 duplicates.insert(index);
1287 }
1288
1289 if !duplicates.is_empty() {
1290 drop(key);
1291 return Err(DuplicateItem::__internal_new(
1292 value,
1293 duplicates.iter().map(|ix| &self.items[*ix]).collect(),
1294 ));
1295 }
1296
1297 let next_index = self.items.next_index();
1298 self.tables
1299 .key_to_item
1300 .insert(next_index, &key, |index| self.items[index].key());
1301 drop(key);
1302 self.items.insert_at_next_index(value);
1303
1304 Ok(next_index)
1305 }
1306
1307 pub(super) fn remove_by_index(&mut self, remove_index: usize) -> Option<T> {
1308 let value = self.items.remove(remove_index)?;
1309
1310 // Remove the value from the table.
1311 self.tables.key_to_item.remove(remove_index, value.key(), |index| {
1312 if index == remove_index {
1313 value.key()
1314 } else {
1315 self.items[index].key()
1316 }
1317 });
1318
1319 Some(value)
1320 }
1321
1322 pub(super) fn replace_at_index(&mut self, index: usize, value: T) -> T {
1323 // We check the key before removing it, to avoid leaving the map in an
1324 // inconsistent state.
1325 let old_key =
1326 self.get_by_index(index).expect("index is known to be valid").key();
1327 if T::upcast_key(old_key) != value.key() {
1328 panic!(
1329 "must insert a value with \
1330 the same key used to create the entry"
1331 );
1332 }
1333
1334 // Now that we know the key is the same, we can replace the value
1335 // directly without needing to tweak any tables.
1336 self.items.replace(index, value)
1337 }
1338}
1339
1340impl<'a, T: IdOrdItem> fmt::Debug for IdOrdMap<T>
1341where
1342 T: fmt::Debug,
1343 T::Key<'a>: fmt::Debug,
1344 T: 'a,
1345{
1346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1347 let mut map = f.debug_map();
1348
1349 for item in self.iter() {
1350 let key = item.key();
1351
1352 // SAFETY:
1353 //
1354 // * Lifetime extension: for a type T and two lifetime params 'a and
1355 // 'b, T<'a> and T<'b> aren't guaranteed to have the same layout,
1356 // but (a) that is true today and (b) it would be shocking and
1357 // break half the Rust ecosystem if that were to change in the
1358 // future.
1359 // * We only use key within the scope of this block before immediately
1360 // dropping it. In particular, map.entry calls key.fmt() without
1361 // holding a reference to it.
1362 let key: T::Key<'a> =
1363 unsafe { core::mem::transmute::<T::Key<'_>, T::Key<'a>>(key) };
1364
1365 map.entry(&key, &item);
1366 }
1367 map.finish()
1368 }
1369}
1370
1371impl<T: IdOrdItem + PartialEq> PartialEq for IdOrdMap<T> {
1372 fn eq(&self, other: &Self) -> bool {
1373 // Items are stored in sorted order, so we can just walk over both
1374 // iterators.
1375 if self.items.len() != other.items.len() {
1376 return false;
1377 }
1378
1379 self.iter().zip(other.iter()).all(|(item1, item2)| {
1380 // Check that the items are equal.
1381 item1 == item2
1382 })
1383 }
1384}
1385
1386// The Eq bound on T ensures that the IdOrdMap forms an equivalence class.
1387impl<T: IdOrdItem + Eq> Eq for IdOrdMap<T> {}
1388
1389/// The `Extend` implementation overwrites duplicates. In the future, there will
1390/// also be an `extend_unique` method that will return an error.
1391impl<T: IdOrdItem> Extend<T> for IdOrdMap<T> {
1392 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1393 for item in iter {
1394 self.insert_overwrite(item);
1395 }
1396 }
1397}
1398
1399impl<'a, T: IdOrdItem> IntoIterator for &'a IdOrdMap<T> {
1400 type Item = &'a T;
1401 type IntoIter = Iter<'a, T>;
1402
1403 #[inline]
1404 fn into_iter(self) -> Self::IntoIter {
1405 self.iter()
1406 }
1407}
1408
1409impl<'a, T: IdOrdItem> IntoIterator for &'a mut IdOrdMap<T>
1410where
1411 T::Key<'a>: Hash,
1412{
1413 type Item = RefMut<'a, T>;
1414 type IntoIter = IterMut<'a, T>;
1415
1416 #[inline]
1417 fn into_iter(self) -> Self::IntoIter {
1418 self.iter_mut()
1419 }
1420}
1421
1422impl<T: IdOrdItem> IntoIterator for IdOrdMap<T> {
1423 type Item = T;
1424 type IntoIter = IntoIter<T>;
1425
1426 #[inline]
1427 fn into_iter(self) -> Self::IntoIter {
1428 IntoIter::new(self.items, self.tables)
1429 }
1430}
1431
1432/// The `FromIterator` implementation for `IdOrdMap` overwrites duplicate
1433/// items.
1434///
1435/// To reject duplicates, use [`IdOrdMap::from_iter_unique`].
1436impl<T: IdOrdItem> FromIterator<T> for IdOrdMap<T> {
1437 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1438 let mut map = IdOrdMap::new();
1439 for value in iter {
1440 map.insert_overwrite(value);
1441 }
1442 map
1443 }
1444}