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

use self::ByteVecError::*;
use self::BVExpectedSize::*;

#[derive(Debug, Clone, Copy)]
pub enum BVExpectedSize {
    LessOrEqualThan(usize),
    MoreThan(usize),
    EqualTo(usize),
}

#[derive(Debug, Clone)]
pub enum ByteVecError {
    StringDecodeUtf8Error(Utf8Error),
    BadSizeDecodeError {
        expected: BVExpectedSize,
        actual: usize,
    },
    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 { expected, actual } => {
                write!(f,
                       "The size expected for the structure is {}, but the size of the given \
                        buffer is {}",
                       match expected {
                           LessOrEqualThan(expected) => format!("less or equal than {}", expected),
                           MoreThan(expected) => format!("more than {}", expected),
                           EqualTo(expected) => expected.to_string(),
                       },
                       actual)
            }
            OverflowError => {
                write!(f,
                       "OverflowError: The size of the data structure surpasses the \
                       max value of the integral generic type")
            }
        }
    }
}

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 max value of the size type",
        }
    }

    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)
    }
}