Skip to main content

serenade_validator/
validator.rs

1//! Validator interface and recursive implementation.
2
3use crate::{Constraint, ConstraintViolationList};
4
5/// Runs constraints and returns a violation list.
6pub trait Validator: Send + Sync {
7    /// Validates `value` at `property_path` against `constraints`.
8    fn validate_value(
9        &self,
10        value: &str,
11        property_path: &str,
12        constraints: &[&dyn Constraint],
13    ) -> ConstraintViolationList;
14}
15
16/// Default validator that applies each constraint in order.
17#[derive(Debug, Default, Clone, Copy)]
18pub struct RecursiveValidator;
19
20impl RecursiveValidator {
21    /// Creates the default validator.
22    #[must_use]
23    pub const fn new() -> Self {
24        Self
25    }
26}
27
28impl Validator for RecursiveValidator {
29    fn validate_value(
30        &self,
31        value: &str,
32        property_path: &str,
33        constraints: &[&dyn Constraint],
34    ) -> ConstraintViolationList {
35        let mut violations = ConstraintViolationList::new();
36        for constraint in constraints {
37            constraint.validate(value, property_path, &mut violations);
38        }
39        violations
40    }
41}
42
43/// Object that can validate itself through a [`Validator`].
44pub trait Validatable {
45    /// Collects violations for this value.
46    fn validate(&self, validator: &dyn Validator) -> ConstraintViolationList;
47}