use std::borrow::Cow;
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock};
use thiserror::Error;
use crate::parse::{
Chain, ChainError, FallbackConfig, Fields, FormatChoice, HopConfig, Parsed, Parser, Resolve,
ResolveError,
};
use crate::path::keys;
use super::fields::json_unread;
use super::{FieldsAt, Json, Kind, Miss, Node, Record, Typed, Walk};
#[cfg(feature = "xml")]
use super::{Xml, XmlAt};
pub const MAX_LAYERS: usize = 8;
const MAX_MOUNT_KEYS: usize = 64;
const OFF: u8 = u8::MAX;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum LayerError {
#[error(transparent)]
Chain(#[from] ChainError),
#[error(transparent)]
Resolve(#[from] ResolveError),
#[error("hop {hop}: {reason}")]
Unsupported {
hop: usize,
reason: &'static str,
},
}
pub struct LayerPlan {
layers: Vec<Layer>,
}
struct Layer {
formats: Vec<Format>,
mount: Vec<String>,
body: bool,
decodes: bool,
}
struct Format {
name: String,
read: Read,
}
enum Read {
Json,
#[cfg(feature = "xml")]
Xml,
Parser(Arc<dyn Parser>),
}
impl fmt::Debug for LayerPlan {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.layers.iter().map(|l| {
let names: Vec<&str> = l.formats.iter().map(|f| f.name.as_str()).collect();
(names, &l.mount, l.body)
}))
.finish()
}
}
impl LayerPlan {
pub fn chain(text: &str, resolve: &dyn Resolve) -> Result<Self, LayerError> {
let chain: Chain = text.parse()?;
Self::compile(&chain.0, resolve)
}
pub fn compile(hops: &[HopConfig], resolve: &dyn Resolve) -> Result<Self, LayerError> {
let unsupported = |hop, reason| Err(LayerError::Unsupported { hop, reason });
if hops.is_empty() {
return unsupported(0, "a chain names at least one hop");
}
if hops.len() > MAX_LAYERS {
return unsupported(MAX_LAYERS, "more hops than MAX_LAYERS");
}
let mut layers: Vec<Layer> = Vec::with_capacity(hops.len());
for (i, hop) in hops.iter().enumerate() {
if hop.each {
return unsupported(i, "`each` reads many values, so its layer has no one place");
}
if !matches!(hop.fallback, None | Some(FallbackConfig::Raw)) {
return unsupported(
i,
"a layer that doesn't open reads as its value: only `raw`",
);
}
let FormatChoice::Named(names) = &hop.format else {
return unsupported(i, "`auto` picks a format per record: name the formats");
};
let Some(first) = names.first() else {
return unsupported(i, "a hop names at least one format");
};
let formats = names
.iter()
.map(|name| Format::resolve(name, hop, resolve))
.collect::<Result<Vec<Format>, ResolveError>>()?;
let (mount, body) = match (i, &hop.field, &hop.prefix) {
(0, Some(_), _) => return unsupported(0, "the first hop reads the record"),
(0, None, Some(p)) if !p.is_empty() => {
return unsupported(0, "the first hop's layer is the record's root");
}
(0, None, _) => (Vec::new(), false),
(_, Some(_), Some(_)) => {
return unsupported(i, "a field hop's layer sits at its field");
}
(_, Some(field), None) => {
let mount: Vec<String> = keys(field).map(Cow::into_owned).collect();
if mount.len() > MAX_MOUNT_KEYS {
return unsupported(i, "the field has too many keys");
}
(mount, false)
}
(_, None, prefix) => {
let key = prefix
.as_deref()
.map_or(first.as_str(), |p| p.strip_suffix('.').unwrap_or(p));
let mut mount = keys(key);
let (Some(key), None) = (mount.next(), mount.next()) else {
return unsupported(i, "a body's prefix is one key");
};
if key.is_empty() {
return unsupported(i, "a body's prefix is one key");
}
let before = &layers[i - 1];
let parser_before = before
.formats
.iter()
.any(|f| matches!(&f.read, Read::Parser(p) if p.hands_on_body()));
if !parser_before {
return unsupported(i, "no format of the hop before hands on a body");
}
if before.decodes {
(Vec::new(), true)
} else {
(vec![key.into_owned()], true)
}
}
};
let decodes = formats
.iter()
.all(|f| matches!(&f.read, Read::Parser(p) if p.decodes()));
layers.push(Layer {
formats,
mount,
body,
decodes,
});
}
Ok(Self { layers })
}
pub fn open<'a>(
&'a self,
record: &'a [u8],
cache: &'a LayerCache<'a>,
) -> Result<Layered<'a, Source<'a>>, Miss> {
let slot = &cache.slots[0];
let opened = *slot.open.get_or_init(|| {
cache.opened.fetch_add(1, Ordering::Relaxed);
open_bytes(&self.layers[0].formats, record, slot, None).ok()
});
let base = opened.ok_or(Miss::Malformed)?;
Ok(Layered {
base: Source(base.source),
layers: self,
cache,
})
}
#[must_use]
pub const fn over<'a, R: Walk<'a>>(
&'a self,
base: R,
cache: &'a LayerCache<'a>,
) -> Layered<'a, R> {
Layered {
base,
layers: self,
cache,
}
}
#[must_use]
pub const fn len(&self) -> usize {
self.layers.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.layers.is_empty()
}
}
impl Format {
fn resolve(name: &str, hop: &HopConfig, resolve: &dyn Resolve) -> Result<Self, ResolveError> {
let read = match name {
"ndjson" => Read::Json,
#[cfg(feature = "xml")]
"xml" => Read::Xml,
_ => Read::Parser(resolve.resolve(name, hop.settings.get(name))?),
};
Ok(Self {
name: name.to_owned(),
read,
})
}
}
#[derive(Debug, Default)]
pub struct LayerCache<'a> {
slots: [Slot<'a>; MAX_LAYERS],
opened: AtomicUsize,
unread: AtomicBool,
}
impl LayerCache<'_> {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn opened(&self) -> usize {
self.opened.load(Ordering::Relaxed)
}
fn read_whole(&self) -> bool {
!self.unread.load(Ordering::Relaxed)
&& self
.slots
.iter()
.all(|s| s.fields.get().is_none_or(|f| !json_unread(f.as_slice())))
}
#[cfg(feature = "scrub")]
pub(crate) fn first_read(&self) -> Option<FirstRead> {
let opened = self.slots[0].open.get().copied().flatten()?;
Some(match opened.source {
Src::Json(_) => FirstRead::Json,
#[cfg(feature = "xml")]
Src::Xml(_) => FirstRead::Xml,
Src::Fields(_) => FirstRead::Fields,
})
}
}
#[cfg(feature = "scrub")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FirstRead {
Json,
#[cfg(feature = "xml")]
Xml,
Fields,
}
#[derive(Debug, Default)]
struct Slot<'a> {
decoded: OnceLock<Vec<u8>>,
body: OnceLock<Vec<u8>>,
fields: OnceLock<Fields<'a>>,
open: OnceLock<Option<Opened<'a>>>,
}
#[derive(Debug, Clone, Copy)]
struct Opened<'a> {
bytes: &'a [u8],
source: Src<'a>,
#[cfg_attr(
not(feature = "scrub"),
expect(dead_code, reason = "read only by scrub write-back")
)]
format: usize,
body: Option<&'a [u8]>,
hint: Option<&'static str>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Unopened {
Plain,
Broken,
}
fn open_bytes<'a>(
formats: &[Format],
bytes: &'a [u8],
slot: &'a Slot<'a>,
hint: Option<&str>,
) -> Result<Opened<'a>, Unopened> {
let first = bytes.iter().find(|b| !b.is_ascii_whitespace()).copied();
let mut named = false;
for (format, f) in formats.iter().enumerate() {
let read = match &f.read {
Read::Json => {
(first == Some(b'{')).then_some((Src::Json(Json::new(bytes)), None, None))
}
#[cfg(feature = "xml")]
Read::Xml => (first == Some(b'<')).then_some((Src::Xml(Xml::new(bytes)), None, None)),
Read::Parser(parser) => {
let mut fields = Fields::new();
let read = match parser.parse(bytes, &mut fields) {
Ok(Parsed::Done) => Some((None, None)),
Ok(Parsed::Body { span, hint }) => bytes.get(span).map(|b| (Some(b), hint)),
Ok(Parsed::Decoded(decoded)) => {
let hint = decoded.hint();
let body = slot.body.get_or_init(|| decoded.into_vec()).as_slice();
Some((Some(body), hint))
}
_ => None,
};
named |= read.is_none() && parser.signature().marks(bytes);
read.map(|(body, hint)| {
(Src::Fields(slot.fields.get_or_init(|| fields)), body, hint)
})
}
};
let Some((source, body, body_hint)) = read else {
named |= hint == Some(f.name.as_str());
continue;
};
return Ok(Opened {
bytes,
source,
format,
body,
hint: body_hint,
});
}
Err(if named {
Unopened::Broken
} else {
Unopened::Plain
})
}
#[derive(Debug, Clone, Copy)]
pub struct Source<'a>(Src<'a>);
#[derive(Debug, Clone, Copy)]
enum Src<'a> {
Json(Json<'a>),
#[cfg(feature = "xml")]
Xml(Xml<'a>),
Fields(&'a Fields<'a>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourceAt<'a>(SrcAt<'a>);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SrcAt<'a> {
Json(&'a str),
#[cfg(feature = "xml")]
Xml(XmlAt),
Fields(FieldsAt<'a>),
}
impl<'a> Record<'a> for Source<'a> {
type At = SourceAt<'a>;
fn find<K: AsRef<str>>(self, path: &[K]) -> Result<SourceAt<'a>, Miss> {
Ok(SourceAt(match self.0 {
Src::Json(r) => SrcAt::Json(r.find(path)?),
#[cfg(feature = "xml")]
Src::Xml(r) => SrcAt::Xml(r.find(path)?),
Src::Fields(r) => SrcAt::Fields(r.find(path)?),
}))
}
fn find_below<K: AsRef<str>>(self, at: SourceAt<'a>, path: &[K]) -> Result<SourceAt<'a>, Miss> {
Ok(SourceAt(match (self.0, at.0) {
(Src::Json(r), SrcAt::Json(at)) => SrcAt::Json(r.find_below(at, path)?),
#[cfg(feature = "xml")]
(Src::Xml(r), SrcAt::Xml(at)) => SrcAt::Xml(r.find_below(at, path)?),
(Src::Fields(r), SrcAt::Fields(at)) => SrcAt::Fields(r.find_below(at, path)?),
_ => return Err(Miss::Malformed),
}))
}
fn typed(self, at: SourceAt<'a>) -> Result<Typed<'a>, Miss> {
match (self.0, at.0) {
(Src::Json(r), SrcAt::Json(at)) => r.typed(at),
#[cfg(feature = "xml")]
(Src::Xml(r), SrcAt::Xml(at)) => r.typed(at),
(Src::Fields(r), SrcAt::Fields(at)) => r.typed(at),
_ => Err(Miss::Malformed),
}
}
fn typed_exact(self, at: SourceAt<'a>) -> Result<Typed<'a>, Miss> {
match (self.0, at.0) {
(Src::Json(r), SrcAt::Json(at)) => r.typed_exact(at),
#[cfg(feature = "xml")]
(Src::Xml(r), SrcAt::Xml(at)) => r.typed_exact(at),
(Src::Fields(r), SrcAt::Fields(at)) => r.typed_exact(at),
_ => Err(Miss::Malformed),
}
}
fn text(self, at: SourceAt<'a>) -> Result<Cow<'a, str>, Miss> {
match (self.0, at.0) {
(Src::Json(r), SrcAt::Json(at)) => r.text(at),
#[cfg(feature = "xml")]
(Src::Xml(r), SrcAt::Xml(at)) => r.text(at),
(Src::Fields(r), SrcAt::Fields(at)) => r.text(at),
_ => Err(Miss::Malformed),
}
}
}
impl<'a> Walk<'a> for Source<'a> {
fn walk<F: FnMut(Node<'a, SourceAt<'a>>)>(self, mut visit: F) -> Result<(), Miss> {
match self.0 {
Src::Json(r) => r.walk(|n| visit(retag(n, |at| SourceAt(SrcAt::Json(at))))),
#[cfg(feature = "xml")]
Src::Xml(r) => r.walk(|n| visit(retag(n, |at| SourceAt(SrcAt::Xml(at))))),
Src::Fields(r) => r.walk(|n| visit(retag(n, |at| SourceAt(SrcAt::Fields(at))))),
}
}
fn read_whole(self) -> bool {
match self.0 {
Src::Fields(r) => r.read_whole(),
_ => true,
}
}
fn bytes(self, at: SourceAt<'a>) -> Result<Cow<'a, [u8]>, Miss> {
match (self.0, at.0) {
(Src::Json(r), SrcAt::Json(at)) => r.bytes(at),
#[cfg(feature = "xml")]
(Src::Xml(r), SrcAt::Xml(at)) => r.bytes(at),
(Src::Fields(r), SrcAt::Fields(at)) => r.bytes(at),
_ => Err(Miss::Malformed),
}
}
}
fn retag<A, B>(n: Node<'_, A>, place: impl FnOnce(A) -> B) -> Node<'_, B> {
Node {
depth: n.depth,
key: n.key,
kind: n.kind,
at: place(n.at),
}
}
#[derive(Debug, Clone, Copy)]
pub struct Layered<'a, R> {
base: R,
layers: &'a LayerPlan,
cache: &'a LayerCache<'a>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LayeredAt<'a, A> {
place: Place<'a, A>,
toward: u8,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Place<'a, A> {
Base(A),
Root(u8),
Inner(u8, SourceAt<'a>),
}
#[derive(Clone, Copy)]
enum Start<'a, A> {
BaseRoot,
At(Place<'a, A>),
}
impl<A> Start<'_, A> {
const fn layer(&self) -> usize {
match self {
Self::BaseRoot | Self::At(Place::Base(_)) => 0,
Self::At(Place::Root(k) | Place::Inner(k, _)) => *k as usize,
}
}
}
const fn layer_root<'a, A>(k: usize) -> Start<'a, A> {
if k == 0 {
Start::BaseRoot
} else {
Start::At(Place::Root(index(k)))
}
}
#[allow(
clippy::cast_possible_truncation,
reason = "a layer index is below MAX_LAYERS"
)]
const fn index(k: usize) -> u8 {
k as u8
}
impl<'a, R: Walk<'a>> Layered<'a, R>
where
R::At: PartialEq,
{
fn opened(self, k: usize) -> Option<Opened<'a>> {
self.cache.slots.get(k)?.open.get().copied().flatten()
}
fn source(self, k: u8) -> Result<Source<'a>, Miss> {
self.opened(usize::from(k))
.map(|o| Source(o.source))
.ok_or(Miss::Malformed)
}
fn open_body(self, j: usize) -> Option<Opened<'a>> {
self.open_from(j, |_| {
let before = self.opened(j.checked_sub(1)?)?;
Some((before.body?, before.hint))
})
}
fn open_value(
self,
j: usize,
read: impl FnOnce() -> Result<Cow<'a, [u8]>, Miss>,
) -> Option<Opened<'a>> {
self.open_from(j, |slot| match read() {
Ok(Cow::Borrowed(bytes)) => Some((bytes, None)),
Ok(Cow::Owned(bytes)) => Some((slot.decoded.get_or_init(|| bytes).as_slice(), None)),
Err(_) => {
self.cache.unread.store(true, Ordering::Relaxed);
None
}
})
}
fn open_from(
self,
j: usize,
bytes: impl FnOnce(&'a Slot<'a>) -> Option<(&'a [u8], Option<&'static str>)>,
) -> Option<Opened<'a>> {
let slot = self.cache.slots.get(j)?;
let layer = self.layers.layers.get(j)?;
*slot.open.get_or_init(|| {
self.cache.opened.fetch_add(1, Ordering::Relaxed);
let (bytes, hint) = bytes(slot)?;
let opened = open_bytes(&layer.formats, bytes, slot, hint);
if matches!(opened, Err(Unopened::Broken)) {
self.cache.unread.store(true, Ordering::Relaxed);
}
opened.ok()
})
}
fn descend<K: AsRef<str>>(
self,
from: Start<'a, R::At>,
toward: u8,
path: &[K],
) -> Result<LayeredAt<'a, R::At>, Miss> {
let k = from.layer();
let Some(next) = self.layers.layers.get(k + 1).filter(|_| toward != OFF) else {
return self.read(from, OFF, path);
};
let matched = usize::from(toward);
let rest = next.mount.get(matched..).unwrap_or_default();
let n = rest
.iter()
.zip(path)
.take_while(|(m, key)| m.as_str() == key.as_ref())
.count();
if n < rest.len() {
let toward = if n == path.len() {
index(matched + n)
} else {
OFF
};
return self.read(from, toward, path);
}
let opened = if next.body {
self.open_body(k + 1)
} else {
let anchor = self.read(from, OFF, &path[..n])?;
let at_mount = matched == 0
|| self
.read(layer_root(k), OFF, &next.mount)
.is_ok_and(|at| same_value(self, at, anchor));
if at_mount {
self.open_value(k + 1, || self.bytes(anchor))
} else {
None
}
};
if opened.is_none() {
return self.read(from, OFF, path);
}
self.descend(Start::At(Place::Root(index(k + 1))), 0, &path[n..])
}
fn read<K: AsRef<str>>(
self,
from: Start<'a, R::At>,
toward: u8,
path: &[K],
) -> Result<LayeredAt<'a, R::At>, Miss> {
let place = match from {
Start::BaseRoot => Place::Base(self.base.find(path)?),
Start::At(Place::Base(at)) => Place::Base(self.base.find_below(at, path)?),
Start::At(Place::Root(k)) if path.is_empty() => Place::Root(k),
Start::At(Place::Root(k)) => match self.source(k)?.find(path) {
Ok(at) => Place::Inner(k, at),
Err(Miss::MissingRoot) => return Err(Miss::MissingField),
Err(miss) => return Err(miss),
},
Start::At(Place::Inner(k, at)) => {
Place::Inner(k, self.source(k)?.find_below(at, path)?)
}
};
Ok(LayeredAt { place, toward })
}
}
impl<'a, R: Walk<'a>> Record<'a> for Layered<'a, R>
where
R::At: PartialEq,
{
type At = LayeredAt<'a, R::At>;
fn find<K: AsRef<str>>(self, path: &[K]) -> Result<Self::At, Miss> {
if path.is_empty() {
return Err(Miss::MissingRoot);
}
self.descend(Start::BaseRoot, 0, path)
}
fn find_below<K: AsRef<str>>(self, at: Self::At, path: &[K]) -> Result<Self::At, Miss> {
if path.is_empty() {
return Ok(at);
}
self.descend(Start::At(at.place), at.toward, path)
}
fn typed(self, at: Self::At) -> Result<Typed<'a>, Miss> {
match at.place {
Place::Base(at) => self.base.typed(at),
Place::Root(_) => Ok(Typed::Map),
Place::Inner(k, at) => self.source(k)?.typed(at),
}
}
fn typed_exact(self, at: Self::At) -> Result<Typed<'a>, Miss> {
match at.place {
Place::Base(at) => self.base.typed_exact(at),
Place::Root(_) => Ok(Typed::Map),
Place::Inner(k, at) => self.source(k)?.typed_exact(at),
}
}
fn text(self, at: Self::At) -> Result<Cow<'a, str>, Miss> {
match at.place {
Place::Base(at) => self.base.text(at),
Place::Root(k) => {
let bytes = self.opened(usize::from(k)).ok_or(Miss::Malformed)?.bytes;
std::str::from_utf8(bytes)
.map(Cow::Borrowed)
.map_err(|_| Miss::Malformed)
}
Place::Inner(k, at) => self.source(k)?.text(at),
}
}
}
type Visit<'v, 'a, A> = dyn FnMut(Node<'a, LayeredAt<'a, A>>) + 'v;
impl<'a, R: Walk<'a>> Walk<'a> for Layered<'a, R>
where
R::At: PartialEq,
{
fn walk<F: FnMut(Node<'a, Self::At>)>(self, mut visit: F) -> Result<(), Miss> {
self.walk_layer(self.base, 0, 0, Place::Base, &mut visit)
}
fn read_whole(self) -> bool {
self.base.read_whole() && self.cache.read_whole()
}
fn bytes(self, at: Self::At) -> Result<Cow<'a, [u8]>, Miss> {
match at.place {
Place::Base(at) => self.base.bytes(at),
Place::Root(k) => self
.opened(usize::from(k))
.map(|o| Cow::Borrowed(o.bytes))
.ok_or(Miss::Malformed),
Place::Inner(k, at) => self.source(k)?.bytes(at),
}
}
}
impl<'a, R: Walk<'a>> Layered<'a, R>
where
R::At: PartialEq,
{
fn walk_layer<S: Walk<'a>>(
self,
record: S,
k: usize,
offset: usize,
wrap: impl Fn(S::At) -> Place<'a, R::At>,
visit: &mut Visit<'_, 'a, R::At>,
) -> Result<(), Miss>
where
S::At: PartialEq,
{
let next = self.layers.layers.get(k + 1);
let mount = next.filter(|l| !l.body).map(|l| l.mount.as_slice());
let mut body_nodes = Vec::new();
let body = match next
.filter(|l| l.body)
.and_then(|l| Some((l, self.open_body(k + 1)?)))
{
Some((layer, opened)) => {
let walked = if layer.mount.is_empty() {
let mut nodes = Vec::new();
let walked = self.walk_beside(k + 1, offset, opened, &mut |n| nodes.push(n));
if walked {
body_nodes = nodes;
}
walked
} else {
let key = layer.mount.first().cloned().map(Cow::Owned);
let root = root_node(k + 1, offset, key);
self.walk_inner(k + 1, offset + 1, root, &mut |n| body_nodes.push(n))
};
self.opened(k).and_then(|o| o.body).filter(|_| walked)
}
None => None,
};
let mut path: Vec<Option<Cow<'a, str>>> = Vec::new();
let mut skip: Option<usize> = None;
let mut met = false;
record.walk(|node| {
if let Some(depth) = skip {
if node.depth > depth {
return;
}
skip = None;
}
if let Some(body) = body
&& node.kind == Kind::Str
&& record
.bytes(node.at)
.is_ok_and(|b| matches!(b, Cow::Borrowed(b) if overlaps(b, body)))
{
return;
}
path.truncate(node.depth);
path.push(node.key.clone());
let at = LayeredAt {
place: wrap(node.at),
toward: OFF,
};
let mounted = mount.filter(|m| {
m.len() == path.len()
&& path
.iter()
.zip(*m)
.all(|(key, m)| key.as_deref() == Some(m.as_str()))
});
let found = mounted.is_some_and(|m| {
let first = !std::mem::replace(&mut met, true);
let named = first
&& record
.find(m)
.is_ok_and(|at| same_value(record, at, node.at));
if !named {
self.cache.unread.store(true, Ordering::Relaxed);
}
named
});
if found && self.open_value(k + 1, || record.bytes(node.at)).is_some() {
let root = root_node(k + 1, offset + node.depth, node.key.clone());
if self.walk_inner(k + 1, offset + node.depth + 1, root, visit) {
if matches!(node.kind, Kind::Map | Kind::List) {
skip = Some(node.depth);
}
return;
}
}
visit(Node {
depth: offset + node.depth,
key: node.key,
kind: node.kind,
at,
});
})?;
for n in body_nodes {
visit(n);
}
Ok(())
}
fn walk_beside(
self,
j: usize,
offset: usize,
opened: Opened<'a>,
visit: &mut Visit<'_, 'a, R::At>,
) -> bool {
let place = move |at| Place::Inner(index(j), at);
let walked = self
.walk_layer(Source(opened.source), j, offset, place, visit)
.is_ok();
if !walked {
self.cache.unread.store(true, Ordering::Relaxed);
}
walked
}
fn walk_inner(
self,
j: usize,
offset: usize,
root: Node<'a, LayeredAt<'a, R::At>>,
visit: &mut Visit<'_, 'a, R::At>,
) -> bool {
let Some(opened) = self.opened(j) else {
return false;
};
let mut root = Some(root);
let mut first = |n: Node<'a, LayeredAt<'a, R::At>>| {
if let Some(root) = root.take() {
visit(root);
}
visit(n);
};
let place = move |at| Place::Inner(index(j), at);
let walked = self.walk_layer(Source(opened.source), j, offset, place, &mut first);
if walked.is_err() {
self.cache.unread.store(true, Ordering::Relaxed);
}
match (walked, root) {
(Ok(()), Some(root)) => {
visit(root);
true
}
(Ok(()) | Err(_), None) => true,
(Err(_), Some(_)) => false,
}
}
}
const fn root_node<A>(
j: usize,
depth: usize,
key: Option<Cow<'_, str>>,
) -> Node<'_, LayeredAt<'_, A>> {
Node {
depth,
key,
kind: Kind::Map,
at: LayeredAt {
place: Place::Root(index(j)),
toward: 0,
},
}
}
fn same_value<'a, S: Walk<'a>>(record: S, a: S::At, b: S::At) -> bool
where
S::At: PartialEq,
{
a == b
|| matches!(
(record.bytes(a), record.bytes(b)),
(Ok(Cow::Borrowed(x)), Ok(Cow::Borrowed(y)))
if !x.is_empty() && x.as_ptr_range() == y.as_ptr_range()
)
}
fn overlaps(a: &[u8], b: &[u8]) -> bool {
let (a, b) = (a.as_ptr_range(), b.as_ptr_range());
a.start.addr() < b.end.addr() && b.start.addr() < a.end.addr()
}
#[cfg(feature = "scrub")]
mod write;
#[cfg(test)]
mod tests;