1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use super::Validator;
use thiserror::Error;
#[derive(Clone, Copy, Debug, Error)]
#[error("Value is shorter than minimum length of {0}")]
pub struct ValueTooShortError(usize);
#[derive(Clone, Copy, Debug)]
pub struct MinLengthValidator {
min_length: usize
}
impl MinLengthValidator {
pub fn new(min_length: usize) -> Self {
Self { min_length }
}
}
impl<T: AsRef<str>> Validator<T> for MinLengthValidator {
type Err = ValueTooShortError;
fn validate(self, data: &T) -> Result<(), Self::Err> {
if data.as_ref().len() < self.min_length {
return Err(ValueTooShortError(self.min_length));
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, Error)]
#[error("Value is longer than maximum length of {0}")]
pub struct ValueTooLongError(usize);
#[derive(Clone, Copy, Debug)]
pub struct MaxLengthValidator {
max_length: usize
}
impl MaxLengthValidator {
pub fn new(max_length: usize) -> Self {
Self { max_length }
}
}
impl<T: AsRef<str>> Validator<T> for MaxLengthValidator {
type Err = ValueTooLongError;
fn validate(self, data: &T) -> Result<(), Self::Err> {
if data.as_ref().len() > self.max_length {
return Err(ValueTooLongError(self.max_length));
}
Ok(())
}
}