laravel-data 0.2.0

Powerful data objects for Laravel Rust: a port of spatie/laravel-data.
Documentation
//! Partials: the `include`, `exclude`, `only` and `except` paths, such as `songs.{name, artist}`.

use std::collections::BTreeMap;

/// A tree of partial paths.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Partials {
    /// `*`: every property on this level.
    pub(crate) all: bool,
    /// `**`: every property on this level and below.
    pub(crate) recursive: bool,
    pub(crate) children: BTreeMap<String, Partials>,
}

impl Partials {
    /// Parses paths such as `songs`, `songs.name`, `songs.{name, artist}`, `songs.*` and `**`.
    #[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),
        }
    }

    /// Merges another tree into this one.
    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()
    }

    /// Whether `key` is named on this level, by name, `*` or `**`.
    pub(crate) fn contains(&self, key: &str) -> bool {
        self.all || self.recursive || self.children.contains_key(key)
    }

    /// Whether `key` is named as a leaf: the property itself, not only its children.
    pub(crate) fn contains_leaf(&self, key: &str) -> bool {
        self.all || self.recursive || self.children.get(key).is_some_and(Self::is_empty)
    }

    /// The tree below `key`.
    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
    }
}

/// Splits a path on dots outside braces.
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"));
    }
}