Skip to main content

immutable_chunkmap/
map.rs

1use crate::avl::{Iter, IterMut, Tree, WeakTree};
2pub use crate::chunk::DEFAULT_SIZE;
3use core::{
4    borrow::Borrow,
5    cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd},
6    default::Default,
7    fmt::{self, Debug, Formatter},
8    hash::{Hash, Hasher},
9    iter::FromIterator,
10    ops::{Index, IndexMut, RangeBounds, RangeFull},
11};
12
13#[cfg(feature = "serde")]
14use serde::{
15    de::{MapAccess, Visitor},
16    ser::SerializeMap,
17    Deserialize, Deserializer, Serialize, Serializer,
18};
19
20#[cfg(feature = "serde")]
21use core::marker::PhantomData;
22
23#[cfg(feature = "rayon")]
24use rayon::{
25    iter::{FromParallelIterator, IntoParallelIterator},
26    prelude::*,
27};
28
29/// This Map uses a similar strategy to BTreeMap to ensure cache
30/// efficient performance on modern hardware while still providing
31/// log(N) get, insert, and remove operations.
32///
33/// For good performance, it is very important to understand
34/// that clone is a fundamental operation, it needs to be fast
35/// for your key and data types, because it's going to be
36/// called a lot whenever you change the map.
37///
38/// # Why
39///
40/// 1. Multiple threads can read this structure even while one thread
41/// is updating it. Using a library like arc_swap you can avoid ever
42/// blocking readers.
43///
44/// 2. Snapshotting this structure is free.
45///
46/// # Examples
47/// ```
48/// # extern crate alloc;
49/// use alloc::string::String;
50/// use self::immutable_chunkmap::map::MapM;
51///
52/// let m =
53///    MapM::new()
54///    .insert(String::from("1"), 1).0
55///    .insert(String::from("2"), 2).0
56///    .insert(String::from("3"), 3).0;
57///
58/// assert_eq!(m.get("1"), Option::Some(&1));
59/// assert_eq!(m.get("2"), Option::Some(&2));
60/// assert_eq!(m.get("3"), Option::Some(&3));
61/// assert_eq!(m.get("4"), Option::None);
62///
63/// for (k, v) in &m {
64///   println!("key {}, val: {}", k, v)
65/// }
66/// ```
67#[derive(Clone)]
68#[repr(transparent)]
69pub struct Map<K: Ord + Clone, V: Clone, const SIZE: usize>(Tree<K, V, SIZE>);
70
71/// Map using a smaller chunk size, faster to update, slower to search
72pub type MapS<K, V> = Map<K, V, { DEFAULT_SIZE / 2 }>;
73
74/// Map using the default chunk size, a good balance of update and search
75pub type MapM<K, V> = Map<K, V, DEFAULT_SIZE>;
76
77/// Map using a larger chunk size, faster to search, slower to update
78pub type MapL<K, V> = Map<K, V, { DEFAULT_SIZE * 2 }>;
79
80/// A weak reference to a map.
81#[derive(Clone)]
82pub struct WeakMapRef<K: Ord + Clone, V: Clone, const SIZE: usize>(WeakTree<K, V, SIZE>);
83
84pub type WeakMapRefS<K, V> = WeakMapRef<K, V, { DEFAULT_SIZE / 2 }>;
85pub type WeakMapRefM<K, V> = WeakMapRef<K, V, DEFAULT_SIZE>;
86pub type WeakMapRefL<K, V> = WeakMapRef<K, V, { DEFAULT_SIZE * 2 }>;
87
88impl<K, V, const SIZE: usize> WeakMapRef<K, V, SIZE>
89where
90    K: Ord + Clone,
91    V: Clone,
92{
93    pub fn upgrade(&self) -> Option<Map<K, V, SIZE>> {
94        self.0.upgrade().map(Map)
95    }
96}
97
98impl<K, V, const SIZE: usize> Hash for Map<K, V, SIZE>
99where
100    K: Hash + Ord + Clone,
101    V: Hash + Clone,
102{
103    fn hash<H: Hasher>(&self, state: &mut H) {
104        self.0.hash(state)
105    }
106}
107
108impl<K, V, const SIZE: usize> Default for Map<K, V, SIZE>
109where
110    K: Ord + Clone,
111    V: Clone,
112{
113    fn default() -> Map<K, V, SIZE> {
114        Map::new()
115    }
116}
117
118impl<K, V, const SIZE: usize> PartialEq for Map<K, V, SIZE>
119where
120    K: PartialEq + Ord + Clone,
121    V: PartialEq + Clone,
122{
123    fn eq(&self, other: &Map<K, V, SIZE>) -> bool {
124        self.0 == other.0
125    }
126}
127
128impl<K, V, const SIZE: usize> Eq for Map<K, V, SIZE>
129where
130    K: Eq + Ord + Clone,
131    V: Eq + Clone,
132{
133}
134
135impl<K, V, const SIZE: usize> PartialOrd for Map<K, V, SIZE>
136where
137    K: Ord + Clone,
138    V: PartialOrd + Clone,
139{
140    fn partial_cmp(&self, other: &Map<K, V, SIZE>) -> Option<Ordering> {
141        self.0.partial_cmp(&other.0)
142    }
143}
144
145impl<K, V, const SIZE: usize> Ord for Map<K, V, SIZE>
146where
147    K: Ord + Clone,
148    V: Ord + Clone,
149{
150    fn cmp(&self, other: &Map<K, V, SIZE>) -> Ordering {
151        self.0.cmp(&other.0)
152    }
153}
154
155impl<K, V, const SIZE: usize> Debug for Map<K, V, SIZE>
156where
157    K: Debug + Ord + Clone,
158    V: Debug + Clone,
159{
160    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
161        self.0.fmt(f)
162    }
163}
164
165impl<'a, Q, K, V, const SIZE: usize> Index<&'a Q> for Map<K, V, SIZE>
166where
167    Q: Ord,
168    K: Ord + Clone + Borrow<Q>,
169    V: Clone,
170{
171    type Output = V;
172    fn index(&self, k: &Q) -> &V {
173        self.get(k).expect("element not found for key")
174    }
175}
176
177impl<'a, Q, K, V, const SIZE: usize> IndexMut<&'a Q> for Map<K, V, SIZE>
178where
179    Q: Ord,
180    K: Ord + Clone + Borrow<Q>,
181    V: Clone,
182{
183    fn index_mut(&mut self, k: &'a Q) -> &mut Self::Output {
184        self.get_mut_cow(k).expect("element not found for key")
185    }
186}
187
188impl<K, V, const SIZE: usize> FromIterator<(K, V)> for Map<K, V, SIZE>
189where
190    K: Ord + Clone,
191    V: Clone,
192{
193    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
194        Map::new().insert_many(iter)
195    }
196}
197
198impl<'a, K, V, const SIZE: usize> IntoIterator for &'a Map<K, V, SIZE>
199where
200    K: 'a + Ord + Clone,
201    V: 'a + Clone,
202{
203    type Item = (&'a K, &'a V);
204    type IntoIter = Iter<'a, RangeFull, K, K, V, SIZE>;
205    fn into_iter(self) -> Self::IntoIter {
206        self.0.into_iter()
207    }
208}
209
210#[cfg(feature = "serde")]
211impl<K, V, const SIZE: usize> Serialize for Map<K, V, SIZE>
212where
213    K: Serialize + Clone + Ord,
214    V: Serialize + Clone,
215{
216    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
217    where
218        S: Serializer,
219    {
220        let mut map = serializer.serialize_map(Some(self.len()))?;
221        for (k, v) in self {
222            map.serialize_entry(k, v)?
223        }
224        map.end()
225    }
226}
227
228#[cfg(feature = "serde")]
229struct MapVisitor<K: Clone + Ord, V: Clone, const SIZE: usize> {
230    marker: PhantomData<fn() -> Map<K, V, SIZE>>,
231}
232
233#[cfg(feature = "serde")]
234impl<'a, K, V, const SIZE: usize> Visitor<'a> for MapVisitor<K, V, SIZE>
235where
236    K: Deserialize<'a> + Clone + Ord,
237    V: Deserialize<'a> + Clone,
238{
239    type Value = Map<K, V, SIZE>;
240
241    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
242        formatter.write_str("expected an immutable_chunkmap::Map")
243    }
244
245    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
246    where
247        A: MapAccess<'a>,
248    {
249        let mut t = Map::<K, V, SIZE>::new();
250        while let Some((k, v)) = map.next_entry()? {
251            t.insert_cow(k, v);
252        }
253        Ok(t)
254    }
255}
256
257#[cfg(feature = "serde")]
258impl<'a, K, V, const SIZE: usize> Deserialize<'a> for Map<K, V, SIZE>
259where
260    K: Deserialize<'a> + Clone + Ord,
261    V: Deserialize<'a> + Clone,
262{
263    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
264    where
265        D: Deserializer<'a>,
266    {
267        deserializer.deserialize_map(MapVisitor {
268            marker: PhantomData,
269        })
270    }
271}
272
273#[cfg(feature = "rayon")]
274impl<'a, K, V, const SIZE: usize> IntoParallelIterator for &'a Map<K, V, SIZE>
275where
276    K: 'a + Ord + Clone + Send + Sync,
277    V: Clone + Send + Sync,
278{
279    type Item = (&'a K, &'a V);
280    type Iter = rayon::vec::IntoIter<(&'a K, &'a V)>;
281
282    fn into_par_iter(self) -> Self::Iter {
283        self.into_iter().collect::<Vec<_>>().into_par_iter()
284    }
285}
286
287#[cfg(feature = "rayon")]
288impl<K, V, const SIZE: usize> FromParallelIterator<(K, V)> for Map<K, V, SIZE>
289where
290    K: Ord + Clone + Send + Sync,
291    V: Clone + Send + Sync,
292{
293    fn from_par_iter<I>(i: I) -> Self
294    where
295        I: IntoParallelIterator<Item = (K, V)>,
296    {
297        i.into_par_iter()
298            .fold_with(Map::new(), |mut m, (k, v)| {
299                m.insert_cow(k, v);
300                m
301            })
302            .reduce_with(|m0, m1| m0.union(&m1, |_k, _v0, v1| Some(v1.clone())))
303            .unwrap_or_else(Map::new)
304    }
305}
306
307impl<K, V, const SIZE: usize> Map<K, V, SIZE>
308where
309    K: Ord + Clone,
310    V: Clone,
311{
312    /// Create a new empty map
313    pub fn new() -> Self {
314        Map(Tree::new())
315    }
316
317    /// Create a weak reference to this map
318    pub fn downgrade(&self) -> WeakMapRef<K, V, SIZE> {
319        WeakMapRef(self.0.downgrade())
320    }
321
322    /// Return the number of strong references to this map (see Arc)
323    pub fn strong_count(&self) -> usize {
324        self.0.strong_count()
325    }
326
327    /// Return the number of weak references to this map (see Arc)
328    pub fn weak_count(&self) -> usize {
329        self.0.weak_count()
330    }
331
332    /// This will insert many elements at once, and is
333    /// potentially a lot faster than inserting one by one,
334    /// especially if the data is sorted. It is just a wrapper
335    /// around the more general update_many method.
336    ///
337    /// #Examples
338    ///```
339    /// use self::immutable_chunkmap::map::MapM;
340    ///
341    /// let mut v = vec![(1, 3), (10, 1), (-12, 2), (44, 0), (50, -1)];
342    /// v.sort_unstable_by_key(|&(k, _)| k);
343    ///
344    /// let m = MapM::new().insert_many(v.iter().map(|(k, v)| (*k, *v)));
345    ///
346    /// for (k, v) in &v {
347    ///   assert_eq!(m.get(k), Option::Some(v))
348    /// }
349    /// ```
350    pub fn insert_many<E: IntoIterator<Item = (K, V)>>(&self, elts: E) -> Self {
351        Map(self.0.insert_many(elts))
352    }
353
354    /// This will remove many elements at once, and is potentially a
355    /// lot faster than removing elements one by one, especially if
356    /// the data is sorted. It is just a wrapper around the more
357    /// general update_many method.
358    pub fn remove_many<Q, E>(&self, elts: E) -> Self
359    where
360        E: IntoIterator<Item = Q>,
361        Q: Ord,
362        K: Borrow<Q>,
363    {
364        self.update_many(elts.into_iter().map(|q| (q, ())), |_, _, _| None)
365    }
366
367    /// This method updates multiple bindings in one call. Given an
368    /// iterator of an arbitrary type (Q, D), where Q is any borrowed
369    /// form of K, an update function taking Q, D, the current binding
370    /// in the map, if any, and producing the new binding, if any,
371    /// this method will produce a new map with updated bindings of
372    /// many elements at once. It will skip intermediate node
373    /// allocations where possible. If the data in elts is sorted, it
374    /// will be able to skip many more intermediate allocations, and
375    /// can produce a speedup of about 10x compared to
376    /// inserting/updating one by one. In any case it should always be
377    /// faster than inserting elements one by one, even with random
378    /// unsorted keys.
379    ///
380    /// #Examples
381    /// ```
382    /// use core::iter::FromIterator;
383    /// use self::immutable_chunkmap::map::MapM;
384    ///
385    /// let m = MapM::from_iter((0..4).map(|k| (k, k)));
386    /// let m = m.update_many(
387    ///     (0..4).map(|x| (x, ())),
388    ///     |k, (), cur| cur.map(|(_, c)| (k, c + 1))
389    /// );
390    /// assert_eq!(
391    ///     m.into_iter().map(|(k, v)| (*k, *v)).collect::<Vec<_>>(),
392    ///     vec![(0, 1), (1, 2), (2, 3), (3, 4)]
393    /// );
394    /// ```
395    pub fn update_many<Q, D, E, F>(&self, elts: E, mut f: F) -> Self
396    where
397        E: IntoIterator<Item = (Q, D)>,
398        Q: Ord,
399        K: Borrow<Q>,
400        F: FnMut(Q, D, Option<(&K, &V)>) -> Option<(K, V)>,
401    {
402        Map(self.0.update_many(elts, &mut f))
403    }
404
405    /// return a new map with (k, v) inserted into it. If k
406    /// already exists in the old map, the old binding will be
407    /// returned, and the new map will contain the new
408    /// binding. In fact this method is just a wrapper around
409    /// update.
410    pub fn insert(&self, k: K, v: V) -> (Self, Option<V>) {
411        let (root, prev) = self.0.insert(k, v);
412        (Map(root), prev)
413    }
414
415    /// insert in place using copy on write semantics if self is not a
416    /// unique reference to the map. see `update_cow`.
417    pub fn insert_cow(&mut self, k: K, v: V) -> Option<V> {
418        self.0.insert_cow(k, v)
419    }
420
421    /// return a new map with the binding for q, which can be any
422    /// borrowed form of k, updated to the result of f. If f returns
423    /// None, the binding will be removed from the new map, otherwise
424    /// it will be inserted. This function is more efficient than
425    /// calling `get` and then `insert`, since it makes only one tree
426    /// traversal instead of two. This method runs in log(N) time and
427    /// space where N is the size of the map.
428    ///
429    /// # Examples
430    /// ```
431    /// use self::immutable_chunkmap::map::MapM;
432    ///
433    /// let (m, _) = MapM::new().update(0, 0, |k, d, _| Some((k, d)));
434    /// let (m, _) = m.update(1, 1, |k, d, _| Some((k, d)));
435    /// let (m, _) = m.update(2, 2, |k, d, _| Some((k, d)));
436    /// assert_eq!(m.get(&0), Some(&0));
437    /// assert_eq!(m.get(&1), Some(&1));
438    /// assert_eq!(m.get(&2), Some(&2));
439    ///
440    /// let (m, _) = m.update(0, (), |k, (), v| v.map(move |(_, v)| (k, v + 1)));
441    /// assert_eq!(m.get(&0), Some(&1));
442    /// assert_eq!(m.get(&1), Some(&1));
443    /// assert_eq!(m.get(&2), Some(&2));
444    ///
445    /// let (m, _) = m.update(1, (), |_, (), _| None);
446    /// assert_eq!(m.get(&0), Some(&1));
447    /// assert_eq!(m.get(&1), None);
448    /// assert_eq!(m.get(&2), Some(&2));
449    /// ```
450    pub fn update<Q, D, F>(&self, q: Q, d: D, mut f: F) -> (Self, Option<V>)
451    where
452        Q: Ord,
453        K: Borrow<Q>,
454        F: FnMut(Q, D, Option<(&K, &V)>) -> Option<(K, V)>,
455    {
456        let (root, prev) = self.0.update(q, d, &mut f);
457        (Map(root), prev)
458    }
459
460    /// Perform a copy on write update to the map. In the case that
461    /// self is a unique reference to the map, then the update will be
462    /// performed completly in place. self will be mutated, and no
463    /// previous version will be available. In the case that self has
464    /// a clone, or clones, then only the parts of the map that need
465    /// to be mutated will be copied before the update is
466    /// performed. self will reference the mutated copy, and previous
467    /// versions of the map will not be modified. self will still
468    /// share all the parts of the map that did not need to be mutated
469    /// with any pre existing clones.
470    ///
471    /// COW semantics are a flexible middle way between full
472    /// peristance and full mutability. Needless to say in the case
473    /// where you have a unique reference to the map, using update_cow
474    /// is a lot faster than using update, and a lot more flexible
475    /// than update_many.
476    ///
477    /// Other than copy on write the semanics of this method are
478    /// identical to those of update.
479    ///
480    /// #Examples
481    ///```
482    /// use self::immutable_chunkmap::map::MapM;
483    ///
484    /// let mut m = MapM::new().update(0, 0, |k, d, _| Some((k, d))).0;
485    /// let orig = m.clone();
486    /// m.update_cow(1, 1, |k, d, _| Some((k, d))); // copies the original chunk
487    /// m.update_cow(2, 2, |k, d, _| Some((k, d))); // doesn't copy anything
488    /// assert_eq!(m.len(), 3);
489    /// assert_eq!(orig.len(), 1);
490    /// assert_eq!(m.get(&0), Some(&0));
491    /// assert_eq!(m.get(&1), Some(&1));
492    /// assert_eq!(m.get(&2), Some(&2));
493    /// assert_eq!(orig.get(&0), Some(&0));
494    /// assert_eq!(orig.get(&1), None);
495    /// assert_eq!(orig.get(&2), None);
496    ///```
497    pub fn update_cow<Q, D, F>(&mut self, q: Q, d: D, mut f: F) -> Option<V>
498    where
499        Q: Ord,
500        K: Borrow<Q>,
501        F: FnMut(Q, D, Option<(&K, &V)>) -> Option<(K, V)>,
502    {
503        self.0.update_cow(q, d, &mut f)
504    }
505
506    /// Merge two maps together. Bindings that exist in both maps will
507    /// be passed to f, which may elect to remove the binding by
508    /// returning None. This function runs in O(log(n) + m) time and
509    /// space, where n is the size of the largest map, and m is the
510    /// number of intersecting chunks. It will never be slower than
511    /// calling update_many on the first map with an iterator over the
512    /// second, and will be significantly faster if the intersection
513    /// is minimal or empty.
514    ///
515    /// # Examples
516    /// ```
517    /// use core::iter::FromIterator;
518    /// use self::immutable_chunkmap::map::MapM;
519    ///
520    /// let m0 = MapM::from_iter((0..10).map(|k| (k, 1)));
521    /// let m1 = MapM::from_iter((10..20).map(|k| (k, 1)));
522    /// let m2 = m0.union(&m1, |_k, _v0, _v1| panic!("no intersection expected"));
523    ///
524    /// for i in 0..20 {
525    ///     assert!(m2.get(&i).is_some())
526    /// }
527    ///
528    /// let m3 = MapM::from_iter((5..9).map(|k| (k, 1)));
529    /// let m4 = m3.union(&m2, |_k, v0, v1| Some(v0 + v1));
530    ///
531    /// for i in 0..20 {
532    ///    assert!(
533    ///        *m4.get(&i).unwrap() ==
534    ///        *m3.get(&i).unwrap_or(&0) + *m2.get(&i).unwrap_or(&0)
535    ///    )
536    /// }
537    /// ```
538    pub fn union<F>(&self, other: &Map<K, V, SIZE>, mut f: F) -> Self
539    where
540        F: FnMut(&K, &V, &V) -> Option<V>,
541    {
542        Map(Tree::union(&self.0, &other.0, &mut f))
543    }
544
545    /// Produce a map containing the mapping over F of the
546    /// intersection (by key) of two maps. The function f runs on each
547    /// intersecting element, and has the option to omit elements from
548    /// the intersection by returning None, or change the value any
549    /// way it likes. Runs in O(log(N) + M) time and space where N is
550    /// the size of the smallest map, and M is the number of
551    /// intersecting chunks.
552    ///
553    /// # Examples
554    ///```
555    /// use core::iter::FromIterator;
556    /// use self::immutable_chunkmap::map::MapM;
557    ///
558    /// let m0 = MapM::from_iter((0..100000).map(|k| (k, 1)));
559    /// let m1 = MapM::from_iter((50..30000).map(|k| (k, 1)));
560    /// let m2 = m0.intersect(&m1, |_k, v0, v1| Some(v0 + v1));
561    ///
562    /// for i in 0..100000 {
563    ///     if i >= 30000 || i < 50 {
564    ///         assert!(m2.get(&i).is_none());
565    ///     } else {
566    ///         assert!(*m2.get(&i).unwrap() == 2);
567    ///     }
568    /// }
569    /// ```
570    pub fn intersect<F>(&self, other: &Map<K, V, SIZE>, mut f: F) -> Self
571    where
572        F: FnMut(&K, &V, &V) -> Option<V>,
573    {
574        Map(Tree::intersect(&self.0, &other.0, &mut f))
575    }
576
577    /// Produce a map containing the second map subtracted from the
578    /// first. The function F is called for each intersecting element,
579    /// and ultimately decides whether it appears in the result, for
580    /// example, to compute a classical set diff, the function should
581    /// always return None.
582    ///
583    /// # Examples
584    ///```
585    /// use core::iter::FromIterator;
586    /// use self::immutable_chunkmap::map::MapM;
587    ///
588    /// let m0 = MapM::from_iter((0..10000).map(|k| (k, 1)));
589    /// let m1 = MapM::from_iter((50..3000).map(|k| (k, 1)));
590    /// let m2 = m0.diff(&m1, |_k, _v0, _v1| None);
591    ///
592    /// m2.invariant();
593    /// dbg!(m2.len());
594    /// assert!(m2.len() == 10000 - 2950);
595    /// for i in 0..10000 {
596    ///     if i >= 3000 || i < 50 {
597    ///         assert!(*m2.get(&i).unwrap() == 1);
598    ///     } else {
599    ///         assert!(m2.get(&i).is_none());
600    ///     }
601    /// }
602    /// ```
603    pub fn diff<F>(&self, other: &Map<K, V, SIZE>, mut f: F) -> Self
604    where
605        F: FnMut(&K, &V, &V) -> Option<V>,
606        K: Debug,
607        V: Debug,
608    {
609        Map(Tree::diff(&self.0, &other.0, &mut f))
610    }
611
612    /// lookup the mapping for k. If it doesn't exist return
613    /// None. Runs in log(N) time and constant space. where N
614    /// is the size of the map.
615    pub fn get<'a, Q: ?Sized + Ord>(&'a self, k: &Q) -> Option<&'a V>
616    where
617        K: Borrow<Q>,
618    {
619        self.0.get(k)
620    }
621
622    /// lookup the mapping for k. Return the key. If it doesn't exist
623    /// return None. Runs in log(N) time and constant space. where N
624    /// is the size of the map.
625    pub fn get_key<'a, Q: ?Sized + Ord>(&'a self, k: &Q) -> Option<&'a K>
626    where
627        K: Borrow<Q>,
628    {
629        self.0.get_key(k)
630    }
631
632    /// lookup the mapping for k. Return both the key and the
633    /// value. If it doesn't exist return None. Runs in log(N) time
634    /// and constant space. where N is the size of the map.
635    pub fn get_full<'a, Q: ?Sized + Ord>(&'a self, k: &Q) -> Option<(&'a K, &'a V)>
636    where
637        K: Borrow<Q>,
638    {
639        self.0.get_full(k)
640    }
641
642    /// Get a mutable reference to the value mapped to `k` using copy on write semantics.
643    /// This works as `Arc::make_mut`, it will only clone the parts of the tree that are,
644    /// - required to reach `k`
645    /// - have a strong count > 1
646    ///
647    /// This operation is also triggered by mut indexing on the map, e.g. `&mut m[k]`
648    /// calls `get_mut_cow` on `m`
649    ///
650    /// # Example
651    /// ```
652    /// use core::iter::FromIterator;
653    /// use self::immutable_chunkmap::map::MapM as Map;
654    ///  
655    /// let mut m = Map::from_iter((0..100).map(|k| (k, Map::from_iter((0..100).map(|k| (k, 1))))));
656    /// let orig = m.clone();
657    ///
658    /// if let Some(inner) = m.get_mut_cow(&0) {
659    ///     if let Some(v) = inner.get_mut_cow(&0) {
660    ///         *v += 1
661    ///     }
662    /// }
663    ///
664    /// assert_eq!(m.get(&0).and_then(|m| m.get(&0)), Some(&2));
665    /// assert_eq!(orig.get(&0).and_then(|m| m.get(&0)), Some(&1));
666    /// ```
667    pub fn get_mut_cow<'a, Q: ?Sized + Ord>(&'a mut self, k: &Q) -> Option<&'a mut V>
668    where
669        K: Borrow<Q>,
670    {
671        self.0.get_mut_cow(k)
672    }
673
674    /// Same as `get_mut_cow` except if the value is not in the map it will
675    /// first be inserted by calling `f`
676    pub fn get_or_insert_cow<'a, F>(&'a mut self, k: K, f: F) -> &'a mut V
677    where
678        F: FnOnce() -> V,
679    {
680        self.0.get_or_insert_cow(k, f)
681    }
682
683    /// return a new map with the mapping under k removed. If
684    /// the binding existed in the old map return it. Runs in
685    /// log(N) time and log(N) space, where N is the size of
686    /// the map.
687    pub fn remove<Q: Sized + Ord>(&self, k: &Q) -> (Self, Option<V>)
688    where
689        K: Borrow<Q>,
690    {
691        let (t, prev) = self.0.remove(k);
692        (Map(t), prev)
693    }
694
695    /// remove in place using copy on write semantics if self is not a
696    /// unique reference to the map. see `update_cow`.
697    pub fn remove_cow<Q: Sized + Ord>(&mut self, k: &Q) -> Option<V>
698    where
699        K: Borrow<Q>,
700    {
701        self.0.remove_cow(k)
702    }
703
704    /// get the number of elements in the map O(1) time and space
705    pub fn len(&self) -> usize {
706        self.0.len()
707    }
708
709    /// return an iterator over the subset of elements in the
710    /// map that are within the specified range.
711    ///
712    /// The returned iterator runs in O(log(N) + M) time, and
713    /// constant space. N is the number of elements in the
714    /// tree, and M is the number of elements you examine.
715    ///
716    /// if lbound >= ubound the returned iterator will be empty
717    pub fn range<'a, Q, R>(&'a self, r: R) -> Iter<'a, R, Q, K, V, SIZE>
718    where
719        Q: Ord + ?Sized + 'a,
720        K: Borrow<Q>,
721        R: RangeBounds<Q> + 'a,
722    {
723        self.0.range(r)
724    }
725
726    /// return a mutable iterator over the subset of elements in the
727    /// map that are within the specified range. The iterator will
728    /// copy on write the part of the tree that it visits,
729    /// specifically it will be as if you ran get_mut_cow on every
730    /// element you visit.
731    ///
732    /// The returned iterator runs in O(log(N) + M) time, and
733    /// constant space. N is the number of elements in the
734    /// tree, and M is the number of elements you examine.
735    ///
736    /// if lbound >= ubound the returned iterator will be empty
737    pub fn range_mut_cow<'a, Q, R>(&'a mut self, r: R) -> IterMut<'a, R, Q, K, V, SIZE>
738    where
739        Q: Ord + ?Sized + 'a,
740        K: Borrow<Q>,
741        R: RangeBounds<Q> + 'a,
742    {
743        self.0.range_mut_cow(r)
744    }
745
746    /// return a mutable iterator over the entire map. The iterator
747    /// will copy on write every element in the tree, specifically it
748    /// will be as if you ran get_mut_cow on every element.
749    ///
750    /// The returned iterator runs in O(log(N) + M) time, and
751    /// constant space. N is the number of elements in the
752    /// tree, and M is the number of elements you examine.
753    pub fn iter_mut_cow<'a>(&'a mut self) -> IterMut<'a, RangeFull, K, K, V, SIZE> {
754        self.0.iter_mut_cow()
755    }
756}
757
758impl<K, V, const SIZE: usize> Map<K, V, SIZE>
759where
760    K: Ord + Clone,
761    V: Clone + Default,
762{
763    /// Same as `get_mut_cow` except if the value isn't in the map it will
764    /// be added by calling `V::default`
765    pub fn get_or_default_cow<'a>(&'a mut self, k: K) -> &'a mut V {
766        self.get_or_insert_cow(k, V::default)
767    }
768}
769
770impl<K, V, const SIZE: usize> Map<K, V, SIZE>
771where
772    K: Ord + Clone + Debug,
773    V: Clone + Debug,
774{
775    #[allow(dead_code)]
776    pub fn invariant(&self) -> () {
777        self.0.invariant()
778    }
779}