Skip to main content

toargv_template/
path.rs

1use serde_json::Value;
2
3use crate::error::Error;
4
5/// A validated dotted path into a JSON-compatible configuration tree.
6///
7/// Each segment traverses an object key. Array indexes and escaping literal
8/// dots in keys are not supported.
9#[derive(Clone, Debug, Eq, PartialEq)]
10pub struct ConfigPath {
11    raw: String,
12    segments: Vec<String>,
13}
14
15impl ConfigPath {
16    /// Parses a nonempty dotted path with no empty segments.
17    pub fn parse(path: &str) -> Result<Self, Error> {
18        if path.is_empty() {
19            return Err(Error::InvalidPath {
20                path: path.to_owned(),
21                message: "paths cannot be empty".to_owned(),
22            });
23        }
24
25        let segments: Vec<_> = path.split('.').map(str::to_owned).collect();
26        if segments.iter().any(String::is_empty) {
27            return Err(Error::InvalidPath {
28                path: path.to_owned(),
29                message: "paths cannot contain empty segments".to_owned(),
30            });
31        }
32
33        Ok(Self {
34            raw: path.to_owned(),
35            segments,
36        })
37    }
38
39    /// Resolves this path against `root`.
40    ///
41    /// Returns `None` if a segment is absent or an intermediate value is not
42    /// an object.
43    pub fn resolve<'a>(&self, root: &'a Value) -> Option<&'a Value> {
44        let mut current = root;
45        for segment in &self.segments {
46            current = current.as_object()?.get(segment)?;
47        }
48        Some(current)
49    }
50
51    /// Returns the original dotted path.
52    pub fn as_str(&self) -> &str {
53        &self.raw
54    }
55}