diff --git a/src/dependent_zipper.rs b/src/dependent_zipper.rs index 1e5cb6c6..3b076317 100644 --- a/src/dependent_zipper.rs +++ b/src/dependent_zipper.rs @@ -241,28 +241,133 @@ impl<'trie, PrimaryZ, SecondaryZ, V, C, F : Clone + for <'a> FnOnce(C, &'a [u8], } } +/// Where the walk of [DependentProductZipperG::get_val_at_walk] stands: a read zipper forked from +/// one of the zipper's own factors, or a factor zipper the walk enrolled itself +enum Probe { + Primary(P), + Secondary(usize, S), + Enrolled(N), +} + +impl<'trie, PrimaryZ, SecondaryZ, V, C, F : Clone + for <'a> FnOnce(C, &'a [u8], usize) -> (C, Option)> DependentProductZipperG<'trie, PrimaryZ, SecondaryZ, V, C, F> + where + V: Clone + Send + Sync + 'trie, + PrimaryZ: ZipperMoving + ZipperPath + ZipperReadOnlyValues<'trie, V> + ZipperForking, + SecondaryZ: ZipperMoving + ZipperReadOnlyValues<'trie, V> + ZipperForking, + C: Clone, +{ + /// Internal. `descend_to(path)` then [`get_val`](ZipperReadOnlyValues::get_val), without moving: + /// replays `descend_to` on zippers forked from the factors, calling `enroll` (on a copy of the + /// payload) wherever the walk stands on a leaf, as `enter_factors` does + /// + /// The factor whose zipper is at the focus is `factor_idx(false)` (a factor entered at the focus + /// sits at its root). A location's value is the one of the factor it was reached in, not of a + /// factor entered there. + fn get_val_at_walk(&self, path: &[u8]) -> Option<&'trie V> { + //A value inside the focus's factor is the answer: a descent only enters the next factor at + // a leaf, and a leaf has nothing below it for `path` to continue into + let here = match self.factor_idx(false) { + Some(idx) => self.secondary[idx].get_val_at(path), + None => self.primary.get_val_at(path), + }; + if here.is_some() { + return here + } + let at_leaf = |probe: &Probe, SecondaryZ::ReadZipperT<'_>, SecondaryZ>| match probe { + Probe::Primary(z) => z.child_count() == 0 && z.path_exists(), + Probe::Secondary(_, z) => z.child_count() == 0 && z.path_exists(), + Probe::Enrolled(z) => z.child_count() == 0 && z.path_exists(), + }; + //A fork is `None` where the zipper's focus doesn't exist, so nothing below it does either + let mut probe = match self.factor_idx(false) { + Some(idx) => Probe::Secondary(idx, self.secondary[idx].fork_read_zipper()?), + None => Probe::Primary(self.primary.fork_read_zipper()?), + }; + let mut payload = self.enroll_payload.clone(); + let mut factor_count = self.secondary.len(); + //The product path at the start of `path` and up to `pos`, for `enroll`, built on first use + let mut walked: Option> = None; + //Where in `path` the current factor's zipper stood when the walk took it up + let mut factor_start = 0; + let mut pos = 0; + //`enter_factors`: returns whether a factor was entered + let mut enter = |probe: &mut Probe<_, _, SecondaryZ>, pos: usize, factor_start: &mut usize| -> bool { + if !at_leaf(probe) { + return false + } + let Some(p) = payload.take() else { return false }; + let walked = walked.get_or_insert_with(|| self.path().to_vec()); + walked.truncate(self.path().len()); + walked.extend_from_slice(&path[..pos]); + let (p, entered) = self.enroll.clone()(p, walked, factor_count); + payload = Some(p); + match entered { + Some(z) => { + *probe = Probe::Enrolled(z); + factor_count += 1; + *factor_start = pos; + true + }, + None => false, + } + }; + while pos < path.len() { + enter(&mut probe, pos, &mut factor_start); + let good = match &mut probe { + Probe::Primary(z) => z.descend_to_existing(&path[pos..]), + Probe::Secondary(_, z) => z.descend_to_existing(&path[pos..]), + Probe::Enrolled(z) => z.descend_to_existing(&path[pos..]), + }; + if good == 0 { + //`descend_to` then enters at most one more factor, and takes the rest of the path + // into that factor's zipper whether it exists there or not + enter(&mut probe, pos, &mut factor_start); + break + } + pos += good; + } + match probe { + Probe::Primary(_) => self.primary.get_val_at(&path[factor_start..]), + Probe::Secondary(idx, _) => self.secondary[idx].get_val_at(&path[factor_start..]), + Probe::Enrolled(mut z) => { + if pos < path.len() { + z.descend_to(&path[pos..]); + } + z.get_val() + }, + } + } +} + impl<'trie, PrimaryZ, SecondaryZ, V, C, F : Clone + for <'a> FnOnce(C, &'a [u8], usize) -> (C, Option)> ZipperValuesAt for DependentProductZipperG<'trie, PrimaryZ, SecondaryZ, V, C, F> where - V: Clone + Send + Sync, - PrimaryZ: ZipperMoving + ZipperPath + ZipperValuesAt, - SecondaryZ: ZipperMoving + ZipperPath + ZipperValuesAt, + V: Clone + Send + Sync + 'trie, + PrimaryZ: ZipperMoving + ZipperPath + ZipperReadOnlyValues<'trie, V> + ZipperForking, + SecondaryZ: ZipperMoving + ZipperReadOnlyValues<'trie, V> + ZipperForking, + C: Clone, { + /// The same as `descend_to(path)` then [`val`](ZipperValues::val), also across factor joints + /// + /// A factor past the focus doesn't exist until a descent reaches it: the walk has the enroll + /// function make it, and drops it after. So the value must not live in that factor's zipper, + /// which is why this needs factor zippers whose values outlive them ([ZipperReadOnlyValues]). fn val_at>(&self, path: K) -> Option<&V> { - if let Some(idx) = self.factor_idx(true) { - self.secondary[idx].val_at(path) - } else { - self.primary.val_at(path) + let path = path.as_ref(); + if path.is_empty() { + return self.val() } + self.get_val_at_walk(path) } } impl<'trie, PrimaryZ, SecondaryZ, V, C, F : Clone + for <'a> FnOnce(C, &'a [u8], usize) -> (C, Option)> ZipperReadOnlyValues<'trie, V> for DependentProductZipperG<'trie, PrimaryZ, SecondaryZ, V, C, F> where - V: Clone + Send + Sync, - PrimaryZ: ZipperMoving + ZipperPath + ZipperReadOnlyValues<'trie, V>, - SecondaryZ: ZipperMoving + ZipperReadOnlyValues<'trie, V>, + V: Clone + Send + Sync + 'trie, + PrimaryZ: ZipperMoving + ZipperPath + ZipperReadOnlyValues<'trie, V> + ZipperForking, + SecondaryZ: ZipperMoving + ZipperReadOnlyValues<'trie, V> + ZipperForking, + C: Clone, { fn get_val(&self) -> Option<&'trie V> { if let Some(idx) = self.factor_idx(true) { @@ -271,12 +376,14 @@ impl<'trie, PrimaryZ, SecondaryZ, V, C, F : Clone + for <'a> FnOnce(C, &'a [u8], self.primary.get_val() } } + /// The same as `descend_to(path)` then [`get_val`](ZipperReadOnlyValues::get_val), also across + /// factor joints fn get_val_at>(&self, path: K) -> Option<&'trie V> { - if let Some(idx) = self.factor_idx(true) { - self.secondary[idx].get_val_at(path) - } else { - self.primary.get_val_at(path) + let path = path.as_ref(); + if path.is_empty() { + return self.get_val() } + self.get_val_at_walk(path) } } diff --git a/src/poly_zipper.rs b/src/poly_zipper.rs index 1675a187..a7ebdfd2 100644 --- a/src/poly_zipper.rs +++ b/src/poly_zipper.rs @@ -162,8 +162,10 @@ mod tests { // ====================================================================================== // Cocktail of recursive zipper madness + //No `ZipperValuesAt`: `DependentProductZipperG::val_at` needs factor zippers whose values outlive + // them (`ZipperReadOnlyValues`), which `ReadZipperOwned`, and so `ExprFactor`, is not #[derive(PolyZipperExplicit)] - #[poly_zipper_explicit(traits(Zipper, ZipperValues, ZipperValuesAt, ZipperMoving, ZipperPath, ZipperIteration))] + #[poly_zipper_explicit(traits(Zipper, ZipperValues, ZipperMoving, ZipperPath, ZipperIteration))] pub enum ExprFactor<'trie, V: Clone + Send + Sync + Unpin + 'static = ()> { Specific(ReadZipperOwned), Generic(PrefixZipper<'trie, @@ -184,13 +186,4 @@ mod tests { ExprFactor::Specific(btm.clone().into_read_zipper(path)) } ); - - crate::zipper::zipper_moving_tests::zipper_val_at_tests!(recursive_zipper_madness, - |keys: &[&[u8]]| { - keys.iter().map(|k| (k, ())).collect::>() - }, - |btm: &mut PathMap<()>, path: &[u8]| -> _ { - ExprFactor::Specific(btm.clone().into_read_zipper(path)) - } - ); } diff --git a/src/product_zipper.rs b/src/product_zipper.rs index ff06bbcd..6000eb67 100644 --- a/src/product_zipper.rs +++ b/src/product_zipper.rs @@ -327,8 +327,28 @@ impl<'trie, V: Clone + Send + Sync + Unpin + 'trie, A: Allocator + 'trie> Zipper } impl<'trie, V: Clone + Send + Sync + Unpin + 'trie, A: Allocator + 'trie> ZipperValuesAt for ProductZipper<'_, 'trie, V, A> { + /// The same as `descend_to(path)` then [`val`](ZipperValues::val), also across factor joints. fn val_at>(&self, path: K) -> Option<&V> { - unsafe{ self.z.get_val_at(path) } + let mut path = path.as_ref(); + if path.is_empty() { + return self.val(); + } + let (mut node, mut node_key, _) = self.z.borrow_raw_parts(); + let mut next_factor = self.factor_paths.len(); + loop { + match walk_node_val_at::(node, node_key, path) { + NodeWalk::End(val) => return val, + NodeWalk::Miss => return None, + NodeWalk::Leaf(rem) => { + //If there is a secondary root value, the earlier factor's value takes + // precedence, as in `enroll_next_factor` + let secondary = self.secondaries.get(next_factor)?; + next_factor += 1; + (node, node_key, _) = secondary.borrow_raw_parts(); + path = rem; + } + } + } } } @@ -601,18 +621,107 @@ impl<'trie, PrimaryZ, SecondaryZ, V> ZipperValues } } +/// Where `descend_to(path)` would end, as `(factor, path)`: the factor whose value the focus there +/// shows (`None` for the primary) and the path from that factor zipper's current position. `None` +/// if `path` does not exist. Internal to the `val_at` impls of [ProductZipperG]. +type ValAtTarget<'p> = Option<(Option, &'p [u8])>; + +impl<'trie, PrimaryZ, SecondaryZ, V> ProductZipperG<'trie, PrimaryZ, SecondaryZ, V> + where + V: Clone + Send + Sync, + PrimaryZ: ZipperMoving + ZipperForking, + SecondaryZ: ZipperMoving + ZipperForking, +{ + /// Internal. Replays `descend_to_existing` along `path` on zippers forked from the factors, + /// leaving the factors themselves alone, and says which factor holds the location it ends at + /// + /// The factor whose zipper is at the focus is `factor_idx(false)` (a factor entered at the focus + /// sits at its root); every factor after it is at its root. As in `descend_to_existing`, the walk + /// enters the next factor wherever it stands on a leaf, and a location's value is the one of the + /// factor it was reached in, not of a factor entered there. + fn val_at_target<'p>(&self, path: &'p [u8]) -> ValAtTarget<'p> { + let mut factor = self.factor_idx(false); + let mut entered = self.factor_paths.len(); + //A fork is `None` where the zipper's focus doesn't exist, so nothing below it does either + let fork = |factor: Option| match factor { + Some(idx) => self.secondary[idx].fork_read_zipper().map(Probe::Secondary), + None => self.primary.fork_read_zipper().map(Probe::Primary), + }; + let mut probe = fork(factor)?; + //Where in `path` the current factor's zipper stood when the walk took it up + let mut factor_start = 0; + //The factor that consumed the last byte, and where it started + let mut last = (factor, 0); + let mut pos = 0; + while pos < path.len() { + if entered < self.secondary.len() && probe.child_count() == 0 && probe.path_exists() { + factor = Some(entered); + entered += 1; + factor_start = pos; + probe = fork(factor)?; + } + let good = probe.descend_to_existing(&path[pos..]); + if good == 0 { + //`descend_to` then enters at most one more factor, and takes the rest of the path + // into that factor's zipper whether it exists there or not (an empty factor is + // only passed through this way). The factor's own `val_at` says what is there + if entered < self.secondary.len() && probe.child_count() == 0 && probe.path_exists() { + factor = Some(entered); + factor_start = pos; + } + return Some((factor, &path[factor_start..])) + } + pos += good; + last = (factor, factor_start); + } + Some((last.0, &path[last.1..])) + } +} + +/// A read zipper forked from the primary or from a secondary factor, for +/// [ProductZipperG::val_at_target] +enum Probe { + Primary(P), + Secondary(S), +} + +impl Probe { + fn child_count(&self) -> usize { + match self { Self::Primary(z) => z.child_count(), Self::Secondary(z) => z.child_count() } + } + fn path_exists(&self) -> bool { + match self { Self::Primary(z) => z.path_exists(), Self::Secondary(z) => z.path_exists() } + } + fn descend_to_existing(&mut self, path: &[u8]) -> usize { + match self { Self::Primary(z) => z.descend_to_existing(path), Self::Secondary(z) => z.descend_to_existing(path) } + } +} + impl<'trie, PrimaryZ, SecondaryZ, V> ZipperValuesAt for ProductZipperG<'trie, PrimaryZ, SecondaryZ, V> where V: Clone + Send + Sync, - PrimaryZ: ZipperMoving + ZipperPath + ZipperValuesAt, - SecondaryZ: ZipperMoving + ZipperPath + ZipperValuesAt, + PrimaryZ: ZipperMoving + ZipperPath + ZipperValuesAt + ZipperForking, + SecondaryZ: ZipperMoving + ZipperPath + ZipperValuesAt + ZipperForking, { + /// The same as `descend_to(path)` then [`val`](ZipperValues::val), also across factor joints fn val_at>(&self, path: K) -> Option<&V> { - if let Some(idx) = self.factor_idx(true) { - self.secondary[idx].val_at(path) - } else { - self.primary.val_at(path) + let path = path.as_ref(); + if path.is_empty() { + return self.val() + } + //A value inside the focus's factor is the answer: a descent only enters the next factor at + // a leaf, and a leaf has nothing below it for `path` to continue into + let here = match self.factor_idx(false) { + Some(idx) => self.secondary[idx].val_at(path), + None => self.primary.val_at(path), + }; + if here.is_some() || self.factor_paths.len() >= self.secondary.len() { + return here + } + match self.val_at_target(path)? { + (Some(idx), rest) => self.secondary[idx].val_at(rest), + (None, rest) => self.primary.val_at(rest), } } } @@ -621,8 +730,8 @@ impl<'trie, PrimaryZ, SecondaryZ, V> ZipperReadOnlyValues<'trie, V> for ProductZipperG<'trie, PrimaryZ, SecondaryZ, V> where V: Clone + Send + Sync, - PrimaryZ: ZipperMoving + ZipperPath + ZipperReadOnlyValues<'trie, V>, - SecondaryZ: ZipperMoving + ZipperPath + ZipperReadOnlyValues<'trie, V>, + PrimaryZ: ZipperMoving + ZipperPath + ZipperReadOnlyValues<'trie, V> + ZipperForking, + SecondaryZ: ZipperMoving + ZipperPath + ZipperReadOnlyValues<'trie, V> + ZipperForking, { fn get_val(&self) -> Option<&'trie V> { if let Some(idx) = self.factor_idx(true) { @@ -631,11 +740,24 @@ impl<'trie, PrimaryZ, SecondaryZ, V> ZipperReadOnlyValues<'trie, V> self.primary.get_val() } } + /// The same as `descend_to(path)` then [`get_val`](ZipperReadOnlyValues::get_val), also across + /// factor joints fn get_val_at>(&self, path: K) -> Option<&'trie V> { - if let Some(idx) = self.factor_idx(true) { - self.secondary[idx].get_val_at(path) - } else { - self.primary.get_val_at(path) + let path = path.as_ref(); + if path.is_empty() { + return self.get_val() + } + //See `val_at` + let here = match self.factor_idx(false) { + Some(idx) => self.secondary[idx].get_val_at(path), + None => self.primary.get_val_at(path), + }; + if here.is_some() || self.factor_paths.len() >= self.secondary.len() { + return here + } + match self.val_at_target(path)? { + (Some(idx), rest) => self.secondary[idx].get_val_at(rest), + (None, rest) => self.primary.get_val_at(rest), } } } @@ -1940,6 +2062,147 @@ mod tests { }; } + /// `ProductZipper::val_at(p)` is `descend_to(p); val()`, at and across factor joints. It used to + /// panic with the focus on a joint or inside the first node of a secondary factor + #[test] + fn product_zipper_val_at_matches_descend() { + fn all_paths(max_len: usize) -> Vec> { + let mut out = vec![vec![]]; + let mut i = 0; + while i < out.len() { + if out[i].len() < max_len { + for b in [b'a', b'b', b'c', b'd', b'x'] { + let mut p = out[i].clone(); + p.push(b); + out.push(p); + } + } + i += 1; + } + out + } + let primary = PathMap::from_iter([(b"a".as_slice(), 1u64), (b"bx".as_slice(), 2), (b"b".as_slice(), 3)]); + let secondary = PathMap::from_iter([(b"bcd".as_slice(), 4u64), (b"bce".as_slice(), 5), (b"x".as_slice(), 6)]); + let mut dangling = PathMap::::new(); + dangling.create_path(b"c"); + dangling.set_val_at(b"d", 7); + let third = PathMap::from_iter([(b"a".as_slice(), 8u64), (b"cd".as_slice(), 9)]); + let factor_sets: [&[&PathMap]; 3] = [&[&secondary], &[&secondary, &third], &[&dangling, &secondary]]; + //Miri is too slow for the full sweep + let (focus_len, suffix_len) = if cfg!(miri) { (2, 2) } else { (3, 4) }; + let focuses = all_paths(focus_len); + let suffixes = all_paths(suffix_len); + for factors in factor_sets { + let new_pz = || ProductZipper::new(primary.read_zipper(), factors.iter().map(|m| m.read_zipper())); + for focus in focuses.iter() { + let mut pz = new_pz(); + pz.descend_to(focus); + for suffix in suffixes.iter() { + let mut expected = new_pz(); + expected.descend_to(focus); + expected.descend_to(suffix); + assert_eq!(pz.val_at(suffix), expected.val(), "focus {focus:?} path {suffix:?}"); + } + } + } + //The original report: primary {a}, secondary {bcd, bce}, `val_at([])` at `a` and at `ab` + let primary = PathMap::from_iter([(b"a".as_slice(), 1u64)]); + let secondary = PathMap::from_iter([(b"bcd".as_slice(), 2u64), (b"bce".as_slice(), 3)]); + let mut pz = ProductZipper::new(primary.read_zipper(), [secondary.read_zipper()]); + pz.descend_to(b"a"); + assert_eq!(pz.val_at(b""), Some(&1)); + assert_eq!(pz.val_at(b"bcd"), Some(&2)); + pz.descend_to(b"b"); + assert_eq!(pz.val_at(b""), None); + assert_eq!(pz.val_at(b"ce"), Some(&3)); + + //Keys longer than a node's keys, with the focus partway into a node, across joints + let long = |n: usize, last: u8| { let mut p = vec![b'a'; n]; p.push(last); p }; + let primary = PathMap::from_iter([(long(60, b'b'), 1u64), (long(60, b'c'), 2)]); + let secondary = PathMap::from_iter([(long(70, b'd'), 3u64), (b"x".to_vec(), 4)]); + let new_pz = || ProductZipper::new(primary.read_zipper(), [secondary.read_zipper()]); + for focus_len in [0, 1, 10, 47, 48, 49, 59, 60, 61, 62, 100, 131] { + let mut pz = new_pz(); + let mut focus = long(60, b'b'); + focus.extend(long(70, b'd')); + focus.truncate(focus_len); + pz.descend_to(&focus); + for target in [long(60, b'b'), long(60, b'c'), [long(60, b'b'), long(70, b'd')].concat(), [long(60, b'c'), b"x".to_vec()].concat(), [long(60, b'b'), b"xx".to_vec()].concat()] { + let Some(suffix) = target.strip_prefix(&focus[..]) else { continue }; + let mut expected = new_pz(); + expected.descend_to(&target); + assert_eq!(pz.val_at(suffix), expected.val(), "focus len {focus_len} target {target:?}"); + } + } + } + + /// `ProductZipperG::val_at(p)` and `get_val_at(p)` are its own `descend_to(p)` then `val()`, at + /// and across factor joints. They used to ask only the focus's factor + #[test] + fn product_zipper_g_val_at_matches_descend() { + fn all_paths(max_len: usize) -> Vec> { + let mut out = vec![vec![]]; + let mut i = 0; + while i < out.len() { + if out[i].len() < max_len { + for b in [b'a', b'b', b'c', b'd', b'x'] { + let mut p = out[i].clone(); + p.push(b); + out.push(p); + } + } + i += 1; + } + out + } + let long = |n: usize, last: u8| { let mut p = vec![b'a'; n]; p.push(last); p }; + let primary = PathMap::from_iter([(b"a".as_slice(), 1u64), (b"bx".as_slice(), 2), (b"b".as_slice(), 3)]); + let secondary = PathMap::from_iter([(b"bcd".as_slice(), 4u64), (b"bce".as_slice(), 5), (b"x".as_slice(), 6)]); + let mut dangling = PathMap::::new(); + dangling.create_path(b"c"); + dangling.set_val_at(b"d", 7); + let third = PathMap::from_iter([(b"a".as_slice(), 8u64), (b"cd".as_slice(), 9)]); + let long_primary = PathMap::from_iter([(long(60, b'b'), 1u64), (long(60, b'c'), 2)]); + let long_secondary = PathMap::from_iter([(long(70, b'd'), 3u64), (b"x".to_vec(), 4)]); + let cases: [(&PathMap, &[&PathMap]); 4] = [ + (&primary, &[&secondary]), + (&primary, &[&secondary, &third]), + (&primary, &[&dangling, &secondary]), + (&long_primary, &[&long_secondary]), + ]; + //Miri is too slow for the full sweep + let (focus_len, suffix_len) = if cfg!(miri) { (2, 2) } else { (3, 4) }; + let mut focuses = all_paths(focus_len); + let mut suffixes = all_paths(suffix_len); + let mut long_target = long(60, b'b'); + long_target.extend(long(70, b'd')); + for len in [1, 10, 47, 48, 49, 60, 61, 62, 100, 131] { + focuses.push(long_target[..len].to_vec()); + } + suffixes.extend([long(60, b'b'), long(60, b'c'), long_target.clone(), [long(60, b'c'), b"x".to_vec()].concat()]); + for (p, factors) in cases { + let new_pz = || ProductZipperG::new(p.read_zipper(), factors.iter().map(|m| m.read_zipper())); + for focus in focuses.iter() { + let mut pz = new_pz(); + pz.descend_to(focus); + for suffix in suffixes.iter() { + let mut expected = new_pz(); + expected.descend_to(focus); + expected.descend_to(suffix); + assert_eq!(pz.val_at(suffix), expected.val(), "focus {focus:?} path {suffix:?}"); + assert_eq!(pz.get_val_at(suffix), expected.val(), "focus {focus:?} path {suffix:?}"); + //The suffix's own path, as `val_at` from the focus finds it + let mut full = focus.clone(); + full.extend(suffix); + let mut root = new_pz(); + assert_eq!(root.val_at(&full), expected.val(), "from the root: path {full:?}"); + root.descend_to(&full); + assert_eq!(root.val(), expected.val(), "path {full:?}"); + } + } + } + } + macro_rules! noop { ($x:ident) => {}; (*$x:ident) => {}; } impl_product_zipper_tests!(pz_concrete, ProductZipper, noop); impl_product_zipper_tests!(pz_generic, ProductZipperG, noop); @@ -1969,6 +2232,84 @@ mod tests { impl_product_zipper_tests!(pz_dependent, DependentPZAdapter, noop); + /// `DependentProductZipperG::val_at(p)` and `get_val_at(p)` are its own `descend_to(p)` then + /// `get_val()`, at and across factor joints, with fixed factors and with factors that depend on + /// the path and on the enroll payload. They used to ask only the focus's factor + #[test] + fn dependent_zipper_get_val_at_matches_descend() { + fn all_paths(max_len: usize) -> Vec> { + let mut out = vec![vec![]]; + let mut i = 0; + while i < out.len() { + if out[i].len() < max_len { + for b in [b'a', b'b', b'c', b'd', b'x'] { + let mut p = out[i].clone(); + p.push(b); + out.push(p); + } + } + i += 1; + } + out + } + /// Returns how many lookups found a value, and how many of those crossed a joint + fn check<'t, Z>(new_pz: &dyn Fn() -> Z, focus_factor: fn(&Z) -> usize, focuses: &[Vec], suffixes: &[Vec]) -> (usize, usize) + where Z: ZipperMoving + ZipperPath + ZipperValuesAt + ZipperReadOnlyValues<'t, u64> + { + let (mut crossed, mut found) = (0, 0); + for focus in focuses { + let mut pz = new_pz(); + pz.descend_to(focus); + for suffix in suffixes { + let mut expected = new_pz(); + expected.descend_to(focus); + expected.descend_to(suffix); + let want = expected.get_val(); + assert_eq!(pz.get_val_at(suffix), want, "focus {focus:?} path {suffix:?}"); + assert_eq!(pz.val_at(suffix), want, "focus {focus:?} path {suffix:?}"); + if want.is_some() { + found += 1; + if focus_factor(&expected) > focus_factor(&pz) { crossed += 1 } + } + } + } + (found, crossed) + } + let primary = PathMap::from_iter([(b"a".as_slice(), 1u64), (b"bx".as_slice(), 2), (b"b".as_slice(), 3)]); + let secondary = PathMap::from_iter([(b"bcd".as_slice(), 4u64), (b"bce".as_slice(), 5), (b"x".as_slice(), 6)]); + let mut dangling = PathMap::::new(); + dangling.create_path(b"c"); + dangling.set_val_at(b"d", 7); + let third = PathMap::from_iter([(b"a".as_slice(), 8u64), (b"cd".as_slice(), 9)]); + let (focus_len, suffix_len) = if cfg!(miri) { (2, 2) } else { (3, 4) }; + let focuses = all_paths(focus_len); + let suffixes = all_paths(suffix_len); + + let factor_sets: [&[&PathMap]; 3] = [&[&secondary], &[&secondary, &third], &[&dangling, &secondary]]; + for factors in factor_sets { + let (found, crossed) = check(&|| DependentPZAdapter::new(primary.read_zipper(), factors.iter().map(|m| m.read_zipper())), + |z| z.focus_factor(), &focuses, &suffixes); + assert!(found > 0 && crossed > 0 && crossed < found, "the sweep reaches values across and within joints"); + } + + //The next factor depends on the path's last byte; the payload counts the factors entered and + // stops after three + let (found, crossed) = check(&|| DependentProductZipperG::new_enroll(primary.read_zipper(), 0usize, + |n: usize, path: &[u8], _idx: usize| { + if n >= 3 { return (n, None) } + let m = if path.last() == Some(&b'x') { &third } else { &secondary }; + (n + 1, Some(m.read_zipper())) + }), |z| z.focus_factor(), &focuses, &suffixes); + assert!(found > 0 && crossed > 0); + + //At a joint, a path inside the factor entered there is found by `val_at` too + let mut pz = DependentPZAdapter::new(primary.read_zipper(), [secondary.read_zipper()]); + pz.descend_to(b"a"); + assert_eq!(pz.val_at(b""), Some(&1)); + assert_eq!(pz.val_at(b"bcd"), Some(&4)); + assert_eq!(pz.get_val_at(b"bcd"), Some(&4)); + } + #[cfg(feature="arena_compact")] macro_rules! to_act { (*$x:ident) => { diff --git a/src/trie_map.rs b/src/trie_map.rs index 49c72936..cb80134b 100644 --- a/src/trie_map.rs +++ b/src/trie_map.rs @@ -633,8 +633,7 @@ impl ZipperValuesAt for PathMap if path.is_empty() { return self.root_val(); } - let zipper = self.read_zipper_at_borrowed_path(path); - zipper.get_val() + node_val_at(self.root()?.as_tagged(), &[], path) } } diff --git a/src/trie_node.rs b/src/trie_node.rs index 7a074825..701ebde4 100644 --- a/src/trie_node.rs +++ b/src/trie_node.rs @@ -2630,6 +2630,125 @@ fn traverse_physical_children_internal(node: TaggedNode node_f(node, ctx) } +/// Result of walking a single trie from `(node, node_key)` along a non-empty `path`. +pub(crate) enum NodeWalk<'a, 'p, V> { + /// Reached the exact end of `path` inside this trie; carries the value if present. + End(Option<&'a V>), + /// Stopped at a leaf after advancing at least 1 byte along `path`; carries the remaining suffix. + Leaf(&'p [u8]), + /// Diverged before the end of `path`, or could not advance from the starting point. + Miss, +} + +/// Walks a non-empty `path` from `(node, node_key)` inside a single trie. +/// +/// When `FIND_LEAF` is `false`, `NodeWalk::Leaf` is never returned (returns `NodeWalk::Miss` +/// instead), skipping `node_key_overlap` and `count_branches` work for single-trie `val_at`. +#[inline] +pub(crate) fn walk_node_val_at<'a, 'p, const FIND_LEAF: bool, V: Clone + Send + Sync, A: Allocator>( + mut node: TaggedNodeRef<'a, V, A>, + mut node_key: &[u8], + mut path: &'p [u8], +) -> NodeWalk<'a, 'p, V> { + debug_assert!(!path.is_empty()); + let mut moved = false; + + while !node_key.is_empty() { + let mut buf = [0u8; MAX_NODE_KEY_BYTES]; + let (combined, take) = if node_key.len() >= MAX_NODE_KEY_BYTES { + (&node_key[..MAX_NODE_KEY_BYTES], 0) + } else { + let take = path.len().min(MAX_NODE_KEY_BYTES - node_key.len()); + buf[..node_key.len()].copy_from_slice(node_key); + buf[node_key.len()..node_key.len() + take].copy_from_slice(&path[..take]); + (&buf[..node_key.len() + take], take) + }; + + match node.node_get_child(combined) { + Some((consumed, child)) if consumed < node_key.len() => { + //A child materialized inside `node_key` (e.g. via `create_path` on a WriteZipper) + node = child.as_tagged(); + node_key = &node_key[consumed..]; + } + Some((consumed, child)) => { + let step = consumed - node_key.len(); + if step == path.len() { + //A value at a child's root is held by the parent + return NodeWalk::End(node.node_get_val(&combined[..consumed])); + } + node = child.as_tagged(); + path = &path[step..]; + moved = step > 0; + break; + } + None => { + if node_key.len() > MAX_NODE_KEY_BYTES { + return NodeWalk::Miss; + } + if take == path.len() { + if let Some(val) = node.node_get_val(combined) { + return NodeWalk::End(Some(val)); + } + } + if !FIND_LEAF { + return NodeWalk::Miss; + } + let overlap = node.node_key_overlap(combined); + if overlap <= node_key.len() { + return NodeWalk::Miss; + } + let step = overlap - node_key.len(); + if step == path.len() { + return NodeWalk::End(None); + } + return if node.count_branches(&combined[..overlap]) == 0 { + NodeWalk::Leaf(&path[step..]) + } else { + NodeWalk::Miss + }; + } + } + } + + while let Some((consumed, child)) = node.node_get_child(path) { + if consumed == path.len() { + //A value at a child's root is held by the parent + return NodeWalk::End(node.node_get_val(path)); + } + node = child.as_tagged(); + path = &path[consumed..]; + moved = true; + } + + if let Some(val) = node.node_get_val(path) { + return NodeWalk::End(Some(val)); + } + if !FIND_LEAF { + return NodeWalk::Miss; + } + let overlap = node.node_key_overlap(path); + if overlap == path.len() { + NodeWalk::End(None) + } else if (moved || overlap > 0) && node.count_branches(&path[..overlap]) == 0 { + NodeWalk::Leaf(&path[overlap..]) + } else { + NodeWalk::Miss + } +} + +/// Convenience wrapper around [`walk_node_val_at`] for single-trie `val_at` lookups. +#[inline] +pub(crate) fn node_val_at<'a, V: Clone + Send + Sync, A: Allocator>( + node: TaggedNodeRef<'a, V, A>, + node_key: &[u8], + path: &[u8], +) -> Option<&'a V> { + match walk_node_val_at::(node, node_key, path) { + NodeWalk::End(val) => val, + NodeWalk::Leaf(_) | NodeWalk::Miss => None, + } +} + /// Internal function to walk a mut TrieNodeODRc ref along a path /// /// If `stop_early` is `true`, this function will return the parent node of the path and will never return diff --git a/src/trie_ref.rs b/src/trie_ref.rs index 04b5a708..a2f0b5f8 100644 --- a/src/trie_ref.rs +++ b/src/trie_ref.rs @@ -423,17 +423,11 @@ impl<'a, V: Clone + Send + Sync + Unpin + 'a, A: Allocator + 'a> ZipperReadOnlyV } } fn get_val_at>(&self, path: K) -> Option<&'a V> { - if let Some(focus_node) = self.focus_node { - TrieRefBorrowed::new_with_key_and_path_in( - focus_node, - || self.get_val(), - self.node_key(), - path.as_ref(), - self.alloc.clone(), - ).get_val() - } else { - None + let path = path.as_ref(); + if path.is_empty() { + return self.get_val(); } + node_val_at(self.focus_node?.as_tagged(), self.node_key(), path) } } @@ -659,17 +653,11 @@ impl ZipperValues for TrieRefOw impl ZipperValuesAt for TrieRefOwned { fn val_at>(&self, path: K) -> Option<&V> { - if self.is_valid() { - TrieRefBorrowed::new_with_key_and_path_in( - self.focus_node.as_ref().unwrap(), - || self.val(), - self.node_key(), - path.as_ref(), - self.alloc.clone(), - ).get_val() - } else { - None + let path = path.as_ref(); + if path.is_empty() { + return self.val(); } + node_val_at(self.focus_node.as_ref()?.as_tagged(), self.node_key(), path) } } diff --git a/src/write_zipper.rs b/src/write_zipper.rs index 55c6c3e6..ecab0acc 100644 --- a/src/write_zipper.rs +++ b/src/write_zipper.rs @@ -1519,13 +1519,11 @@ impl <'a, 'path, V: Clone + Send + Sync + Unpin, A: Allocator + 'a> WriteZipperC } /// See [ZipperValuesAt::val_at] pub fn val_at>(&self, path: K) -> Option<&V> { - TrieRefBorrowed::new_with_key_and_path_in( - self.focus_parent(), - || self.val(), - self.key.node_key(), - path.as_ref(), - self.alloc.clone(), - ).get_val() + let path = path.as_ref(); + if path.is_empty() { + return self.val(); + } + node_val_at(self.focus_stack.top()?, self.key.node_key(), path) } /// See [ZipperWriting::get_val_mut] pub fn get_val_mut(&mut self) -> Option<&mut V> { diff --git a/src/zipper.rs b/src/zipper.rs index a4999550..2c26ae0b 100644 --- a/src/zipper.rs +++ b/src/zipper.rs @@ -3231,25 +3231,11 @@ pub(crate) mod read_zipper_core { /// the returned value might outlive the zipper. We need to only expose this through methods /// that have tighter lifetime bounds, or on types that guarantee the root won't be owned pub(crate) unsafe fn get_val_at>(&self, path: K) -> Option<&'a V> { - let val = TrieRefBorrowed::new_with_key_and_path_in( - self.focus_parent(), - || { - // SAFETY: `get_val_at` has the same lifetime contract as `get_val`. This closure is - // only invoked when the target path resolves to the current focus itself, so using - // `self.get_val()` here is equivalent to asking for the current focus value. - unsafe { self.get_val() } - }, - self.node_key(), - path.as_ref(), - self.alloc.clone(), - ).get_val(); - - // SAFETY: `val` points into the trie reachable from `self`. The only reason its inferred - // lifetime is shorter is that `focus_parent()` returns a reference tied to `&self`, even when - // the underlying trie root is owned by the zipper and is therefore guaranteed to stay alive - // for `'a`. This method is already `unsafe` for exactly that reason, and callers must uphold - // the documented requirement that the returned reference not outlive the backing trie storage. - unsafe { core::mem::transmute::, Option<&'a V>>(val) } + let path = path.as_ref(); + if path.is_empty() { + return unsafe { self.get_val() }; + } + node_val_at(*self.focus_node, self.node_key(), path) } /// Convenience form of [`ReadZipperCore::to_next_get_val_observed`] that does not observe path movement.