1use std::{error, fmt};
2
3#[derive(Debug)]
4pub enum Error {
5 VlqLeftover,
7 VlqNoValues,
9 VlqOverflow,
11 BadJson(serde_json::Error),
13 BadSegmentSize(u32),
15 BadSourceReference(u32),
17 BadNameReference(u32),
19}
20impl fmt::Display for Error {
21 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22 match self {
23 Error::VlqLeftover => write!(f, "VLQ string was malformed and data was left over"),
24 Error::VlqNoValues => write!(f, "VLQ string was empty and no values could be decoded"),
25 Error::VlqOverflow => write!(f, "The input encoded a number that didn't fit into i64"),
26 Error::BadJson(err) => write!(f, "JSON parsing error: {err}"),
27 Error::BadSegmentSize(size) => {
28 write!(f, "Mapping segment had an unsupported size of {size}")
29 }
30 Error::BadSourceReference(idx) => {
31 write!(f, "Reference to non-existing source at position {idx}")
32 }
33 Error::BadNameReference(idx) => {
34 write!(f, "Reference to non-existing name at position {idx}")
35 }
36 }
37 }
38}
39
40impl error::Error for Error {
41 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
42 if let Self::BadJson(err) = self { Some(err) } else { None }
43 }
44}
45
46pub type Result<T> = std::result::Result<T, Error>;
48
49impl From<serde_json::Error> for Error {
50 fn from(err: serde_json::Error) -> Error {
51 Error::BadJson(err)
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use std::error::Error as _;
58
59 use super::*;
60
61 fn bad_json_error() -> serde_json::Error {
62 serde_json::from_str::<u32>("not a number").unwrap_err()
63 }
64
65 #[test]
66 fn display_messages() {
67 assert_eq!(
68 Error::VlqLeftover.to_string(),
69 "VLQ string was malformed and data was left over"
70 );
71 assert_eq!(
72 Error::VlqNoValues.to_string(),
73 "VLQ string was empty and no values could be decoded"
74 );
75 assert_eq!(
76 Error::VlqOverflow.to_string(),
77 "The input encoded a number that didn't fit into i64"
78 );
79 assert!(Error::BadJson(bad_json_error()).to_string().starts_with("JSON parsing error:"));
80 assert_eq!(
81 Error::BadSegmentSize(7).to_string(),
82 "Mapping segment had an unsupported size of 7"
83 );
84 assert_eq!(
85 Error::BadSourceReference(3).to_string(),
86 "Reference to non-existing source at position 3"
87 );
88 assert_eq!(
89 Error::BadNameReference(9).to_string(),
90 "Reference to non-existing name at position 9"
91 );
92 }
93
94 #[test]
95 fn error_source() {
96 assert!(Error::BadJson(bad_json_error()).source().is_some());
98 assert!(Error::VlqLeftover.source().is_none());
99 assert!(Error::BadSegmentSize(1).source().is_none());
100 }
101
102 #[test]
103 fn from_serde_json_error() {
104 let err: Error = bad_json_error().into();
105 assert!(matches!(err, Error::BadJson(_)));
106 }
107}