Skip to main content

trilean_json_shape/
path.rs

1//! Where in a document a problem is, and the problems a validation collects.
2
3use std::collections::HashMap;
4use std::error::Error;
5use std::fmt;
6
7/// One step into a document: an object key or an array index.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub enum PathSegment {
10    Key(String),
11    Index(usize),
12}
13
14/// The steps from the root of a document to a value inside it. It also carries what a conversion of one document
15/// remembers between its nodes (which alternative of a union accepted which value), so that choosing among
16/// alternatives costs each value once.
17/// Only this crate makes one (`Shape::from_json` makes a fresh one for each document), so what it remembers cannot
18/// outlive the document it was made on.
19#[derive(Debug)]
20pub struct Path {
21    segments: Vec<PathSegment>,
22    pub(crate) memo: HashMap<(usize, usize), bool>,
23}
24
25impl Path {
26    pub(crate) fn new() -> Self {
27        Path {
28            segments: Vec::new(),
29            memo: HashMap::new(),
30        }
31    }
32
33    pub fn push_key(&mut self, key: &str) {
34        self.segments.push(PathSegment::Key(key.to_owned()));
35    }
36
37    pub fn push_index(&mut self, index: usize) {
38        self.segments.push(PathSegment::Index(index));
39    }
40
41    pub fn pop(&mut self) {
42        self.segments.pop();
43    }
44
45    pub fn segments(&self) -> &[PathSegment] {
46        &self.segments
47    }
48}
49
50/// One problem with a document, at the path of the value it is about.
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct Issue {
53    pub path: Vec<PathSegment>,
54    pub message: String,
55}
56
57impl Issue {
58    /// The path as an RFC 6901 JSON Pointer, which is the empty string for the root.
59    pub fn pointer(&self) -> String {
60        let mut pointer = String::new();
61        for segment in &self.path {
62            pointer.push('/');
63            match segment {
64                PathSegment::Key(key) => {
65                    pointer.push_str(&key.replace('~', "~0").replace('/', "~1"))
66                }
67                PathSegment::Index(index) => pointer.push_str(&index.to_string()),
68            }
69        }
70        pointer
71    }
72}
73
74impl fmt::Display for Issue {
75    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
76        let pointer = self.pointer();
77        let at = if pointer.is_empty() {
78            "(root)"
79        } else {
80            &pointer
81        };
82        write!(formatter, "{at}: {}", self.message)
83    }
84}
85
86/// Every problem a validation found, never empty when it is an error.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct Issues(pub Vec<Issue>);
89
90impl Issues {
91    pub fn at(path: &Path, message: impl Into<String>) -> Self {
92        Issues(vec![Issue {
93            path: path.segments().to_vec(),
94            message: message.into(),
95        }])
96    }
97}
98
99impl fmt::Display for Issues {
100    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
101        for (position, issue) in self.0.iter().enumerate() {
102            if position > 0 {
103                formatter.write_str("; ")?;
104            }
105            write!(formatter, "{issue}")?;
106        }
107        Ok(())
108    }
109}
110
111impl Error for Issues {}
112
113#[cfg(test)]
114mod tests {
115    use crate::{Path, Shape, Value};
116
117    #[derive(Shape, Debug, PartialEq)]
118    #[serde(untagged)]
119    enum Either {
120        Count(u8),
121        Text(String),
122    }
123
124    /// What one conversion remembers is keyed by where a value sits, so a `Path` that met a second document at the
125    /// same address would answer for the first. Here the second document is the same place holding another value.
126    #[test]
127    fn a_path_kept_across_two_documents_would_answer_for_the_first() {
128        let mut document = Value::Number(1.0);
129        let mut path = Path::new();
130        assert_eq!(Either::build(&document, &mut path), Ok(Either::Count(1)));
131        document = Value::String("a".to_owned());
132        assert!(
133            Either::build(&document, &mut path).is_err(),
134            "the memory of the first document is stale for the second, which is why no caller may keep a Path"
135        );
136        // `from_json`, the only way a caller converts, makes a fresh Path for each document.
137        assert_eq!(
138            Either::from_json(&document),
139            Ok(Either::Text("a".to_owned()))
140        );
141    }
142
143    #[test]
144    fn a_fresh_path_has_no_memory() {
145        let path = Path::new();
146        assert!(path.memo.is_empty());
147    }
148}