Skip to main content

laravel_data/
partials.rs

1//! Partials: the `include`, `exclude`, `only` and `except` paths, such as `songs.{name, artist}`.
2
3use std::collections::BTreeMap;
4
5/// A tree of partial paths.
6#[derive(Debug, Clone, Default, PartialEq, Eq)]
7pub struct Partials {
8    /// `*`: every property on this level.
9    pub(crate) all: bool,
10    /// `**`: every property on this level and below.
11    pub(crate) recursive: bool,
12    pub(crate) children: BTreeMap<String, Partials>,
13}
14
15impl Partials {
16    /// Parses paths such as `songs`, `songs.name`, `songs.{name, artist}`, `songs.*` and `**`.
17    #[must_use]
18    pub fn parse<S: AsRef<str>>(paths: impl IntoIterator<Item = S>) -> Self {
19        let mut tree = Self::default();
20        for path in paths {
21            tree.add(&split(path.as_ref()));
22        }
23        tree
24    }
25
26    fn add(&mut self, segments: &[String]) {
27        let Some((first, rest)) = segments.split_first() else {
28            return;
29        };
30        if first.starts_with('{') && first.ends_with('}') {
31            for name in first[1..first.len() - 1].split(',') {
32                let mut path = vec![name.trim().to_owned()];
33                path.extend_from_slice(rest);
34                self.add(&path);
35            }
36            return;
37        }
38        match first.as_str() {
39            "**" => self.recursive = true,
40            "*" => self.all = true,
41            name => self.children.entry(name.to_owned()).or_default().add(rest),
42        }
43    }
44
45    /// Merges another tree into this one.
46    pub(crate) fn merge(&mut self, other: &Self) {
47        self.all |= other.all;
48        self.recursive |= other.recursive;
49        for (name, child) in &other.children {
50            self.children.entry(name.clone()).or_default().merge(child);
51        }
52    }
53
54    pub(crate) fn is_empty(&self) -> bool {
55        !self.all && !self.recursive && self.children.is_empty()
56    }
57
58    /// Whether `key` is named on this level, by name, `*` or `**`.
59    pub(crate) fn contains(&self, key: &str) -> bool {
60        self.all || self.recursive || self.children.contains_key(key)
61    }
62
63    /// Whether `key` is named as a leaf: the property itself, not only its children.
64    pub(crate) fn contains_leaf(&self, key: &str) -> bool {
65        self.all || self.recursive || self.children.get(key).is_some_and(Self::is_empty)
66    }
67
68    /// The tree below `key`.
69    pub(crate) fn child(&self, key: &str) -> Self {
70        let mut child = self.children.get(key).cloned().unwrap_or_default();
71        if self.recursive {
72            child.recursive = true;
73        }
74        child
75    }
76}
77
78/// Splits a path on dots outside braces.
79fn split(path: &str) -> Vec<String> {
80    let mut segments = Vec::new();
81    let mut current = String::new();
82    let mut depth = 0;
83    for character in path.chars() {
84        match character {
85            '{' => {
86                depth += 1;
87                current.push(character);
88            }
89            '}' => {
90                depth -= 1;
91                current.push(character);
92            }
93            '.' if depth == 0 => segments.push(std::mem::take(&mut current)),
94            _ => current.push(character),
95        }
96    }
97    if !current.is_empty() {
98        segments.push(current);
99    }
100    segments.into_iter().map(|segment| segment.trim().to_owned()).collect()
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn parses_nested_and_grouped_paths() {
109        let tree = Partials::parse(["songs.{name, artist}", "title", "*"]);
110        assert!(tree.all);
111        assert!(tree.contains_leaf("title"));
112        let songs = tree.child("songs");
113        assert!(songs.contains_leaf("name") && songs.contains_leaf("artist"));
114        assert!(!songs.contains("year"));
115    }
116}