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
use bson::Bson;
use serde::ser;
use std::{error, fmt, io};
use std::fmt::Display;

/// Possible errors that can arise during encoding.
#[derive(Debug)]
pub enum EncoderError {
    IoError(io::Error),
    InvalidMapKeyType(Bson),
    Unknown(String),
    UnsupportedUnsignedType,
    UnsignedTypesValueExceedsRange(u64),
}

impl From<io::Error> for EncoderError {
    fn from(err: io::Error) -> EncoderError {
        EncoderError::IoError(err)
    }
}

impl fmt::Display for EncoderError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            EncoderError::IoError(ref inner) => inner.fmt(fmt),
            EncoderError::InvalidMapKeyType(ref bson) => write!(fmt, "Invalid map key type: {:?}", bson),
            EncoderError::Unknown(ref inner) => inner.fmt(fmt),
            EncoderError::UnsupportedUnsignedType => fmt.write_str("BSON does not support unsigned type"),
            EncoderError::UnsignedTypesValueExceedsRange(value) => write!(
                fmt,
                "BSON does not support unsigned types.
                 An attempt to encode the value: {} in a signed type failed due to the value's size.",
                value
            ),
        }
    }
}

impl error::Error for EncoderError {
    fn description(&self) -> &str {
        match *self {
            EncoderError::IoError(ref inner) => inner.description(),
            EncoderError::InvalidMapKeyType(_) => "Invalid map key type",
            EncoderError::Unknown(ref inner) => inner,
            EncoderError::UnsupportedUnsignedType => "BSON does not support unsigned type",
            EncoderError::UnsignedTypesValueExceedsRange(_) => "BSON does not support unsigned types.
                 An attempt to encode the value: {} in a signed type failed due to the values size."
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match self {
            &EncoderError::IoError(ref inner) => Some(inner),
            _ => None,
        }
    }
}

impl ser::Error for EncoderError {
    fn custom<T: Display>(msg: T) -> EncoderError {
        EncoderError::Unknown(msg.to_string())
    }
}

/// Alias for `Result<T, EncoderError>`.
pub type EncoderResult<T> = Result<T, EncoderError>;