strid_examples/
validated.rs1use std::{convert::Infallible, error, fmt};
13
14use strid::braid;
15
16#[derive(Debug)]
18pub enum InvalidScopeToken {
19 EmptyString,
21 InvalidCharacter { position: usize, value: u8 },
23}
24
25impl fmt::Display for InvalidScopeToken {
26 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
27 match self {
28 Self::EmptyString => f.write_str("scope cannot be empty"),
29 Self::InvalidCharacter { position, value } => f.write_fmt(format_args!(
30 "invalid scope character at position {}: {:02x}",
31 position, value
32 )),
33 }
34 }
35}
36
37impl From<Infallible> for InvalidScopeToken {
38 #[inline(always)]
39 fn from(x: Infallible) -> Self {
40 match x {}
41 }
42}
43
44impl error::Error for InvalidScopeToken {}
45
46#[braid(serde, validator, ref_doc = "A borrowed reference to a [`ScopeToken`]")]
55pub struct ScopeToken(String);
56
57impl strid::Validator for ScopeToken {
58 type Error = InvalidScopeToken;
59
60 fn validate(s: &str) -> Result<(), Self::Error> {
61 if s.is_empty() {
62 Err(InvalidScopeToken::EmptyString)
63 } else if let Some((position, &value)) = s
64 .as_bytes()
65 .iter()
66 .enumerate()
67 .find(|&(_, &b)| b <= 0x20 || b == 0x22 || b == 0x5C || 0x7F <= b)
68 {
69 Err(InvalidScopeToken::InvalidCharacter { position, value })
70 } else {
71 Ok(())
72 }
73 }
74}