1use std::fmt;
2use std::num::{ParseFloatError, ParseIntError};
3
4#[derive(Debug, Clone)]
5pub enum ParseError {
6 IncompleteHeader,
7 IncompleteFrame,
8 IncompleteVelocitySection,
9 InvalidVectorLength {
10 expected: usize,
11 found: usize,
12 },
13 InvalidNumberFormat(String),
14 MissingSpecVersion,
15 UnsupportedSpecVersion(u32),
16 InvalidMetadataJson(String),
17 IncompleteForceSection,
18 IncompleteEnergySection,
19 IncompleteSection(String),
21 UnknownSection(String),
22 ValidationError(String),
23 NonFiniteValue(String),
26 InvalidFixedFlag(String),
28 InvalidCount(String),
32 InvalidUnits(String),
37 UnsupportedVersion(u32),
40 IndexOutOfBounds {
47 index: usize,
48 len: usize,
49 },
50 MassMismatch {
55 symbol: String,
56 first_mass: f64,
57 found_mass: f64,
58 atom_index: usize,
59 },
60 Io(String),
62}
63
64impl fmt::Display for ParseError {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 match self {
67 ParseError::IncompleteHeader => {
68 write!(f, "file ended unexpectedly while parsing frame header")
69 }
70 ParseError::IncompleteFrame => {
71 write!(f, "file ended unexpectedly while reading atom data")
72 }
73 ParseError::IncompleteVelocitySection => {
74 write!(f, "file ended unexpectedly while reading velocity section")
75 }
76 ParseError::InvalidVectorLength { expected, found } => {
77 write!(f, "expected {expected} values on line, found {found}")
78 }
79 ParseError::InvalidNumberFormat(msg) => {
80 write!(f, "invalid number format: {msg}")
81 }
82 ParseError::MissingSpecVersion => {
83 write!(
84 f,
85 "line 2 must be a JSON object containing \"con_spec_version\""
86 )
87 }
88 ParseError::UnsupportedSpecVersion(v) | ParseError::UnsupportedVersion(v) => {
89 write!(f, "unsupported con_spec_version: {v}")
90 }
91 ParseError::InvalidMetadataJson(msg) => {
92 write!(f, "invalid JSON metadata on line 2: {msg}")
93 }
94 ParseError::IncompleteForceSection => {
95 write!(f, "file ended unexpectedly while reading force section")
96 }
97 ParseError::IncompleteEnergySection => {
98 write!(f, "file ended unexpectedly while reading energy section")
99 }
100 ParseError::IncompleteSection(name) => {
101 write!(f, "file ended unexpectedly while reading {name} section")
102 }
103 ParseError::UnknownSection(name) => {
104 write!(f, "unknown section type in metadata: {name}")
105 }
106 ParseError::ValidationError(msg) => {
107 write!(f, "CON validation failed: {msg}")
108 }
109 ParseError::NonFiniteValue(token) => {
110 write!(f, "non-finite value: {token}")
111 }
112 ParseError::InvalidFixedFlag(msg) => {
113 write!(f, "invalid fixed flag: {msg}")
114 }
115 ParseError::InvalidCount(msg) => {
116 write!(f, "invalid count: {msg}")
117 }
118 ParseError::InvalidUnits(msg) => {
119 write!(f, "invalid units: {msg}")
120 }
121 ParseError::IndexOutOfBounds { index, len } => {
122 write!(
123 f,
124 "atom index {index} is out of bounds (builder holds {len} atoms)"
125 )
126 }
127 ParseError::MassMismatch {
128 symbol,
129 first_mass,
130 found_mass,
131 atom_index,
132 } => {
133 write!(
134 f,
135 "atoms of type {symbol} have inconsistent masses: first {first_mass}, atom {atom_index} has {found_mass} (CON stores one mass per type)"
136 )
137 }
138 ParseError::Io(msg) => write!(f, "index read failed: {msg}"),
139 }
140 }
141}
142
143impl std::error::Error for ParseError {}
144
145const CELL_FIELD: &str = "cell field ";
147const CELL_VALUE_JOINT: &str = " is ";
148
149impl ParseError {
150 pub fn non_finite_cell(field: &str, value: impl std::fmt::Display) -> Self {
157 ParseError::NonFiniteValue(format!("{CELL_FIELD}{field}{CELL_VALUE_JOINT}{value}"))
158 }
159
160 #[must_use]
167 pub fn from_cell_text(message: &str) -> Option<Self> {
168 let rest = message.strip_prefix("non-finite value: ")?;
169 rest.starts_with(CELL_FIELD)
170 .then(|| ParseError::NonFiniteValue(rest.to_string()))
171 }
172
173 #[must_use]
176 pub fn from_non_finite_text(message: &str) -> Option<Self> {
177 let rest = message.strip_prefix("non-finite value: ")?;
178 (!rest.is_empty()).then(|| ParseError::NonFiniteValue(rest.to_string()))
179 }
180
181 pub fn is_non_finite_cell(&self) -> bool {
183 matches!(self, ParseError::NonFiniteValue(text) if text.starts_with(CELL_FIELD))
184 }
185
186 #[must_use]
188 pub fn named_frame(&self) -> Option<u64> {
189 let ParseError::NonFiniteValue(text) = self else {
190 return None;
191 };
192 let rest = text.strip_prefix(CELL_FIELD)?;
193 let (field, _) = rest.split_once(CELL_VALUE_JOINT)?;
194 let (_, frame) = field.split_once(" of frame ")?;
195 frame.parse().ok()
196 }
197
198 #[must_use]
202 pub fn in_frame(self, frame: u64) -> Self {
203 let ParseError::NonFiniteValue(text) = &self else {
204 return self;
205 };
206 let Some(rest) = text.strip_prefix(CELL_FIELD) else {
207 return self;
208 };
209 match rest.split_once(CELL_VALUE_JOINT) {
210 Some((field, value)) if !field.contains(' ') => ParseError::NonFiniteValue(format!(
211 "{CELL_FIELD}{field} of frame {frame}{CELL_VALUE_JOINT}{value}"
212 )),
213 _ => self,
214 }
215 }
216}
217
218impl ParseError {
219 pub fn class_name(&self) -> &'static str {
221 match self {
222 ParseError::IncompleteHeader => "IncompleteHeader",
223 ParseError::IncompleteFrame => "IncompleteFrame",
224 ParseError::IncompleteVelocitySection => "IncompleteVelocitySection",
225 ParseError::InvalidVectorLength { .. } => "InvalidVectorLength",
226 ParseError::InvalidNumberFormat(_) => "InvalidNumberFormat",
227 ParseError::MissingSpecVersion => "MissingSpecVersion",
228 ParseError::UnsupportedSpecVersion(_) | ParseError::UnsupportedVersion(_) => {
229 "UnsupportedVersion"
230 }
231 ParseError::InvalidMetadataJson(_) => "InvalidMetadataJson",
232 ParseError::IncompleteForceSection => "IncompleteForceSection",
233 ParseError::IncompleteEnergySection => "IncompleteEnergySection",
234 ParseError::IncompleteSection(_) => "IncompleteSection",
235 ParseError::UnknownSection(_) => "UnknownSection",
236 ParseError::ValidationError(_) => "ValidationError",
237 ParseError::IndexOutOfBounds { .. } => "IndexOutOfBounds",
238 ParseError::MassMismatch { .. } => "MassMismatch",
239 ParseError::NonFiniteValue(_) => "NonFiniteValue",
240 ParseError::InvalidFixedFlag(_) => "InvalidFixedFlag",
241 ParseError::InvalidCount(_) => "InvalidCount",
242 ParseError::InvalidUnits(_) => "InvalidUnits",
243 ParseError::Io(_) => "Io",
244 }
245 }
246
247 pub fn line(&self) -> u32 {
252 match self {
253 ParseError::MissingSpecVersion
254 | ParseError::InvalidMetadataJson(_)
255 | ParseError::UnsupportedSpecVersion(_)
256 | ParseError::UnsupportedVersion(_) => 2,
257 _ => 0,
258 }
259 }
260}
261
262impl From<ParseFloatError> for ParseError {
263 fn from(e: ParseFloatError) -> Self {
264 ParseError::InvalidNumberFormat(e.to_string())
265 }
266}
267
268impl From<ParseIntError> for ParseError {
269 fn from(e: ParseIntError) -> Self {
270 ParseError::InvalidNumberFormat(e.to_string())
271 }
272}
273
274impl From<serde_json::Error> for ParseError {
275 fn from(e: serde_json::Error) -> Self {
276 ParseError::InvalidMetadataJson(e.to_string())
277 }
278}
279
280#[derive(Debug, Clone)]
288pub enum ConvertError {
289 Parse(ParseError),
290 Message(String),
291}
292
293impl ConvertError {
294 pub fn parse_error(&self) -> Option<&ParseError> {
296 match self {
297 ConvertError::Parse(error) => Some(error),
298 ConvertError::Message(_) => None,
299 }
300 }
301
302 pub fn is_non_finite_cell(&self) -> bool {
304 self.parse_error()
305 .is_some_and(ParseError::is_non_finite_cell)
306 }
307
308 #[must_use]
311 pub fn in_frame(self, frame: u64) -> Self {
312 match self {
313 ConvertError::Parse(error) => ConvertError::Parse(error.in_frame(frame)),
314 message => message,
315 }
316 }
317}
318
319impl fmt::Display for ConvertError {
320 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321 match self {
322 ConvertError::Parse(error) => write!(f, "{error}"),
323 ConvertError::Message(message) => f.write_str(message),
324 }
325 }
326}
327
328impl std::error::Error for ConvertError {
329 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
330 match self {
331 ConvertError::Parse(error) => Some(error),
332 ConvertError::Message(_) => None,
333 }
334 }
335}
336
337impl PartialEq<str> for ConvertError {
340 fn eq(&self, other: &str) -> bool {
341 matches!(self, ConvertError::Message(message) if message == other)
342 }
343}
344
345impl PartialEq<&str> for ConvertError {
346 fn eq(&self, other: &&str) -> bool {
347 self == *other
348 }
349}
350
351impl From<ParseError> for ConvertError {
352 fn from(error: ParseError) -> Self {
353 ConvertError::Parse(error)
354 }
355}
356
357impl From<String> for ConvertError {
358 fn from(message: String) -> Self {
359 ConvertError::Message(message)
360 }
361}
362
363impl From<&str> for ConvertError {
364 fn from(message: &str) -> Self {
365 ConvertError::Message(message.to_string())
366 }
367}
368
369impl From<ConvertError> for String {
372 fn from(error: ConvertError) -> Self {
373 error.to_string()
374 }
375}
376
377#[derive(Debug)]
382pub struct LocatedParseError {
383 pub error: ParseError,
384 pub line: u32,
385 pub frame_index: u64,
386}
387
388impl LocatedParseError {
389 pub fn new(error: ParseError, cursor_line: u32, frame_index: u64) -> Self {
390 let line = if cursor_line != 0 {
391 cursor_line
392 } else {
393 error.line()
394 };
395 Self {
396 error: error.in_frame(frame_index),
397 line,
398 frame_index,
399 }
400 }
401}
402
403impl fmt::Display for LocatedParseError {
404 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405 write!(f, "{}", self.error)
406 }
407}
408
409impl std::error::Error for LocatedParseError {
410 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
411 Some(&self.error)
412 }
413}