1use std::error::Error;
4use std::fmt;
5use std::io;
6use std::str;
7
8use wire_format::WireType;
9
10pub type ProtobufResult<T> = Result<T, ProtobufError>;
12
13#[derive(Debug)]
16pub enum WireError {
17 UnexpectedEof,
19 UnexpectedWireType(WireType),
21 IncorrectTag(u32),
23 IncompleteMap,
25 IncorrectVarint,
27 Utf8Error,
29 InvalidEnumValue(i32),
31 OverRecursionLimit,
33 TruncatedMessage,
35 Other,
37}
38
39#[derive(Debug)]
41pub enum ProtobufError {
42 IoError(io::Error),
44 WireError(WireError),
46 Utf8(str::Utf8Error),
48 MessageNotInitialized {
50 message: &'static str,
52 },
53}
54
55impl ProtobufError {
56 #[doc(hidden)]
58 pub fn message_not_initialized(message: &'static str) -> ProtobufError {
59 ProtobufError::MessageNotInitialized { message: message }
60 }
61}
62
63impl fmt::Display for ProtobufError {
64 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
65 fmt::Debug::fmt(self, f)
66 }
67}
68
69impl Error for ProtobufError {
70 fn description(&self) -> &str {
71 match self {
72 &ProtobufError::IoError(ref e) => e.description(),
74 &ProtobufError::WireError(ref e) => match *e {
75 WireError::Utf8Error => "invalid UTF-8 sequence",
76 WireError::UnexpectedWireType(..) => "unexpected wire type",
77 WireError::InvalidEnumValue(..) => "invalid enum value",
78 WireError::IncorrectTag(..) => "incorrect tag",
79 WireError::IncorrectVarint => "incorrect varint",
80 WireError::IncompleteMap => "incomplete map",
81 WireError::UnexpectedEof => "unexpected EOF",
82 WireError::OverRecursionLimit => "over recursion limit",
83 WireError::TruncatedMessage => "truncated message",
84 WireError::Other => "other error",
85 },
86 &ProtobufError::Utf8(ref e) => &e.description(),
87 &ProtobufError::MessageNotInitialized { .. } => "not all message fields set",
88 }
89 }
90
91 fn cause(&self) -> Option<&Error> {
92 match self {
93 &ProtobufError::IoError(ref e) => Some(e),
94 &ProtobufError::Utf8(ref e) => Some(e),
95 &ProtobufError::WireError(..) => None,
96 &ProtobufError::MessageNotInitialized { .. } => None,
97 }
98 }
99}
100
101impl From<io::Error> for ProtobufError {
102 fn from(err: io::Error) -> Self {
103 ProtobufError::IoError(err)
104 }
105}
106
107impl From<str::Utf8Error> for ProtobufError {
108 fn from(err: str::Utf8Error) -> Self {
109 ProtobufError::Utf8(err)
110 }
111}
112
113impl From<ProtobufError> for io::Error {
114 fn from(err: ProtobufError) -> Self {
115 match err {
116 ProtobufError::IoError(e) => e,
117 ProtobufError::WireError(e) => {
118 io::Error::new(io::ErrorKind::InvalidData, ProtobufError::WireError(e))
119 }
120 ProtobufError::MessageNotInitialized { message: msg } => io::Error::new(
121 io::ErrorKind::InvalidInput,
122 ProtobufError::MessageNotInitialized { message: msg },
123 ),
124 e => io::Error::new(io::ErrorKind::Other, Box::new(e)),
125 }
126 }
127}