1use core::fmt;
26
27#[derive(Clone, Debug, PartialEq, Eq)]
29pub struct Violation {
30 pub pointer: String,
34 pub code: ViolationCode,
36 pub message: String,
38}
39
40impl fmt::Display for Violation {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 let at = if self.pointer.is_empty() { "/" } else { &self.pointer };
43 write!(f, "{at}: {}", self.message)
44 }
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
49#[non_exhaustive]
50pub enum ViolationCode {
51 TooLong,
53 TooShort,
55 PatternMismatch,
57 EmptyRequiredList,
59 TooManyItems,
61 OutOfRange,
63 Inconsistent,
65 MissingConditional,
67 ExclusiveChoice,
69 Imprecise,
71}
72
73impl ViolationCode {
74 #[must_use]
76 pub const fn as_str(self) -> &'static str {
77 match self {
78 Self::TooLong => "too_long",
79 Self::TooShort => "too_short",
80 Self::PatternMismatch => "pattern_mismatch",
81 Self::EmptyRequiredList => "empty_required_list",
82 Self::TooManyItems => "too_many_items",
83 Self::OutOfRange => "out_of_range",
84 Self::Inconsistent => "inconsistent",
85 Self::MissingConditional => "missing_conditional",
86 Self::ExclusiveChoice => "exclusive_choice",
87 Self::Imprecise => "imprecise",
88 }
89 }
90}
91
92impl fmt::Display for ViolationCode {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 f.write_str(self.as_str())
95 }
96}
97
98#[derive(Clone, Debug, PartialEq, Eq, Default)]
100pub struct Violations(Vec<Violation>);
101
102impl Violations {
103 #[must_use]
105 pub fn as_slice(&self) -> &[Violation] {
106 &self.0
107 }
108
109 #[must_use]
111 pub fn is_empty(&self) -> bool {
112 self.0.is_empty()
113 }
114
115 #[must_use]
117 pub fn len(&self) -> usize {
118 self.0.len()
119 }
120
121 #[must_use]
123 pub fn into_vec(self) -> Vec<Violation> {
124 self.0
125 }
126
127 pub fn iter(&self) -> core::slice::Iter<'_, Violation> {
129 self.0.iter()
130 }
131}
132
133impl IntoIterator for Violations {
134 type Item = Violation;
135 type IntoIter = std::vec::IntoIter<Violation>;
136 fn into_iter(self) -> Self::IntoIter {
137 self.0.into_iter()
138 }
139}
140
141impl<'a> IntoIterator for &'a Violations {
142 type Item = &'a Violation;
143 type IntoIter = core::slice::Iter<'a, Violation>;
144 fn into_iter(self) -> Self::IntoIter {
145 self.iter()
146 }
147}
148
149impl fmt::Display for Violations {
150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151 for (i, v) in self.0.iter().enumerate() {
152 if i > 0 {
153 f.write_str("; ")?;
154 }
155 write!(f, "{v}")?;
156 }
157 Ok(())
158 }
159}
160
161impl std::error::Error for Violations {}
162
163#[derive(Debug, Default)]
165pub struct Validator {
166 path: String,
167 found: Vec<Violation>,
168}
169
170impl Validator {
171 #[must_use]
173 pub fn new() -> Self {
174 Self::default()
175 }
176
177 pub fn report(&mut self, code: ViolationCode, message: impl Into<String>) {
179 self.found.push(Violation { pointer: self.path.clone(), code, message: message.into() });
180 }
181
182 pub fn report_at(&mut self, field: &str, code: ViolationCode, message: impl Into<String>) {
184 self.enter(field);
185 self.report(code, message);
186 self.leave();
187 }
188
189 pub fn enter(&mut self, segment: &str) {
191 self.path.push('/');
192 for ch in segment.chars() {
193 match ch {
194 '~' => self.path.push_str("~0"),
195 '/' => self.path.push_str("~1"),
196 c => self.path.push(c),
197 }
198 }
199 }
200
201 pub fn leave(&mut self) {
207 let cut = self.path.rfind('/').expect("leave() without a matching enter()");
208 self.path.truncate(cut);
209 }
210
211 pub fn field(&mut self, segment: &str, value: &impl Validate) {
213 self.enter(segment);
214 value.validate_in(self);
215 self.leave();
216 }
217
218 #[must_use]
220 pub fn pointer(&self) -> &str {
221 &self.path
222 }
223
224 #[must_use]
226 pub fn finish(self) -> Violations {
227 Violations(self.found)
228 }
229}
230
231pub trait Validate {
236 fn validate_in(&self, v: &mut Validator);
238
239 fn validate(&self) -> Result<(), Violations> {
245 let mut v = Validator::new();
246 self.validate_in(&mut v);
247 let found = v.finish();
248 if found.is_empty() { Ok(()) } else { Err(found) }
249 }
250}
251
252impl<T: Validate> Validate for Option<T> {
253 fn validate_in(&self, v: &mut Validator) {
254 if let Some(inner) = self {
255 inner.validate_in(v);
256 }
257 }
258}
259
260impl<T: Validate> Validate for Vec<T> {
261 fn validate_in(&self, v: &mut Validator) {
262 for (i, item) in self.iter().enumerate() {
263 v.enter(&i.to_string());
264 item.validate_in(v);
265 v.leave();
266 }
267 }
268}
269
270impl<T: Validate> Validate for Box<T> {
271 fn validate_in(&self, v: &mut Validator) {
272 T::validate_in(self, v);
273 }
274}
275
276macro_rules! impl_validate_noop {
278 ($($t:ty),* $(,)?) => {
279 $(impl Validate for $t {
280 fn validate_in(&self, _v: &mut Validator) {}
281 })*
282 };
283}
284
285impl_validate_noop!(bool, i8, i16, i32, i64, u8, u16, u32, u64, usize, String, serde_json::Value);
286
287macro_rules! validate_fields {
294 ($self:ident, $v:ident, $($field:ident as $wire:literal),* $(,)?) => {
295 $( $v.field($wire, &$self.$field); )*
296 };
297}
298
299pub(crate) use validate_fields;
300
301#[cfg(test)]
302mod tests {
303 use super::*;
304
305 struct Leaf(bool);
306 impl Validate for Leaf {
307 fn validate_in(&self, v: &mut Validator) {
308 if !self.0 {
309 v.report(ViolationCode::OutOfRange, "leaf is false");
310 }
311 }
312 }
313
314 #[test]
315 fn pointer_tracks_nesting_and_escapes_rfc6901() {
316 let mut v = Validator::new();
317 v.enter("a/b");
318 v.enter("c~d");
319 v.report(ViolationCode::TooLong, "boom");
320 v.leave();
321 v.leave();
322 let found = v.finish();
323 assert_eq!(found.as_slice()[0].pointer, "/a~1b/c~0d");
324 }
325
326 #[test]
327 fn vec_and_option_are_walked_with_indices() {
328 let value = vec![Leaf(true), Leaf(false), Leaf(false)];
329 let err = value.validate().unwrap_err();
330 assert_eq!(err.len(), 2);
331 assert_eq!(err.as_slice()[0].pointer, "/1");
332 assert_eq!(err.as_slice()[1].pointer, "/2");
333 assert!(Some(Leaf(true)).validate().is_ok());
334 assert!(Option::<Leaf>::None.validate().is_ok());
335 }
336}