From b1f9cd98b64308f9fdf186fa0e3adb57aaad8bda Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Mon, 30 Nov 2026 20:31:35 +0000 Subject: [PATCH 1/4] PrefixZipper: subtries on and off the prefix A location on the prefix holds "the rest of the prefix, then the source", with the source's root value at the end of the prefix; a location off the prefix holds nothing. The subtrie methods ignored both: * get_focus / get_focus_at / try_borrow_focus forwarded to the source zipper, which sits at its own root while the focus is on the prefix, so graft, join_into, meet_into, subtract_into, restrict, graft_src_at and graft_masked_branches from the prefix read the source's root node, and from off the prefix the whole source. * trie_ref_at_path handed the path to the source without stripping the rest of the prefix, and read the source off the prefix. * make_map / try_make_map returned the whole source off the prefix, and over an empty source lost the prefix chain that path_exists and child_count report (it is a dangling path). The source's root value was dropped unless graft_root_vals is on. The prefix part is now built as an owned trie over the source's nodes (stem_map), as get_trie_ref already did; try_borrow_focus answers None on the prefix, since no stored node backs it. A location on the prefix can't be expressed with the source's TrieRefT, so PrefixZipper's TrieRefT becomes TrieRef. --- src/prefix_zipper.rs | 217 ++++++++++++++++++++++++++++++++----------- 1 file changed, 162 insertions(+), 55 deletions(-) diff --git a/src/prefix_zipper.rs b/src/prefix_zipper.rs index 74f6bdf4..312bee69 100644 --- a/src/prefix_zipper.rs +++ b/src/prefix_zipper.rs @@ -3,7 +3,7 @@ use fast_slice_utils::{find_prefix_overlap, starts_with}; use crate::alloc::Allocator; use crate::utils::ByteMask; use crate::PathMap; -use crate::trie_node::TaggedNodeRef; +use crate::trie_node::{AbstractNodeRef, TaggedNodeRef}; use crate::zipper::*; #[derive(Clone)] @@ -229,6 +229,43 @@ impl<'prefix, Z> PrefixZipper<'prefix, Z> { } } +impl<'prefix, Z> PrefixZipper<'prefix, Z> { + /// Builds the subtrie at the location `stem.len()` bytes above the source's root along the + /// prefix: the `stem` path, then the source's `subtrie`, with the source's root value at the + /// end of `stem` + /// + /// The chain along `stem` exists whenever the source's root does, even with nothing below it, + /// so it is created as a dangling path in that case. Returns an empty map if the source's root + /// does not exist. + fn stem_map(&self, stem: &[u8], subtrie: PathMap) -> PathMap + where Z: ZipperSubtries + { + debug_assert!(!stem.is_empty()); + let mut map = PathMap::new_in(self.source.alloc()); + if self.source.path_exists() { + let mut wz = map.write_zipper_at_path(stem); + wz.graft_map(subtrie); + //The source's root value is strictly below the stem's root, so it is part of the + // subtrie regardless of whether `graft_map` carries root values + if let Some(val) = self.source.val() { + wz.set_val(val.clone()); + } + wz.create_path(); + } + map + } + + /// The [TrieRef] counterpart of [Self::stem_map] + fn stem_trie_ref<'a, V: Clone + Send + Sync + Unpin, A: Allocator + 'a>(&self, stem: &[u8], subtrie: Option>) -> TrieRef<'a, V, A> + where Z: ZipperSubtries + { + match subtrie { + Some(subtrie) if self.source.path_exists() => TrieRef::from(self.stem_map(stem, subtrie)), + _ => TrieRefOwned::new_invalid_in(self.source.alloc()).into(), + } + } +} + impl<'prefix, Z> ZipperConcrete for PrefixZipper<'prefix, Z> where Z: ZipperConcrete @@ -712,39 +749,20 @@ impl<'prefix, V: Clone + Send + Sync + Unpin, Z, A: Allocator> ZipperSubtries { - if prefix_path.len() > 0 { - let mut new_map = PathMap::new_in(self.source.alloc()); - let mut wz = new_map.write_zipper_at_path(prefix_path); - let leaf_map = match leaf_map { - Some(map) => map, - None => PathMap::new_in(self.source.alloc()) - }; - wz.graft_map(leaf_map); - Some(new_map) - } else { - leaf_map - } - }, - None => { - leaf_map - } + Some([]) => self.source.try_make_map(), + Some(stem) => Some(self.stem_map(stem, self.source.try_make_map()?)), + None => Some(PathMap::new_in(self.source.alloc())), } } fn trie_ref(&self) -> Option> { if !self.native_subtries() { return None } - if let Some(prefix_path) = self.prefix_path_below_focus() { - if prefix_path.len() > 0 { - return self.try_make_map().map(|temp_map| TrieRef::from(temp_map)) - } else { - return self.source.trie_ref() - } - } else { - Some(TrieRefOwned::new_invalid_in(self.source.alloc()).into()) + match self.prefix_path_below_focus() { + Some([]) => self.source.trie_ref(), + Some(stem) => Some(self.stem_trie_ref(stem, self.source.try_make_map())), + None => Some(TrieRefOwned::new_invalid_in(self.source.alloc()).into()), } } fn alloc(&self) -> A { self.source.alloc() } @@ -755,43 +773,64 @@ impl<'prefix, V: Clone + Send + Sync + Unpin, Z, A: Allocator> ZipperInfallibleS Z: ZipperInfallibleSubtries + ZipperSubtries { fn make_map(&self) -> PathMap { - let leaf_map = self.source.make_map(); match self.prefix_path_below_focus() { - Some(prefix_path) => { - if prefix_path.len() > 0 { - let mut new_map = PathMap::new_in(leaf_map.alloc.clone()); - let mut wz = new_map.write_zipper_at_path(prefix_path); - wz.graft_map(leaf_map); - new_map - } else { - leaf_map - } - }, - None => { - leaf_map - } + Some([]) => self.source.make_map(), + Some(stem) => self.stem_map(stem, self.source.make_map()), + None => PathMap::new_in(self.source.alloc()), } } fn get_trie_ref(&self) -> TrieRef<'_, V, A> { - if let Some(prefix_path) = self.prefix_path_below_focus() { - if prefix_path.len() > 0 { - let temp_map = self.make_map(); - return TrieRef::from(temp_map) - } else { - return self.source.get_trie_ref() - } + match self.prefix_path_below_focus() { + Some([]) => self.source.get_trie_ref(), + Some(stem) => self.stem_trie_ref(stem, Some(self.source.make_map())), + None => TrieRefOwned::new_invalid_in(self.source.alloc()).into(), + } + } + fn get_focus(&self) -> OpaqueAbstractNodeRef<'_, V, A> { + self.get_focus_at([]) + } + fn get_focus_at>(&self, path: K) -> OpaqueAbstractNodeRef<'_, V, A> { + let path = path.as_ref(); + let Some(rest_prefix) = self.prefix_path_below_focus() else { + return OpaqueAbstractNodeRef(AbstractNodeRef::None) + }; + if let Some(source_path) = path.strip_prefix(rest_prefix) { + //The location is the source's root or below it + self.source.get_focus_at(source_path) + } else if rest_prefix.starts_with(path) { + //The location is on the prefix, strictly above the source's root + let stem = self.stem_map(&rest_prefix[path.len()..], self.source.make_map()); + OpaqueAbstractNodeRef(stem.into_root().0.map_or(AbstractNodeRef::None, AbstractNodeRef::OwnedRc)) } else { - TrieRefOwned::new_invalid_in(self.source.alloc()).into() + OpaqueAbstractNodeRef(AbstractNodeRef::None) + } + } + fn try_borrow_focus(&self) -> Option> { + //The nodes along the prefix are not stored anywhere, so there is nothing to borrow + match self.position { + PrefixPos::Source => self.source.try_borrow_focus(), + _ => None, } } - fn get_focus(&self) -> OpaqueAbstractNodeRef<'_, V, A> { self.source.get_focus() } - fn get_focus_at>(&self, path: K) -> OpaqueAbstractNodeRef<'_, V, A> { self.source.get_focus_at(path) } - fn try_borrow_focus(&self) -> Option> { self.source.try_borrow_focus() } } -impl<'prefix, 'a, V: Clone + Send + Sync + 'a, Z, A: Allocator + 'a> ZipperReadOnlySubtries<'a, V, A> for PrefixZipper<'prefix, Z> where Z: ZipperReadOnlySubtries<'a, V, A>, Self: zipper_priv::ZipperReadOnlyPriv<'a, V, A> + ZipperSubtries { - type TrieRefT = >::TrieRefT; - fn trie_ref_at_path>(&self, path: K) -> Self::TrieRefT { self.source.trie_ref_at_path(path) } +impl<'prefix, 'a, V: Clone + Send + Sync + Unpin + 'a, Z, A: Allocator + 'a> ZipperReadOnlySubtries<'a, V, A> for PrefixZipper<'prefix, Z> where Z: ZipperReadOnlySubtries<'a, V, A>, Self: zipper_priv::ZipperReadOnlyPriv<'a, V, A> + ZipperSubtries { + //A location on the prefix has no counterpart in the source, so the source's own `TrieRefT` can't + // express it. It is built as an owned trie instead, as in `get_trie_ref` + type TrieRefT = TrieRef<'a, V, A>; + fn trie_ref_at_path>(&self, path: K) -> Self::TrieRefT { + let path = path.as_ref(); + let Some(rest_prefix) = self.prefix_path_below_focus() else { + return TrieRefOwned::new_invalid_in(self.source.alloc()).into() + }; + if let Some(source_path) = path.strip_prefix(rest_prefix) { + self.source.trie_ref_at_path(source_path).into() + } else if rest_prefix.starts_with(path) { + self.stem_trie_ref(&rest_prefix[path.len()..], self.source.try_make_map()) + } else { + TrieRefOwned::new_invalid_in(self.source.alloc()).into() + } + } } crate::zipper::impl_zipper_debug!( @@ -1217,4 +1256,72 @@ mod tests { assert_eq!(nested.origin_path(), &[5u8]); assert_eq!(nested.get_val(), Some(&1)); } + + fn dump(map: &PathMap) -> Vec<(Vec, Option)> { + let mut z = map.read_zipper(); + let mut out = vec![]; + while z.to_next_step() { + out.push((z.path().to_vec(), z.get_val().cloned())); + } + out + } + + /// Subtries taken on the prefix are "the rest of the prefix, then the source", with the source's + /// root value at the end of the prefix; off the prefix there is nothing + #[test] + fn prefix_zipper_subtries_from_the_prefix() { + use crate::utils::ByteMask; + use crate::zipper::*; + let src: PathMap = [(&[][..], 5u64), (&[7u8][..], 1)].into_iter().collect(); + let view = vec![(vec![1], None), (vec![1, 2], Some(5)), (vec![1, 2, 7], Some(1))]; + let mut pz = PrefixZipper::new(&[1u8, 2][..], src.read_zipper()); + + assert_eq!(dump(&pz.make_map()), view); + assert_eq!(dump(&pz.try_make_map().unwrap()), view); + assert_eq!(dump(&pz.get_trie_ref().make_map()), view); + let mut dst = PathMap::::new(); + dst.write_zipper().graft(&pz); + assert_eq!(dump(&dst), view); + let mut dst = PathMap::::new(); + dst.write_zipper().join_into(&pz); + assert_eq!(dump(&dst), view); + //`get_focus_at` on the prefix, and at the source's root + let mut dst = PathMap::::new(); + dst.write_zipper().graft_src_at(&pz, &[1u8]); + assert_eq!(dump(&dst), vec![(vec![2], Some(5)), (vec![2, 7], Some(1))]); + let mut dst = PathMap::::new(); + dst.write_zipper().graft_src_at(&pz, &[1u8, 2]); + assert_eq!(dump(&dst), vec![(vec![7], Some(1))]); + + let t = pz.trie_ref_at_path(&[1u8]); + assert!(t.path_exists()); + assert_eq!(t.val(), None); + assert_eq!(t.child_mask(), ByteMask::from(2)); + assert_eq!(pz.trie_ref_at_path(&[1u8, 2]).val(), Some(&5)); + assert_eq!(pz.trie_ref_at_path(&[1u8, 2, 7]).val(), Some(&1)); + assert!(!pz.trie_ref_at_path(&[1u8, 3]).path_exists()); + assert!(!pz.trie_ref_at_path(&[7u8]).path_exists()); + //There is no stored node to borrow on the prefix + assert!(pz.try_borrow_focus().is_none()); + + //Off the prefix + pz.descend_to_byte(0); + assert!(dump(&pz.make_map()).is_empty()); + assert!(!pz.get_trie_ref().path_exists()); + assert!(!pz.trie_ref_at_path(&[]).path_exists()); + let mut dst: PathMap = [(&[3u8][..], 3u64)].into_iter().collect(); + dst.write_zipper().graft(&pz); + assert!(dump(&dst).is_empty()); + + //Over an empty source the prefix exists, as a dangling path + let empty = PathMap::::new(); + let pz = PrefixZipper::new(&[2u8, 3][..], empty.read_zipper()); + assert!(pz.path_exists()); + let stem = vec![(vec![2], None), (vec![2, 3], None)]; + assert_eq!(dump(&pz.make_map()), stem); + let mut dst = PathMap::::new(); + dst.write_zipper().graft(&pz); + assert_eq!(dump(&dst), stem); + assert!(pz.trie_ref_at_path(&[2u8, 3]).path_exists()); + } } From ff7db5a76ae0254dd492c5ce3aceeb770a3c48e9 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Mon, 30 Nov 2026 20:31:43 +0000 Subject: [PATCH 2/4] PrefixZipper: moves at the seam and one byte off the prefix * descend_until (and descend_until_max_bytes) consumed the rest of the prefix and kept descending into the source even when the source's root has a value or branches; it now stops there. * to_next_sibling_byte / to_prev_sibling_byte returned None one byte off the prefix, where the next prefix byte is a sibling, so to_next_step and to_prev_step from there stopped instead of moving to the next existing path. * to_next_k_path from off the prefix gave up, although the prefix may sort after the focus and hold the next location at that depth. * val_count off the prefix reported the source's whole count instead of 0. --- src/prefix_zipper.rs | 144 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 130 insertions(+), 14 deletions(-) diff --git a/src/prefix_zipper.rs b/src/prefix_zipper.rs index 312bee69..a9b4f88c 100644 --- a/src/prefix_zipper.rs +++ b/src/prefix_zipper.rs @@ -200,6 +200,38 @@ impl<'prefix, Z> PrefixZipper<'prefix, Z> } } +impl<'prefix, Z> PrefixZipper<'prefix, Z> + where + Z: ZipperMoving +{ + /// Moves to the next (`NEXT`) or previous sibling byte + fn to_sibling_byte(&mut self) -> Option { + match self.position { + PrefixPos::Source => { + let byte = if NEXT { self.source.to_next_sibling_byte() } else { self.source.to_prev_sibling_byte() }?; + *self.path.last_mut().unwrap() = byte; + Some(byte) + }, + //One byte off the prefix, the parent is on the prefix, and its only child is the next + // prefix byte + PrefixPos::PrefixOff { valid, invalid: 1 } if self.source.path_exists() => { + let byte = self.prefix[self.origin_depth + valid]; + let focus_byte = self.path.last_mut().unwrap(); + if (NEXT && byte > *focus_byte) || (!NEXT && byte < *focus_byte) { + *focus_byte = byte; + self.set_valid(valid + 1); + Some(byte) + } else { + None + } + }, + //A focus on the prefix is its parent's only child, and further off the prefix the + // parent doesn't exist + _ => None, + } + } +} + impl<'prefix, Z> PrefixZipper<'prefix, Z> { /// Private function to deal with `at` methods, that take paths relative to the zipper focus #[inline] @@ -435,7 +467,11 @@ impl<'prefix, Z> ZipperMoving for PrefixZipper<'prefix, Z> } fn val_count(&self) -> usize { - self.source.val_count() + match self.position { + //Off the prefix there is nothing, but the source is still at its root + PrefixPos::PrefixOff {..} => 0, + _ => self.source.val_count(), + } } fn descend_to_existing>(&mut self, patho: K) -> usize { @@ -504,28 +540,23 @@ impl<'prefix, Z> ZipperMoving for PrefixZipper<'prefix, Z> //Consuming the remainder of the prefix is itself a movement, so it must be reflected in the // return value even when the source zipper can't descend any further let descended_prefix = self.consume_prefix(obs); + //The source's root ends the descent like any other location if it has a value or doesn't + // have exactly one child + if descended_prefix && (self.source.is_val() || self.source.child_count() != 1) { + return true; + } //Fan the descended bytes out to our own path buffer as well as the caller's observer descended_prefix | self.source.descend_until_observed(&mut (&mut self.path, &mut *obs)) } #[inline] fn to_next_sibling_byte(&mut self) -> Option { - if !self.position.is_source() { - return None; - } - let byte = self.source.to_next_sibling_byte()?; - *self.path.last_mut().unwrap() = byte; - Some(byte) + self.to_sibling_byte::() } #[inline] fn to_prev_sibling_byte(&mut self) -> Option { - if !self.position.is_source() { - return None; - } - let byte = self.source.to_prev_sibling_byte()?; - *self.path.last_mut().unwrap() = byte; - Some(byte) + self.to_sibling_byte::() } fn ascend(&mut self, steps: usize) -> usize { let ascended = match self.ascend_n(steps) { @@ -654,7 +685,21 @@ impl<'prefix, Z> ZipperIteration for PrefixZipper<'prefix, Z> obs.ascend(depth); return false; } - if self.position.is_invalid() { + if let PrefixPos::PrefixOff { valid, invalid } = self.position { + //Off the prefix, the only location that can follow the focus is on the prefix: it must + // sort after the focus, and the common root must be on the prefix (where the focus left + // it, or above) + let mismatch = self.origin_depth + valid; + if k >= invalid && self.path[mismatch] < self.prefix[mismatch] && self.source.path_exists() { + self.ascend(invalid); + obs.ascend(invalid); + if self.descend_first_k_path_observed(invalid, obs) { + return true; + } + self.ascend(k - invalid); + obs.ascend(k - invalid); + return false; + } self.ascend(k); obs.ascend(k); return false; @@ -1324,4 +1369,75 @@ mod tests { assert_eq!(dump(&dst), stem); assert!(pz.trie_ref_at_path(&[2u8, 3]).path_exists()); } + + /// Moves that end, start or look one byte off the prefix, or stop at the source's root + #[test] + fn prefix_zipper_moves_around_the_prefix() { + use crate::utils::ByteMask; + use crate::zipper::*; + //`descend_until` stops at the source's root when it has a value or branches + let src: PathMap = [(&[][..], 5u64), (&[3u8, 4][..], 6)].into_iter().collect(); + let mut pz = PrefixZipper::new(&[1u8][..], src.read_zipper()); + assert!(pz.descend_until()); + assert_eq!(pz.path(), &[1]); + assert_eq!(pz.val(), Some(&5)); + assert!(pz.descend_until()); + assert_eq!(pz.path(), &[1, 3, 4]); + let src: PathMap = [(&[3u8][..], 1u64), (&[4u8][..], 2)].into_iter().collect(); + let mut pz = PrefixZipper::new(&[1u8, 2][..], src.read_zipper()); + assert!(pz.descend_until_max_bytes(5)); + assert_eq!(pz.path(), &[1, 2]); + assert_eq!(pz.child_count(), 2); + + //One byte off the prefix, the next prefix byte is a sibling + let src: PathMap = [(&[9u8][..], 1u64), (&[8u8][..], 2)].into_iter().collect(); + let mut pz = PrefixZipper::new(&[2u8][..], src.read_zipper()); + pz.descend_to_byte(0); + assert_eq!(pz.to_next_sibling_byte(), Some(2)); + assert_eq!(pz.path(), &[2]); + assert_eq!(pz.child_mask(), ByteMask::from_iter([8u8, 9])); + assert_eq!(pz.to_next_sibling_byte(), None); + assert_eq!(pz.to_prev_sibling_byte(), None); + pz.reset(); + pz.descend_to_byte(3); + assert_eq!(pz.to_next_sibling_byte(), None); + assert_eq!(pz.to_prev_sibling_byte(), Some(2)); + assert_eq!(pz.get_val_at(&[9u8]), Some(&1)); + pz.reset(); + pz.descend_to(&[0u8, 0]); + assert_eq!(pz.to_next_sibling_byte(), None); + pz.reset(); + pz.descend_to_byte(0); + assert!(pz.to_next_step()); + assert_eq!(pz.path(), &[2]); + pz.reset(); + pz.descend_to_byte(3); + assert!(pz.to_prev_step()); + assert_eq!(pz.path(), &[2, 9]); + pz.reset(); + pz.descend_to_byte(1); + assert!(pz.to_next_k_path(1)); + assert_eq!(pz.path(), &[2]); + pz.reset(); + pz.descend_to(&[1u8, 0]); + assert!(pz.to_next_k_path(2)); + assert_eq!(pz.path(), &[2, 8]); + pz.reset(); + pz.descend_to(&[1u8, 0]); + assert!(!pz.to_next_k_path(1)); + assert_eq!(pz.path(), &[1]); + pz.reset(); + pz.descend_to_byte(3); + assert!(!pz.to_next_k_path(1)); + assert_eq!(pz.path(), &[]); + + //`val_count` off the prefix + pz.reset(); + assert_eq!(pz.val_count(), 2); + pz.descend_to_byte(0); + assert_eq!(pz.val_count(), 0); + pz.reset(); + pz.descend_to(&[2u8, 9]); + assert_eq!(pz.val_count(), 1); + } } From f78a8f5f9611bfdfe5601de8478ebf8a4016431f Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Tue, 1 Dec 2026 20:12:46 +0000 Subject: [PATCH 3/4] PrefixZipper: build prefix stems directly and streamline seam moves * Build prefix subtrie nodes directly with wrap_stem_node (LineListNode / DenseByteNode) instead of allocating a temporary PathMap + WriteZipper, grafting, double-cloning root values under graft_root_vals, and calling create_path. Short-circuit on !source.path_exists() before touching get_focus / trie_ref / val, use get_focus directly for ZipperInfallibleSubtries, and propagate None from source.trie_ref() in ZipperSubtries::trie_ref. * Implement descend_until_max_bytes_observed natively on PrefixZipper to avoid default TruncatingObserver overshoot-and-ascend and forward directly to source when in PrefixPos::Source. * Clean up prefix/source dispatch in consume_prefix, descend_until_observed, descend_first_k_path_observed, to_next_k_path_observed, to_next_val_observed, to_sibling_byte, val_count, try_borrow_focus, get_focus_at, and trie_ref_at_path. --- src/prefix_zipper.rs | 416 +++++++++++++++++++++++++++++-------------- 1 file changed, 278 insertions(+), 138 deletions(-) diff --git a/src/prefix_zipper.rs b/src/prefix_zipper.rs index a9b4f88c..00accf5f 100644 --- a/src/prefix_zipper.rs +++ b/src/prefix_zipper.rs @@ -3,7 +3,7 @@ use fast_slice_utils::{find_prefix_overlap, starts_with}; use crate::alloc::Allocator; use crate::utils::ByteMask; use crate::PathMap; -use crate::trie_node::{AbstractNodeRef, TaggedNodeRef}; +use crate::trie_node::{AbstractNodeRef, TaggedNodeRef, TrieNodeODRc}; use crate::zipper::*; #[derive(Clone)] @@ -120,21 +120,21 @@ impl<'prefix, Z> PrefixZipper<'prefix, Z> /// Descends over whatever remains of the `prefix`, leaving the focus at the source's root /// /// Returns `true` if the focus moved. The descended bytes are appended to this zipper's path - /// buffer and reported to `obs`. Does nothing if the focus is already within the source. + /// buffer and reported to `obs`. Does nothing if the focus is not on the prefix or if the + /// source's root does not exist. + #[inline] fn consume_prefix(&mut self, obs: &mut Obs) -> bool { + let PrefixPos::Prefix { valid } = self.position else { + return false; + }; if !self.source.path_exists() { return false; } - match self.position.prefixed_depth() { - Some(prefixed_depth) => { - let prefix_rest = &self.prefix[self.origin_depth + prefixed_depth..]; - self.path.extend_from_slice(prefix_rest); - obs.descend_to(prefix_rest); - self.position = PrefixPos::Source; - true - }, - None => false, - } + let prefix_rest = &self.prefix[self.origin_depth + valid..]; + self.path.extend_from_slice(prefix_rest); + obs.descend_to(prefix_rest); + self.position = PrefixPos::Source; + true } fn ascend_n(&mut self, mut steps: usize) -> Result<(), usize> { @@ -198,12 +198,7 @@ impl<'prefix, Z> PrefixZipper<'prefix, Z> self.set_valid(0); Some(ascended) } -} -impl<'prefix, Z> PrefixZipper<'prefix, Z> - where - Z: ZipperMoving -{ /// Moves to the next (`NEXT`) or previous sibling byte fn to_sibling_byte(&mut self) -> Option { match self.position { @@ -214,10 +209,11 @@ impl<'prefix, Z> PrefixZipper<'prefix, Z> }, //One byte off the prefix, the parent is on the prefix, and its only child is the next // prefix byte - PrefixPos::PrefixOff { valid, invalid: 1 } if self.source.path_exists() => { + PrefixPos::PrefixOff { valid, invalid: 1 } => { let byte = self.prefix[self.origin_depth + valid]; let focus_byte = self.path.last_mut().unwrap(); - if (NEXT && byte > *focus_byte) || (!NEXT && byte < *focus_byte) { + let in_dir = if NEXT { byte > *focus_byte } else { byte < *focus_byte }; + if in_dir && self.source.path_exists() { *focus_byte = byte; self.set_valid(valid + 1); Some(byte) @@ -232,7 +228,7 @@ impl<'prefix, Z> PrefixZipper<'prefix, Z> } } -impl<'prefix, Z> PrefixZipper<'prefix, Z> { +impl<'prefix, Z> PrefixZipper<'prefix, Z> { /// Private function to deal with `at` methods, that take paths relative to the zipper focus #[inline] fn adjust_lookup_path<'a>(&'a self, path: &'a [u8]) -> Option<&'a [u8]> { @@ -259,42 +255,90 @@ impl<'prefix, Z> PrefixZipper<'prefix, Z> { PrefixPos::Source => Some(&[]), } } -} -impl<'prefix, Z> PrefixZipper<'prefix, Z> { - /// Builds the subtrie at the location `stem.len()` bytes above the source's root along the - /// prefix: the `stem` path, then the source's `subtrie`, with the source's root value at the - /// end of `stem` - /// - /// The chain along `stem` exists whenever the source's root does, even with nothing below it, - /// so it is created as a dangling path in that case. Returns an empty map if the source's root - /// does not exist. - fn stem_map(&self, stem: &[u8], subtrie: PathMap) -> PathMap + /// Builds the root node of the subtrie `stem.len()` bytes above the source's root: the `stem` + /// path, then `child`, with the source's root value at the end of `stem` (or a dangling path + /// if both are empty) + fn wrap_stem_node( + &self, + stem: &[u8], + child: Option>, + ) -> TrieNodeODRc where Z: ZipperSubtries { debug_assert!(!stem.is_empty()); - let mut map = PathMap::new_in(self.source.alloc()); - if self.source.path_exists() { - let mut wz = map.write_zipper_at_path(stem); - wz.graft_map(subtrie); - //The source's root value is strictly below the stem's root, so it is part of the - // subtrie regardless of whether `graft_map` carries root values - if let Some(val) = self.source.val() { - wz.set_val(val.clone()); + let alloc = self.source.alloc(); + let child = child.filter(|node| !node.as_tagged().node_is_empty()); + let val = self.source.val().cloned(); + #[cfg(not(feature = "all_dense_nodes"))] + { + use crate::line_list_node::LineListNode; + use crate::trie_node::TrieNode; + let mut node = LineListNode::new_in(alloc.clone()); + match (child, val) { + (Some(child), Some(val)) => { + //A list node holds a value and onward child at the same key only at length 1 + let (head, last) = stem.split_at(stem.len() - 1); + node.node_set_val(last, val).unwrap_or_else(|_| unreachable!()); + node.node_set_branch(last, child).unwrap_or_else(|_| unreachable!()); + let leaf = TrieNodeODRc::new_in(node, alloc.clone()); + if head.is_empty() { + return leaf; + } + let mut parent = LineListNode::new_in(alloc.clone()); + parent.node_set_branch(head, leaf).unwrap_or_else(|_| unreachable!()); + TrieNodeODRc::new_in(parent, alloc) + }, + (None, Some(val)) => { + node.node_set_val(stem, val).unwrap_or_else(|_| unreachable!()); + TrieNodeODRc::new_in(node, alloc) + }, + (child, None) => { + node.node_set_branch(stem, child.unwrap_or_else(TrieNodeODRc::new_empty)) + .unwrap_or_else(|_| unreachable!()); + TrieNodeODRc::new_in(node, alloc) + }, + } + } + #[cfg(feature = "all_dense_nodes")] + { + use crate::dense_byte_node::DenseByteNode; + let (&last, head) = stem.split_last().unwrap(); + let mut leaf = DenseByteNode::with_capacity_in(1, alloc.clone()); + match (child, val) { + (None, None) => { leaf.set_dangling_cf(last); }, + (child, val) => { + if let Some(child) = child { leaf.set_child(last, child); } + if let Some(val) = val { leaf.set_val(last, val); } + }, + } + let mut node = TrieNodeODRc::new_in(leaf, alloc.clone()); + for &b in head.iter().rev() { + let mut parent = DenseByteNode::with_capacity_in(1, alloc.clone()); + parent.set_child(b, node); + node = TrieNodeODRc::new_in(parent, alloc.clone()); } - wz.create_path(); + node } - map } - /// The [TrieRef] counterpart of [Self::stem_map] - fn stem_trie_ref<'a, V: Clone + Send + Sync + Unpin, A: Allocator + 'a>(&self, stem: &[u8], subtrie: Option>) -> TrieRef<'a, V, A> + /// Builds the subtrie root node for `stem` from an infallible source, or `None` if the + /// source's root does not exist + fn stem_node(&self, stem: &[u8]) -> Option> + where Z: ZipperInfallibleSubtries + ZipperSubtries + { + self.source.path_exists().then(|| self.wrap_stem_node(stem, self.source.get_focus().into_option())) + } + + /// Fallible counterpart of [Self::stem_node] for [ZipperSubtries] + fn try_stem_node(&self, stem: &[u8]) -> Option>> where Z: ZipperSubtries { - match subtrie { - Some(subtrie) if self.source.path_exists() => TrieRef::from(self.stem_map(stem, subtrie)), - _ => TrieRefOwned::new_invalid_in(self.source.alloc()).into(), + if !self.source.path_exists() { + return Some(None); } + let child = self.source.trie_ref()?.get_focus().into_option(); + Some(Some(self.wrap_stem_node(stem, child))) } } @@ -467,11 +511,7 @@ impl<'prefix, Z> ZipperMoving for PrefixZipper<'prefix, Z> } fn val_count(&self) -> usize { - match self.position { - //Off the prefix there is nothing, but the source is still at its root - PrefixPos::PrefixOff {..} => 0, - _ => self.source.val_count(), - } + if self.position.is_invalid() { 0 } else { self.source.val_count() } } fn descend_to_existing>(&mut self, patho: K) -> usize { @@ -537,18 +577,42 @@ impl<'prefix, Z> ZipperMoving for PrefixZipper<'prefix, Z> if self.position.is_invalid() { return false; } - //Consuming the remainder of the prefix is itself a movement, so it must be reflected in the - // return value even when the source zipper can't descend any further let descended_prefix = self.consume_prefix(obs); - //The source's root ends the descent like any other location if it has a value or doesn't - // have exactly one child - if descended_prefix && (self.source.is_val() || self.source.child_count() != 1) { + //The source's root ends the descent if it holds a value; if it branches or is a leaf, + // the source's own `descend_until_observed` is already a no-op + if descended_prefix && self.source.is_val() { return true; } - //Fan the descended bytes out to our own path buffer as well as the caller's observer descended_prefix | self.source.descend_until_observed(&mut (&mut self.path, &mut *obs)) } + fn descend_until_max_bytes_observed(&mut self, max_bytes: usize, obs: &mut Obs) -> bool { + if max_bytes == 0 { + return false; + } + let (descended_prefix, remaining) = match self.position { + PrefixPos::Source => (false, max_bytes), + PrefixPos::Prefix { valid } => { + if !self.source.path_exists() { + return false; + } + let rest = &self.prefix[self.origin_depth + valid..]; + let taken_len = max_bytes.min(rest.len()); + let taken = &rest[..taken_len]; + self.path.extend_from_slice(taken); + obs.descend_to(taken); + self.set_valid(valid + taken_len); + let remaining = max_bytes - taken_len; + if remaining == 0 || self.source.is_val() { + return true; + } + (true, remaining) + }, + PrefixPos::PrefixOff {..} => return false, + }; + descended_prefix | self.source.descend_until_max_bytes_observed(remaining, &mut (&mut self.path, &mut *obs)) + } + #[inline] fn to_next_sibling_byte(&mut self) -> Option { self.to_sibling_byte::() @@ -625,7 +689,10 @@ impl<'prefix, Z> ZipperIteration for PrefixZipper<'prefix, Z> self.ascend(invalid); obs.ascend(invalid); } - if self.consume_prefix(obs) && self.source.is_val() { + if !self.consume_prefix(obs) { + break 'search false; + } + if self.source.is_val() { break 'search true; } } @@ -643,38 +710,46 @@ impl<'prefix, Z> ZipperIteration for PrefixZipper<'prefix, Z> if self.position.is_invalid() { return false; } - //As in `descend_until`, consuming the prefix is movement in its own right - let descended_prefix = self.consume_prefix(obs); - descended_prefix | self.source.descend_last_path_observed(&mut (&mut self.path, &mut *obs)) + self.consume_prefix(obs) | self.source.descend_last_path_observed(&mut (&mut self.path, &mut *obs)) } fn descend_first_k_path_observed(&mut self, k: usize, obs: &mut Obs) -> bool { if k == 0 { return false; } - if self.position.is_invalid() || !self.source.path_exists() { - return false; - } - //The prefix is a single forced path, so the bytes it contributes always exist and never - //branch. Descend as much of `k` as the prefix covers, then ask the source for the rest. - let prefix_rest = match self.position.prefixed_depth() { - Some(prefixed_depth) => self.prefix.len() - self.origin_depth - prefixed_depth, - None => 0, - }; - if k <= prefix_rest { - let taken = &self.prefix[self.path.len()..self.path.len() + k]; - self.path.extend_from_slice(taken); - obs.descend_to(taken); - self.set_valid(self.path.len() - self.origin_depth); - return true - } - self.consume_prefix(obs); - if self.source.descend_first_k_path_observed(k - prefix_rest, &mut (&mut self.path, &mut *obs)) { - true - } else { - self.ascend(prefix_rest); - obs.ascend(prefix_rest); - false + match self.position { + PrefixPos::PrefixOff {..} => false, + PrefixPos::Source => { + self.source.descend_first_k_path_observed(k, &mut (&mut self.path, &mut *obs)) + }, + PrefixPos::Prefix { valid } => { + if !self.source.path_exists() { + return false; + } + //The prefix is a single forced path, so the bytes it contributes always exist and + // never branch. Descend as much of `k` as the prefix covers, then ask the source + // for the rest. + let rest = &self.prefix[self.origin_depth + valid..]; + let rest_len = rest.len(); + if k <= rest_len { + let taken = &rest[..k]; + self.path.extend_from_slice(taken); + obs.descend_to(taken); + self.set_valid(valid + k); + return true; + } + self.path.extend_from_slice(rest); + obs.descend_to(rest); + self.position = PrefixPos::Source; + if self.source.descend_first_k_path_observed(k - rest_len, &mut (&mut self.path, &mut *obs)) { + true + } else { + self.path.truncate(self.path.len() - rest_len); + self.position = PrefixPos::Prefix { valid }; + obs.ascend(rest_len); + false + } + }, } } @@ -685,48 +760,45 @@ impl<'prefix, Z> ZipperIteration for PrefixZipper<'prefix, Z> obs.ascend(depth); return false; } - if let PrefixPos::PrefixOff { valid, invalid } = self.position { - //Off the prefix, the only location that can follow the focus is on the prefix: it must - // sort after the focus, and the common root must be on the prefix (where the focus left - // it, or above) - let mismatch = self.origin_depth + valid; - if k >= invalid && self.path[mismatch] < self.prefix[mismatch] && self.source.path_exists() { - self.ascend(invalid); - obs.ascend(invalid); - if self.descend_first_k_path_observed(invalid, obs) { - return true; + let rewind = match self.position { + PrefixPos::PrefixOff { valid, invalid } => { + //Off the prefix, the only location that can follow the focus is on the prefix: it + // must sort after the focus, and the common root must be on the prefix (where the + // focus left it, or above) + let mismatch = self.origin_depth + valid; + if k >= invalid && self.path[mismatch] < self.prefix[mismatch] && self.source.path_exists() { + self.ascend(invalid); + obs.ascend(invalid); + if self.descend_first_k_path_observed(invalid, obs) { + return true; + } + k - invalid + } else { + k } - self.ascend(k - invalid); - obs.ascend(k - invalid); - return false; - } - self.ascend(k); - obs.ascend(k); - return false; - } - //Only the portion of `k` inside the source can have alternatives to step to, so `k` is - //clamped to the source's depth. Iterating at the clamped depth visits exactly the same - //positions, because the prefix above it is a single forced path. - let source_depth = self.source.depth(); - if source_depth == 0 { - //Entirely within the prefix, which offers no alternatives - let ascended = self.ascend(k); - debug_assert_eq!(ascended, k); - obs.ascend(k); - return false - } - let clamped = k.min(source_depth); - if self.source.to_next_k_path_observed(clamped, &mut (&mut self.path, &mut *obs)) { - true - } else { - //The source rewound to its root; ascend the rest of `k` back up through the prefix - let remaining = k - clamped; - if remaining > 0 { - self.ascend(remaining); - obs.ascend(remaining); - } - false + }, + PrefixPos::Source => { + //Only the portion of `k` inside the source can have alternatives to step to, so + // `k` is clamped to the source's depth. Iterating at the clamped depth visits + // exactly the same positions, because the prefix above it is a single forced path. + let source_depth = self.source.depth(); + if source_depth > 0 { + let clamped = k.min(source_depth); + if self.source.to_next_k_path_observed(clamped, &mut (&mut self.path, &mut *obs)) { + return true; + } + k - clamped + } else { + k + } + }, + PrefixPos::Prefix {..} => k, + }; + if rewind > 0 { + self.ascend(rewind); + obs.ascend(rewind); } + false } } @@ -796,7 +868,7 @@ impl<'prefix, V: Clone + Send + Sync + Unpin, Z, A: Allocator> ZipperSubtries self.source.try_make_map(), - Some(stem) => Some(self.stem_map(stem, self.source.try_make_map()?)), + Some(stem) => Some(PathMap::new_with_root_in(self.try_stem_node(stem)?, None, self.source.alloc())), None => Some(PathMap::new_in(self.source.alloc())), } } @@ -806,7 +878,9 @@ impl<'prefix, V: Clone + Send + Sync + Unpin, Z, A: Allocator> ZipperSubtries self.source.trie_ref(), - Some(stem) => Some(self.stem_trie_ref(stem, self.source.try_make_map())), + Some(stem) => Some(TrieRefOwned::new_with_node_and_val_in( + self.try_stem_node(stem)?, None, self.source.alloc(), + ).into()), None => Some(TrieRefOwned::new_invalid_in(self.source.alloc()).into()), } } @@ -820,19 +894,23 @@ impl<'prefix, V: Clone + Send + Sync + Unpin, Z, A: Allocator> ZipperInfallibleS fn make_map(&self) -> PathMap { match self.prefix_path_below_focus() { Some([]) => self.source.make_map(), - Some(stem) => self.stem_map(stem, self.source.make_map()), + Some(stem) => PathMap::new_with_root_in(self.stem_node(stem), None, self.source.alloc()), None => PathMap::new_in(self.source.alloc()), } } fn get_trie_ref(&self) -> TrieRef<'_, V, A> { match self.prefix_path_below_focus() { Some([]) => self.source.get_trie_ref(), - Some(stem) => self.stem_trie_ref(stem, Some(self.source.make_map())), + Some(stem) => TrieRefOwned::new_with_node_and_val_in(self.stem_node(stem), None, self.source.alloc()).into(), None => TrieRefOwned::new_invalid_in(self.source.alloc()).into(), } } fn get_focus(&self) -> OpaqueAbstractNodeRef<'_, V, A> { - self.get_focus_at([]) + match self.prefix_path_below_focus() { + Some([]) => self.source.get_focus(), + Some(stem) => OpaqueAbstractNodeRef(self.stem_node(stem).map_or(AbstractNodeRef::None, AbstractNodeRef::OwnedRc)), + None => OpaqueAbstractNodeRef(AbstractNodeRef::None), + } } fn get_focus_at>(&self, path: K) -> OpaqueAbstractNodeRef<'_, V, A> { let path = path.as_ref(); @@ -842,24 +920,24 @@ impl<'prefix, V: Clone + Send + Sync + Unpin, Z, A: Allocator> ZipperInfallibleS if let Some(source_path) = path.strip_prefix(rest_prefix) { //The location is the source's root or below it self.source.get_focus_at(source_path) - } else if rest_prefix.starts_with(path) { + } else if let Some(stem) = rest_prefix.strip_prefix(path) { //The location is on the prefix, strictly above the source's root - let stem = self.stem_map(&rest_prefix[path.len()..], self.source.make_map()); - OpaqueAbstractNodeRef(stem.into_root().0.map_or(AbstractNodeRef::None, AbstractNodeRef::OwnedRc)) + OpaqueAbstractNodeRef(self.stem_node(stem).map_or(AbstractNodeRef::None, AbstractNodeRef::OwnedRc)) } else { OpaqueAbstractNodeRef(AbstractNodeRef::None) } } fn try_borrow_focus(&self) -> Option> { //The nodes along the prefix are not stored anywhere, so there is nothing to borrow - match self.position { - PrefixPos::Source => self.source.try_borrow_focus(), - _ => None, - } + if self.position.is_source() { self.source.try_borrow_focus() } else { None } } } -impl<'prefix, 'a, V: Clone + Send + Sync + Unpin + 'a, Z, A: Allocator + 'a> ZipperReadOnlySubtries<'a, V, A> for PrefixZipper<'prefix, Z> where Z: ZipperReadOnlySubtries<'a, V, A>, Self: zipper_priv::ZipperReadOnlyPriv<'a, V, A> + ZipperSubtries { +impl<'prefix, 'a, V: Clone + Send + Sync + Unpin + 'a, Z, A: Allocator + 'a> ZipperReadOnlySubtries<'a, V, A> for PrefixZipper<'prefix, Z> + where + Z: ZipperReadOnlySubtries<'a, V, A>, + Self: zipper_priv::ZipperReadOnlyPriv<'a, V, A> + ZipperSubtries, +{ //A location on the prefix has no counterpart in the source, so the source's own `TrieRefT` can't // express it. It is built as an owned trie instead, as in `get_trie_ref` type TrieRefT = TrieRef<'a, V, A>; @@ -870,8 +948,12 @@ impl<'prefix, 'a, V: Clone + Send + Sync + Unpin + 'a, Z, A: Allocator + 'a> Zip }; if let Some(source_path) = path.strip_prefix(rest_prefix) { self.source.trie_ref_at_path(source_path).into() - } else if rest_prefix.starts_with(path) { - self.stem_trie_ref(&rest_prefix[path.len()..], self.source.try_make_map()) + } else if let Some(stem) = rest_prefix.strip_prefix(path) { + let root = self.source.path_exists().then(|| { + let child = self.source.trie_ref_at_path([]).into().get_focus().into_option(); + self.wrap_stem_node(stem, child) + }); + TrieRefOwned::new_with_node_and_val_in(root, None, self.source.alloc()).into() } else { TrieRefOwned::new_invalid_in(self.source.alloc()).into() } @@ -1368,6 +1450,40 @@ mod tests { dst.write_zipper().graft(&pz); assert_eq!(dump(&dst), stem); assert!(pz.trie_ref_at_path(&[2u8, 3]).path_exists()); + + //All four (child, val) combinations with 1-byte and long (> MAX_NODE_KEY_BYTES) stems, + // plus a missing source and a write-zipper source + let long_stem = vec![b'a'; crate::trie_node::MAX_NODE_KEY_BYTES + 12]; + for stem in [&[9u8][..], &long_stem[..]] { + for (entries, want_at_stem, want_child) in [ + (&[(&[][..], 5u64), (&[7u8][..], 1)][..], Some(5), Some(1)), + (&[(&[][..], 5u64)][..], Some(5), None), + (&[(&[7u8][..], 1)][..], None, Some(1)), + (&[][..], None, None), + ] { + let mut src: PathMap = entries.iter().copied().collect(); + let pz = PrefixZipper::new(stem, src.read_zipper()); + let mut child_path = stem.to_vec(); + child_path.push(7); + for map in [pz.make_map(), pz.try_make_map().unwrap(), pz.get_trie_ref().make_map(), pz.trie_ref().unwrap().make_map(), pz.trie_ref_at_path(&[]).make_map()] { + assert!(map.path_exists_at(stem)); + assert_eq!(map.val_at(stem).copied(), want_at_stem); + assert_eq!(map.val_at(&child_path).copied(), want_child); + } + let wz_pz = PrefixZipper::new(stem, src.write_zipper()); + let map = wz_pz.make_map(); + assert!(map.path_exists_at(stem)); + assert_eq!(map.val_at(stem).copied(), want_at_stem); + assert_eq!(map.val_at(&child_path).copied(), want_child); + } + let missing_src: PathMap = [(&[0u8][..], 1u64)].into_iter().collect(); + let pz = PrefixZipper::new(stem, missing_src.read_zipper_at_path(&[5u8])); + assert!(dump(&pz.make_map()).is_empty()); + assert!(dump(&pz.try_make_map().unwrap()).is_empty()); + assert!(!pz.get_trie_ref().path_exists()); + assert!(!pz.trie_ref().unwrap().path_exists()); + assert!(!pz.trie_ref_at_path(&[]).path_exists()); + } } /// Moves that end, start or look one byte off the prefix, or stop at the source's root @@ -1389,6 +1505,24 @@ mod tests { assert_eq!(pz.path(), &[1, 2]); assert_eq!(pz.child_count(), 2); + //`descend_until_max_bytes_observed` mid-prefix, across the seam, and inside the source + let src: PathMap = [(&[3u8, 4, 5][..], 1u64)].into_iter().collect(); + let mut pz = PrefixZipper::new(&[1u8, 2][..], src.read_zipper()); + let mut obs = Vec::::new(); + assert!(!pz.descend_until_max_bytes_observed(0, &mut obs)); + assert!(pz.descend_until_max_bytes_observed(1, &mut obs)); + assert_eq!(pz.path(), &[1]); + assert_eq!(obs, &[1]); + assert!(pz.descend_until_max_bytes_observed(2, &mut obs)); + assert_eq!(pz.path(), &[1, 2, 3]); + assert_eq!(obs, &[1, 2, 3]); + assert!(pz.descend_until_max_bytes_observed(1, &mut obs)); + assert_eq!(pz.path(), &[1, 2, 3, 4]); + assert_eq!(obs, &[1, 2, 3, 4]); + assert!(pz.descend_until_max_bytes_observed(5, &mut obs)); + assert_eq!(pz.path(), &[1, 2, 3, 4, 5]); + assert_eq!(obs, &[1, 2, 3, 4, 5]); + //One byte off the prefix, the next prefix byte is a sibling let src: PathMap = [(&[9u8][..], 1u64), (&[8u8][..], 2)].into_iter().collect(); let mut pz = PrefixZipper::new(&[2u8][..], src.read_zipper()); @@ -1427,6 +1561,12 @@ mod tests { assert!(!pz.to_next_k_path(1)); assert_eq!(pz.path(), &[1]); pz.reset(); + pz.descend_to(&[1u8, 0, 0]); + let mut obs = pz.path().to_vec(); + assert!(!pz.to_next_k_path_observed(3, &mut obs)); + assert_eq!(pz.path(), &[]); + assert_eq!(obs, &[]); + pz.reset(); pz.descend_to_byte(3); assert!(!pz.to_next_k_path(1)); assert_eq!(pz.path(), &[]); From cef4e22aa4476f07a01ad3cb3da66b2e7934bfb4 Mon Sep 17 00:00:00 2001 From: Igor Malovitsa Date: Wed, 2 Dec 2026 22:46:09 +0000 Subject: [PATCH 4/4] Addressed the performance regressions in PrefixZipper::try_make_map and PrefixZipper::trie_ref_at_path --- src/prefix_zipper.rs | 172 +++++++++++++++++++++++++++++-------------- src/trie_ref.rs | 24 ++++++ 2 files changed, 140 insertions(+), 56 deletions(-) diff --git a/src/prefix_zipper.rs b/src/prefix_zipper.rs index 00accf5f..f3e00631 100644 --- a/src/prefix_zipper.rs +++ b/src/prefix_zipper.rs @@ -8,9 +8,9 @@ use crate::zipper::*; #[derive(Clone)] enum PrefixPos { + Source, Prefix { valid: usize }, PrefixOff { valid: usize, invalid: usize }, - Source, } impl PrefixPos { @@ -257,19 +257,19 @@ impl<'prefix, Z> PrefixZipper<'prefix, Z> { } /// Builds the root node of the subtrie `stem.len()` bytes above the source's root: the `stem` - /// path, then `child`, with the source's root value at the end of `stem` (or a dangling path - /// if both are empty) + /// path, then `child`, with `val` at the end of `stem` (or a dangling path if both are empty). + /// `child` must already have empty nodes filtered out. fn wrap_stem_node( &self, stem: &[u8], child: Option>, + val: Option, ) -> TrieNodeODRc where Z: ZipperSubtries { debug_assert!(!stem.is_empty()); + debug_assert!(child.as_ref().map_or(true, |node| !node.as_tagged().node_is_empty())); let alloc = self.source.alloc(); - let child = child.filter(|node| !node.as_tagged().node_is_empty()); - let val = self.source.val().cloned(); #[cfg(not(feature = "all_dense_nodes"))] { use crate::line_list_node::LineListNode; @@ -327,7 +327,11 @@ impl<'prefix, Z> PrefixZipper<'prefix, Z> { fn stem_node(&self, stem: &[u8]) -> Option> where Z: ZipperInfallibleSubtries + ZipperSubtries { - self.source.path_exists().then(|| self.wrap_stem_node(stem, self.source.get_focus().into_option())) + self.source.path_exists().then(|| { + let child = self.source.get_focus().into_option() + .filter(|node| !node.as_tagged().node_is_empty()); + self.wrap_stem_node(stem, child, self.source.val().cloned()) + }) } /// Fallible counterpart of [Self::stem_node] for [ZipperSubtries] @@ -337,8 +341,37 @@ impl<'prefix, Z> PrefixZipper<'prefix, Z> { if !self.source.path_exists() { return Some(None); } - let child = self.source.trie_ref()?.get_focus().into_option(); - Some(Some(self.wrap_stem_node(stem, child))) + let (child, root_val) = self.source.try_make_map()?.into_root(); + #[cfg(feature = "graft_root_vals")] + let val = root_val; + #[cfg(not(feature = "graft_root_vals"))] + let val = { + let _ = root_val; + self.source.val().cloned() + }; + Some(Some(self.wrap_stem_node(stem, child, val))) + } + + /// Outlined slow path for [ZipperReadOnlySubtries::trie_ref_at_path] when the focus is on the prefix + #[inline(never)] + fn trie_ref_at_path_from_prefix<'a, V: Clone + Send + Sync + Unpin + 'a, A: Allocator + 'a>( + &self, + valid: usize, + path: &[u8], + ) -> TrieRef<'a, V, A> + where Z: ZipperReadOnlySubtries<'a, V, A> + ZipperSubtries + { + let rest_prefix = &self.prefix[self.origin_depth + valid..]; + let min_len = path.len().min(rest_prefix.len()); + if path[..min_len] == rest_prefix[..min_len] { + if path.len() >= rest_prefix.len() { + return self.source.trie_ref_at_path(&path[rest_prefix.len()..]).into(); + } + if let Some(Some(root)) = self.try_stem_node(&rest_prefix[path.len()..]) { + return TrieRefOwned::new_with_node_and_val_in(Some(root), None, self.source.alloc()).into(); + } + } + TrieRefBorrowed::new_invalid_in(self.source.alloc()).into() } } @@ -861,29 +894,40 @@ impl<'prefix, V: Clone + Send + Sync + Unpin, Z, A: Allocator> ZipperSubtries { + #[inline] fn native_subtries(&self) -> bool { self.source.native_subtries() } + #[inline] fn try_make_map(&self) -> Option> { if !self.native_subtries() { return None } - match self.prefix_path_below_focus() { - Some([]) => self.source.try_make_map(), - Some(stem) => Some(PathMap::new_with_root_in(self.try_stem_node(stem)?, None, self.source.alloc())), - None => Some(PathMap::new_in(self.source.alloc())), + match self.position { + PrefixPos::Source => self.source.try_make_map(), + PrefixPos::Prefix { valid } => { + let stem = &self.prefix[self.origin_depth + valid..]; + Some(PathMap::new_with_root_in(self.try_stem_node(stem)?, None, self.source.alloc())) + }, + PrefixPos::PrefixOff { .. } => Some(PathMap::new_in(self.source.alloc())), } } + #[inline] fn trie_ref(&self) -> Option> { if !self.native_subtries() { return None } - match self.prefix_path_below_focus() { - Some([]) => self.source.trie_ref(), - Some(stem) => Some(TrieRefOwned::new_with_node_and_val_in( - self.try_stem_node(stem)?, None, self.source.alloc(), - ).into()), - None => Some(TrieRefOwned::new_invalid_in(self.source.alloc()).into()), + match self.position { + PrefixPos::Source => self.source.trie_ref(), + PrefixPos::Prefix { valid } => { + let stem = &self.prefix[self.origin_depth + valid..]; + Some(match self.try_stem_node(stem)? { + Some(root) => TrieRefOwned::new_with_node_and_val_in(Some(root), None, self.source.alloc()).into(), + None => TrieRefBorrowed::new_invalid_in(self.source.alloc()).into(), + }) + }, + PrefixPos::PrefixOff { .. } => Some(TrieRefBorrowed::new_invalid_in(self.source.alloc()).into()), } } + #[inline] fn alloc(&self) -> A { self.source.alloc() } } @@ -891,42 +935,67 @@ impl<'prefix, V: Clone + Send + Sync + Unpin, Z, A: Allocator> ZipperInfallibleS where Z: ZipperInfallibleSubtries + ZipperSubtries { + #[inline] fn make_map(&self) -> PathMap { - match self.prefix_path_below_focus() { - Some([]) => self.source.make_map(), - Some(stem) => PathMap::new_with_root_in(self.stem_node(stem), None, self.source.alloc()), - None => PathMap::new_in(self.source.alloc()), + match self.position { + PrefixPos::Source => self.source.make_map(), + PrefixPos::Prefix { valid } => { + let stem = &self.prefix[self.origin_depth + valid..]; + PathMap::new_with_root_in(self.stem_node(stem), None, self.source.alloc()) + }, + PrefixPos::PrefixOff { .. } => PathMap::new_in(self.source.alloc()), } } + #[inline] fn get_trie_ref(&self) -> TrieRef<'_, V, A> { - match self.prefix_path_below_focus() { - Some([]) => self.source.get_trie_ref(), - Some(stem) => TrieRefOwned::new_with_node_and_val_in(self.stem_node(stem), None, self.source.alloc()).into(), - None => TrieRefOwned::new_invalid_in(self.source.alloc()).into(), + match self.position { + PrefixPos::Source => self.source.get_trie_ref(), + PrefixPos::Prefix { valid } => { + let stem = &self.prefix[self.origin_depth + valid..]; + match self.stem_node(stem) { + Some(root) => TrieRefOwned::new_with_node_and_val_in(Some(root), None, self.source.alloc()).into(), + None => TrieRefBorrowed::new_invalid_in(self.source.alloc()).into(), + } + }, + PrefixPos::PrefixOff { .. } => TrieRefBorrowed::new_invalid_in(self.source.alloc()).into(), } } + #[inline] fn get_focus(&self) -> OpaqueAbstractNodeRef<'_, V, A> { - match self.prefix_path_below_focus() { - Some([]) => self.source.get_focus(), - Some(stem) => OpaqueAbstractNodeRef(self.stem_node(stem).map_or(AbstractNodeRef::None, AbstractNodeRef::OwnedRc)), - None => OpaqueAbstractNodeRef(AbstractNodeRef::None), + match self.position { + PrefixPos::Source => self.source.get_focus(), + PrefixPos::Prefix { valid } => { + let stem = &self.prefix[self.origin_depth + valid..]; + OpaqueAbstractNodeRef(self.stem_node(stem).map_or(AbstractNodeRef::None, AbstractNodeRef::OwnedRc)) + }, + PrefixPos::PrefixOff { .. } => OpaqueAbstractNodeRef(AbstractNodeRef::None), } } + #[inline] fn get_focus_at>(&self, path: K) -> OpaqueAbstractNodeRef<'_, V, A> { - let path = path.as_ref(); - let Some(rest_prefix) = self.prefix_path_below_focus() else { - return OpaqueAbstractNodeRef(AbstractNodeRef::None) - }; - if let Some(source_path) = path.strip_prefix(rest_prefix) { - //The location is the source's root or below it - self.source.get_focus_at(source_path) - } else if let Some(stem) = rest_prefix.strip_prefix(path) { - //The location is on the prefix, strictly above the source's root - OpaqueAbstractNodeRef(self.stem_node(stem).map_or(AbstractNodeRef::None, AbstractNodeRef::OwnedRc)) - } else { - OpaqueAbstractNodeRef(AbstractNodeRef::None) + match self.position { + PrefixPos::Source => self.source.get_focus_at(path), + PrefixPos::Prefix { valid } => { + let path = path.as_ref(); + let rest_prefix = &self.prefix[self.origin_depth + valid..]; + let min_len = path.len().min(rest_prefix.len()); + if path[..min_len] == rest_prefix[..min_len] { + if path.len() >= rest_prefix.len() { + //The location is the source's root or below it + return self.source.get_focus_at(&path[rest_prefix.len()..]); + } + //The location is on the prefix, strictly above the source's root + return OpaqueAbstractNodeRef( + self.stem_node(&rest_prefix[path.len()..]) + .map_or(AbstractNodeRef::None, AbstractNodeRef::OwnedRc) + ); + } + OpaqueAbstractNodeRef(AbstractNodeRef::None) + }, + PrefixPos::PrefixOff { .. } => OpaqueAbstractNodeRef(AbstractNodeRef::None), } } + #[inline] fn try_borrow_focus(&self) -> Option> { //The nodes along the prefix are not stored anywhere, so there is nothing to borrow if self.position.is_source() { self.source.try_borrow_focus() } else { None } @@ -941,21 +1010,12 @@ impl<'prefix, 'a, V: Clone + Send + Sync + Unpin + 'a, Z, A: Allocator + 'a> Zip //A location on the prefix has no counterpart in the source, so the source's own `TrieRefT` can't // express it. It is built as an owned trie instead, as in `get_trie_ref` type TrieRefT = TrieRef<'a, V, A>; + #[inline] fn trie_ref_at_path>(&self, path: K) -> Self::TrieRefT { - let path = path.as_ref(); - let Some(rest_prefix) = self.prefix_path_below_focus() else { - return TrieRefOwned::new_invalid_in(self.source.alloc()).into() - }; - if let Some(source_path) = path.strip_prefix(rest_prefix) { - self.source.trie_ref_at_path(source_path).into() - } else if let Some(stem) = rest_prefix.strip_prefix(path) { - let root = self.source.path_exists().then(|| { - let child = self.source.trie_ref_at_path([]).into().get_focus().into_option(); - self.wrap_stem_node(stem, child) - }); - TrieRefOwned::new_with_node_and_val_in(root, None, self.source.alloc()).into() - } else { - TrieRefOwned::new_invalid_in(self.source.alloc()).into() + match self.position { + PrefixPos::Source => self.source.trie_ref_at_path(path).into(), + PrefixPos::Prefix { valid } => self.trie_ref_at_path_from_prefix(valid, path.as_ref()), + PrefixPos::PrefixOff { .. } => TrieRefBorrowed::new_invalid_in(self.source.alloc()).into(), } } } diff --git a/src/trie_ref.rs b/src/trie_ref.rs index 04b5a708..85926cbe 100644 --- a/src/trie_ref.rs +++ b/src/trie_ref.rs @@ -216,6 +216,7 @@ impl<'a, V: Clone + Send + Sync + 'a, A: Allocator + 'a> TrieRefBorrowed<'a, V, } /// Makes a new `TrieRef` that points to no trie node. + #[inline] pub(crate) fn new_invalid_in(alloc: A) -> Self { Self { focus_node: None, @@ -290,6 +291,7 @@ impl<'a, V: Clone + Send + Sync + 'a, A: Allocator + 'a> TrieRefBorrowed<'a, V, } impl Zipper for TrieRefBorrowed<'_, V, A> { + #[inline] fn path_exists(&self) -> bool { //A TrieRef created at a non-existent path should not be given a focus_node debug_assert!(if let Some(node) = self.focus_node { @@ -561,6 +563,7 @@ impl TrieRefOwned { } /// Makes a `TrieRefOwned` from a node and a val + #[inline] pub(crate) fn new_with_node_and_val_in(focus_node: Option>, val: Option, alloc: A) -> Self { match focus_node { Some(_) => Self { focus_node: focus_node, val_or_key: ValOrKey { val: (VAL_SENTINEL, core::mem::ManuallyDrop::new(val)) }, alloc }, @@ -568,6 +571,7 @@ impl TrieRefOwned { } } /// Makes a new `TrieRef` that points to no trie node. + #[inline] pub(crate) fn new_invalid_in(alloc: A) -> Self { Self { focus_node: None, @@ -609,6 +613,7 @@ impl TrieRefOwned { } impl Zipper for TrieRefOwned { + #[inline] fn path_exists(&self) -> bool { //A TrieRef created at a non-existent path should not be given a focus_node debug_assert!(if let Some(node) = self.focus_node.as_ref() { @@ -810,42 +815,49 @@ pub enum TrieRef<'a, V: Clone + Send + Sync, A: Allocator = GlobalAlloc> { } impl<'a, V: Clone + Send + Sync, A: Allocator> From> for TrieRef<'a, V, A> { + #[inline] fn from(src: TrieRefBorrowed<'a, V, A>) -> Self { TrieRef::Borrowed(src) } } impl From> for TrieRef<'_, V, A> { + #[inline] fn from(src: TrieRefOwned) -> Self { TrieRef::Owned(src) } } impl From> for TrieRef<'_, V, A> { + #[inline] fn from(map: PathMap) -> Self { TrieRefOwned::from(map).into() } } impl Zipper for TrieRef<'_, V, A> { + #[inline] fn path_exists(&self) -> bool { match self { TrieRef::Borrowed(trie_ref) => trie_ref.path_exists(), TrieRef::Owned(trie_ref) => trie_ref.path_exists(), } } + #[inline] fn is_val(&self) -> bool { match self { TrieRef::Borrowed(trie_ref) => trie_ref.is_val(), TrieRef::Owned(trie_ref) => trie_ref.is_val(), } } + #[inline] fn child_count(&self) -> usize { match self { TrieRef::Borrowed(trie_ref) => trie_ref.child_count(), TrieRef::Owned(trie_ref) => trie_ref.child_count(), } } + #[inline] fn child_mask(&self) -> ByteMask { match self { TrieRef::Borrowed(trie_ref) => trie_ref.child_mask(), @@ -855,6 +867,7 @@ impl Zipper for TrieRef<'_, V, A> } impl ZipperValues for TrieRef<'_, V, A> { + #[inline] fn val(&self) -> Option<&V> { match self { TrieRef::Borrowed(trie_ref) => trie_ref.val(), @@ -864,6 +877,7 @@ impl ZipperValues for TrieRef<' } impl ZipperValuesAt for TrieRef<'_, V, A> { + #[inline] fn val_at>(&self, path: K) -> Option<&V> { match self { TrieRef::Borrowed(trie_ref) => trie_ref.val_at(path), @@ -883,9 +897,13 @@ impl ZipperForking for TrieRef< } impl ZipperSubtries for TrieRef<'_, V, A> { + #[inline] fn native_subtries(&self) -> bool { true } + #[inline] fn try_make_map(&self) -> Option> { Some(self.make_map()) } + #[inline] fn trie_ref(&self) -> Option> { Some(self.get_trie_ref()) } + #[inline] fn alloc(&self) -> A { match self { TrieRef::Borrowed(trie_ref) => trie_ref.alloc(), @@ -895,27 +913,32 @@ impl ZipperSubtries for Trie } impl ZipperInfallibleSubtries for TrieRef<'_, V, A> { + #[inline] fn make_map(&self) -> PathMap { match self { TrieRef::Borrowed(trie_ref) => trie_ref.make_map(), TrieRef::Owned(trie_ref) => trie_ref.make_map(), } } + #[inline] fn get_trie_ref(&self) -> TrieRef<'_, V, A> { self.clone() } + #[inline] fn get_focus(&self) -> OpaqueAbstractNodeRef<'_, V, A> { match self { TrieRef::Borrowed(trie_ref) => trie_ref.get_focus(), TrieRef::Owned(trie_ref) => trie_ref.get_focus(), } } + #[inline] fn get_focus_at>(&self, path: K) -> OpaqueAbstractNodeRef<'_, V, A> { match self { TrieRef::Borrowed(trie_ref) => trie_ref.get_focus_at(path), TrieRef::Owned(trie_ref) => trie_ref.get_focus_at(path), } } + #[inline] fn try_borrow_focus(&self) -> Option> { match self { TrieRef::Borrowed(trie_ref) => trie_ref.try_borrow_focus(), @@ -943,6 +966,7 @@ impl<'a, V: Clone + Send + Sync + Unpin + 'a, A: Allocator + 'a> ZipperReadOnlyC impl<'a, V: Clone + Send + Sync + Unpin + 'a, A: Allocator + 'a> ZipperReadOnlySubtries<'a, V, A> for TrieRef<'a, V, A> { type TrieRefT = TrieRef<'a, V, A>; + #[inline] fn trie_ref_at_path>(&self, path: K) -> TrieRef<'a, V, A> { match self { TrieRef::Borrowed(trie_ref) => TrieRef::Borrowed(trie_ref.trie_ref_at_path(path)),