qubit_validator/validator.rs
1// =============================================================================
2// Copyright (c) 2025 - 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9//! The typed validator contract.
10
11use std::error::Error;
12
13/// Validates a borrowed value using an immutable, typed context.
14///
15/// # Examples
16///
17/// ```
18/// use std::fmt;
19///
20/// use qubit_validator::Validator;
21///
22/// #[derive(Debug, Eq, PartialEq)]
23/// struct EmptyText;
24///
25/// impl fmt::Display for EmptyText {
26/// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
27/// formatter.write_str("text must not be empty")
28/// }
29/// }
30///
31/// impl std::error::Error for EmptyText {}
32///
33/// struct NonEmpty;
34///
35/// impl Validator<str> for NonEmpty {
36/// type Error = EmptyText;
37///
38/// fn validate(&self, value: &str, _: &()) -> Result<(), Self::Error> {
39/// if value.is_empty() { Err(EmptyText) } else { Ok(()) }
40/// }
41/// }
42///
43/// assert!(NonEmpty.validate("ready", &()).is_ok());
44/// assert_eq!(NonEmpty.validate("", &()).unwrap_err(), EmptyText);
45/// ```
46///
47/// # Type Parameters
48///
49/// - `T`: Borrowed value type accepted by the validator.
50/// - `C`: Immutable context supplied for each validation call.
51pub trait Validator<T: ?Sized, C: ?Sized = ()> {
52 /// The domain error returned when the value is invalid.
53 type Error: Error + 'static;
54
55 /// Validates `value` with `context`.
56 ///
57 /// # Parameters
58 ///
59 /// - `value`: The borrowed value to validate.
60 /// - `context`: Immutable domain context for this call.
61 ///
62 /// # Errors
63 ///
64 /// Returns the validator-specific error when the value is invalid.
65 fn validate(&self, value: &T, context: &C) -> Result<(), Self::Error>;
66}