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
//! Custom error typ

/// Custom error type.
/// 
/// Contents of message contains specific invalid input
/// if it occurs during parsing of input.
#[derive(Debug)]
pub struct Error {
    message: String
}

impl std::error::Error for Error {}
unsafe impl Send for Error {}
unsafe impl Sync for Error {}

impl Error {
    pub(crate) fn new(message: &str) -> Error {
        Error {
            message: String::from(message),
        }
    }

    pub(crate) fn from_remain(remain: &str) -> Error {
        Error {
            message: format_error_message(remain)
        }
    }

    /// Returns the error message
    pub fn message(&self) -> &String {
        &self.message
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

fn format_error_message(remain: &str) -> String {
    let invalid: &str;
    if remain.len() >= 3 {
        invalid = &remain[..3];
    } else {
        invalid = &remain[..remain.len()];
    }
    return format!("invalid sequence: \"{}\"", invalid).to_lowercase();
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn message_format() {
        assert_eq!(format_error_message("abcdefg"),"invalid sequence: \"abc\"");
        assert_eq!(format_error_message("abc"),"invalid sequence: \"abc\"");
        assert_eq!(format_error_message("ab"),"invalid sequence: \"ab\"");
        assert_eq!(format_error_message("a"),"invalid sequence: \"a\"");
    }
}