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
//! Error types and helper functions.

/// Error enumerates all possible errors returned by this library.
#[derive(thiserror::Error, Debug)]
pub enum Error {
    /// Represents an generic parse error.
    #[error("Generic parse error")]
    ParseError,

    /// Thrown when trying to parse a tag with an unsupported tag format.
    #[error("Unsupported tag format")]
    UnsupportedTagFormat,

    /// Represents an generic parse error.
    #[error("Incomplete parse error")]
    ParseIncomplete(nom::Needed),

    /// Represents an generic parse error.
    #[error("Nom parse error")]
    VerboseParseError {
        errors: Vec<(Vec<u8>, nom::error::VerboseErrorKind)>,
    },

    /// Represents decode error.
    #[error("Malformed base64 data")]
    Base64DecodeError { source: base64::DecodeError },

    /// Represents decode error.
    #[error("Invalid Base64 length")]
    Base64InvalidLengthError { length: usize },

    /// Represents decode error.
    #[error("Malformed envelope content")]
    EnvelopeParseError,

    /// Represents decode error.
    #[error("Envelope name mismatch")]
    EnvelopeNameMismatch { expected: String, actual: String },

    /// Happens when trying to write tag data even though no data is available.
    #[error("No tag data available")]
    NoTagDataAvailable,

    /// Represents all other cases of `std::io::Error`.
    #[error(transparent)]
    IOError(#[from] std::io::Error),
}

fn map_err(item: (&[u8], nom::error::VerboseErrorKind)) -> (Vec<u8>, nom::error::VerboseErrorKind) {
    let (data, kind) = item;
    (data.to_owned(), kind)
}

impl From<nom::Err<nom::error::VerboseError<&[u8]>>> for Error {
    fn from(e: nom::Err<nom::error::VerboseError<&[u8]>>) -> Self {
        match e {
            nom::Err::Error(err) => {
                let errors = err.errors.into_iter().map(map_err).collect();
                Error::VerboseParseError { errors }
            }
            nom::Err::Failure(err) => {
                let errors = err.errors.into_iter().map(map_err).collect();
                Error::VerboseParseError { errors }
            }
            nom::Err::Incomplete(_needed) => Error::ParseError,
        }
    }
}