#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ErrorKind {
InvalidHex,
InvalidRgb,
InvalidHsl,
InvalidFunction,
InvalidGradient,
InvalidGradientCoordinates,
InvalidDarken,
InvalidLighten,
InvalidUnknown,
}
impl core::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::InvalidHex => write!(f, "invalid hex format"),
Self::InvalidRgb => write!(f, "invalid rgb format"),
Self::InvalidHsl => write!(f, "invalid hsl format"),
Self::InvalidGradient => write!(f, "invalid gradient format"),
Self::InvalidGradientCoordinates => write!(f, "invalid gradient coordinates format"),
Self::InvalidDarken => write!(f, "invalid darken format"),
Self::InvalidLighten => write!(f, "invalid lighten format"),
Self::InvalidFunction => write!(f, "invalid color function"),
Self::InvalidUnknown => write!(f, "invalid unknown format"),
}
}
}
#[derive(Clone)]
pub struct Error {
kind: ErrorKind,
message: String,
}
impl core::fmt::Debug for Error {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut debug = fmt.debug_struct("Error");
debug
.field("kind", &self.kind())
.field("message", &self.message())
.finish()
}
}
impl Eq for Error {}
impl PartialEq for Error {
fn eq(&self, other: &Self) -> bool {
self.kind == other.kind
}
}
impl core::hash::Hash for Error {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.kind.hash(state);
}
}
impl PartialOrd for Error {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Error {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.kind.cmp(&other.kind)
}
}
impl Error {
pub fn new<T: AsRef<str>>(kind: ErrorKind, message: T) -> Self {
let message: &str = message.as_ref();
Self {
kind,
message: message.to_string(),
}
}
pub fn kind(&self) -> ErrorKind {
self.kind.clone()
}
pub fn message(&self) -> String {
self.message.clone()
}
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if self.message.is_empty() {
write!(f, "{}", self.kind)
} else {
write!(f, "{} ({})", self.kind, self.message)
}
}
}
impl std::error::Error for Error {}
pub type Result<T> = core::result::Result<T, Error>;