trilean_json_shape/
path.rs1use std::collections::HashMap;
4use std::error::Error;
5use std::fmt;
6
7#[derive(Clone, Debug, PartialEq, Eq)]
9pub enum PathSegment {
10 Key(String),
11 Index(usize),
12}
13
14#[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#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct Issue {
53 pub path: Vec<PathSegment>,
54 pub message: String,
55}
56
57impl Issue {
58 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#[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 #[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 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}