use core::fmt;
use icu_calendar::CalendarError;
#[derive(Debug, Default, Clone, Copy)]
pub enum ErrorKind {
#[default]
Generic,
Type,
Range,
Syntax,
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Generic => "Error",
Self::Type => "TypeError",
Self::Range => "RangeError",
Self::Syntax => "SyntaxError",
}
.fmt(f)
}
}
#[derive(Debug, Clone)]
pub struct TemporalError {
kind: ErrorKind,
msg: Box<str>,
}
impl TemporalError {
fn new(kind: ErrorKind) -> Self {
Self {
kind,
msg: Box::default(),
}
}
#[must_use]
pub fn general<S>(msg: S) -> Self
where
S: Into<Box<str>>,
{
Self::new(ErrorKind::Generic).with_message(msg)
}
#[must_use]
pub fn range() -> Self {
Self::new(ErrorKind::Range)
}
#[must_use]
pub fn r#type() -> Self {
Self::new(ErrorKind::Type)
}
#[must_use]
pub fn syntax() -> Self {
Self::new(ErrorKind::Syntax)
}
#[must_use]
pub fn abrupt_end() -> Self {
Self::syntax().with_message("Abrupt end to parsing target.")
}
#[must_use]
pub fn with_message<S>(mut self, msg: S) -> Self
where
S: Into<Box<str>>,
{
self.msg = msg.into();
self
}
#[must_use]
pub fn kind(&self) -> ErrorKind {
self.kind
}
#[must_use]
pub fn message(&self) -> &str {
&self.msg
}
}
impl fmt::Display for TemporalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.kind)?;
let msg = self.msg.trim();
if !msg.is_empty() {
write!(f, ": {msg}")?;
}
Ok(())
}
}
impl From<CalendarError> for TemporalError {
fn from(value: CalendarError) -> Self {
TemporalError::general(value.to_string())
}
}