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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
use std::error::Error;
use std::fmt::{Display, Error as FmtError, Formatter};
use std::string::FromUtf8Error;

use protocol_common::error::EnumValueOutOfRangeError;

#[derive(Copy, Clone, Debug)]
pub enum FieldName {
	Name(&'static str),
	Index(usize),
}

#[derive(Copy, Clone, Debug)]
pub struct FieldSpec {
	pub field: FieldName,
	pub ty: Option<&'static str>,
}

#[derive(Debug)]
pub enum SerializeErrorType {
	ArrayTooLarge(usize),
	InvalidFlagId(u16),
}

#[derive(Debug)]
pub enum DeserializeErrorType {
	UnexpectedEndOfMessage,
	Utf8Error(FromUtf8Error),
	InvalidEnumValue(usize),
}

#[derive(Debug)]
pub struct SerializeError {
	pub ty: SerializeErrorType,
	pub trace: Vec<FieldSpec>,
}

#[derive(Debug)]
pub struct DeserializeError {
	pub ty: DeserializeErrorType,
	pub trace: Vec<FieldSpec>,
}

impl Display for SerializeErrorType {
	fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
		use SerializeErrorType::*;
		match self {
			ArrayTooLarge(size) => write!(
				fmt,
				"Array too large. This type of array can have at most {size} elements.",
				size = size
			),
			InvalidFlagId(id) => write!(
				fmt,
				"Flags may only take on ids less than 255. Flag had an id of {id}.",
				id = id
			),
		}
	}
}

impl Display for DeserializeErrorType {
	fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
		use DeserializeErrorType::*;

		match self {
			UnexpectedEndOfMessage => {
				write!(
					fmt,
					"Reached the end of the buffer before deserialization was complete!"
				)
			},
			Utf8Error(e) => {
				write!(
					fmt,
					"A string contained invalid UTF-8. Inner error: {}",
					e
				)
			},
			InvalidEnumValue(v) => {
				write!(
					fmt,
					"Attempted to deserialize an enum with an invalid value. {} does not deserialize to an enum case.",
					v
				)
			}
		}
	}
}

fn display_trace(trace: &[FieldSpec], fmt: &mut Formatter) -> Result<(), FmtError> {
	for spec in trace.iter().rev() {
		match spec.field {
			FieldName::Name(field) => writeln!(
				fmt,
				"\tat {ty}::{field},",
				ty = spec.ty.unwrap_or("<unnamed>"),
				field = field
			)?,
			FieldName::Index(i) => writeln!(fmt, "\tat index ${idx},", idx = i)?,
		}
	}

	Ok(())
}

impl Display for SerializeError {
	fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
		writeln!(fmt, "{}", self.ty)?;
		display_trace(&self.trace, fmt)
	}
}

impl Display for DeserializeError {
	fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
		writeln!(fmt, "{}", self.ty)?;
		display_trace(&self.trace, fmt)
	}
}

impl Error for SerializeError {}

impl Error for DeserializeError {
	fn cause(&self) -> Option<&Error> {
		use DeserializeErrorType::*;
		match self.ty {
			Utf8Error(ref e) => Some(e),
			_ => None,
		}
	}
}

impl From<FromUtf8Error> for DeserializeError {
	fn from(e: FromUtf8Error) -> Self {
		Self {
			ty: DeserializeErrorType::Utf8Error(e),
			trace: vec![],
		}
	}
}

impl From<EnumValueOutOfRangeError<u8>> for DeserializeError {
	fn from(e: EnumValueOutOfRangeError<u8>) -> Self {
		Self {
			ty: DeserializeErrorType::InvalidEnumValue(e.0 as usize),
			trace: vec![],
		}
	}
}

impl From<EnumValueOutOfRangeError<u16>> for DeserializeError {
	fn from(e: EnumValueOutOfRangeError<u16>) -> Self {
		Self {
			ty: DeserializeErrorType::InvalidEnumValue(e.0 as usize),
			trace: vec![],
		}
	}
}

impl From<!> for DeserializeError {
	fn from(never: !) -> Self {
		never
	}
}

impl From<!> for SerializeError {
	fn from(never: !) -> Self {
		never
	}
}

fn append_to<T>(mut v: Vec<T>, elem: T) -> Vec<T> {
	v.push(elem);
	v
}

pub trait ChainError<T> {
	fn chain(self, elem: T) -> Self;
}

impl<T, E, U> ChainError<U> for Result<T, E>
where
	E: ChainError<U>,
{
	fn chain(self, elem: U) -> Self {
		self.map_err(move |e| e.chain(elem))
	}
}

impl ChainError<FieldSpec> for SerializeError {
	fn chain(self, elem: FieldSpec) -> Self {
		Self {
			trace: append_to(self.trace, elem),
			..self
		}
	}
}

impl ChainError<FieldSpec> for DeserializeError {
	fn chain(self, elem: FieldSpec) -> Self {
		Self {
			trace: append_to(self.trace, elem),
			..self
		}
	}
}