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