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