use std::collections::BTreeMap;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Partials {
pub(crate) all: bool,
pub(crate) recursive: bool,
pub(crate) children: BTreeMap<String, Partials>,
}
impl Partials {
#[must_use]
pub fn parse<S: AsRef<str>>(paths: impl IntoIterator<Item = S>) -> Self {
let mut tree = Self::default();
for path in paths {
tree.add(&split(path.as_ref()));
}
tree
}
fn add(&mut self, segments: &[String]) {
let Some((first, rest)) = segments.split_first() else {
return;
};
if first.starts_with('{') && first.ends_with('}') {
for name in first[1..first.len() - 1].split(',') {
let mut path = vec![name.trim().to_owned()];
path.extend_from_slice(rest);
self.add(&path);
}
return;
}
match first.as_str() {
"**" => self.recursive = true,
"*" => self.all = true,
name => self.children.entry(name.to_owned()).or_default().add(rest),
}
}
pub(crate) fn merge(&mut self, other: &Self) {
self.all |= other.all;
self.recursive |= other.recursive;
for (name, child) in &other.children {
self.children.entry(name.clone()).or_default().merge(child);
}
}
pub(crate) fn is_empty(&self) -> bool {
!self.all && !self.recursive && self.children.is_empty()
}
pub(crate) fn contains(&self, key: &str) -> bool {
self.all || self.recursive || self.children.contains_key(key)
}
pub(crate) fn contains_leaf(&self, key: &str) -> bool {
self.all || self.recursive || self.children.get(key).is_some_and(Self::is_empty)
}
pub(crate) fn child(&self, key: &str) -> Self {
let mut child = self.children.get(key).cloned().unwrap_or_default();
if self.recursive {
child.recursive = true;
}
child
}
}
fn split(path: &str) -> Vec<String> {
let mut segments = Vec::new();
let mut current = String::new();
let mut depth = 0;
for character in path.chars() {
match character {
'{' => {
depth += 1;
current.push(character);
}
'}' => {
depth -= 1;
current.push(character);
}
'.' if depth == 0 => segments.push(std::mem::take(&mut current)),
_ => current.push(character),
}
}
if !current.is_empty() {
segments.push(current);
}
segments.into_iter().map(|segment| segment.trim().to_owned()).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_nested_and_grouped_paths() {
let tree = Partials::parse(["songs.{name, artist}", "title", "*"]);
assert!(tree.all);
assert!(tree.contains_leaf("title"));
let songs = tree.child("songs");
assert!(songs.contains_leaf("name") && songs.contains_leaf("artist"));
assert!(!songs.contains("year"));
}
}