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
#[derive(Debug,thiserror::Error)]
#[non_exhaustive]
pub struct DeserializeError {
	#[source]
	pub kind: DeserializeErrorKind,
	pub location: Option<crate::Location>,
}

impl DeserializeError {
	pub(crate) fn with_location(mut self, location: crate::Location) -> Self {
		if self.location.is_none() {
			self.location = Some(location);
		}
		self
	}
}

impl std::fmt::Display for DeserializeError {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		if let Some(location) = self.location {
			write!(f, "{} at {}", self.kind, location)
		} else {
			write!(f, "{}", self.kind)
		}
	}
}

impl serde::de::Error for DeserializeError {
	fn custom<T: std::fmt::Display>(msg: T) -> Self {
		DeserializeError {
			kind: DeserializeErrorKind::Custom(format!("{}", msg)),
			location: None,
		}
	}
}

impl From<std::io::Error> for DeserializeError {
	fn from(e: std::io::Error) -> Self {
		DeserializeError {
			kind: DeserializeErrorKind::Io(e),
			location: None,
		}
	}
}

#[non_exhaustive]
#[derive(Debug,thiserror::Error)]
pub enum DeserializeErrorKind {
	#[error("{0}")]
	Custom(String),
	#[error("{0}")]
	Invalid(String),
	#[error("Expected integer, got {0:?}")]
	IntFraction(String),
	#[error("{0:?} is too big")]
	IntOverflow(String),
	#[error("Expected unsigned integer, got -{0}")]
	IntSigned(u128),
	#[error("Unexpected characters after number {0:?}")]
	NumTrailing(String),
	#[error("e exponents only supported in base 10")]
	NumExpBase,
	#[error("Could not parse exponent as integer: {0}")]
	NumExpInvalid(#[source] std::num::ParseIntError),
	#[error(transparent)]
	Io(#[from] std::io::Error),
	#[error("{0} is not supported.")]
	Unimplemented(&'static str),
	#[error("Invalid UTF-8")]
	InvalidUtf8,
}

impl DeserializeErrorKind {
	pub(crate) fn at(self, location: crate::Location) -> DeserializeError {
		DeserializeError {
			kind: self,
			location: Some(location),
		}
	}
}