1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use std::fmt;
use std::iter::{empty, once};
use url;
#[derive(Default, Debug, Clone)]
pub struct ValidationError {
msg: String,
instance_path: Vec<String>,
schema_path: Vec<String>,
}
fn path_to_string(path: &[String]) -> String {
if path.is_empty() {
"/".to_string()
} else {
"/".to_owned() + &path.join("/")
}
}
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"At {} with schema at {}: {}",
path_to_string(&self.instance_path),
path_to_string(&self.schema_path),
self.msg
)
}
}
impl From<url::ParseError> for ValidationError {
fn from(err: url::ParseError) -> ValidationError {
ValidationError::new(&format!("Invalid URL: {:?}", err))
}
}
impl ValidationError {
pub fn new(msg: &str) -> ValidationError {
ValidationError {
msg: String::from(msg),
..Default::default()
}
}
pub fn add_ctx(mut self, instance_context: String, schema_context: String) -> Self {
self.instance_path.push(instance_context);
self.schema_path.push(schema_context);
self
}
pub fn instance_ctx(mut self, instance_context: String) -> Self {
self.instance_path.push(instance_context);
self
}
pub fn schema_ctx(mut self, schema_context: String) -> Self {
self.schema_path.push(schema_context);
self
}
}
pub type ErrorIterator<'a> = Box<dyn Iterator<Item = ValidationError> + 'a>;
pub fn make_error<'a, O: Into<String>>(message: O) -> ErrorIterator<'a> {
Box::new(once(ValidationError::new(&message.into())))
}
pub fn no_error<'a>() -> ErrorIterator<'a> {
Box::new(empty())
}