garde/rules/
ascii.rs

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