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
use std::str::Utf8Error;
use std::convert::From;
use std::error::Error;
use std::fmt::{self, Display};

use self::ByteVecError::*;
use self::BVWantedSize::*;

#[derive(Debug, Clone, Copy)]
pub enum BVWantedSize {
    MoreThan(u32),
    EqualTo(u32),
}

#[derive(Debug, Clone)]
pub enum ByteVecError {
    StringDecodeUtf8Error(Utf8Error),
    BadSizeDecodeError {
        wanted: BVWantedSize,
        actual: u32,
    },
    OverflowError,
}

impl Display for ByteVecError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            StringDecodeUtf8Error(utf8_error) => write!(f, "StringDecodeUtf8Error: {}", utf8_error),
            BadSizeDecodeError { wanted, actual } => {
                write!(f,
                       "The size specified for the structure is {}, but the size of the given \
                        buffer is {}",
                       match wanted {
                           MoreThan(wanted) => format!("more than {}", wanted),
                           EqualTo(wanted) => wanted.to_string(),
                       },
                       actual)
            }
            OverflowError => {
                write!(f,
                       "OverflowError: The size of the data structure surpasses the u32 max size \
                        (4GB)")
            }
        }
    }
}

impl Error for ByteVecError {
    fn description(&self) -> &str {
        match *self {
            StringDecodeUtf8Error(ref utf8_error) => utf8_error.description(),
            BadSizeDecodeError { .. } => {
                "the size specified for the structure differs from the size of the given buffer"
            }
            OverflowError => "the size of the data structure surpasses the u32 max size",
        }
    }

    fn cause(&self) -> Option<&Error> {
        match *self {
            StringDecodeUtf8Error(ref utf8_error) => Some(utf8_error),
            _ => None,
        }
    }
}

impl From<Utf8Error> for ByteVecError {
    fn from(error: Utf8Error) -> ByteVecError {
        StringDecodeUtf8Error(error)
    }
}