use std::error::Error;
use std::path::Path;
use std::{fmt, fs, io};
#[cfg(doc)]
use super::Input;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct InputError {
pub name: String,
pub problems: Vec<Problem>,
io_failure: Option<io::ErrorKind>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Problem {
pub line: Option<usize>,
pub column: Option<usize>,
pub field: String,
pub message: String,
}
pub(crate) fn read_text(path: &Path) -> Result<(String, String), InputError> {
let name = path.display().to_string();
match fs::read_to_string(path) {
Ok(text) => Ok((name, text)),
Err(error) => Err(InputError::unread(name, &error)),
}
}
impl InputError {
#[must_use]
pub fn try_new(
name: impl Into<String>,
problems: impl IntoIterator<Item = Problem>,
) -> Option<Self> {
let problems = problems.into_iter().collect::<Vec<_>>();
(!problems.is_empty()).then(|| Self {
name: name.into(),
problems,
io_failure: None,
})
}
#[must_use]
pub fn whole(name: impl Into<String>, message: impl Into<String>) -> Self {
Self::one(
name.into(),
Problem {
line: None,
column: None,
field: String::new(),
message: message.into(),
},
)
}
pub(crate) fn one(name: String, problem: Problem) -> Self {
Self {
name,
problems: vec![problem],
io_failure: None,
}
}
pub(crate) fn unread(name: String, error: &io::Error) -> Self {
Self {
io_failure: Some(error.kind()),
..Self::whole(name, error.to_string())
}
}
#[must_use]
pub const fn io_failure(&self) -> Option<io::ErrorKind> {
self.io_failure
}
}
impl fmt::Display for InputError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
for (index, problem) in self.problems.iter().enumerate() {
if index > 0 {
writeln!(formatter)?;
}
write!(formatter, "{}", self.name)?;
if let Some(line) = problem.line {
write!(formatter, ":{line}")?;
if let Some(column) = problem.column {
write!(formatter, ":{column}")?;
}
}
if problem.field.is_empty() {
write!(formatter, ": {}", problem.message)?;
} else {
write!(formatter, ": {}: {}", problem.field, problem.message)?;
}
}
Ok(())
}
}
impl Error for InputError {}