Skip to main content

serenade_validator/
violation.rs

1//! Constraint violations.
2
3/// One failed constraint on a property path.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct Violation {
6    /// Property path (empty for object-level).
7    pub property_path: String,
8    /// Human-readable message.
9    pub message: String,
10    /// Constraint type name (for example `NotBlank`).
11    pub code: &'static str,
12}
13
14impl Violation {
15    /// Creates a violation for `property_path`.
16    #[must_use]
17    pub fn new(
18        property_path: impl Into<String>,
19        message: impl Into<String>,
20        code: &'static str,
21    ) -> Self {
22        Self {
23            property_path: property_path.into(),
24            message: message.into(),
25            code,
26        }
27    }
28}
29
30/// Ordered list of [`Violation`]s.
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
32pub struct ConstraintViolationList {
33    items: Vec<Violation>,
34}
35
36impl ConstraintViolationList {
37    /// Creates an empty list.
38    #[must_use]
39    pub fn new() -> Self {
40        Self::default()
41    }
42
43    /// Appends a violation.
44    pub fn add(&mut self, violation: Violation) {
45        self.items.push(violation);
46    }
47
48    /// Returns `true` when no violations were recorded.
49    #[must_use]
50    pub const fn is_empty(&self) -> bool {
51        self.items.is_empty()
52    }
53
54    /// Number of violations.
55    #[must_use]
56    pub const fn len(&self) -> usize {
57        self.items.len()
58    }
59
60    /// Borrowed slice of violations.
61    #[must_use]
62    pub fn as_slice(&self) -> &[Violation] {
63        &self.items
64    }
65}