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
use std::fmt;
use std::io;
use std::error;
use std::result;
use serde::{ser, de};
#[derive(Clone, PartialEq, Debug)]
pub enum ErrorCode {
Unsupported(char),
EOFWhileParsing,
StackUnderflow,
NegativeLength,
StringNotUTF8,
InvalidStackTop(&'static str, String),
ValueNotHashable,
Recursive,
UnresolvedGlobal,
UnsupportedGlobal(Vec<u8>, Vec<u8>),
MissingMemo(u32),
InvalidLiteral(Vec<u8>),
TrailingBytes,
InvalidValue(String),
Structure(String),
}
impl fmt::Display for ErrorCode {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
ErrorCode::Unsupported(ch) => write!(fmt, "unsupported opcode {:?}", ch),
ErrorCode::EOFWhileParsing => write!(fmt, "EOF while parsing"),
ErrorCode::StackUnderflow => write!(fmt, "pickle stack underflow"),
ErrorCode::NegativeLength => write!(fmt, "negative length prefix"),
ErrorCode::StringNotUTF8 => write!(fmt, "string is not UTF-8 encoded"),
ErrorCode::InvalidStackTop(what, ref it) =>
write!(fmt, "invalid stack top, expected {}, got {}", what, it),
ErrorCode::ValueNotHashable => write!(fmt, "dict key or set item not hashable"),
ErrorCode::Recursive => write!(fmt, "recursive structure found"),
ErrorCode::UnresolvedGlobal => write!(fmt, "unresolved global reference"),
ErrorCode::UnsupportedGlobal(ref m, ref g) =>
write!(fmt, "unsupported global: {}.{}",
String::from_utf8_lossy(m), String::from_utf8_lossy(g)),
ErrorCode::MissingMemo(n) => write!(fmt, "missing memo with id {}", n),
ErrorCode::InvalidLiteral(ref l) =>
write!(fmt, "literal is invalid: {}", String::from_utf8_lossy(l)),
ErrorCode::TrailingBytes => write!(fmt, "trailing bytes found"),
ErrorCode::InvalidValue(ref s) => write!(fmt, "invalid value: {}", s),
ErrorCode::Structure(ref s) => fmt.write_str(s),
}
}
}
#[derive(Debug)]
pub enum Error {
Io(io::Error),
Eval(ErrorCode, usize),
Syntax(ErrorCode),
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Error {
Error::Io(error)
}
}
pub type Result<T> = result::Result<T, Error>;
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Io(ref error) => error.fmt(fmt),
Error::Eval(ref code, offset) => write!(fmt, "eval error at offset {}: {}",
offset, code),
Error::Syntax(ref code) => write!(fmt, "decoding error: {}", code)
}
}
}
impl error::Error for Error {}
impl de::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Error {
Error::Syntax(ErrorCode::Structure(msg.to_string()))
}
}
impl ser::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Error {
Error::Syntax(ErrorCode::Structure(msg.to_string()))
}
}