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
77
use std::error::Error as StdError;
use std::fmt;

/// An error encountered while parsing or executing a selector.
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
}

impl Error {
    fn new(kind: ErrorKind) -> Self {
        Error { kind }
    }

    /// Create an error indicating the caller provided an empty path to search.
    pub(crate) fn empty_path() -> Self {
        Error::new(ErrorKind::EmptyPath)
    }

    /// Create an error indicating the caller provided a non-empty string that
    /// couldn't be parsed to a searchable path.
    pub(crate) fn invalid_segment(segment: String) -> Self {
        Error::new(ErrorKind::InvalidSegment(segment))
    }
}

impl std::error::Error for Error {
    fn cause(&self) -> Option<&std::error::Error> {
        None
    }

    fn description(&self) -> &str {
        self.kind.description()
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.description().fmt(f)
    }
}

#[derive(Debug)]
enum ErrorKind {
    /// The selector parser was passed an empty string.
    EmptyPath,
    /// The selector parser was passed a non-empty string that had
    /// an invalid part after being split by the path separator.
    InvalidSegment(String),
}

impl std::error::Error for ErrorKind {
    fn cause(&self) -> Option<&std::error::Error> {
        None
    }

    fn description(&self) -> &str {
        match self {
            ErrorKind::EmptyPath => "Empty path",
            ErrorKind::InvalidSegment(_) => "Invalid path segment",
        }
    }
}

impl fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ErrorKind::EmptyPath => self.description().fmt(f),
            ErrorKind::InvalidSegment(segment) => write!(
                f,
                "{}: `{}` is not an identifier",
                self.description(),
                segment
            ),
        }
    }
}