1use std::fmt;
4
5#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
7#[error("wire syntax error at byte {offset}: {kind}")]
8pub struct WireError {
9 pub offset: usize,
11 pub kind: WireErrorKind,
12}
13
14#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
16#[non_exhaustive]
17pub enum WireErrorKind {
18 #[error("segment not terminated by '")]
20 UnterminatedSegment,
21 #[error("release character ? at end of input")]
23 DanglingEscape,
24 #[error("malformed binary length")]
26 BadBinaryLength,
27 #[error("binary data of {declared} bytes runs past the end of the input")]
29 BinaryOverrun { declared: usize },
30 #[error("binary marker @ inside a text element")]
32 BinaryInsideText,
33 #[error("binary data not followed by a separator")]
35 DataAfterBinary,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
40#[non_exhaustive]
41pub enum ErrorKind {
42 #[error("mandatory element missing")]
44 Missing,
45 #[error("too long: {actual} bytes, at most {max} allowed")]
47 TooLong { max: usize, actual: usize },
48 #[error("wrong length: {actual} bytes, exactly {expected} required")]
50 WrongLength { expected: usize, actual: usize },
51 #[error("character {found:?} not allowed in format {format}")]
53 InvalidCharacter { format: &'static str, found: char },
54 #[error("character {found:?} is outside ISO 8859-1")]
56 NotLatin1 { found: char },
57 #[error("leading zero not allowed in format {format}")]
59 LeadingZero { format: &'static str },
60 #[error("number too large")]
62 NumberTooLarge,
63 #[error("not a valid date (JJJJMMTT)")]
65 InvalidDate,
66 #[error("not a valid time (hhmmss)")]
68 InvalidTime,
69 #[error("expected J or N")]
71 InvalidYesNo,
72 #[error("not a valid value with decimal comma")]
74 InvalidValue,
75 #[error("binary data where text was expected")]
77 ExpectedText,
78 #[error("text where binary data was expected")]
80 ExpectedBinary,
81 #[error("{actual} repetitions, at least {min} required")]
83 TooFewRepetitions { min: usize, actual: usize },
84 #[error("{actual} repetitions, at most {max} allowed")]
86 TooManyRepetitions { max: usize, actual: usize },
87 #[error("unexpected data after the last defined element")]
89 UnexpectedData,
90 #[error("malformed segment header: {0}")]
92 InvalidHeader(String),
93 #[error("expected segment {expected_code} v{expected_version}")]
95 WrongSegment {
96 expected_code: &'static str,
97 expected_version: u16,
98 },
99 #[error("no definition for this segment code and version")]
101 UnknownSegment,
102 #[error(transparent)]
104 Wire(#[from] WireError),
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct SegmentId {
110 pub code: String,
111 pub version: u16,
112 pub number: u16,
114}
115
116#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct CodecError {
125 pub segment: Option<SegmentId>,
126 pub de: Option<usize>,
127 pub element: Option<usize>,
128 pub field: String,
129 pub kind: ErrorKind,
130}
131
132impl CodecError {
133 pub fn new(kind: ErrorKind) -> Self {
135 CodecError {
136 segment: None,
137 de: None,
138 element: None,
139 field: String::new(),
140 kind,
141 }
142 }
143
144 pub fn in_field(mut self, name: &str) -> Self {
146 if self.field.is_empty() {
147 self.field = name.to_string();
148 } else if self.field.starts_with('[') {
149 self.field = format!("{name}{}", self.field);
150 } else {
151 self.field = format!("{name}.{}", self.field);
152 }
153 self
154 }
155
156 pub fn in_index(mut self, index: usize) -> Self {
158 if self.field.is_empty() || self.field.starts_with('[') {
159 self.field = format!("[{index}]{}", self.field);
160 } else {
161 self.field = format!("[{index}].{}", self.field);
162 }
163 self
164 }
165
166 pub fn at_element(mut self, element: usize) -> Self {
168 self.element.get_or_insert(element);
169 self
170 }
171
172 pub fn at_de(mut self, de: usize) -> Self {
174 self.de.get_or_insert(de);
175 self
176 }
177
178 pub fn in_segment(mut self, id: SegmentId) -> Self {
180 self.segment.get_or_insert(id);
181 self
182 }
183}
184
185impl From<ErrorKind> for CodecError {
186 fn from(kind: ErrorKind) -> Self {
187 CodecError::new(kind)
188 }
189}
190
191impl From<WireError> for CodecError {
192 fn from(e: WireError) -> Self {
193 CodecError::new(ErrorKind::Wire(e))
194 }
195}
196
197impl fmt::Display for CodecError {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 if let Some(seg) = &self.segment {
200 write!(f, "{} v{} (segment {})", seg.code, seg.version, seg.number)?;
201 } else {
202 f.write_str("segment")?;
203 }
204 if let Some(de) = self.de {
205 write!(f, ", DE {de}")?;
206 }
207 if let Some(el) = self.element {
208 write!(f, ", element {el}")?;
209 }
210 if !self.field.is_empty() {
211 write!(f, " ({})", self.field)?;
212 }
213 write!(f, ": {}", self.kind)
214 }
215}
216
217impl std::error::Error for CodecError {
218 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
219 match &self.kind {
220 ErrorKind::Wire(e) => Some(e),
221 _ => None,
222 }
223 }
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 #[test]
231 fn field_paths_compose_from_the_inside_out() {
232 let e = CodecError::new(ErrorKind::Missing)
233 .in_field("name")
234 .in_index(2)
235 .in_field("methods")
236 .in_field("parameters");
237 assert_eq!(e.field, "parameters.methods[2].name");
238 }
239
240 #[test]
241 fn display_names_segment_position_field_and_rule() {
242 let e = CodecError::new(ErrorKind::TooLong {
243 max: 30,
244 actual: 31,
245 })
246 .at_element(12)
247 .in_field("name")
248 .at_de(5)
249 .in_segment(SegmentId {
250 code: "HITANS".into(),
251 version: 6,
252 number: 4,
253 });
254 assert_eq!(
255 e.to_string(),
256 "HITANS v6 (segment 4), DE 5, element 12 (name): too long: 31 bytes, at most 30 allowed"
257 );
258 }
259}