midl_parser/
linked_hash_map.rs

1// This file is copy-paste from
2// https://github.com/contain-rs/linked-hash-map/blob/master/src/lib.rs
3// rev df65b33f8a9dbd06b95b0a6af7521f0d47233545.
4// to avoid conflicting versions in dependent crates.
5// Should be used as an external dependency when private dependencies implemented:
6// https://github.com/rust-lang/rust/issues/44663
7
8// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
9// file at the top-level directory of this distribution and at
10// http://rust-lang.org/COPYRIGHT.
11//
12// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
13// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
14// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
15// option. This file may not be copied, modified, or distributed
16// except according to those terms.
17
18//! A `HashMap` wrapper that holds key-value pairs in insertion order.
19//!
20//! # Examples
21//!
22//! ```
23//! use midl_parser::linked_hash_map::LinkedHashMap;
24//!
25//! let mut map = LinkedHashMap::new();
26//! map.insert(2, 20);
27//! map.insert(1, 10);
28//! map.insert(3, 30);
29//! assert_eq!(map[&1], 10);
30//! assert_eq!(map[&2], 20);
31//! assert_eq!(map[&3], 30);
32//!
33//! let items: Vec<(i32, i32)> = map.iter().map(|t| (*t.0, *t.1)).collect();
34//! assert_eq!(items, [(2, 20), (1, 10), (3, 30)]);
35//! ```
36
37#![forbid(missing_docs)]
38#![cfg_attr(all(feature = "nightly", test), feature(test))]
39#![cfg_attr(feature = "clippy", feature(plugin))]
40#![cfg_attr(feature = "clippy", plugin(clippy))]
41#![cfg_attr(feature = "clippy", deny(clippy))]
42
43// Optional Serde support
44// #[cfg(feature = "serde_impl")]
45// pub mod serde;
46// Optional Heapsize support
47// #[cfg(feature = "heapsize_impl")]
48// mod heapsize;
49
50use std::borrow::Borrow;
51use std::cmp::Ordering;
52use std::collections::hash_map::HashMap;
53use std::collections::hash_map::{self};
54use std::fmt;
55use std::hash::BuildHasher;
56use std::hash::Hash;
57use std::hash::Hasher;
58use std::iter;
59use std::marker;
60use std::mem;
61use std::ops::Index;
62use std::ops::IndexMut;
63use std::ptr;
64
65struct KeyRef<K> {
66    k: *const K,
67}
68
69struct Node<K, V> {
70    next: *mut Node<K, V>,
71    prev: *mut Node<K, V>,
72    key: K,
73    value: V,
74}
75
76/// A linked hash map.
77pub struct LinkedHashMap<K, V, S = hash_map::RandomState> {
78    map: HashMap<KeyRef<K>, *mut Node<K, V>, S>,
79    head: *mut Node<K, V>,
80    free: *mut Node<K, V>,
81}
82
83impl<K: Hash> Hash for KeyRef<K> {
84    fn hash<H: Hasher>(&self, state: &mut H) {
85        unsafe { (*self.k).hash(state) }
86    }
87}
88
89impl<K: PartialEq> PartialEq for KeyRef<K> {
90    fn eq(&self, other: &Self) -> bool {
91        unsafe { (*self.k).eq(&*other.k) }
92    }
93}
94
95impl<K: Eq> Eq for KeyRef<K> {}
96
97// This type exists only to support borrowing `KeyRef`s, which cannot be borrowed to `Q` directly
98// due to conflicting implementations of `Borrow`. The layout of `&Qey<Q>` must be identical to
99// `&Q` in order to support transmuting in the `Qey::from_ref` method.
100#[derive(Hash, PartialEq, Eq)]
101struct Qey<Q: ?Sized>(Q);
102
103impl<Q: ?Sized> Qey<Q> {
104    fn from_ref(q: &Q) -> &Self {
105        unsafe { mem::transmute(q) }
106    }
107}
108
109impl<K, Q: ?Sized> Borrow<Qey<Q>> for KeyRef<K>
110where
111    K: Borrow<Q>,
112{
113    fn borrow(&self) -> &Qey<Q> {
114        Qey::from_ref(unsafe { (*self.k).borrow() })
115    }
116}
117
118impl<K, V> Node<K, V> {
119    fn new(k: K, v: V) -> Self {
120        Node {
121            key: k,
122            value: v,
123            next: ptr::null_mut(),
124            prev: ptr::null_mut(),
125        }
126    }
127}
128
129unsafe fn drop_empty_node<K, V>(the_box: *mut Node<K, V>) {
130    // Prevent compiler from trying to drop the un-initialized key and values in the node.
131    let Node { key, value, .. } = *Box::from_raw(the_box);
132    mem::forget(key);
133    mem::forget(value);
134}
135
136impl<K: Hash + Eq, V> LinkedHashMap<K, V> {
137    /// Creates a linked hash map.
138    pub fn new() -> Self {
139        Self::with_map(HashMap::new())
140    }
141
142    /// Creates an empty linked hash map with the given initial capacity.
143    pub fn with_capacity(capacity: usize) -> Self {
144        Self::with_map(HashMap::with_capacity(capacity))
145    }
146}
147
148impl<K, V, S> LinkedHashMap<K, V, S> {
149    #[inline]
150    fn detach(&mut self, node: *mut Node<K, V>) {
151        unsafe {
152            (*(*node).prev).next = (*node).next;
153            (*(*node).next).prev = (*node).prev;
154        }
155    }
156
157    #[inline]
158    fn attach(&mut self, node: *mut Node<K, V>) {
159        unsafe {
160            (*node).next = (*self.head).next;
161            (*node).prev = self.head;
162            (*self.head).next = node;
163            (*(*node).next).prev = node;
164        }
165    }
166
167    // Caller must check `!self.head.is_null()`
168    unsafe fn drop_entries(&mut self) {
169        let mut cur = (*self.head).next;
170        while cur != self.head {
171            let next = (*cur).next;
172            Box::from_raw(cur);
173            cur = next;
174        }
175    }
176
177    fn clear_free_list(&mut self) {
178        unsafe {
179            let mut free = self.free;
180            while !free.is_null() {
181                let next_free = (*free).next;
182                drop_empty_node(free);
183                free = next_free;
184            }
185            self.free = ptr::null_mut();
186        }
187    }
188
189    fn ensure_guard_node(&mut self) {
190        if self.head.is_null() {
191            // allocate the guard node if not present
192            unsafe {
193                let node_layout = std::alloc::Layout::new::<Node<K, V>>();
194                self.head = std::alloc::alloc(node_layout) as *mut Node<K, V>;
195                (*self.head).next = self.head;
196                (*self.head).prev = self.head;
197            }
198        }
199    }
200}
201
202impl<K: Hash + Eq, V, S: BuildHasher> LinkedHashMap<K, V, S> {
203    fn with_map(map: HashMap<KeyRef<K>, *mut Node<K, V>, S>) -> Self {
204        LinkedHashMap {
205            map,
206            head: ptr::null_mut(),
207            free: ptr::null_mut(),
208        }
209    }
210
211    /// Creates an empty linked hash map with the given initial hash builder.
212    pub fn with_hasher(hash_builder: S) -> Self {
213        Self::with_map(HashMap::with_hasher(hash_builder))
214    }
215
216    /// Creates an empty linked hash map with the given initial capacity and hash builder.
217    pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self {
218        Self::with_map(HashMap::with_capacity_and_hasher(capacity, hash_builder))
219    }
220
221    /// Reserves capacity for at least `additional` more elements to be inserted into the map. The
222    /// map may reserve more space to avoid frequent allocations.
223    ///
224    /// # Panics
225    ///
226    /// Panics if the new allocation size overflows `usize.`
227    pub fn reserve(&mut self, additional: usize) {
228        self.map.reserve(additional);
229    }
230
231    /// Shrinks the capacity of the map as much as possible. It will drop down as much as possible
232    /// while maintaining the internal rules and possibly leaving some space in accordance with the
233    /// resize policy.
234    pub fn shrink_to_fit(&mut self) {
235        self.map.shrink_to_fit();
236        self.clear_free_list();
237    }
238
239    /// Gets the given key's corresponding entry in the map for in-place manipulation.
240    ///
241    /// # Examples
242    ///
243    /// ```
244    /// use midl_parser::linked_hash_map::LinkedHashMap;
245    ///
246    /// let mut letters = LinkedHashMap::new();
247    ///
248    /// for ch in "a short treatise on fungi".chars() {
249    ///     let counter = letters.entry(ch).or_insert(0);
250    ///     *counter += 1;
251    /// }
252    ///
253    /// assert_eq!(letters[&'s'], 2);
254    /// assert_eq!(letters[&'t'], 3);
255    /// assert_eq!(letters[&'u'], 1);
256    /// assert_eq!(letters.get(&'y'), None);
257    /// ```
258    pub fn entry(&mut self, k: K) -> Entry<K, V, S> {
259        let self_ptr: *mut Self = self;
260
261        if let Some(entry) = self.map.get_mut(&KeyRef { k: &k }) {
262            return Entry::Occupied(OccupiedEntry {
263                entry: *entry,
264                map: self_ptr,
265                marker: marker::PhantomData,
266            });
267        }
268
269        Entry::Vacant(VacantEntry { key: k, map: self })
270    }
271
272    /// Returns an iterator visiting all entries in insertion order.
273    /// Iterator element type is `OccupiedEntry<K, V, S>`. Allows for removal
274    /// as well as replacing the entry.
275    ///
276    /// # Examples
277    /// ```
278    /// use midl_parser::linked_hash_map::LinkedHashMap;
279    ///
280    /// let mut map = LinkedHashMap::new();
281    /// map.insert("a", 10);
282    /// map.insert("c", 30);
283    /// map.insert("b", 20);
284    ///
285    /// {
286    ///     let mut iter = map.entries();
287    ///     let mut entry = iter.next().unwrap();
288    ///     assert_eq!(&"a", entry.key());
289    ///     *entry.get_mut() = 17;
290    /// }
291    ///
292    /// assert_eq!(&17, map.get(&"a").unwrap());
293    /// ```
294    pub fn entries(&mut self) -> Entries<K, V, S> {
295        let head = if !self.head.is_null() {
296            unsafe { (*self.head).prev }
297        } else {
298            ptr::null_mut()
299        };
300        Entries {
301            map: self,
302            head,
303            remaining: self.len(),
304            marker: marker::PhantomData,
305        }
306    }
307
308    /// Inserts a key-value pair into the map. If the key already existed, the old value is
309    /// returned.
310    ///
311    /// # Examples
312    ///
313    /// ```
314    /// use midl_parser::linked_hash_map::LinkedHashMap;
315    /// let mut map = LinkedHashMap::new();
316    ///
317    /// map.insert(1, "a");
318    /// map.insert(2, "b");
319    /// assert_eq!(map[&1], "a");
320    /// assert_eq!(map[&2], "b");
321    /// ```
322    pub fn insert(&mut self, k: K, v: V) -> Option<V> {
323        self.ensure_guard_node();
324
325        let (node, old_val) = match self.map.get(&KeyRef { k: &k }) {
326            Some(node) => {
327                let old_val = unsafe { ptr::replace(&mut (**node).value, v) };
328                (*node, Some(old_val))
329            }
330            None => {
331                let node = if self.free.is_null() {
332                    Box::into_raw(Box::new(Node::new(k, v)))
333                } else {
334                    // use a recycled box
335                    unsafe {
336                        let free = self.free;
337                        self.free = (*free).next;
338                        ptr::write(free, Node::new(k, v));
339                        free
340                    }
341                };
342                (node, None)
343            }
344        };
345        match old_val {
346            Some(_) => {
347                // Existing node, just update LRU position
348                self.detach(node);
349                self.attach(node);
350            }
351            None => {
352                let keyref = unsafe { &(*node).key };
353                self.map.insert(KeyRef { k: keyref }, node);
354                self.attach(node);
355            }
356        }
357        old_val
358    }
359
360    /// Checks if the map contains the given key.
361    pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool
362    where
363        K: Borrow<Q>,
364        Q: Eq + Hash,
365    {
366        self.map.contains_key(Qey::from_ref(k))
367    }
368
369    /// Returns the value corresponding to the key in the map.
370    ///
371    /// # Examples
372    ///
373    /// ```
374    /// use midl_parser::linked_hash_map::LinkedHashMap;
375    /// let mut map = LinkedHashMap::new();
376    ///
377    /// map.insert(1, "a");
378    /// map.insert(2, "b");
379    /// map.insert(2, "c");
380    /// map.insert(3, "d");
381    ///
382    /// assert_eq!(map.get(&1), Some(&"a"));
383    /// assert_eq!(map.get(&2), Some(&"c"));
384    /// ```
385    pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
386    where
387        K: Borrow<Q>,
388        Q: Eq + Hash,
389    {
390        self.map
391            .get(Qey::from_ref(k))
392            .map(|e| unsafe { &(**e).value })
393    }
394
395    /// Returns the mutable reference corresponding to the key in the map.
396    ///
397    /// # Examples
398    ///
399    /// ```
400    /// use midl_parser::linked_hash_map::LinkedHashMap;
401    /// let mut map = LinkedHashMap::new();
402    ///
403    /// map.insert(1, "a");
404    /// map.insert(2, "b");
405    ///
406    /// *map.get_mut(&1).unwrap() = "c";
407    /// assert_eq!(map.get(&1), Some(&"c"));
408    /// ```
409    pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
410    where
411        K: Borrow<Q>,
412        Q: Eq + Hash,
413    {
414        self.map
415            .get(Qey::from_ref(k))
416            .map(|e| unsafe { &mut (**e).value })
417    }
418
419    /// Returns the value corresponding to the key in the map.
420    ///
421    /// If value is found, it is moved to the end of the list.
422    /// This operation can be used in implemenation of LRU cache.
423    ///
424    /// # Examples
425    ///
426    /// ```
427    /// use midl_parser::linked_hash_map::LinkedHashMap;
428    /// let mut map = LinkedHashMap::new();
429    ///
430    /// map.insert(1, "a");
431    /// map.insert(2, "b");
432    /// map.insert(3, "d");
433    ///
434    /// assert_eq!(map.get_refresh(&2), Some(&mut "b"));
435    ///
436    /// assert_eq!((&2, &"b"), map.iter().rev().next().unwrap());
437    /// ```
438    pub fn get_refresh<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
439    where
440        K: Borrow<Q>,
441        Q: Eq + Hash,
442    {
443        let (value, node_ptr_opt) = match self.map.get(Qey::from_ref(k)) {
444            None => (None, None),
445            Some(node) => (Some(unsafe { &mut (**node).value }), Some(*node)),
446        };
447        if let Some(node_ptr) = node_ptr_opt {
448            self.detach(node_ptr);
449            self.attach(node_ptr);
450        }
451        value
452    }
453
454    /// Removes and returns the value corresponding to the key from the map.
455    ///
456    /// # Examples
457    ///
458    /// ```
459    /// use midl_parser::linked_hash_map::LinkedHashMap;
460    /// let mut map = LinkedHashMap::new();
461    ///
462    /// map.insert(2, "a");
463    ///
464    /// assert_eq!(map.remove(&1), None);
465    /// assert_eq!(map.remove(&2), Some("a"));
466    /// assert_eq!(map.remove(&2), None);
467    /// assert_eq!(map.len(), 0);
468    /// ```
469    pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
470    where
471        K: Borrow<Q>,
472        Q: Eq + Hash,
473    {
474        let removed = self.map.remove(Qey::from_ref(k));
475        removed.map(|node| {
476            self.detach(node);
477            unsafe {
478                // add to free list
479                (*node).next = self.free;
480                self.free = node;
481                // drop the key and return the value
482                drop(ptr::read(&(*node).key));
483                ptr::read(&(*node).value)
484            }
485        })
486    }
487
488    /// Returns the maximum number of key-value pairs the map can hold without reallocating.
489    ///
490    /// # Examples
491    ///
492    /// ```
493    /// use midl_parser::linked_hash_map::LinkedHashMap;
494    /// let mut map: LinkedHashMap<i32, &str> = LinkedHashMap::new();
495    /// let capacity = map.capacity();
496    /// ```
497    pub fn capacity(&self) -> usize {
498        self.map.capacity()
499    }
500
501    /// Removes the first entry.
502    ///
503    /// Can be used in implementation of LRU cache.
504    ///
505    /// # Examples
506    ///
507    /// ```
508    /// use midl_parser::linked_hash_map::LinkedHashMap;
509    /// let mut map = LinkedHashMap::new();
510    /// map.insert(1, 10);
511    /// map.insert(2, 20);
512    /// map.pop_front();
513    /// assert_eq!(map.get(&1), None);
514    /// assert_eq!(map.get(&2), Some(&20));
515    /// ```
516    #[inline]
517    pub fn pop_front(&mut self) -> Option<(K, V)> {
518        if self.is_empty() {
519            return None;
520        }
521        let lru = unsafe { (*self.head).prev };
522        self.detach(lru);
523        self.map
524            .remove(&KeyRef {
525                k: unsafe { &(*lru).key },
526            })
527            .map(|e| {
528                let e = *unsafe { Box::from_raw(e) };
529                (e.key, e.value)
530            })
531    }
532
533    /// Gets the first entry.
534    ///
535    /// # Examples
536    ///
537    /// ```
538    /// use midl_parser::linked_hash_map::LinkedHashMap;
539    /// let mut map = LinkedHashMap::new();
540    /// map.insert(1, 10);
541    /// map.insert(2, 20);
542    /// assert_eq!(map.front(), Some((&1, &10)));
543    /// ```
544    #[inline]
545    pub fn front(&self) -> Option<(&K, &V)> {
546        if self.is_empty() {
547            return None;
548        }
549        let lru = unsafe { (*self.head).prev };
550        self.map
551            .get(&KeyRef {
552                k: unsafe { &(*lru).key },
553            })
554            .map(|e| unsafe { (&(**e).key, &(**e).value) })
555    }
556
557    /// Removes the last entry.
558    ///
559    /// # Examples
560    ///
561    /// ```
562    /// use midl_parser::linked_hash_map::LinkedHashMap;
563    /// let mut map = LinkedHashMap::new();
564    /// map.insert(1, 10);
565    /// map.insert(2, 20);
566    /// map.pop_back();
567    /// assert_eq!(map.get(&1), Some(&10));
568    /// assert_eq!(map.get(&2), None);
569    /// ```
570    #[inline]
571    pub fn pop_back(&mut self) -> Option<(K, V)> {
572        if self.is_empty() {
573            return None;
574        }
575        let mru = unsafe { (*self.head).next };
576        self.detach(mru);
577        self.map
578            .remove(&KeyRef {
579                k: unsafe { &(*mru).key },
580            })
581            .map(|e| {
582                let e = *unsafe { Box::from_raw(e) };
583                (e.key, e.value)
584            })
585    }
586
587    /// Gets the last entry.
588    ///
589    /// # Examples
590    ///
591    /// ```
592    /// use midl_parser::linked_hash_map::LinkedHashMap;
593    /// let mut map = LinkedHashMap::new();
594    /// map.insert(1, 10);
595    /// map.insert(2, 20);
596    /// assert_eq!(map.back(), Some((&2, &20)));
597    /// ```
598    #[inline]
599    pub fn back(&mut self) -> Option<(&K, &V)> {
600        if self.is_empty() {
601            return None;
602        }
603        let mru = unsafe { (*self.head).next };
604        self.map
605            .get(&KeyRef {
606                k: unsafe { &(*mru).key },
607            })
608            .map(|e| unsafe { (&(**e).key, &(**e).value) })
609    }
610
611    /// Returns the number of key-value pairs in the map.
612    pub fn len(&self) -> usize {
613        self.map.len()
614    }
615
616    /// Returns whether the map is currently empty.
617    pub fn is_empty(&self) -> bool {
618        self.len() == 0
619    }
620
621    /// Returns a reference to the map's hasher.
622    pub fn hasher(&self) -> &S {
623        self.map.hasher()
624    }
625
626    /// Clears the map of all key-value pairs.
627    pub fn clear(&mut self) {
628        self.map.clear();
629        // update the guard node if present
630        if !self.head.is_null() {
631            unsafe {
632                self.drop_entries();
633                (*self.head).prev = self.head;
634                (*self.head).next = self.head;
635            }
636        }
637    }
638
639    /// Returns a double-ended iterator visiting all key-value pairs in order of insertion.
640    /// Iterator element type is `(&'a K, &'a V)`
641    ///
642    /// # Examples
643    /// ```
644    /// use midl_parser::linked_hash_map::LinkedHashMap;
645    ///
646    /// let mut map = LinkedHashMap::new();
647    /// map.insert("a", 10);
648    /// map.insert("c", 30);
649    /// map.insert("b", 20);
650    ///
651    /// let mut iter = map.iter();
652    /// assert_eq!((&"a", &10), iter.next().unwrap());
653    /// assert_eq!((&"c", &30), iter.next().unwrap());
654    /// assert_eq!((&"b", &20), iter.next().unwrap());
655    /// assert_eq!(None, iter.next());
656    /// ```
657    pub fn iter(&self) -> Iter<K, V> {
658        let head = if self.head.is_null() {
659            ptr::null_mut()
660        } else {
661            unsafe { (*self.head).prev }
662        };
663        Iter {
664            head,
665            tail: self.head,
666            remaining: self.len(),
667            marker: marker::PhantomData,
668        }
669    }
670
671    /// Returns a double-ended iterator visiting all key-value pairs in order of insertion.
672    /// Iterator element type is `(&'a K, &'a mut V)`
673    /// # Examples
674    /// ```
675    /// use midl_parser::linked_hash_map::LinkedHashMap;
676    ///
677    /// let mut map = LinkedHashMap::new();
678    /// map.insert("a", 10);
679    /// map.insert("c", 30);
680    /// map.insert("b", 20);
681    ///
682    /// {
683    ///     let mut iter = map.iter_mut();
684    ///     let mut entry = iter.next().unwrap();
685    ///     assert_eq!(&"a", entry.0);
686    ///     *entry.1 = 17;
687    /// }
688    ///
689    /// assert_eq!(&17, map.get(&"a").unwrap());
690    /// ```
691    pub fn iter_mut(&mut self) -> IterMut<K, V> {
692        let head = if self.head.is_null() {
693            ptr::null_mut()
694        } else {
695            unsafe { (*self.head).prev }
696        };
697        IterMut {
698            head,
699            tail: self.head,
700            remaining: self.len(),
701            marker: marker::PhantomData,
702        }
703    }
704
705    /// Returns a double-ended iterator visiting all key in order of insertion.
706    ///
707    /// # Examples
708    /// ```
709    /// use midl_parser::linked_hash_map::LinkedHashMap;
710    ///
711    /// let mut map = LinkedHashMap::new();
712    /// map.insert('a', 10);
713    /// map.insert('c', 30);
714    /// map.insert('b', 20);
715    ///
716    /// let mut keys = map.keys();
717    /// assert_eq!(&'a', keys.next().unwrap());
718    /// assert_eq!(&'c', keys.next().unwrap());
719    /// assert_eq!(&'b', keys.next().unwrap());
720    /// assert_eq!(None, keys.next());
721    /// ```
722    pub fn keys(&self) -> Keys<K, V> {
723        Keys { inner: self.iter() }
724    }
725
726    /// Returns a double-ended iterator visiting all values in order of insertion.
727    ///
728    /// # Examples
729    /// ```
730    /// use midl_parser::linked_hash_map::LinkedHashMap;
731    ///
732    /// let mut map = LinkedHashMap::new();
733    /// map.insert('a', 10);
734    /// map.insert('c', 30);
735    /// map.insert('b', 20);
736    ///
737    /// let mut values = map.values();
738    /// assert_eq!(&10, values.next().unwrap());
739    /// assert_eq!(&30, values.next().unwrap());
740    /// assert_eq!(&20, values.next().unwrap());
741    /// assert_eq!(None, values.next());
742    /// ```
743    pub fn values(&self) -> Values<K, V> {
744        Values { inner: self.iter() }
745    }
746}
747
748impl<'a, K, V, S, Q: ?Sized> Index<&'a Q> for LinkedHashMap<K, V, S>
749where
750    K: Hash + Eq + Borrow<Q>,
751    S: BuildHasher,
752    Q: Eq + Hash,
753{
754    type Output = V;
755
756    fn index(&self, index: &'a Q) -> &V {
757        self.get(index).expect("no entry found for key")
758    }
759}
760
761impl<'a, K, V, S, Q: ?Sized> IndexMut<&'a Q> for LinkedHashMap<K, V, S>
762where
763    K: Hash + Eq + Borrow<Q>,
764    S: BuildHasher,
765    Q: Eq + Hash,
766{
767    fn index_mut(&mut self, index: &'a Q) -> &mut V {
768        self.get_mut(index).expect("no entry found for key")
769    }
770}
771
772impl<K: Hash + Eq + Clone, V: Clone, S: BuildHasher + Clone> Clone for LinkedHashMap<K, V, S> {
773    fn clone(&self) -> Self {
774        let mut map = Self::with_hasher(self.map.hasher().clone());
775        map.extend(self.iter().map(|(k, v)| (k.clone(), v.clone())));
776        map
777    }
778}
779
780impl<K: Hash + Eq, V, S: BuildHasher + Default> Default for LinkedHashMap<K, V, S> {
781    fn default() -> Self {
782        Self::with_hasher(S::default())
783    }
784}
785
786impl<K: Hash + Eq, V, S: BuildHasher> Extend<(K, V)> for LinkedHashMap<K, V, S> {
787    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
788        for (k, v) in iter {
789            self.insert(k, v);
790        }
791    }
792}
793
794impl<'a, K, V, S> Extend<(&'a K, &'a V)> for LinkedHashMap<K, V, S>
795where
796    K: 'a + Hash + Eq + Copy,
797    V: 'a + Copy,
798    S: BuildHasher,
799{
800    fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
801        for (&k, &v) in iter {
802            self.insert(k, v);
803        }
804    }
805}
806
807impl<K: Hash + Eq, V, S: BuildHasher + Default> iter::FromIterator<(K, V)>
808    for LinkedHashMap<K, V, S>
809{
810    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
811        let iter = iter.into_iter();
812        let mut map = Self::with_capacity_and_hasher(iter.size_hint().0, S::default());
813        map.extend(iter);
814        map
815    }
816}
817
818impl<A: fmt::Debug + Hash + Eq, B: fmt::Debug, S: BuildHasher> fmt::Debug
819    for LinkedHashMap<A, B, S>
820{
821    /// Returns a string that lists the key-value pairs in insertion order.
822    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
823        f.debug_map().entries(self).finish()
824    }
825}
826
827impl<K: Hash + Eq, V: PartialEq, S: BuildHasher> PartialEq for LinkedHashMap<K, V, S> {
828    fn eq(&self, other: &Self) -> bool {
829        self.len() == other.len() && self.iter().eq(other)
830    }
831}
832
833impl<K: Hash + Eq, V: Eq, S: BuildHasher> Eq for LinkedHashMap<K, V, S> {}
834
835impl<K: Hash + Eq + PartialOrd, V: PartialOrd, S: BuildHasher> PartialOrd
836    for LinkedHashMap<K, V, S>
837{
838    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
839        self.iter().partial_cmp(other)
840    }
841
842    fn lt(&self, other: &Self) -> bool {
843        self.iter().lt(other)
844    }
845
846    fn le(&self, other: &Self) -> bool {
847        self.iter().le(other)
848    }
849
850    fn ge(&self, other: &Self) -> bool {
851        self.iter().ge(other)
852    }
853
854    fn gt(&self, other: &Self) -> bool {
855        self.iter().gt(other)
856    }
857}
858
859impl<K: Hash + Eq + Ord, V: Ord, S: BuildHasher> Ord for LinkedHashMap<K, V, S> {
860    fn cmp(&self, other: &Self) -> Ordering {
861        self.iter().cmp(other)
862    }
863}
864
865impl<K: Hash + Eq, V: Hash, S: BuildHasher> Hash for LinkedHashMap<K, V, S> {
866    fn hash<H: Hasher>(&self, h: &mut H) {
867        for e in self.iter() {
868            e.hash(h);
869        }
870    }
871}
872
873unsafe impl<K: Send, V: Send, S: Send> Send for LinkedHashMap<K, V, S> {}
874
875unsafe impl<K: Sync, V: Sync, S: Sync> Sync for LinkedHashMap<K, V, S> {}
876
877impl<K, V, S> Drop for LinkedHashMap<K, V, S> {
878    fn drop(&mut self) {
879        if !self.head.is_null() {
880            unsafe {
881                self.drop_entries();
882                drop_empty_node(self.head);
883            }
884        }
885        self.clear_free_list();
886    }
887}
888
889/// An insertion-order iterator over a `LinkedHashMap`'s entries, with immutable references to the
890/// values.
891pub struct Iter<'a, K: 'a, V: 'a> {
892    head: *const Node<K, V>,
893    tail: *const Node<K, V>,
894    remaining: usize,
895    marker: marker::PhantomData<(&'a K, &'a V)>,
896}
897
898/// An insertion-order iterator over a `LinkedHashMap`'s entries, with mutable references to the
899/// values.
900pub struct IterMut<'a, K: 'a, V: 'a> {
901    head: *mut Node<K, V>,
902    tail: *mut Node<K, V>,
903    remaining: usize,
904    marker: marker::PhantomData<(&'a K, &'a mut V)>,
905}
906
907/// A consuming insertion-order iterator over a `LinkedHashMap`'s entries.
908pub struct IntoIter<K, V> {
909    head: *mut Node<K, V>,
910    tail: *mut Node<K, V>,
911    remaining: usize,
912    marker: marker::PhantomData<(K, V)>,
913}
914
915/// An insertion-order iterator over a `LinkedHashMap`'s entries represented as
916/// an `OccupiedEntry`.
917pub struct Entries<'a, K: 'a, V: 'a, S: 'a = hash_map::RandomState> {
918    map: *mut LinkedHashMap<K, V, S>,
919    head: *mut Node<K, V>,
920    remaining: usize,
921    marker: marker::PhantomData<(&'a K, &'a mut V, &'a S)>,
922}
923
924unsafe impl<'a, K, V> Send for Iter<'a, K, V>
925where
926    K: Send,
927    V: Send,
928{
929}
930
931unsafe impl<'a, K, V> Send for IterMut<'a, K, V>
932where
933    K: Send,
934    V: Send,
935{
936}
937
938unsafe impl<K, V> Send for IntoIter<K, V>
939where
940    K: Send,
941    V: Send,
942{
943}
944
945unsafe impl<'a, K, V, S> Send for Entries<'a, K, V, S>
946where
947    K: Send,
948    V: Send,
949    S: Send,
950{
951}
952
953unsafe impl<'a, K, V> Sync for Iter<'a, K, V>
954where
955    K: Sync,
956    V: Sync,
957{
958}
959
960unsafe impl<'a, K, V> Sync for IterMut<'a, K, V>
961where
962    K: Sync,
963    V: Sync,
964{
965}
966
967unsafe impl<K, V> Sync for IntoIter<K, V>
968where
969    K: Sync,
970    V: Sync,
971{
972}
973
974unsafe impl<'a, K, V, S> Sync for Entries<'a, K, V, S>
975where
976    K: Sync,
977    V: Sync,
978    S: Sync,
979{
980}
981
982impl<'a, K, V> Clone for Iter<'a, K, V> {
983    fn clone(&self) -> Self {
984        Iter { ..*self }
985    }
986}
987
988impl<K, V> Clone for IntoIter<K, V>
989where
990    K: Clone,
991    V: Clone,
992{
993    fn clone(&self) -> Self {
994        if self.remaining == 0 {
995            return IntoIter { ..*self };
996        }
997
998        fn clone_node<K, V>(e: *mut Node<K, V>) -> *mut Node<K, V>
999        where
1000            K: Clone,
1001            V: Clone,
1002        {
1003            Box::into_raw(Box::new(Node::new(unsafe { (*e).key.clone() }, unsafe {
1004                (*e).value.clone()
1005            })))
1006        }
1007
1008        let mut cur = self.head;
1009        let head = clone_node(cur);
1010        let mut tail = head;
1011        for _ in 1..self.remaining {
1012            unsafe {
1013                (*tail).prev = clone_node((*cur).prev);
1014                (*(*tail).prev).next = tail;
1015                tail = (*tail).prev;
1016                cur = (*cur).prev;
1017            }
1018        }
1019
1020        IntoIter {
1021            head,
1022            tail,
1023            remaining: self.remaining,
1024            marker: marker::PhantomData,
1025        }
1026    }
1027}
1028
1029impl<'a, K, V> Iterator for Iter<'a, K, V> {
1030    type Item = (&'a K, &'a V);
1031
1032    fn next(&mut self) -> Option<(&'a K, &'a V)> {
1033        if self.head == self.tail {
1034            None
1035        } else {
1036            self.remaining -= 1;
1037            unsafe {
1038                let r = Some((&(*self.head).key, &(*self.head).value));
1039                self.head = (*self.head).prev;
1040                r
1041            }
1042        }
1043    }
1044
1045    fn size_hint(&self) -> (usize, Option<usize>) {
1046        (self.remaining, Some(self.remaining))
1047    }
1048}
1049
1050impl<'a, K, V> Iterator for IterMut<'a, K, V> {
1051    type Item = (&'a K, &'a mut V);
1052
1053    fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1054        if self.head == self.tail {
1055            None
1056        } else {
1057            self.remaining -= 1;
1058            unsafe {
1059                let r = Some((&(*self.head).key, &mut (*self.head).value));
1060                self.head = (*self.head).prev;
1061                r
1062            }
1063        }
1064    }
1065
1066    fn size_hint(&self) -> (usize, Option<usize>) {
1067        (self.remaining, Some(self.remaining))
1068    }
1069}
1070
1071impl<K, V> Iterator for IntoIter<K, V> {
1072    type Item = (K, V);
1073
1074    fn next(&mut self) -> Option<(K, V)> {
1075        if self.remaining == 0 {
1076            return None;
1077        }
1078        self.remaining -= 1;
1079        unsafe {
1080            let prev = (*self.head).prev;
1081            let e = *Box::from_raw(self.head);
1082            self.head = prev;
1083            Some((e.key, e.value))
1084        }
1085    }
1086
1087    fn size_hint(&self) -> (usize, Option<usize>) {
1088        (self.remaining, Some(self.remaining))
1089    }
1090}
1091
1092impl<'a, K, V, S: BuildHasher> Iterator for Entries<'a, K, V, S> {
1093    type Item = OccupiedEntry<'a, K, V, S>;
1094
1095    fn next(&mut self) -> Option<OccupiedEntry<'a, K, V, S>> {
1096        if self.remaining == 0 {
1097            None
1098        } else {
1099            self.remaining -= 1;
1100            unsafe {
1101                let r = Some(OccupiedEntry {
1102                    map: self.map,
1103                    entry: self.head,
1104                    marker: marker::PhantomData,
1105                });
1106
1107                self.head = (*self.head).prev;
1108                r
1109            }
1110        }
1111    }
1112
1113    fn size_hint(&self) -> (usize, Option<usize>) {
1114        (self.remaining, Some(self.remaining))
1115    }
1116}
1117
1118impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> {
1119    fn next_back(&mut self) -> Option<(&'a K, &'a V)> {
1120        if self.head == self.tail {
1121            None
1122        } else {
1123            self.remaining -= 1;
1124            unsafe {
1125                self.tail = (*self.tail).next;
1126                Some((&(*self.tail).key, &(*self.tail).value))
1127            }
1128        }
1129    }
1130}
1131
1132impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> {
1133    fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1134        if self.head == self.tail {
1135            None
1136        } else {
1137            self.remaining -= 1;
1138            unsafe {
1139                self.tail = (*self.tail).next;
1140                Some((&(*self.tail).key, &mut (*self.tail).value))
1141            }
1142        }
1143    }
1144}
1145
1146impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
1147    fn next_back(&mut self) -> Option<(K, V)> {
1148        if self.remaining == 0 {
1149            return None;
1150        }
1151        self.remaining -= 1;
1152        unsafe {
1153            let next = (*self.tail).next;
1154            let e = *Box::from_raw(self.tail);
1155            self.tail = next;
1156            Some((e.key, e.value))
1157        }
1158    }
1159}
1160
1161impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {
1162    fn len(&self) -> usize {
1163        self.remaining
1164    }
1165}
1166
1167impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {
1168    fn len(&self) -> usize {
1169        self.remaining
1170    }
1171}
1172
1173impl<K, V> ExactSizeIterator for IntoIter<K, V> {
1174    fn len(&self) -> usize {
1175        self.remaining
1176    }
1177}
1178
1179impl<K, V> Drop for IntoIter<K, V> {
1180    fn drop(&mut self) {
1181        for _ in 0..self.remaining {
1182            unsafe {
1183                let next = (*self.tail).next;
1184                Box::from_raw(self.tail);
1185                self.tail = next;
1186            }
1187        }
1188    }
1189}
1190
1191/// An insertion-order iterator over a `LinkedHashMap`'s keys.
1192pub struct Keys<'a, K: 'a, V: 'a> {
1193    inner: Iter<'a, K, V>,
1194}
1195
1196impl<'a, K, V> Clone for Keys<'a, K, V> {
1197    fn clone(&self) -> Self {
1198        Keys {
1199            inner: self.inner.clone(),
1200        }
1201    }
1202}
1203
1204impl<'a, K, V> Iterator for Keys<'a, K, V> {
1205    type Item = &'a K;
1206
1207    #[inline]
1208    fn next(&mut self) -> Option<&'a K> {
1209        self.inner.next().map(|e| e.0)
1210    }
1211    #[inline]
1212    fn size_hint(&self) -> (usize, Option<usize>) {
1213        self.inner.size_hint()
1214    }
1215}
1216
1217impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> {
1218    #[inline]
1219    fn next_back(&mut self) -> Option<&'a K> {
1220        self.inner.next_back().map(|e| e.0)
1221    }
1222}
1223
1224impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {
1225    fn len(&self) -> usize {
1226        self.inner.len()
1227    }
1228}
1229
1230/// An insertion-order iterator over a `LinkedHashMap`'s values.
1231pub struct Values<'a, K: 'a, V: 'a> {
1232    inner: Iter<'a, K, V>,
1233}
1234
1235impl<'a, K, V> Clone for Values<'a, K, V> {
1236    fn clone(&self) -> Self {
1237        Values {
1238            inner: self.inner.clone(),
1239        }
1240    }
1241}
1242
1243impl<'a, K, V> Iterator for Values<'a, K, V> {
1244    type Item = &'a V;
1245
1246    #[inline]
1247    fn next(&mut self) -> Option<&'a V> {
1248        self.inner.next().map(|e| e.1)
1249    }
1250    #[inline]
1251    fn size_hint(&self) -> (usize, Option<usize>) {
1252        self.inner.size_hint()
1253    }
1254}
1255
1256impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> {
1257    #[inline]
1258    fn next_back(&mut self) -> Option<&'a V> {
1259        self.inner.next_back().map(|e| e.1)
1260    }
1261}
1262
1263impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {
1264    fn len(&self) -> usize {
1265        self.inner.len()
1266    }
1267}
1268
1269impl<'a, K: Hash + Eq, V, S: BuildHasher> IntoIterator for &'a LinkedHashMap<K, V, S> {
1270    type Item = (&'a K, &'a V);
1271    type IntoIter = Iter<'a, K, V>;
1272    fn into_iter(self) -> Iter<'a, K, V> {
1273        self.iter()
1274    }
1275}
1276
1277impl<'a, K: Hash + Eq, V, S: BuildHasher> IntoIterator for &'a mut LinkedHashMap<K, V, S> {
1278    type Item = (&'a K, &'a mut V);
1279    type IntoIter = IterMut<'a, K, V>;
1280    fn into_iter(self) -> IterMut<'a, K, V> {
1281        self.iter_mut()
1282    }
1283}
1284
1285impl<K: Hash + Eq, V, S: BuildHasher> IntoIterator for LinkedHashMap<K, V, S> {
1286    type Item = (K, V);
1287    type IntoIter = IntoIter<K, V>;
1288    fn into_iter(mut self) -> IntoIter<K, V> {
1289        let (head, tail) = if !self.head.is_null() {
1290            unsafe { ((*self.head).prev, (*self.head).next) }
1291        } else {
1292            (ptr::null_mut(), ptr::null_mut())
1293        };
1294        let len = self.len();
1295
1296        if !self.head.is_null() {
1297            unsafe { drop_empty_node(self.head) }
1298        }
1299        self.clear_free_list();
1300        // drop the HashMap but not the LinkedHashMap
1301        unsafe {
1302            ptr::drop_in_place(&mut self.map);
1303        }
1304        mem::forget(self);
1305
1306        IntoIter {
1307            head,
1308            tail,
1309            remaining: len,
1310            marker: marker::PhantomData,
1311        }
1312    }
1313}
1314
1315/// A view into a single location in a map, which may be vacant or occupied.
1316pub enum Entry<'a, K: 'a, V: 'a, S: 'a = hash_map::RandomState> {
1317    /// An occupied Entry.
1318    Occupied(OccupiedEntry<'a, K, V, S>),
1319    /// A vacant Entry.
1320    Vacant(VacantEntry<'a, K, V, S>),
1321}
1322
1323/// A view into a single occupied location in a `LinkedHashMap`.
1324pub struct OccupiedEntry<'a, K: 'a, V: 'a, S: 'a = hash_map::RandomState> {
1325    entry: *mut Node<K, V>,
1326    map: *mut LinkedHashMap<K, V, S>,
1327    marker: marker::PhantomData<&'a K>,
1328}
1329
1330/// A view into a single empty location in a `LinkedHashMap`.
1331pub struct VacantEntry<'a, K: 'a, V: 'a, S: 'a = hash_map::RandomState> {
1332    key: K,
1333    map: &'a mut LinkedHashMap<K, V, S>,
1334}
1335
1336impl<'a, K: Hash + Eq, V, S: BuildHasher> Entry<'a, K, V, S> {
1337    /// Returns the entry key
1338    ///
1339    /// # Examples
1340    ///
1341    /// ```
1342    /// use midl_parser::linked_hash_map::LinkedHashMap;
1343    ///
1344    /// let mut map = LinkedHashMap::<String, u32>::new();
1345    ///
1346    /// assert_eq!("hello", map.entry("hello".to_string()).key());
1347    /// ```
1348    pub fn key(&self) -> &K {
1349        match *self {
1350            Entry::Occupied(ref e) => e.key(),
1351            Entry::Vacant(ref e) => e.key(),
1352        }
1353    }
1354
1355    /// Ensures a value is in the entry by inserting the default if empty, and returns
1356    /// a mutable reference to the value in the entry.
1357    pub fn or_insert(self, default: V) -> &'a mut V {
1358        match self {
1359            Entry::Occupied(entry) => entry.into_mut(),
1360            Entry::Vacant(entry) => entry.insert(default),
1361        }
1362    }
1363
1364    /// Ensures a value is in the entry by inserting the result of the default function if empty,
1365    /// and returns a mutable reference to the value in the entry.
1366    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
1367        match self {
1368            Entry::Occupied(entry) => entry.into_mut(),
1369            Entry::Vacant(entry) => entry.insert(default()),
1370        }
1371    }
1372}
1373
1374impl<'a, K: Hash + Eq, V, S: BuildHasher> OccupiedEntry<'a, K, V, S> {
1375    /// Gets a reference to the entry key
1376    ///
1377    /// # Examples
1378    ///
1379    /// ```
1380    /// use midl_parser::linked_hash_map::LinkedHashMap;
1381    ///
1382    /// let mut map = LinkedHashMap::new();
1383    ///
1384    /// map.insert("foo".to_string(), 1);
1385    /// assert_eq!("foo", map.entry("foo".to_string()).key());
1386    /// ```
1387    pub fn key(&self) -> &K {
1388        unsafe { &(*self.entry).key }
1389    }
1390
1391    /// Gets a reference to the value in the entry.
1392    pub fn get(&self) -> &V {
1393        unsafe { &(*self.entry).value }
1394    }
1395
1396    /// Gets a mutable reference to the value in the entry.
1397    pub fn get_mut(&mut self) -> &mut V {
1398        unsafe { &mut (*self.entry).value }
1399    }
1400
1401    /// Converts the OccupiedEntry into a mutable reference to the value in the entry
1402    /// with a lifetime bound to the map itself
1403    pub fn into_mut(self) -> &'a mut V {
1404        unsafe { &mut (*self.entry).value }
1405    }
1406
1407    /// Sets the value of the entry, and returns the entry's old value
1408    pub fn insert(&mut self, value: V) -> V {
1409        unsafe {
1410            (*self.map).ensure_guard_node();
1411
1412            let old_val = mem::replace(&mut (*self.entry).value, value);
1413            let node_ptr: *mut Node<K, V> = self.entry;
1414
1415            // Existing node, just update LRU position
1416            (*self.map).detach(node_ptr);
1417            (*self.map).attach(node_ptr);
1418
1419            old_val
1420        }
1421    }
1422
1423    /// Takes the value out of the entry, and returns it
1424    pub fn remove(self) -> V {
1425        unsafe { (*self.map).remove(&(*self.entry).key) }.unwrap()
1426    }
1427}
1428
1429impl<'a, K: 'a + Hash + Eq, V: 'a, S: BuildHasher> VacantEntry<'a, K, V, S> {
1430    /// Gets a reference to the entry key
1431    ///
1432    /// # Examples
1433    ///
1434    /// ```
1435    /// use midl_parser::linked_hash_map::LinkedHashMap;
1436    ///
1437    /// let mut map = LinkedHashMap::<String, u32>::new();
1438    ///
1439    /// assert_eq!("foo", map.entry("foo".to_string()).key());
1440    /// ```
1441    pub fn key(&self) -> &K {
1442        &self.key
1443    }
1444
1445    /// Sets the value of the entry with the VacantEntry's key,
1446    /// and returns a mutable reference to it
1447    pub fn insert(self, value: V) -> &'a mut V {
1448        self.map.ensure_guard_node();
1449
1450        let node = if self.map.free.is_null() {
1451            Box::into_raw(Box::new(Node::new(self.key, value)))
1452        } else {
1453            // use a recycled box
1454            unsafe {
1455                let free = self.map.free;
1456                self.map.free = (*free).next;
1457                ptr::write(free, Node::new(self.key, value));
1458                free
1459            }
1460        };
1461
1462        let keyref = unsafe { &(*node).key };
1463
1464        self.map.attach(node);
1465
1466        let ret = self.map.map.entry(KeyRef { k: keyref }).or_insert(node);
1467        unsafe { &mut (**ret).value }
1468    }
1469}
1470
1471#[cfg(all(feature = "nightly", test))]
1472mod bench {
1473    extern crate test;
1474
1475    use super::LinkedHashMap;
1476
1477    #[bench]
1478    fn not_recycled_cycling(b: &mut test::Bencher) {
1479        let mut hash_map = LinkedHashMap::with_capacity(1000);
1480        for i in 0usize..1000 {
1481            hash_map.insert(i, i);
1482        }
1483        b.iter(|| {
1484            for i in 0usize..1000 {
1485                hash_map.remove(&i);
1486            }
1487            hash_map.clear_free_list();
1488            for i in 0usize..1000 {
1489                hash_map.insert(i, i);
1490            }
1491        })
1492    }
1493
1494    #[bench]
1495    fn recycled_cycling(b: &mut test::Bencher) {
1496        let mut hash_map = LinkedHashMap::with_capacity(1000);
1497        for i in 0usize..1000 {
1498            hash_map.insert(i, i);
1499        }
1500        b.iter(|| {
1501            for i in 0usize..1000 {
1502                hash_map.remove(&i);
1503            }
1504            for i in 0usize..1000 {
1505                hash_map.insert(i, i);
1506            }
1507        })
1508    }
1509}