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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use jsona::dom::Keys;
use std::fmt;

/// An error that can occur during validation.
#[derive(Debug)]
pub struct Error {
    pub keys: Keys,
    /// Type of validation error.
    pub kind: ErrorKind,
}

/// Kinds of errors that may happen during validation
#[derive(Debug)]
pub enum ErrorKind {
    InvalidFile,
    InvalidValue,
    MismatchType,
    ConflictPattern(String),
    ConflictDef(String),
    UnknownDef(String),
}

impl Error {
    pub const fn invalid_file(keys: Keys) -> Self {
        Error {
            keys,
            kind: ErrorKind::InvalidFile,
        }
    }
    pub const fn invalid_value(keys: Keys) -> Self {
        Error {
            keys,
            kind: ErrorKind::InvalidValue,
        }
    }
    pub const fn mismatch_type(keys: Keys) -> Self {
        Error {
            keys,
            kind: ErrorKind::MismatchType,
        }
    }
    pub fn conflict_pattern(keys: Keys, pattern: &str) -> Self {
        Error {
            keys,
            kind: ErrorKind::ConflictPattern(pattern.to_string()),
        }
    }
    pub fn conflict_def(keys: Keys, def: &str) -> Self {
        Error {
            keys,
            kind: ErrorKind::ConflictDef(def.to_string()),
        }
    }
    pub fn unknown_def(keys: Keys, def: &str) -> Self {
        Error {
            keys,
            kind: ErrorKind::UnknownDef(def.to_string()),
        }
    }
}

impl std::error::Error for Error {}

/// Textual representation of various validation errors.
impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            ErrorKind::InvalidFile => f.write_str("invalid jsona file"),
            ErrorKind::InvalidValue => f.write_str("invalid value"),
            ErrorKind::MismatchType => f.write_str("mismatch type"),
            ErrorKind::ConflictPattern(name) => write!(f, "conflict pattern {}", name),
            ErrorKind::ConflictDef(name) => write!(f, "conflict def {}", name),
            ErrorKind::UnknownDef(name) => write!(f, "unknown def {}", name),
        }
    }
}