use std::fmt;
use std::num::{ParseFloatError, ParseIntError};
#[derive(Debug, Clone)]
pub enum ParseError {
IncompleteHeader,
IncompleteFrame,
IncompleteVelocitySection,
InvalidVectorLength {
expected: usize,
found: usize,
},
InvalidNumberFormat(String),
MissingSpecVersion,
UnsupportedSpecVersion(u32),
InvalidMetadataJson(String),
IncompleteForceSection,
IncompleteEnergySection,
IncompleteSection(String),
UnknownSection(String),
ValidationError(String),
NonFiniteValue(String),
InvalidFixedFlag(String),
InvalidCount(String),
InvalidUnits(String),
UnsupportedVersion(u32),
IndexOutOfBounds {
index: usize,
len: usize,
},
MassMismatch {
symbol: String,
first_mass: f64,
found_mass: f64,
atom_index: usize,
},
Io(String),
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::IncompleteHeader => {
write!(f, "file ended unexpectedly while parsing frame header")
}
ParseError::IncompleteFrame => {
write!(f, "file ended unexpectedly while reading atom data")
}
ParseError::IncompleteVelocitySection => {
write!(f, "file ended unexpectedly while reading velocity section")
}
ParseError::InvalidVectorLength { expected, found } => {
write!(f, "expected {expected} values on line, found {found}")
}
ParseError::InvalidNumberFormat(msg) => {
write!(f, "invalid number format: {msg}")
}
ParseError::MissingSpecVersion => {
write!(
f,
"line 2 must be a JSON object containing \"con_spec_version\""
)
}
ParseError::UnsupportedSpecVersion(v) | ParseError::UnsupportedVersion(v) => {
write!(f, "unsupported con_spec_version: {v}")
}
ParseError::InvalidMetadataJson(msg) => {
write!(f, "invalid JSON metadata on line 2: {msg}")
}
ParseError::IncompleteForceSection => {
write!(f, "file ended unexpectedly while reading force section")
}
ParseError::IncompleteEnergySection => {
write!(f, "file ended unexpectedly while reading energy section")
}
ParseError::IncompleteSection(name) => {
write!(f, "file ended unexpectedly while reading {name} section")
}
ParseError::UnknownSection(name) => {
write!(f, "unknown section type in metadata: {name}")
}
ParseError::ValidationError(msg) => {
write!(f, "CON validation failed: {msg}")
}
ParseError::NonFiniteValue(token) => {
write!(f, "non-finite value: {token}")
}
ParseError::InvalidFixedFlag(msg) => {
write!(f, "invalid fixed flag: {msg}")
}
ParseError::InvalidCount(msg) => {
write!(f, "invalid count: {msg}")
}
ParseError::InvalidUnits(msg) => {
write!(f, "invalid units: {msg}")
}
ParseError::IndexOutOfBounds { index, len } => {
write!(
f,
"atom index {index} is out of bounds (builder holds {len} atoms)"
)
}
ParseError::MassMismatch {
symbol,
first_mass,
found_mass,
atom_index,
} => {
write!(
f,
"atoms of type {symbol} have inconsistent masses: first {first_mass}, atom {atom_index} has {found_mass} (CON stores one mass per type)"
)
}
ParseError::Io(msg) => write!(f, "index read failed: {msg}"),
}
}
}
impl std::error::Error for ParseError {}
const CELL_FIELD: &str = "cell field ";
const CELL_VALUE_JOINT: &str = " is ";
impl ParseError {
pub fn non_finite_cell(field: &str, value: impl std::fmt::Display) -> Self {
ParseError::NonFiniteValue(format!("{CELL_FIELD}{field}{CELL_VALUE_JOINT}{value}"))
}
#[must_use]
pub fn from_cell_text(message: &str) -> Option<Self> {
let rest = message.strip_prefix("non-finite value: ")?;
rest.starts_with(CELL_FIELD)
.then(|| ParseError::NonFiniteValue(rest.to_string()))
}
#[must_use]
pub fn from_non_finite_text(message: &str) -> Option<Self> {
let rest = message.strip_prefix("non-finite value: ")?;
(!rest.is_empty()).then(|| ParseError::NonFiniteValue(rest.to_string()))
}
pub fn is_non_finite_cell(&self) -> bool {
matches!(self, ParseError::NonFiniteValue(text) if text.starts_with(CELL_FIELD))
}
#[must_use]
pub fn named_frame(&self) -> Option<u64> {
let ParseError::NonFiniteValue(text) = self else {
return None;
};
let rest = text.strip_prefix(CELL_FIELD)?;
let (field, _) = rest.split_once(CELL_VALUE_JOINT)?;
let (_, frame) = field.split_once(" of frame ")?;
frame.parse().ok()
}
#[must_use]
pub fn in_frame(self, frame: u64) -> Self {
let ParseError::NonFiniteValue(text) = &self else {
return self;
};
let Some(rest) = text.strip_prefix(CELL_FIELD) else {
return self;
};
match rest.split_once(CELL_VALUE_JOINT) {
Some((field, value)) if !field.contains(' ') => ParseError::NonFiniteValue(format!(
"{CELL_FIELD}{field} of frame {frame}{CELL_VALUE_JOINT}{value}"
)),
_ => self,
}
}
}
impl ParseError {
pub fn class_name(&self) -> &'static str {
match self {
ParseError::IncompleteHeader => "IncompleteHeader",
ParseError::IncompleteFrame => "IncompleteFrame",
ParseError::IncompleteVelocitySection => "IncompleteVelocitySection",
ParseError::InvalidVectorLength { .. } => "InvalidVectorLength",
ParseError::InvalidNumberFormat(_) => "InvalidNumberFormat",
ParseError::MissingSpecVersion => "MissingSpecVersion",
ParseError::UnsupportedSpecVersion(_) | ParseError::UnsupportedVersion(_) => {
"UnsupportedVersion"
}
ParseError::InvalidMetadataJson(_) => "InvalidMetadataJson",
ParseError::IncompleteForceSection => "IncompleteForceSection",
ParseError::IncompleteEnergySection => "IncompleteEnergySection",
ParseError::IncompleteSection(_) => "IncompleteSection",
ParseError::UnknownSection(_) => "UnknownSection",
ParseError::ValidationError(_) => "ValidationError",
ParseError::IndexOutOfBounds { .. } => "IndexOutOfBounds",
ParseError::MassMismatch { .. } => "MassMismatch",
ParseError::NonFiniteValue(_) => "NonFiniteValue",
ParseError::InvalidFixedFlag(_) => "InvalidFixedFlag",
ParseError::InvalidCount(_) => "InvalidCount",
ParseError::InvalidUnits(_) => "InvalidUnits",
ParseError::Io(_) => "Io",
}
}
pub fn line(&self) -> u32 {
match self {
ParseError::MissingSpecVersion
| ParseError::InvalidMetadataJson(_)
| ParseError::UnsupportedSpecVersion(_)
| ParseError::UnsupportedVersion(_) => 2,
_ => 0,
}
}
}
impl From<ParseFloatError> for ParseError {
fn from(e: ParseFloatError) -> Self {
ParseError::InvalidNumberFormat(e.to_string())
}
}
impl From<ParseIntError> for ParseError {
fn from(e: ParseIntError) -> Self {
ParseError::InvalidNumberFormat(e.to_string())
}
}
impl From<serde_json::Error> for ParseError {
fn from(e: serde_json::Error) -> Self {
ParseError::InvalidMetadataJson(e.to_string())
}
}
#[derive(Debug, Clone)]
pub enum ConvertError {
Parse(ParseError),
Message(String),
}
impl ConvertError {
pub fn parse_error(&self) -> Option<&ParseError> {
match self {
ConvertError::Parse(error) => Some(error),
ConvertError::Message(_) => None,
}
}
pub fn is_non_finite_cell(&self) -> bool {
self.parse_error()
.is_some_and(ParseError::is_non_finite_cell)
}
#[must_use]
pub fn in_frame(self, frame: u64) -> Self {
match self {
ConvertError::Parse(error) => ConvertError::Parse(error.in_frame(frame)),
message => message,
}
}
}
impl fmt::Display for ConvertError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConvertError::Parse(error) => write!(f, "{error}"),
ConvertError::Message(message) => f.write_str(message),
}
}
}
impl std::error::Error for ConvertError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ConvertError::Parse(error) => Some(error),
ConvertError::Message(_) => None,
}
}
}
impl PartialEq<str> for ConvertError {
fn eq(&self, other: &str) -> bool {
matches!(self, ConvertError::Message(message) if message == other)
}
}
impl PartialEq<&str> for ConvertError {
fn eq(&self, other: &&str) -> bool {
self == *other
}
}
impl From<ParseError> for ConvertError {
fn from(error: ParseError) -> Self {
ConvertError::Parse(error)
}
}
impl From<String> for ConvertError {
fn from(message: String) -> Self {
ConvertError::Message(message)
}
}
impl From<&str> for ConvertError {
fn from(message: &str) -> Self {
ConvertError::Message(message.to_string())
}
}
impl From<ConvertError> for String {
fn from(error: ConvertError) -> Self {
error.to_string()
}
}
#[derive(Debug)]
pub struct LocatedParseError {
pub error: ParseError,
pub line: u32,
pub frame_index: u64,
}
impl LocatedParseError {
pub fn new(error: ParseError, cursor_line: u32, frame_index: u64) -> Self {
let line = if cursor_line != 0 {
cursor_line
} else {
error.line()
};
Self {
error: error.in_frame(frame_index),
line,
frame_index,
}
}
}
impl fmt::Display for LocatedParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.error)
}
}
impl std::error::Error for LocatedParseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.error)
}
}