1#![allow(deprecated)]
2use std::fmt;
27
28pub trait Validate {
57 fn validate(&self) -> Result<(), ValidationErrors> {
59 let mut errors = Vec::new();
60 self.validate_into(&Path::root(), &mut errors);
61 if errors.is_empty() {
62 Ok(())
63 } else {
64 Err(ValidationErrors(errors))
65 }
66 }
67
68 fn validate_into(&self, path: &Path<'_>, errors: &mut Vec<ValidationError>);
71}
72
73#[derive(Clone, Debug, PartialEq)]
75pub struct ValidationErrors(Vec<ValidationError>);
76
77impl ValidationErrors {
78 pub fn len(&self) -> usize {
80 self.0.len()
81 }
82
83 pub fn is_empty(&self) -> bool {
85 self.0.is_empty()
86 }
87
88 pub fn iter(&self) -> std::slice::Iter<'_, ValidationError> {
90 self.0.iter()
91 }
92
93 pub fn into_vec(self) -> Vec<ValidationError> {
95 self.0
96 }
97}
98
99impl IntoIterator for ValidationErrors {
100 type Item = ValidationError;
101 type IntoIter = std::vec::IntoIter<ValidationError>;
102
103 fn into_iter(self) -> Self::IntoIter {
104 self.0.into_iter()
105 }
106}
107
108impl<'a> IntoIterator for &'a ValidationErrors {
109 type Item = &'a ValidationError;
110 type IntoIter = std::slice::Iter<'a, ValidationError>;
111
112 fn into_iter(self) -> Self::IntoIter {
113 self.0.iter()
114 }
115}
116
117impl fmt::Display for ValidationErrors {
119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 for (index, error) in self.0.iter().enumerate() {
121 if index > 0 {
122 f.write_str("\n")?;
123 }
124 write!(f, "{error}")?;
125 }
126 Ok(())
127 }
128}
129
130impl std::error::Error for ValidationErrors {}
131
132#[derive(Clone, Copy, Debug)]
135pub struct Path<'a> {
136 parent: Option<&'a Path<'a>>,
137 segment: Segment<'a>,
138}
139
140#[derive(Clone, Copy, Debug)]
141enum Segment<'a> {
142 Root,
143 Field(&'a str),
144 Index(usize),
145 Key(&'a str),
146}
147
148impl<'a> Path<'a> {
149 pub fn root() -> Path<'static> {
151 Path {
152 parent: None,
153 segment: Segment::Root,
154 }
155 }
156
157 pub fn field(&'a self, name: &'a str) -> Path<'a> {
159 Path {
160 parent: Some(self),
161 segment: Segment::Field(name),
162 }
163 }
164
165 pub fn index(&'a self, index: usize) -> Path<'a> {
167 Path {
168 parent: Some(self),
169 segment: Segment::Index(index),
170 }
171 }
172
173 pub fn key(&'a self, key: &'a str) -> Path<'a> {
175 Path {
176 parent: Some(self),
177 segment: Segment::Key(key),
178 }
179 }
180
181 fn write(&self, out: &mut String) {
182 if let Some(parent) = self.parent {
183 parent.write(out);
184 }
185 match self.segment {
186 Segment::Root => {}
187 Segment::Field(name) => {
188 if !out.is_empty() {
189 out.push('.');
190 }
191 out.push_str(name);
192 }
193 Segment::Index(index) => out.push_str(&format!("[{index}]")),
194 Segment::Key(key) => out.push_str(&format!("[{key:?}]")),
195 }
196 }
197}
198
199impl fmt::Display for Path<'_> {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201 let mut out = String::new();
202 self.write(&mut out);
203 f.write_str(&out)
204 }
205}
206
207fn push(result: Result<(), ValidationError>, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
209 if let Err(mut error) = result {
210 error.path = path.to_string();
211 errors.push(error);
212 }
213}
214
215#[doc(hidden)]
218pub fn sort_by_key(errors: &mut [ValidationError], start: usize, path: &Path<'_>) {
219 if errors.len() <= start + 1 {
220 return;
221 }
222 let prefix = path.to_string().len();
223 errors[start..].sort_by(|a, b| key_of(&a.path, prefix).cmp(key_of(&b.path, prefix)));
224}
225
226fn key_of(path: &str, prefix: usize) -> &str {
228 let rest = path.get(prefix..).unwrap_or("");
229 let mut escaped = false;
230 for (at, c) in rest.char_indices().skip(2) {
231 match c {
232 '\\' if !escaped => escaped = true,
233 '"' if !escaped => return &rest[..at],
234 _ => escaped = false,
235 }
236 }
237 rest
238}
239
240#[derive(Clone, Debug, PartialEq)]
243#[non_exhaustive]
244pub enum Rule {
245 MinLength(u64),
247 MaxLength(u64),
249 Pattern(&'static str),
251 Minimum(f64),
253 ExclusiveMinimum(f64),
255 Maximum(f64),
257 ExclusiveMaximum(f64),
259 MultipleOf(f64),
261 MinItems(u64),
263 MaxItems(u64),
265 UniqueItems,
267 MinProperties(u64),
269 MaxProperties(u64),
271}
272
273impl fmt::Display for Rule {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 match self {
276 Rule::MinLength(n) => write!(f, "minLength {n}"),
277 Rule::MaxLength(n) => write!(f, "maxLength {n}"),
278 Rule::Pattern(p) => write!(f, "pattern {p:?}"),
279 Rule::Minimum(n) => write!(f, "minimum {n}"),
280 Rule::ExclusiveMinimum(n) => write!(f, "exclusiveMinimum {n}"),
281 Rule::Maximum(n) => write!(f, "maximum {n}"),
282 Rule::ExclusiveMaximum(n) => write!(f, "exclusiveMaximum {n}"),
283 Rule::MultipleOf(n) => write!(f, "multipleOf {n}"),
284 Rule::MinItems(n) => write!(f, "minItems {n}"),
285 Rule::MaxItems(n) => write!(f, "maxItems {n}"),
286 Rule::UniqueItems => write!(f, "uniqueItems"),
287 Rule::MinProperties(n) => write!(f, "minProperties {n}"),
288 Rule::MaxProperties(n) => write!(f, "maxProperties {n}"),
289 }
290 }
291}
292
293#[derive(Clone, Debug, PartialEq)]
295pub struct ValidationError {
296 pub path: String,
298 pub rule: Rule,
300 pub actual: String,
303}
304
305impl ValidationError {
306 pub fn new(rule: Rule, actual: impl Into<String>) -> Self {
308 ValidationError {
309 path: String::new(),
310 rule,
311 actual: actual.into(),
312 }
313 }
314}
315
316impl fmt::Display for ValidationError {
317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318 if self.path.is_empty() {
319 write!(f, "{} breaks {}", self.actual, self.rule)
320 } else {
321 write!(f, "{}: {} breaks {}", self.path, self.actual, self.rule)
322 }
323 }
324}
325
326impl std::error::Error for ValidationError {}
327
328impl<T: Validate + ?Sized> Validate for Box<T> {
329 fn validate_into(&self, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
330 (**self).validate_into(path, errors);
331 }
332}
333
334impl<T: Validate> Validate for Option<T> {
335 fn validate_into(&self, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
336 if let Some(value) = self {
337 value.validate_into(path, errors);
338 }
339 }
340}
341
342impl<T: Validate> Validate for Vec<T> {
343 fn validate_into(&self, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
344 for (index, item) in self.iter().enumerate() {
345 item.validate_into(&path.index(index), errors);
346 }
347 }
348}
349
350impl<T: Validate, S> Validate for std::collections::HashMap<String, T, S> {
351 fn validate_into(&self, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
352 let start = errors.len();
353 for (key, value) in self {
354 value.validate_into(&path.key(key), errors);
355 }
356 sort_by_key(errors, start, path);
357 }
358}
359
360pub trait Number: Copy + PartialOrd + fmt::Display {
362 fn as_f64(self) -> f64;
364 fn is_multiple(self, factor: Self) -> bool;
366}
367
368macro_rules! integer {
369 ($($t:ty),*) => {$(
370 impl Number for $t {
371 fn as_f64(self) -> f64 {
372 self as f64
373 }
374 fn is_multiple(self, factor: Self) -> bool {
375 self.checked_rem(factor).is_none_or(|rest| rest == 0)
376 }
377 }
378 )*};
379}
380
381integer!(i8, i16, i32, i64, u8, u16, u32, u64);
382
383macro_rules! float {
384 ($($t:ty => $tolerance:expr),*) => {$(
385 impl Number for $t {
386 fn as_f64(self) -> f64 {
387 f64::from(self)
388 }
389 fn is_multiple(self, factor: Self) -> bool {
390 let quotient = self / factor;
391 (quotient - quotient.round()).abs() <= $tolerance * quotient.abs().max(1.0)
392 }
393 }
394 )*};
395}
396
397float!(f32 => 1e-5, f64 => 1e-9);
398
399fn check_length(value: &str, min: Option<u64>, max: Option<u64>) -> Result<(), ValidationError> {
401 let length = value.chars().count() as u64;
402 if let Some(min) = min.filter(|min| length < *min) {
403 return Err(ValidationError::new(
404 Rule::MinLength(min),
405 format!("length {length}"),
406 ));
407 }
408 if let Some(max) = max.filter(|max| length > *max) {
409 return Err(ValidationError::new(
410 Rule::MaxLength(max),
411 format!("length {length}"),
412 ));
413 }
414 Ok(())
415}
416
417fn check_minimum<T: Number>(value: T, bound: T) -> Result<(), ValidationError> {
419 if value < bound {
420 return Err(ValidationError::new(
421 Rule::Minimum(bound.as_f64()),
422 value.to_string(),
423 ));
424 }
425 Ok(())
426}
427
428fn check_exclusive_minimum<T: Number>(value: T, bound: T) -> Result<(), ValidationError> {
430 if value <= bound {
431 return Err(ValidationError::new(
432 Rule::ExclusiveMinimum(bound.as_f64()),
433 value.to_string(),
434 ));
435 }
436 Ok(())
437}
438
439fn check_maximum<T: Number>(value: T, bound: T) -> Result<(), ValidationError> {
441 if value > bound {
442 return Err(ValidationError::new(
443 Rule::Maximum(bound.as_f64()),
444 value.to_string(),
445 ));
446 }
447 Ok(())
448}
449
450fn check_exclusive_maximum<T: Number>(value: T, bound: T) -> Result<(), ValidationError> {
452 if value >= bound {
453 return Err(ValidationError::new(
454 Rule::ExclusiveMaximum(bound.as_f64()),
455 value.to_string(),
456 ));
457 }
458 Ok(())
459}
460
461fn check_multiple_of<T: Number>(value: T, factor: T) -> Result<(), ValidationError> {
463 if !value.is_multiple(factor) {
464 return Err(ValidationError::new(
465 Rule::MultipleOf(factor.as_f64()),
466 value.to_string(),
467 ));
468 }
469 Ok(())
470}
471
472fn check_items(count: usize, min: Option<u64>, max: Option<u64>) -> Result<(), ValidationError> {
474 let count = count as u64;
475 if let Some(min) = min.filter(|min| count < *min) {
476 return Err(ValidationError::new(
477 Rule::MinItems(min),
478 format!("{count} items"),
479 ));
480 }
481 if let Some(max) = max.filter(|max| count > *max) {
482 return Err(ValidationError::new(
483 Rule::MaxItems(max),
484 format!("{count} items"),
485 ));
486 }
487 Ok(())
488}
489
490fn check_unique_items<T: PartialEq>(items: &[T]) -> Result<(), ValidationError> {
492 for (index, item) in items.iter().enumerate() {
493 if let Some(first) = items[..index].iter().position(|earlier| earlier == item) {
494 return Err(ValidationError::new(
495 Rule::UniqueItems,
496 format!("items {first} and {index} are equal"),
497 ));
498 }
499 }
500 Ok(())
501}
502
503fn check_properties(
505 count: usize,
506 min: Option<u64>,
507 max: Option<u64>,
508) -> Result<(), ValidationError> {
509 let count = count as u64;
510 if let Some(min) = min.filter(|min| count < *min) {
511 return Err(ValidationError::new(
512 Rule::MinProperties(min),
513 format!("{count} properties"),
514 ));
515 }
516 if let Some(max) = max.filter(|max| count > *max) {
517 return Err(ValidationError::new(
518 Rule::MaxProperties(max),
519 format!("{count} properties"),
520 ));
521 }
522 Ok(())
523}
524
525#[doc(hidden)]
526pub fn length(
527 value: &str,
528 min: Option<u64>,
529 max: Option<u64>,
530 path: &Path<'_>,
531 errors: &mut Vec<ValidationError>,
532) {
533 push(check_length(value, min, max), path, errors);
534}
535
536#[doc(hidden)]
537pub fn minimum<T: Number>(value: T, bound: T, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
538 push(check_minimum(value, bound), path, errors);
539}
540
541#[doc(hidden)]
542pub fn exclusive_minimum<T: Number>(
543 value: T,
544 bound: T,
545 path: &Path<'_>,
546 errors: &mut Vec<ValidationError>,
547) {
548 push(check_exclusive_minimum(value, bound), path, errors);
549}
550
551#[doc(hidden)]
552pub fn maximum<T: Number>(value: T, bound: T, path: &Path<'_>, errors: &mut Vec<ValidationError>) {
553 push(check_maximum(value, bound), path, errors);
554}
555
556#[doc(hidden)]
557pub fn exclusive_maximum<T: Number>(
558 value: T,
559 bound: T,
560 path: &Path<'_>,
561 errors: &mut Vec<ValidationError>,
562) {
563 push(check_exclusive_maximum(value, bound), path, errors);
564}
565
566#[doc(hidden)]
567pub fn multiple_of<T: Number>(
568 value: T,
569 factor: T,
570 path: &Path<'_>,
571 errors: &mut Vec<ValidationError>,
572) {
573 push(check_multiple_of(value, factor), path, errors);
574}
575
576#[doc(hidden)]
577pub fn items(
578 count: usize,
579 min: Option<u64>,
580 max: Option<u64>,
581 path: &Path<'_>,
582 errors: &mut Vec<ValidationError>,
583) {
584 push(check_items(count, min, max), path, errors);
585}
586
587#[doc(hidden)]
588pub fn unique_items<T: PartialEq>(items: &[T], path: &Path<'_>, errors: &mut Vec<ValidationError>) {
589 push(check_unique_items(items), path, errors);
590}
591
592#[doc(hidden)]
593pub fn properties(
594 count: usize,
595 min: Option<u64>,
596 max: Option<u64>,
597 path: &Path<'_>,
598 errors: &mut Vec<ValidationError>,
599) {
600 push(check_properties(count, min, max), path, errors);
601}