garde/rules/
prefix.rs

1//! Prefix validation.
2//!
3//! ```rust
4//! const PRE: &str = "test_";
5//!
6//! #[derive(garde::Validate)]
7//! struct Test {
8//!     #[garde(prefix("test_"))]
9//!     v: String,
10//!     #[garde(prefix(PRE))]
11//!     w: String,
12//! }
13//! ```
14//!
15//! The entrypoint is the [`Prefix`] trait. Implementing this trait for a type allows that type to be used with the `#[garde(prefix)]` rule.
16//!
17//! This trait has a blanket implementation for all `T: garde::rules::AsStr`.
18
19use super::AsStr;
20use crate::error::Error;
21
22pub fn apply<T: Prefix>(v: &T, (pat,): (&str,)) -> Result<(), Error> {
23    if !v.validate_prefix(pat) {
24        return Err(Error::new(format!("value does not begin with \"{pat}\"")));
25    }
26    Ok(())
27}
28
29pub trait Prefix {
30    fn validate_prefix(&self, pat: &str) -> bool;
31}
32
33impl<T: AsStr> Prefix for T {
34    fn validate_prefix(&self, pat: &str) -> bool {
35        self.as_str().starts_with(pat)
36    }
37}
38
39impl<T: Prefix> Prefix for Option<T> {
40    fn validate_prefix(&self, pat: &str) -> bool {
41        match self {
42            Some(value) => value.validate_prefix(pat),
43            None => true,
44        }
45    }
46}