1use alloc::borrow::ToOwned;
12use alloc::format;
13use alloc::string::{String, ToString};
14use alloc::vec::Vec;
15use core::fmt;
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum PathSegment {
20 Key(&'static str),
22 Index(usize),
24}
25
26#[derive(Clone, Debug, Default)]
31pub struct ValidationPath {
32 segments: Vec<PathSegment>,
33}
34
35impl ValidationPath {
36 #[must_use]
38 pub fn new() -> Self {
39 Self::default()
40 }
41
42 pub fn push_key(&mut self, key: &'static str) {
44 self.segments.push(PathSegment::Key(key));
45 }
46
47 pub fn push_index(&mut self, index: usize) {
49 self.segments.push(PathSegment::Index(index));
50 }
51
52 pub fn pop(&mut self) {
54 self.segments.pop();
55 }
56
57 #[must_use]
59 pub fn to_pointer(&self) -> String {
60 if self.segments.is_empty() {
61 return String::new();
62 }
63 let mut out = String::new();
64 for segment in &self.segments {
65 out.push('/');
66 match segment {
67 PathSegment::Key(k) => {
68 out.push_str(&k.replace('~', "~0").replace('/', "~1"));
70 }
71 PathSegment::Index(i) => {
72 out.push_str(&i.to_string());
73 }
74 }
75 }
76 out
77 }
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
82#[non_exhaustive]
83pub enum ViolationKind {
84 Occurrence,
88 Type,
92 Property,
96 UnknownEnumValue,
102 UnknownField,
108 Protocol,
112}
113
114impl fmt::Display for ViolationKind {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 f.write_str(match self {
117 ViolationKind::Occurrence => "occurrence",
118 ViolationKind::Type => "type",
119 ViolationKind::Property => "property",
120 ViolationKind::UnknownEnumValue => "unknown enum value",
121 ViolationKind::UnknownField => "unknown field",
122 ViolationKind::Protocol => "protocol",
123 })
124 }
125}
126
127#[derive(Clone, Debug, PartialEq, Eq)]
129pub struct Violation {
130 pub path: String,
132 pub kind: ViolationKind,
134 pub reason: String,
136}
137
138impl fmt::Display for Violation {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 if self.path.is_empty() {
141 write!(f, "{}", self.reason)
142 } else {
143 write!(f, "{}: {}", self.path, self.reason)
144 }
145 }
146}
147
148#[derive(Clone, Debug, Default, PartialEq, Eq)]
150pub struct Violations {
151 items: Vec<Violation>,
152}
153
154impl Violations {
155 #[must_use]
157 pub fn new() -> Self {
158 Self::default()
159 }
160
161 #[must_use]
162 pub fn is_empty(&self) -> bool {
164 self.items.is_empty()
165 }
166
167 #[must_use]
168 pub fn len(&self) -> usize {
170 self.items.len()
171 }
172
173 #[must_use]
174 pub fn as_slice(&self) -> &[Violation] {
176 &self.items
177 }
178
179 #[must_use]
181 pub fn first(&self) -> Option<&Violation> {
182 self.items.first()
183 }
184
185 pub fn push(&mut self, path: &ValidationPath, kind: ViolationKind, reason: impl Into<String>) {
187 self.items.push(Violation {
188 path: path.to_pointer(),
189 kind,
190 reason: reason.into(),
191 });
192 }
193
194 pub fn retain_kinds(&mut self, mut keep: impl FnMut(ViolationKind) -> bool) {
196 self.items.retain(|v| keep(v.kind));
197 }
198
199 #[must_use]
200 pub fn into_vec(self) -> Vec<Violation> {
202 self.items
203 }
204}
205
206impl IntoIterator for Violations {
207 type Item = Violation;
208 type IntoIter = alloc::vec::IntoIter<Violation>;
209
210 fn into_iter(self) -> Self::IntoIter {
211 self.items.into_iter()
212 }
213}
214
215impl fmt::Display for Violations {
216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 for (i, v) in self.items.iter().enumerate() {
218 if i > 0 {
219 f.write_str("; ")?;
220 }
221 write!(f, "{v}")?;
222 }
223 Ok(())
224 }
225}
226
227#[cfg(feature = "std")]
228impl std::error::Error for Violations {}
229
230pub trait Validate {
234 fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations);
236
237 fn validate(&self) -> Result<(), Violations> {
239 let mut path = ValidationPath::new();
240 let mut out = Violations::new();
241 self.validate_at(&mut path, &mut out);
242 if out.is_empty() { Ok(()) } else { Err(out) }
243 }
244}
245
246impl<T: Validate> Validate for Option<T> {
247 fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
248 if let Some(v) = self {
249 v.validate_at(path, out);
250 }
251 }
252}
253
254impl<T: Validate> Validate for Vec<T> {
255 fn validate_at(&self, path: &mut ValidationPath, out: &mut Violations) {
256 for (index, item) in self.iter().enumerate() {
257 path.push_index(index);
258 item.validate_at(path, out);
259 path.pop();
260 }
261 }
262}
263
264pub fn string(
270 value: &str,
271 min: Option<u32>,
272 max: Option<u32>,
273 path: &ValidationPath,
274 out: &mut Violations,
275) {
276 let len = value.chars().count();
277 if let Some(max) = max {
278 if len > max as usize {
279 out.push(
280 path,
281 ViolationKind::Property,
282 format!("maxLength {max} exceeded (got {len} characters)"),
283 );
284 }
285 }
286 if let Some(min) = min {
287 if len < min as usize {
288 out.push(
289 path,
290 ViolationKind::Property,
291 format!("minLength {min} not reached (got {len} characters)"),
292 );
293 }
294 }
295}
296
297pub fn int_range(
299 value: i64,
300 min: Option<f64>,
301 max: Option<f64>,
302 path: &ValidationPath,
303 out: &mut Violations,
304) {
305 #[allow(clippy::cast_precision_loss)]
306 range(value as f64, min, max, path, out);
307}
308
309pub fn range(
311 value: f64,
312 min: Option<f64>,
313 max: Option<f64>,
314 path: &ValidationPath,
315 out: &mut Violations,
316) {
317 if !value.is_finite() {
318 out.push(
319 path,
320 ViolationKind::Type,
321 "value is not a finite JSON number".to_owned(),
322 );
323 return;
324 }
325 if let Some(min) = min {
326 if value < min {
327 out.push(
328 path,
329 ViolationKind::Property,
330 format!("minimum {min} violated (got {value})"),
331 );
332 }
333 }
334 if let Some(max) = max {
335 if value > max {
336 out.push(
337 path,
338 ViolationKind::Property,
339 format!("maximum {max} violated (got {value})"),
340 );
341 }
342 }
343}
344
345pub fn list_len(
347 len: usize,
348 min: Option<u32>,
349 max: Option<u32>,
350 path: &ValidationPath,
351 out: &mut Violations,
352) {
353 if let Some(min) = min {
354 if len < min as usize {
355 out.push(
356 path,
357 ViolationKind::Occurrence,
358 format!("minItems {min} not reached (got {len})"),
359 );
360 }
361 }
362 if let Some(max) = max {
363 if len > max as usize {
364 out.push(
365 path,
366 ViolationKind::Occurrence,
367 format!("maxItems {max} exceeded (got {len})"),
368 );
369 }
370 }
371}
372
373pub fn unknown_enum_value(
375 value: &str,
376 type_name: &'static str,
377 path: &ValidationPath,
378 out: &mut Violations,
379) {
380 out.push(
381 path,
382 ViolationKind::UnknownEnumValue,
383 format!("{value:?} is not a defined value of {type_name}"),
384 );
385}