use super::EntryPattern;
use super::Matcher;
use smallvec::SmallVec;
use std::collections::HashMap;
use std::ops::ControlFlow;
type Owners = SmallVec<[usize; 1]>;
type KeyMap = HashMap<Box<[u8]>, Owners>;
fn add_owner(map: &mut KeyMap, key: &[u8], owner: usize) {
map.entry(key.into()).or_default().push(owner);
}
fn visit_owners(
owners: &Owners,
visit: &mut impl FnMut(usize) -> ControlFlow<()>,
) -> ControlFlow<()> {
owners.iter().try_for_each(|owner| visit(*owner))
}
fn key_lengths(map: &KeyMap) -> Box<[usize]> {
let mut lengths: Vec<usize> = map.keys().map(|key| key.len()).collect();
lengths.sort_unstable();
lengths.dedup();
lengths.into_boxed_slice()
}
#[derive(Default)]
pub(super) struct DirectIndex {
floating: KeyMap,
anchored: KeyMap,
longest_anchored: usize,
suffixes: KeyMap,
suffix_lengths: Box<[usize]>,
match_all: Owners,
}
impl DirectIndex {
pub(super) fn new<'a>(patterns: impl IntoIterator<Item = (usize, &'a EntryPattern)>) -> Self {
let mut index = Self::default();
for (position, pattern) in patterns {
match &pattern.matcher {
Matcher::All => index.match_all.push(position),
Matcher::Name(name) => add_owner(&mut index.floating, name.as_bytes(), position),
Matcher::Suffix(suffix) => {
add_owner(&mut index.suffixes, suffix.as_bytes(), position);
}
Matcher::Path(path) => add_owner(&mut index.anchored, path.as_bytes(), position),
Matcher::Glob { .. } => {}
}
}
index.suffix_lengths = key_lengths(&index.suffixes);
index.longest_anchored = index
.anchored
.keys()
.map(|key| key.len())
.max()
.unwrap_or(0);
index
}
pub(super) fn visit(
&self,
path: &[u8],
mut visit: impl FnMut(usize) -> ControlFlow<()>,
) -> ControlFlow<()> {
visit_owners(&self.match_all, &mut visit)?;
self.visit_anchored(path, &mut visit)?;
path.split(|byte| *byte == b'/')
.try_for_each(|component| self.visit_component(component, &mut visit))
}
fn visit_anchored(
&self,
path: &[u8],
visit: &mut impl FnMut(usize) -> ControlFlow<()>,
) -> ControlFlow<()> {
if self.anchored.is_empty() {
return ControlFlow::Continue(());
}
let slashes = path
.iter()
.enumerate()
.take(self.longest_anchored.saturating_add(1))
.filter(|(_, byte)| **byte == b'/')
.map(|(at, _)| at);
let end = (path.len() <= self.longest_anchored).then_some(path.len());
slashes.chain(end).try_for_each(|boundary| {
path.get(..boundary)
.and_then(|prefix| self.anchored.get(prefix))
.map_or(ControlFlow::Continue(()), |owners| {
visit_owners(owners, visit)
})
})
}
fn visit_component(
&self,
component: &[u8],
visit: &mut impl FnMut(usize) -> ControlFlow<()>,
) -> ControlFlow<()> {
if let Some(owners) = self.floating.get(component) {
visit_owners(owners, visit)?;
}
for length in &self.suffix_lengths {
let Some(start) = component.len().checked_sub(*length) else {
break;
};
if let Some(owners) = component
.get(start..)
.and_then(|suffix| self.suffixes.get(suffix))
{
visit_owners(owners, visit)?;
}
}
ControlFlow::Continue(())
}
}