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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
use std::error::Error as ErrorTrait;
use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Errors {
pub(crate) inner: Vec<Error>,
}
impl Errors {
pub fn into_inner(self) -> Vec<Error> {
self.inner
}
}
impl ErrorTrait for Errors {}
impl fmt::Display for Errors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let uncloseds = self.inner.iter().filter_map(|e| {
if let Error::Unclosed(i) = e {
Some(i)
} else {
None
}
});
let missings = self.inner.iter().filter_map(|e| {
if let Error::Missing(k) = e {
Some(k)
} else {
None
}
});
let extras = self.inner.iter().filter_map(|e| {
if let Error::Extra(k) = e {
Some(k)
} else {
None
}
});
let uncloseds_count = uncloseds.clone().count();
let missings_count = missings.clone().count();
let extras_count = extras.clone().count();
format_error(
f,
"unclosed delimiter opened at byte",
uncloseds,
uncloseds_count,
false,
)?;
if uncloseds_count > 0 && missings_count > 0 {
write!(f, "; ")?;
}
format_error(f, "missing key", missings, missings_count, true)?;
if (uncloseds_count > 0 || missings_count > 0) && extras_count > 0 {
write!(f, "; ")?;
}
format_error(f, "extraneous key", extras, extras_count, true)?;
Ok(())
}
}
fn format_error(
f: &mut fmt::Formatter<'_>,
problem: &str,
iter: impl Iterator<Item = impl fmt::Display>,
count: usize,
quotes: bool,
) -> fmt::Result {
if count > 0 {
let s = if count != 1 {
"s"
} else {
""
};
write!(f, "{}{}: ", problem, s)?;
for (i, error) in iter.enumerate() {
let sep = if i + 1 == count {
""
} else if i + 2 == count {
if count == 2 {
" and "
} else {
", and "
}
} else {
", "
};
if quotes {
write!(f, "\"{}\"{}", error, sep)?;
} else {
write!(f, "{}{}", error, sep)?;
}
}
}
Ok(())
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Error {
Missing(String),
Extra(String),
Unclosed(usize),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Missing(k) => write!(f, "missing key \"{}\"", k),
Self::Extra(k) => write!(f, "extraneous key \"{}\"", k),
Self::Unclosed(i) => {
write!(f, "unclosed delimitor opened at byte {}", i)
}
}
}
}