Skip to main content

pour/
inner.rs

1use super::*;
2use num_traits::Zero;
3use std::fmt::{self, Debug, Formatter};
4
5/// The log of the branching factor for a radix trie
6const LOG_BRANCHING_FACTOR: u8 = 2;
7
8/// The branching factor for a radix trie
9const BRANCHING_FACTOR: usize = 1 << LOG_BRANCHING_FACTOR;
10
11/// The bin mask
12const BIN_MASK: u8 = BRANCHING_FACTOR as u8 - 1;
13
14/// Round a depth to a bin depth
15pub fn round_depth<D>(depth: D) -> D
16where
17    D: PrimInt,
18{
19    let lbf: D = num_traits::NumCast::from(LOG_BRANCHING_FACTOR).unwrap();
20    (depth / lbf) * lbf
21}
22
23/// Get the bin in a byte at a depth
24pub fn byte_bin(byte: u8, depth: usize) -> usize {
25    let byte_depth = round_depth(depth % 8);
26    let bin_mask = BIN_MASK.wrapping_shl(byte_depth as u32);
27    let bin_bits = byte & bin_mask;
28    bin_bits.wrapping_shr(byte_depth as u32) as usize
29}
30
31/// Get the bin in a pattern at a depth
32pub fn pattern_bin<P, D>(pattern: P, depth: D) -> usize
33where
34    P: Pattern<D>,
35    D: Copy + AsPrimitive<usize>,
36{
37    let byte = pattern.byte(depth);
38    byte_bin(byte, depth.as_())
39}
40
41/// An `IdMap`'s internal data.
42#[derive(Clone)]
43pub struct InnerMap<K: RadixKey, V: Clone> {
44    pattern: K::PatternType,
45    depth: K::DepthType,
46    len: usize,
47    branches: [Branch<K, V>; BRANCHING_FACTOR],
48}
49
50impl<K: RadixKey + Debug, V: Clone + Debug> Debug for InnerMap<K, V> {
51    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
52        fmt.debug_struct("InnerMap")
53            .field("len", &self.len)
54            .field("branches", &self.branches)
55            .finish()
56    }
57}
58
59impl<K: RadixKey, V: Clone> InnerMap<K, V> {
60    /// The size of the map this `InnerMap` represents
61    pub fn len(&self) -> usize {
62        self.len
63    }
64    /// The depth of this `InnerMap`
65    pub fn depth(&self) -> usize {
66        self.depth.to_usize().unwrap_or(usize::MAX)
67    }
68    /// Whether this `InnerMap` is a root `InnerMap`, i.e. can be placed directly into a `Set`
69    pub fn is_root(&self) -> bool {
70        K::pattern_no(self.depth) == 0
71    }
72    /// Whether this `InnerMap` is empty
73    pub fn is_empty(&self) -> bool {
74        self.len == 0
75    }
76    /// Create an empty `InnerMap`
77    fn empty() -> InnerMap<K, V> {
78        InnerMap {
79            pattern: K::PatternType::default(),
80            depth: K::DepthType::zero(),
81            len: 0,
82            branches: InnerMap::empty_branches(),
83        }
84    }
85    /// Get the branches for an empty `InnerMap`
86    fn empty_branches() -> [Branch<K, V>; BRANCHING_FACTOR] {
87        Default::default()
88    }
89    /// Create an `InnerMap` representing a singleton
90    pub fn singleton(key: K, value: V) -> InnerMap<K, V> {
91        let depth = K::DepthType::zero();
92        let pattern = key.pattern(depth);
93        let bin = pattern_bin(pattern, depth);
94        let mut branches = InnerMap::empty_branches();
95        branches[bin] = Branch::Mapping(key, value);
96        InnerMap {
97            pattern,
98            depth,
99            len: 1,
100            branches,
101        }
102    }
103    /// Create a consed, leveled `InnerMap` holding two key-value pairs, guaranteed to have different keys
104    fn double_in<C: ConsCtx<K, V>>(
105        first: (K, V),
106        second: (K, V),
107        depth: K::DepthType,
108        ctx: &mut C,
109    ) -> Arc<InnerMap<K, V>> {
110        let first_pattern = first.0.pattern(depth);
111        let second_pattern = second.0.pattern(depth);
112        let diff = first_pattern.diff(second_pattern);
113        if diff.as_() >= K::PatternType::MAX_BITS {
114            unimplemented!("Level++")
115        } else {
116            let depth = round_depth(diff);
117            let len = 2;
118            let mut branches = InnerMap::empty_branches();
119            branches[pattern_bin(first_pattern, depth)] = Branch::Mapping(first.0, first.1);
120            branches[pattern_bin(second_pattern, depth)] = Branch::Mapping(second.0, second.1);
121            ctx.cons(InnerMap {
122                depth,
123                len,
124                branches,
125                pattern: first_pattern,
126            })
127        }
128    }
129    /// Convert an `InnerMap` into an `IdMap` within a given context
130    pub(super) fn into_idmap_in<C: ConsCtx<K, V>>(self, ctx: &mut C) -> IdMap<K, V> {
131        if !self.is_root() {
132            unimplemented!("Non root InnerMap conversion")
133        }
134        IdMap(self.cons_in(ctx))
135    }
136    /// Cons a tree in a given context
137    fn cons_in<C: ConsCtx<K, V>>(self, ctx: &mut C) -> Option<Arc<InnerMap<K, V>>> {
138        let premap = self.into_premap();
139        premap.into_inner_in(ctx)
140    }
141    /// Convert a tree to a branch in a given context
142    fn into_branch_in<C: ConsCtx<K, V>>(self, ctx: &mut C) -> Branch<K, V> {
143        let premap = self.into_premap();
144        premap.into_branch_in(ctx)
145    }
146    /// Convert a rooted `InnerMap` into a `PreMap<T>`
147    fn into_premap(mut self) -> PreMap<K, V> {
148        let level = K::pattern_no(self.depth);
149        let mut last_tree = &mut None;
150        let mut last_map = 0;
151        let mut no_maps = 0;
152        let mut tree_len = 0;
153        let mut no_trees = 0;
154        let depth = self.depth();
155        for (ix, branch) in self.branches.iter_mut().enumerate() {
156            match branch {
157                Branch::Tree(t) => {
158                    if let Some(tree) = t {
159                        tree_len += tree.len();
160                        no_trees += 1;
161                        let tree_depth = tree.depth();
162                        debug_assert!(
163                            tree_depth > depth || tree_depth == 0,
164                            "0 < Subtree #{} depth {} <= InnerMap depth {}",
165                            ix,
166                            tree_depth,
167                            depth
168                        );
169                        last_tree = t;
170                    }
171                }
172                Branch::Mapping(_, _) => {
173                    no_maps += 1;
174                    last_map = ix;
175                }
176            }
177        }
178        debug_assert_eq!(
179            tree_len + no_maps,
180            self.len,
181            "Tree length = {} + no_maps = {} != self.len = {}",
182            tree_len,
183            no_maps,
184            self.len
185        );
186        if last_tree.is_none() {
187            debug_assert_eq!(no_trees, 0, "Last tree is none, but there are trees")
188        } else {
189            debug_assert_ne!(no_trees, 0, "There are no trees, but the last tree is Some")
190        }
191        if no_trees == BRANCHING_FACTOR {
192            debug_assert_eq!(no_maps, 0, "There are no maps, since everything's a tree")
193        }
194        if no_maps == BRANCHING_FACTOR {
195            debug_assert_eq!(no_trees, 0, "There are no trees, since everything's a map")
196        }
197        match (last_tree, no_maps, no_trees) {
198            (None, 0, 0) => PreMap::Empty,
199            (None, 1, 0) => PreMap::Mapping(self, last_map),
200            (branch @ Some(_), 0, 1) => {
201                let tree = branch.as_ref().unwrap();
202                if K::pattern_no(tree.depth) <= level {
203                    let mut root = None;
204                    std::mem::swap(branch, &mut root);
205                    PreMap::Root(root.unwrap())
206                } else {
207                    PreMap::Ready(self)
208                }
209            }
210            _ => PreMap::Ready(self),
211        }
212    }
213    /// Mutate this `InnerMap`, given a `this` pointer to itself, returning a result and an optional new `InnerMap<K, V>`.
214    /// The returned `InnerMap` is always on the same level (i.e. `pattern_no`)
215    ///
216    /// Returns `None` if no changes were performed.
217    pub(super) fn mutate<B, M, R, C>(
218        &self,
219        this: &Arc<InnerMap<K, V>>,
220        key: B,
221        mutator: M,
222        ctx: &mut C,
223    ) -> (Option<InnerMap<K, V>>, R)
224    where
225        B: Borrow<K>,
226        M: FnOnce(B, Option<&V>) -> (Mutation<K, V>, R),
227        C: ConsCtx<K, V>,
228    {
229        let bkey = key.borrow();
230        let pattern = bkey.pattern(self.depth);
231        let residual = self.depth % K::PatternType::max_bits();
232        let diff = self.pattern.diff(pattern);
233        if diff < residual {
234            // The key cannot be in this bin, so handle that
235            // Note we *know* that this implies the key can be on this level!
236            let (mutation, result) = mutator(key, None);
237            let (key, value) = match mutation {
238                Mutation::Null => return (None, result),
239                Mutation::Remove => return (None, result),
240                Mutation::Update(_) => return (None, result),
241                Mutation::Insert(key, value) => (key, value),
242            };
243            let depth = round_depth(self.depth - residual + diff);
244            let this_bin = pattern_bin(self.pattern, depth);
245            let other_bin = pattern_bin(pattern, depth);
246            let mut branches = Self::empty_branches();
247            branches[this_bin] = Branch::Tree(Some(this.clone()));
248            branches[other_bin] = Branch::Mapping(key, value);
249            let inner = InnerMap {
250                len: self.len + 1,
251                depth,
252                branches,
253                pattern,
254            };
255            return (Some(inner), result);
256        }
257        // The key may be in a sub-bin
258        let bin = pattern_bin(pattern, self.depth);
259        let (mutated_branch, result) =
260            self.branches[bin].mutate(this, key, mutator, self.depth, ctx);
261        if let Some(mutated_branch) = mutated_branch {
262            let len = self.len - self.branches[bin].len() + mutated_branch.len();
263            let mut branches = Self::empty_branches();
264            for (ix, (new_branch, old_branch)) in
265                branches.iter_mut().zip(self.branches.iter()).enumerate()
266            {
267                if ix != bin {
268                    *new_branch = old_branch.clone_in(ctx)
269                }
270            }
271            branches[bin] = mutated_branch;
272            let inner = InnerMap {
273                pattern: self.pattern,
274                depth: self.depth,
275                len,
276                branches,
277            };
278            (Some(inner), result)
279        } else {
280            (None, result)
281        }
282    }
283    /// Get an element in this `InnerMap`
284    pub(super) fn get(&self, key: &K) -> Option<&V> {
285        let pattern = key.pattern(self.depth);
286        let depth: usize = self.depth.as_();
287        let residual = depth % K::PatternType::MAX_BITS;
288        let diff: usize = self.pattern.diff(pattern).as_();
289        if diff < residual {
290            return None;
291        }
292        let bin = pattern_bin(pattern, self.depth);
293        match &self.branches[bin] {
294            Branch::Mapping(entry_key, value) if entry_key == key => Some(value),
295            Branch::Tree(Some(tree)) => tree.get(key),
296            _ => None,
297        }
298    }
299    /// Mutate the values of an `InnerMap` in a given context, yielding a new `InnerMap` on the same level if anything changed
300    pub(super) fn mutate_vals_in<M, C>(
301        &self,
302        mutator: &mut M,
303        ctx: &mut C,
304    ) -> Option<InnerMap<K, V>>
305    where
306        M: UnaryMutator<K, V>,
307        C: ConsCtx<K, V>,
308    {
309        let mut branches = InnerMap::empty_branches();
310        let mut mutated_branches = [false; BRANCHING_FACTOR];
311        // Mutate branches
312        for ((new_branch, is_mutated), old_branch) in branches
313            .iter_mut()
314            .zip(mutated_branches.iter_mut())
315            .zip(self.branches.iter())
316        {
317            if let Some(branch) = old_branch.mutate_vals_in(mutator, ctx) {
318                *new_branch = branch;
319                *is_mutated = true;
320            }
321        }
322        // If no branches were mutated, early exit with no changes
323        if mutated_branches.iter().all(|x| !x) {
324            return None;
325        }
326        // Clone over unchanged branches
327        for ((new_branch, is_mutated), old_branch) in branches
328            .iter_mut()
329            .zip(mutated_branches.iter())
330            .zip(self.branches.iter())
331        {
332            if !*is_mutated {
333                *new_branch = old_branch.clone_in(ctx)
334            }
335        }
336        // Build a new `InnerMap` from the mutated branches
337        let len = branches.iter().map(|branch| branch.len()).sum();
338        let inner = InnerMap {
339            branches,
340            len,
341            pattern: self.pattern,
342            depth: self.depth,
343        };
344        Some(inner)
345    }
346    /// Join-mutate two maps by applying a binary mutator to their key intersection and unary
347    /// mutators to their left and right intersection.
348    pub(super) fn join_mutate_in<IM, LM, RM, C>(
349        &self,
350        other: &Self,
351        intersection_mutator: &mut IM,
352        left_mutator: &mut LM,
353        right_mutator: &mut RM,
354        ctx: &mut C,
355    ) -> BinaryResult<InnerMap<K, V>>
356    where
357        IM: BinaryMutator<K, V>,
358        LM: UnaryMutator<K, V>,
359        RM: UnaryMutator<K, V>,
360        C: ConsCtx<K, V>,
361    {
362        if self as *const _ == other as *const _ {
363            match intersection_mutator.kind() {
364                BinaryMutatorKind::Nilpotent => return New(InnerMap::empty()),
365                BinaryMutatorKind::Idempotent => return Ambi,
366                BinaryMutatorKind::Left => return Ambi,
367                BinaryMutatorKind::Right => return Ambi,
368                BinaryMutatorKind::Ambi => return Ambi,
369                BinaryMutatorKind::General => {}
370            }
371        }
372        use BinaryResult::*;
373        let mut branches = Self::empty_branches();
374        let mut sources = [New(()); BRANCHING_FACTOR];
375        let mut left_count = 0;
376        let mut right_count = 0;
377        let mut ambi_count = 0;
378        let mut new_count = 0;
379        let editor = branches.iter_mut().zip(sources.iter_mut());
380        let inputs = self.branches.iter().zip(other.branches.iter());
381        // Perform branch-wise merges
382        for ((branch, source), (left, right)) in editor.zip(inputs) {
383            match left.join_mutate_in(
384                right,
385                intersection_mutator,
386                left_mutator,
387                right_mutator,
388                self.depth,
389                ctx,
390            ) {
391                New(new_branch) => {
392                    *branch = new_branch;
393                    new_count += 1;
394                }
395                Left => {
396                    left_count += 1;
397                    *source = Left
398                }
399                Right => {
400                    right_count += 1;
401                    *source = Right
402                }
403                Ambi => {
404                    ambi_count += 1;
405                    *source = Ambi
406                }
407            }
408        }
409        // Short circuit left and right returns
410        if new_count == 0 {
411            match (left_count, right_count, ambi_count) {
412                (0, 0, _) => {
413                    debug_assert_eq!(ambi_count, BRANCHING_FACTOR);
414                    return Ambi;
415                }
416                (left_count, 0, ambi_count) => {
417                    debug_assert_eq!(left_count + ambi_count, BRANCHING_FACTOR);
418                    return Left;
419                }
420                (0, right_count, ambi_count) => {
421                    debug_assert_eq!(right_count + ambi_count, BRANCHING_FACTOR);
422                    return Right;
423                }
424                _ => {}
425            }
426        }
427
428        // Copy over left and right sources
429        let editor = branches.iter_mut().zip(sources.iter_mut());
430        let inputs = self.branches.iter().zip(other.branches.iter());
431        for ((branch, source), (left, right)) in editor.zip(inputs) {
432            match source {
433                New(()) => {}
434                Ambi => *branch = left.clone_in(ctx),
435                Left => *branch = left.clone_in(ctx),
436                Right => *branch = right.clone_in(ctx),
437            }
438        }
439        // Build a new `InnerMap` from the fused branches
440        let len = branches.iter().map(|branch| branch.len()).sum();
441        let inner = InnerMap {
442            branches,
443            len,
444            pattern: self.pattern,
445            depth: self.depth,
446        };
447        New(inner)
448    }
449}
450
451impl<K: RadixKey, V: Clone + Eq> InnerMap<K, V> {
452    /// Check whether two `InnerMap`s are recursively equal, i.e. contain the same data versus point to the same data
453    pub fn rec_eq(&self, other: &InnerMap<K, V>) -> bool {
454        if self as *const _ == other as *const _ {
455            return true;
456        }
457        self.depth == other.depth
458            && self.len == other.len
459            && self
460                .branches
461                .iter()
462                .zip(other.branches.iter())
463                .all(|(this, other)| this.rec_eq(other))
464    }
465    /// Check whether this map is a submap of another. A map is considered to be a submap of itself.
466    ///
467    /// If `cons` is true, this map is assumed to be hash-consed with the other
468    pub(super) fn is_submap(&self, other: &InnerMap<K, V>, cons: bool) -> bool {
469        if self as *const _ as *const u8 == other as *const _ as *const u8 {
470            // This is correct since both sides implement Eq
471            return true;
472        }
473        if self.len > other.len {
474            // Length heuristic
475            return false;
476        }
477        self.branches
478            .iter()
479            .zip(other.branches.iter())
480            .all(|(left, right)| left.is_submap(right, cons))
481    }
482    /// Check whether this map's key set is a subset of another map's keyset.
483    pub(super) fn domain_is_subset<U: Clone + Eq>(&self, other: &InnerMap<K, U>) -> bool {
484        if self as *const _ as *const u8 == other as *const _ as *const u8 {
485            // This is correct since both sides implement Eq
486            return true;
487        }
488        if self.len > other.len {
489            return false;
490        }
491        self.branches
492            .iter()
493            .zip(other.branches.iter())
494            .all(|(left, right)| left.domain_is_subset(right))
495    }
496    /// Check whether this map's domains intersect
497    pub(super) fn domains_intersect<U: Clone + Eq>(&self, other: &InnerMap<K, U>) -> bool {
498        if self as *const _ as *const u8 == other as *const _ as *const u8 {
499            // This is correct since both sides implement Eq
500            return true;
501        }
502        self.branches
503            .iter()
504            .zip(other.branches.iter())
505            .any(|(left, right)| left.domains_intersect(right))
506    }
507}
508
509/// A borrowed iterator over an `IdMap`
510#[derive(Debug, Clone)]
511pub struct IdMapIter<'a, K: RadixKey, V: Clone> {
512    inner_stack: Vec<(&'a InnerMap<K, V>, usize)>,
513}
514
515impl<'a, K: RadixKey, V: Clone> IdMapIter<'a, K, V> {
516    /// Create a new, empty iterator
517    pub fn empty() -> IdMapIter<'a, K, V> {
518        IdMapIter {
519            inner_stack: Vec::new(),
520        }
521    }
522    /// Add a new root to a given iterator
523    pub(super) fn root(&mut self, root: &'a InnerMap<K, V>) {
524        self.inner_stack.push((root, 0))
525    }
526}
527
528impl<'a, K: RadixKey, V: Clone> Iterator for IdMapIter<'a, K, V> {
529    type Item = (&'a K, &'a V);
530    fn next(&mut self) -> Option<(&'a K, &'a V)> {
531        loop {
532            let (top, ix) = self.inner_stack.last_mut()?;
533            if *ix >= BRANCHING_FACTOR {
534                self.inner_stack.pop();
535                continue;
536            }
537            match &top.branches[*ix] {
538                Branch::Mapping(key, value) => {
539                    *ix += 1;
540                    return Some((key, value));
541                }
542                Branch::Tree(None) => {
543                    *ix += 1;
544                }
545                Branch::Tree(Some(tree)) => {
546                    *ix += 1;
547                    self.inner_stack.push((&*tree, 0));
548                }
549            }
550        }
551    }
552}
553
554/// An iterator over an `IdMap`
555#[derive(Debug, Clone)]
556pub struct IdMapIntoIter<K: RadixKey, V: Clone> {
557    inner_stack: Vec<(Arc<InnerMap<K, V>>, usize)>,
558}
559
560impl<K: RadixKey, V: Clone> IdMapIntoIter<K, V> {
561    /// Create a new, empty iterator
562    pub fn empty() -> IdMapIntoIter<K, V> {
563        IdMapIntoIter {
564            inner_stack: Vec::new(),
565        }
566    }
567    /// Add a new root to a given iterator
568    pub(super) fn root(&mut self, root: Arc<InnerMap<K, V>>) {
569        self.inner_stack.push((root, 0))
570    }
571}
572
573impl<K: RadixKey, V: Clone> Iterator for IdMapIntoIter<K, V> {
574    type Item = (K, V);
575    fn next(&mut self) -> Option<(K, V)> {
576        loop {
577            let (top, ix) = self.inner_stack.last_mut()?;
578            if *ix >= BRANCHING_FACTOR {
579                self.inner_stack.pop();
580                continue;
581            }
582            match top.branches[*ix].clone() {
583                Branch::Mapping(key, value) => {
584                    *ix += 1;
585                    return Some((key, value));
586                }
587                Branch::Tree(None) => {
588                    *ix += 1;
589                }
590                Branch::Tree(Some(tree)) => {
591                    *ix += 1;
592                    self.inner_stack.push((tree, 0));
593                }
594            }
595        }
596    }
597}
598
599/// An `InnerMap` converted to a "pre-map"
600#[derive(Debug, Clone)]
601enum PreMap<K: RadixKey, V: Clone> {
602    /// An empty map
603    Empty,
604    /// A single non-null root tree entry
605    Root(Arc<InnerMap<K, V>>),
606    /// A single mapping
607    Mapping(InnerMap<K, V>, usize),
608    /// A map ready for direct conversion
609    Ready(InnerMap<K, V>),
610}
611
612impl<K: RadixKey, V: Clone> PreMap<K, V> {
613    pub fn into_inner_in<C: ConsCtx<K, V>>(self, ctx: &mut C) -> Option<Arc<InnerMap<K, V>>> {
614        use PreMap::*;
615        match self {
616            Empty => None,
617            Root(root) => Some(root),
618            Ready(map) | Mapping(map, _) => Some(ctx.cons(map)),
619        }
620    }
621    pub fn into_branch_in<C: ConsCtx<K, V>>(self, ctx: &mut C) -> Branch<K, V> {
622        use Branch::*;
623        use PreMap::{Mapping, *};
624        match self {
625            Empty => Tree(None),
626            Root(root) => Tree(Some(root)),
627            Mapping(mut map, ix) => {
628                let mut result = Tree(None);
629                std::mem::swap(&mut result, &mut map.branches[ix]);
630                result
631            }
632            Ready(map) => Tree(Some(ctx.cons(map))),
633        }
634    }
635}
636
637/// An branch in a layer of an `IdMap`, which is either empty, a mapping or a recursive tree
638#[derive(Debug, Clone)]
639enum Branch<K: RadixKey, V: Clone> {
640    /// A single mapping
641    Mapping(K, V),
642    /// A tree of recursive mappings
643    Tree(Option<Arc<InnerMap<K, V>>>),
644}
645
646impl<K: RadixKey, V: Clone> Default for Branch<K, V> {
647    fn default() -> Branch<K, V> {
648        Branch::Tree(None)
649    }
650}
651
652impl<K: RadixKey, V: Clone + Eq> Branch<K, V> {
653    /// Check whether two branches are recursively equal
654    pub fn rec_eq(&self, other: &Branch<K, V>) -> bool {
655        use Branch::*;
656        match (self, other) {
657            (Mapping(this_key, this_value), Mapping(other_key, other_value)) => {
658                this_key == other_key && this_value == other_value
659            }
660            (Tree(None), Tree(None)) => true,
661            (Tree(Some(this)), Tree(Some(other))) => this.rec_eq(other),
662            _ => false,
663        }
664    }
665    /// Check whether this branch is a submap of another. A map is considered to be a submap of itself.
666    ///
667    /// If `cons` is true, this map is assumed to be hash-consed with the other
668    fn is_submap(&self, other: &Branch<K, V>, cons: bool) -> bool {
669        use Branch::*;
670        match (self, other) {
671            (Tree(None), _) => true,
672            (_, Tree(None)) => false,
673            (Tree(Some(this)), Tree(Some(other))) => {
674                if Arc::ptr_eq(this, other) {
675                    true
676                } else if cons && this.len() == other.len() {
677                    false
678                } else {
679                    this.is_submap(other, cons)
680                }
681            }
682            (Tree(Some(this)), Mapping(key, value)) => {
683                if this.len() != 1 {
684                    false
685                } else {
686                    this.get(key) == Some(value)
687                }
688            }
689            (Mapping(key, value), Tree(Some(other))) => other.get(key) == Some(value),
690            (Mapping(left_key, left_value), Mapping(right_key, right_value)) => {
691                left_key == right_key && left_value == right_value
692            }
693        }
694    }
695    /// Check whether this branch's domain is a subset of another's.
696    fn domain_is_subset<U: Clone + Eq>(&self, other: &Branch<K, U>) -> bool {
697        use Branch::*;
698        match (self, other) {
699            (Tree(None), _) => true,
700            (_, Tree(None)) => false,
701            (Tree(Some(this)), Tree(Some(other))) => {
702                if Arc::as_ptr(this) as *const u8 == Arc::as_ptr(other) as *const u8 {
703                    true
704                } else {
705                    this.domain_is_subset(other)
706                }
707            }
708            (Tree(Some(this)), Mapping(key, _)) => {
709                if this.len() != 1 {
710                    false
711                } else {
712                    this.get(key).is_some()
713                }
714            }
715            (Mapping(key, _), Tree(Some(other))) => other.get(key).is_some(),
716            (Mapping(left_key, _), Mapping(right_key, _)) => left_key == right_key,
717        }
718    }
719    /// Check whether this branch's domain intersects another's
720    fn domains_intersect<U: Clone + Eq>(&self, other: &Branch<K, U>) -> bool {
721        use Branch::*;
722        match (self, other) {
723            (Tree(None), _) => false,
724            (_, Tree(None)) => false,
725            (Tree(Some(this)), Tree(Some(other))) => this.domains_intersect(other),
726            (Tree(Some(this)), Mapping(key, _)) => this.get(key).is_some(),
727            (Mapping(key, _), Tree(Some(other))) => other.get(key).is_some(),
728            (Mapping(left_key, _), Mapping(right_key, _)) => left_key == right_key,
729        }
730    }
731}
732
733impl<K: RadixKey, V: Clone> Branch<K, V> {
734    /// Clone a branch in a given context, consing appropriately
735    pub fn clone_in<C: ConsCtx<K, V>>(&self, ctx: &mut C) -> Branch<K, V> {
736        use Branch::*;
737        match self {
738            Mapping(key, value) => Mapping(key.clone(), value.clone()),
739            Tree(None) => Tree(None),
740            Tree(Some(tree)) => Tree(Some(ctx.cons_recursive(tree))),
741        }
742    }
743    /// Mutate this `Branch`, given a `this` pointer to itself, returning a result and an optional new `Branch<K, V>`.
744    ///
745    /// Returns `None` if no changes were performed.
746    pub(super) fn mutate<B, M, R, C>(
747        &self,
748        this: &Arc<InnerMap<K, V>>,
749        key: B,
750        mutator: M,
751        depth: K::DepthType,
752        ctx: &mut C,
753    ) -> (Option<Branch<K, V>>, R)
754    where
755        B: Borrow<K>,
756        M: FnOnce(B, Option<&V>) -> (Mutation<K, V>, R),
757        C: ConsCtx<K, V>,
758    {
759        use Branch::*;
760        let bkey = key.borrow();
761        match self {
762            Mapping(entry_key, value) if entry_key == bkey => {
763                let (mutation, result) = mutator(key, Some(value));
764                let mutated = match mutation {
765                    Mutation::Null => None,
766                    Mutation::Remove => Some(Tree(None)),
767                    Mutation::Insert(_, _) => None,
768                    Mutation::Update(value) => Some(Mapping(entry_key.clone(), value)),
769                };
770                (mutated, result)
771            }
772            Mapping(entry_key, entry_value) => {
773                let (mutation, result) = mutator(key, None);
774                let mutated = match mutation {
775                    Mutation::Null => None,
776                    Mutation::Remove => None,
777                    Mutation::Insert(key, value) => Some(Tree(Some(InnerMap::double_in(
778                        (key, value),
779                        (entry_key.clone(), entry_value.clone()),
780                        depth,
781                        ctx,
782                    )))),
783                    Mutation::Update(_) => None,
784                };
785                (mutated, result)
786            }
787            Tree(None) => {
788                let (mutation, result) = mutator(key, None);
789                let mutated = match mutation {
790                    Mutation::Null => None,
791                    Mutation::Remove => None,
792                    Mutation::Insert(key, value) => Some(Mapping(key, value)),
793                    Mutation::Update(_) => None,
794                };
795                (mutated, result)
796            }
797            Tree(Some(tree)) => {
798                let (try_tree, result) = tree.mutate(this, key, mutator, ctx);
799                let mutated = if let Some(tree) = try_tree {
800                    Some(tree.into_branch_in(ctx))
801                } else {
802                    None
803                };
804                (mutated, result)
805            }
806        }
807    }
808    /// Mutate the values stored in a branch, returning `Some` if anything changed
809    fn mutate_vals_in<M, C>(&self, mutator: &mut M, ctx: &mut C) -> Option<Branch<K, V>>
810    where
811        M: UnaryMutator<K, V>,
812        C: ConsCtx<K, V>,
813    {
814        use Branch::*;
815        use UnaryResult::*;
816        match mutator.kind() {
817            UnaryMutatorKind::Null => return None,
818            UnaryMutatorKind::Delete => {
819                return if self.is_empty() {
820                    None
821                } else {
822                    Some(Tree(None))
823                }
824            }
825            _ => {}
826        }
827        match self {
828            Mapping(key, value) => match mutator.mutate(key, value) {
829                New(None) => Some(Tree(None)),
830                New(Some(value)) => Some(Mapping(key.clone(), value)),
831                Old => None,
832            },
833            Tree(Some(tree)) => {
834                let mutated_tree = tree.mutate_vals_in(mutator, ctx)?;
835                Some(mutated_tree.into_branch_in(ctx))
836            }
837            Tree(None) => None,
838        }
839    }
840    /// Join-mutate two branches by applying a binary mutator to their key intersection and unary
841    /// mutators to their left and right intersection.
842    pub(super) fn join_mutate_in<IM, LM, RM, C>(
843        &self,
844        other: &Self,
845        intersection_mutator: &mut IM,
846        left_mutator: &mut LM,
847        right_mutator: &mut RM,
848        depth: K::DepthType,
849        ctx: &mut C,
850    ) -> BinaryResult<Branch<K, V>>
851    where
852        IM: BinaryMutator<K, V>,
853        LM: UnaryMutator<K, V>,
854        RM: UnaryMutator<K, V>,
855        C: ConsCtx<K, V>,
856    {
857        use BinaryResult::*;
858        use Branch::*;
859        match (self, other) {
860            (this, Tree(None)) => BinaryResult::or_left(this.mutate_vals_in(left_mutator, ctx)),
861            (Tree(None), other) => BinaryResult::or_right(other.mutate_vals_in(right_mutator, ctx)),
862            (Mapping(lkey, lvalue), Mapping(rkey, rvalue)) => {
863                if lkey == rkey {
864                    match intersection_mutator.kind() {
865                        BinaryMutatorKind::Left => Left,
866                        BinaryMutatorKind::Right => Right,
867                        BinaryMutatorKind::Ambi => Ambi,
868                        _ => intersection_mutator
869                            .mutate_bin(lkey, lvalue, rvalue)
870                            .map(|value| {
871                                if let Some(value) = value {
872                                    Mapping(lkey.clone(), value)
873                                } else {
874                                    Tree(None)
875                                }
876                            }),
877                    }
878                } else {
879                    use UnaryResult::{New as Nw, Old};
880                    let left = left_mutator.mutate(lkey, lvalue);
881                    let right = right_mutator.mutate(rkey, rvalue);
882                    let (left, right) = match (left, right) {
883                        (Old, Nw(None)) => return Left,
884                        (Nw(None), Old) => return Right,
885                        (Nw(None), Nw(None)) => return New(Tree(None)),
886                        (Nw(Some(left)), Nw(None)) => return New(Mapping(lkey.clone(), left)),
887                        (Nw(None), Nw(Some(right))) => return New(Mapping(rkey.clone(), right)),
888                        (Nw(Some(left)), Nw(Some(right))) => (left, right),
889                        (Nw(Some(left)), Old) => (left, rvalue.clone()),
890                        (Old, Nw(Some(right))) => (lvalue.clone(), right),
891                        (Old, Old) => (lvalue.clone(), rvalue.clone()),
892                    };
893                    let inner = InnerMap::double_in(
894                        (lkey.clone(), left),
895                        (rkey.clone(), right),
896                        depth,
897                        ctx,
898                    );
899                    New(Tree(Some(inner)))
900                }
901            }
902            (Tree(Some(this)), Tree(Some(other))) => this
903                .join_mutate_in(
904                    other,
905                    intersection_mutator,
906                    left_mutator,
907                    right_mutator,
908                    ctx,
909                )
910                .map(|tree| tree.into_branch_in(ctx)),
911            (Tree(Some(this)), Mapping(key, value)) => Branch::join_mutate_mapping(
912                (key, value),
913                this,
914                Swapped::ref_cast_mut(intersection_mutator),
915                // NOTE: right and left are swapped here, then we swap sides again
916                right_mutator,
917                left_mutator,
918                ctx,
919            )
920            .swap_sides(),
921            (Mapping(key, value), Tree(Some(other))) => Branch::join_mutate_mapping(
922                (key, value),
923                other,
924                intersection_mutator,
925                left_mutator,
926                right_mutator,
927                ctx,
928            ),
929        }
930    }
931    /// A helper to perform an intersection-mapped mutation on a mapping
932    pub fn join_mutate_mapping<IM, LM, RM, C>(
933        left: (&K, &V),
934        right: &Arc<InnerMap<K, V>>,
935        intersection_mutator: &mut IM,
936        left_mutator: &mut LM,
937        right_mutator: &mut RM,
938        ctx: &mut C,
939    ) -> BinaryResult<Branch<K, V>>
940    where
941        IM: BinaryMutator<K, V>,
942        LM: UnaryMutator<K, V>,
943        RM: UnaryMutator<K, V>,
944        C: ConsCtx<K, V>,
945    {
946        use BinaryResult::*;
947        use Branch::*;
948        use UnaryResult::{New as Nw, Old};
949        let key = left.0;
950        let left_value = left.1;
951        match right_mutator.kind() {
952            UnaryMutatorKind::Null => {
953                // The right tree is always left alone except for the target, so insert into it unchanged.
954                let (mutated_tree, ()) = right.mutate(
955                    right,
956                    key,
957                    |key, right_value| {
958                        use Mutation::*;
959                        let mutation = if let Some(right_value) = right_value {
960                            match intersection_mutator.mutate_bin(key, left_value, right_value) {
961                                New(Some(value)) => Update(value),
962                                New(None) => Remove,
963                                Left => Update(left_value.clone()),
964                                Right | Ambi => Null,
965                            }
966                        } else {
967                            match left_mutator.mutate(key, left_value) {
968                                Old => Insert(key.clone(), left_value.clone()),
969                                Nw(Some(value)) => Insert(key.clone(), value),
970                                Nw(None) => Null,
971                            }
972                        };
973                        (mutation, ())
974                    },
975                    ctx,
976                );
977                if let Some(mutated_tree) = mutated_tree {
978                    New(mutated_tree.into_branch_in(ctx))
979                } else {
980                    Right
981                }
982            }
983            UnaryMutatorKind::Delete => {
984                // The right tree is always deleted except for the target, so extract the target value and operate on that
985                let right_value = right.get(key);
986                if let Some(right_value) = right_value {
987                    match intersection_mutator.mutate_bin(key, left_value, right_value) {
988                        // The left is alone and unchanged
989                        Left | Ambi => Left,
990                        // Only the right remains, so return it as a new mapping
991                        Right => New(Mapping(key.clone(), right_value.clone())),
992                        // A new value has been created, so return it as a new mapping
993                        New(Some(value)) => New(Mapping(key.clone(), value)),
994                        // Everything has been deleted, so return the empty tree
995                        New(None) => New(Tree(None)),
996                    }
997                } else {
998                    match left_mutator.mutate(key, left_value) {
999                        // The left is alone and unchanged
1000                        Old => Left,
1001                        // The left has been modified, so return it as a new mapping
1002                        Nw(Some(left)) => New(Mapping(key.clone(), left)),
1003                        // Everything has been deleted, so return the empty tree
1004                        Nw(None) => New(Tree(None)),
1005                    }
1006                }
1007            }
1008            UnaryMutatorKind::General => {
1009                //TODO: new recursive subroutine needed here for maximum efficiency
1010                let mut left_mutated = false;
1011                let mut mutator = FilterMap::annotated(|entry_key, right_value| {
1012                    if entry_key == key {
1013                        left_mutated = true;
1014                        match intersection_mutator.mutate_bin(key, left_value, right_value) {
1015                            Ambi => Old,
1016                            Right => Old,
1017                            Left => Nw(Some(right_value.clone())),
1018                            New(n) => Nw(n),
1019                        }
1020                    } else {
1021                        right_mutator.mutate(entry_key, right_value)
1022                    }
1023                });
1024                let mutated_tree = right.mutate_vals_in(&mut mutator, ctx);
1025                let uninserted_tree = match (mutated_tree, left_mutated) {
1026                    (Some(tree), true) => return New(tree.into_branch_in(ctx)),
1027                    (Some(tree), false) => match tree.cons_in(ctx) {
1028                        Some(tree) => tree,
1029                        None => return Left,
1030                    },
1031                    (None, true) => return New(Tree(None)),
1032                    (None, false) => return Left,
1033                };
1034                let (inserted_tree, _) = uninserted_tree.mutate(
1035                    &uninserted_tree,
1036                    key,
1037                    |key, _value| (Mutation::Insert(key.clone(), left_value.clone()), ()),
1038                    ctx,
1039                );
1040                New(inserted_tree
1041                    .expect("If the left was not inserted, it can't be in the tree")
1042                    .into_branch_in(ctx))
1043            }
1044        }
1045    }
1046    /// Get whether this `Branch` is empty
1047    pub fn is_empty(&self) -> bool {
1048        matches!(self, Branch::Tree(None))
1049    }
1050    /// The number of mappings this `Branch` represents
1051    pub fn len(&self) -> usize {
1052        use Branch::*;
1053        match self {
1054            Mapping(_, _) => 1,
1055            Tree(None) => 0,
1056            Tree(Some(t)) => t.len(),
1057        }
1058    }
1059}
1060
1061impl<K: RadixKey + Hash, V: Clone + Hash> Hash for Branch<K, V> {
1062    fn hash<H: Hasher>(&self, hasher: &mut H) {
1063        match self {
1064            Branch::Mapping(key, value) => {
1065                // To make this `NonNull`, unlike the pointer
1066                0x34u8.hash(hasher);
1067                key.hash(hasher);
1068                value.hash(hasher)
1069            }
1070            Branch::Tree(None) => std::ptr::null::<*const InnerMap<K, V>>().hash(hasher),
1071            Branch::Tree(Some(tree)) => Arc::as_ptr(tree).hash(hasher),
1072        }
1073    }
1074}
1075
1076impl<K: RadixKey, V: Clone + Eq> PartialEq for Branch<K, V> {
1077    fn eq(&self, other: &Branch<K, V>) -> bool {
1078        use Branch::*;
1079        match (self, other) {
1080            (Mapping(key1, value1), Mapping(key2, value2)) => key1 == key2 && value1 == value2,
1081            (Tree(None), Tree(None)) => true,
1082            (Tree(Some(this)), Tree(Some(other))) => Arc::ptr_eq(this, other),
1083            _ => false,
1084        }
1085    }
1086}
1087
1088impl<K: RadixKey + Eq, V: Clone + Eq> Eq for Branch<K, V> {}
1089
1090impl<K: RadixKey + PartialOrd, V: Clone + Eq + PartialOrd> PartialOrd for Branch<K, V> {
1091    fn partial_cmp(&self, other: &Branch<K, V>) -> Option<Ordering> {
1092        use Branch::*;
1093        use Ordering::*;
1094        match (self, other) {
1095            (Mapping(key1, value1), Mapping(key2, value2)) => {
1096                (key1, value1).partial_cmp(&(key2, value2))
1097            }
1098            (Mapping(_, _), Tree(None)) => Some(Less),
1099            (Mapping(_, _), Tree(Some(_))) => Some(Less),
1100            (Tree(None), Mapping(_, _)) => Some(Greater),
1101            (Tree(None), Tree(None)) => Some(Equal),
1102            (Tree(None), Tree(Some(_))) => Some(Less),
1103            (Tree(Some(_)), Mapping(_, _)) => Some(Greater),
1104            (Tree(Some(_)), Tree(None)) => Some(Greater),
1105            (Tree(Some(tree1)), Tree(Some(tree2))) => {
1106                Arc::as_ptr(tree1).partial_cmp(&Arc::as_ptr(&tree2))
1107            }
1108        }
1109    }
1110}
1111
1112impl<K: RadixKey + Eq + Ord, V: Clone + Eq + Ord> Ord for Branch<K, V> {
1113    fn cmp(&self, other: &Branch<K, V>) -> Ordering {
1114        use Branch::*;
1115        use Ordering::*;
1116        match (self, other) {
1117            (Mapping(key1, value1), Mapping(key2, value2)) => (key1, value1).cmp(&(key2, value2)),
1118            (Mapping(_, _), Tree(None)) => Less,
1119            (Mapping(_, _), Tree(Some(_))) => Less,
1120            (Tree(None), Mapping(_, _)) => Greater,
1121            (Tree(None), Tree(None)) => Equal,
1122            (Tree(None), Tree(Some(_))) => Less,
1123            (Tree(Some(_)), Mapping(_, _)) => Greater,
1124            (Tree(Some(_)), Tree(None)) => Greater,
1125            (Tree(Some(tree1)), Tree(Some(tree2))) => Arc::as_ptr(tree1).cmp(&Arc::as_ptr(&tree2)),
1126        }
1127    }
1128}
1129
1130impl<K: RadixKey, V: Clone + Eq> PartialEq for InnerMap<K, V> {
1131    fn eq(&self, other: &InnerMap<K, V>) -> bool {
1132        self.branches == other.branches
1133    }
1134}
1135
1136impl<K: RadixKey, V: Clone + Eq> Eq for InnerMap<K, V> {}
1137
1138impl<K: RadixKey + PartialOrd, V: Clone + Eq + PartialOrd> PartialOrd for InnerMap<K, V> {
1139    fn partial_cmp(&self, other: &InnerMap<K, V>) -> Option<Ordering> {
1140        self.branches.partial_cmp(&other.branches)
1141    }
1142}
1143
1144impl<K: RadixKey + Eq + Ord, V: Clone + Eq + Ord> Ord for InnerMap<K, V> {
1145    fn cmp(&self, other: &InnerMap<K, V>) -> Ordering {
1146        self.branches.cmp(&other.branches)
1147    }
1148}
1149
1150impl<K: RadixKey + Hash, V: Clone + Hash> Hash for InnerMap<K, V> {
1151    fn hash<H: Hasher>(&self, hasher: &mut H) {
1152        self.branches.hash(hasher);
1153    }
1154}
1155
1156#[cfg(test)]
1157mod tests {
1158    use super::*;
1159
1160    #[test]
1161    fn basic_double_in_test() {
1162        let double = InnerMap::double_in((0b110, 3), (0b011, 2), 0, &mut ());
1163        assert_eq!(double.len(), 2);
1164        assert_eq!(double.depth(), 0);
1165        let double = InnerMap::double_in((0b111, 3), (0b011, 2), 0, &mut ());
1166        assert_eq!(double.len(), 2);
1167        assert_eq!(double.depth(), 2);
1168        let double = InnerMap::double_in((0b111, 3), (0b1111, 2), 0, &mut ());
1169        assert_eq!(double.len(), 2);
1170        assert_eq!(double.depth(), 2);
1171        let double = InnerMap::double_in((0b1111, 3), (0b11111, 2), 0, &mut ());
1172        assert_eq!(double.len(), 2);
1173        assert_eq!(double.depth(), 4);
1174    }
1175
1176    #[test]
1177    fn empty_inner_consing() {
1178        let empty = InnerMap::<u64, u64>::empty();
1179        assert_eq!(empty.len(), 0);
1180        assert!(empty.is_empty());
1181        assert_eq!(empty.clone().cons_in(&mut ()), None);
1182        assert_eq!(empty.into_idmap_in(&mut ()), IdMap::EMPTY);
1183    }
1184
1185    #[test]
1186    fn basic_branch_ordering() {
1187        use Branch::*;
1188        let sorted_branches = [
1189            Mapping(3, 5),
1190            Mapping(3, 7),
1191            Mapping(4, 5),
1192            Mapping(4, 7),
1193            Tree(None),
1194            Tree(Some(InnerMap::double_in((3, 5), (4, 7), 0, &mut ()))),
1195        ];
1196        for (i, l) in sorted_branches.iter().enumerate() {
1197            for (j, r) in sorted_branches.iter().enumerate() {
1198                assert_eq!(
1199                    i.cmp(&j),
1200                    l.cmp(r),
1201                    "Comparison of {:?}@{} {:?}@{} wrong",
1202                    l,
1203                    i,
1204                    r,
1205                    j
1206                );
1207                assert_eq!(
1208                    i.partial_cmp(&j),
1209                    l.partial_cmp(r),
1210                    "Partial comparison of {:?}@{} {:?}@{} wrong",
1211                    l,
1212                    i,
1213                    r,
1214                    j
1215                )
1216            }
1217        }
1218    }
1219
1220    #[test]
1221    fn basic_branch_joins() {
1222        use Branch::*;
1223        let map1 = Mapping(3, 6);
1224        let map2 = Mapping(3, 5);
1225        let map3 = Mapping(4, 13);
1226        assert_eq!(
1227            map1.join_mutate_in(
1228                &map2,
1229                &mut LeftMutator,
1230                &mut NullMutator,
1231                &mut NullMutator,
1232                0,
1233                &mut ()
1234            ),
1235            BinaryResult::Left
1236        );
1237        assert_eq!(
1238            map1.join_mutate_in(
1239                &map2,
1240                &mut RightMutator,
1241                &mut NullMutator,
1242                &mut NullMutator,
1243                0,
1244                &mut ()
1245            ),
1246            BinaryResult::Right
1247        );
1248        assert_eq!(
1249            map1.join_mutate_in(
1250                &map2,
1251                &mut AmbiMutator,
1252                &mut NullMutator,
1253                &mut NullMutator,
1254                0,
1255                &mut ()
1256            ),
1257            BinaryResult::Ambi
1258        );
1259        assert_eq!(
1260            map1.join_mutate_in(
1261                &map3,
1262                &mut LeftMutator,
1263                &mut DeleteMutator,
1264                &mut NullMutator,
1265                0,
1266                &mut ()
1267            ),
1268            BinaryResult::Right
1269        );
1270        assert_eq!(
1271            map1.join_mutate_in(
1272                &map3,
1273                &mut LeftMutator,
1274                &mut NullMutator,
1275                &mut DeleteMutator,
1276                0,
1277                &mut ()
1278            ),
1279            BinaryResult::Left
1280        );
1281        assert_eq!(
1282            map1.join_mutate_in(
1283                &map3,
1284                &mut LeftMutator,
1285                &mut DeleteMutator,
1286                &mut DeleteMutator,
1287                0,
1288                &mut ()
1289            ),
1290            BinaryResult::New(Tree(None))
1291        );
1292        assert!(map1
1293            .join_mutate_in(
1294                &map3,
1295                &mut LeftMutator,
1296                &mut NullMutator,
1297                &mut NullMutator,
1298                0,
1299                &mut ()
1300            )
1301            .unwrap()
1302            .rec_eq(&Tree(Some(InnerMap::double_in(
1303                (3, 6),
1304                (4, 13),
1305                0,
1306                &mut ()
1307            )))));
1308    }
1309}