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
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use std::fmt::{self, Display, Debug, Formatter};
use std::error::Error;

use super::{MsgPack};

/// An error that occurred when trying to access a field as a different type
/// 
/// The "as_type" functions of [MsgPack](enum.MsgPack.html) can throw this
/// error. It contains the original object and a string representation of the
/// attempted conversion.
pub struct ConversionError {
    /// The original object, owned.
    pub original: MsgPack,
    /// A string that contains which type conversion was attempted.
    pub attempted: &'static str,
}

impl Display for ConversionError {
    fn fmt (&self, f: &mut Formatter) -> fmt::Result {
        let original_type = match self.original {
            MsgPack::Nil => "nil",
            MsgPack::Int(_) => "int",
            MsgPack::Uint(_) => "uint",
            MsgPack::Float(_) => "float",
            MsgPack::Boolean(_) => "boolean",
            MsgPack::String(_) => "string",
            MsgPack::Binary(_) => "binary",
            MsgPack::Array(_) => "array",
            MsgPack::Map(_) => "map",
            MsgPack::Extension(_) => "extension",
        };
        write!(f, "MsgPack conversion error: cannot use {} as {}", original_type, self.attempted)
    }
}

impl Debug for ConversionError {
    fn fmt (&self, f: &mut Formatter) -> fmt::Result {
        let original_type = match self.original {
            MsgPack::Nil => "nil",
            MsgPack::Int(_) => "int",
            MsgPack::Uint(_) => "uint",
            MsgPack::Float(_) => "float",
            MsgPack::Boolean(_) => "boolean",
            MsgPack::String(_) => "string",
            MsgPack::Binary(_) => "binary",
            MsgPack::Array(_) => "array",
            MsgPack::Map(_) => "map",
            MsgPack::Extension(_) => "extension",
        };
        write!(f, "MsgPack conversion error: cannot use {} as {} (original value: {:?})", original_type, self.attempted, self.original)
    }
}

impl Error for ConversionError {}

impl ConversionError {
    /// Recovers the MsgPack object from the error
    /// 
    ///     use msgpack_simple::MsgPack;
    /// 
    ///     let float = MsgPack::Float(42.0);
    ///     let error = float.as_int().unwrap_err(); // trigger and capture an error
    ///     let recovered = error.recover();
    /// 
    ///     assert!(recovered.is_float());
    ///     assert_eq!(recovered.as_float().unwrap(), 42.0);
    pub fn recover (self) -> MsgPack {
        self.original
    }
}

/// An error that occurred while parsing a binary as MsgPack
pub struct ParseError {
    /// The byte where the error was found
    pub byte: usize
}

impl Display for ParseError {
    fn fmt (&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "MsgPack parse error at byte {}", self.byte)
    }
}

impl Debug for ParseError {
    fn fmt (&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "MsgPack parse error at byte {}", self.byte)
    }
}

impl Error for ParseError {}

impl ParseError {
    /// Creates another error of the same type with a byte offset
    /// 
    ///     use msgpack_simple::ParseError;
    /// 
    ///     let error = ParseError { byte: 5 };
    ///     let other = error.offset(3);
    /// 
    ///     assert_eq!(other.byte, 8);
    pub fn offset (&self, value: usize) -> ParseError {
        ParseError { byte: self.byte + value }
    }

    /// Takes a result with ParseError as its error type and returns the same
    /// with a byte offset on the error
    /// 
    ///     use msgpack_simple::ParseError;
    /// 
    ///     let result: Result<(), ParseError> = Err(ParseError { byte: 39 });
    ///     let other = ParseError::offset_result(result, 3);
    /// 
    ///     let error = other.unwrap_err();
    ///     assert_eq!(error.byte, 42);
    pub fn offset_result <T> (result: Result<T, ParseError>, value: usize) -> Result<T, ParseError> {
        result.map_err(|err| err.offset(value))
    }
}

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

    #[test]
    fn conversion_error () {
        let error = ConversionError { original: MsgPack::Float(4.2), attempted: "int" };
        let error_message = format!("{}", error);
        assert_eq!(error_message, "MsgPack conversion error: cannot use float as int");

        let recovered = error.recover();
        assert!(recovered.is_float());
        assert_eq!(recovered.as_float().unwrap(), 4.2);
    }

    #[test]
    fn parse_error () {
        let error = ParseError { byte: 42 };
        let error_message = format!("{}", error);
        assert_eq!(error_message, "MsgPack parse error at byte 42");
    }
}