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
use crate::validator::error::ValidationError;

#[derive(Debug, Default)]
pub struct ValidationState {
    errors: Vec<ValidationError>,
}

impl ValidationState {
    pub fn new() -> ValidationState {
        ValidationState { errors: vec![] }
    }

    pub fn new_with_error(error: ValidationError) -> ValidationState {
        ValidationState { errors: vec![error] }
    }

    pub fn new_with_errors<I>(errors: I) -> ValidationState
    where
        I: IntoIterator<Item = ValidationError>,
    {
        ValidationState {
            errors: errors.into_iter().collect(),
        }
    }

    pub fn push_error(&mut self, error: ValidationError) {
        self.errors.push(error)
    }

    pub fn extend(&mut self, other: ValidationState) {
        self.errors.extend(other.errors);
    }

    pub fn is_valid(&self) -> bool {
        self.errors.is_empty()
    }

    pub fn errors(&self) -> &Vec<ValidationError> {
        &self.errors
    }
}

impl From<ValidationError> for ValidationState {
    fn from(error: ValidationError) -> ValidationState {
        ValidationState { errors: vec![error] }
    }
}

impl<T> From<T> for ValidationState
where
    T: IntoIterator<Item = ValidationError>,
{
    fn from(iter: T) -> Self {
        ValidationState {
            errors: iter.into_iter().collect(),
        }
    }
}