use core::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SemverErrorKind {
UnexpectedCharacter(char),
MaxLengthExceeded,
MaxSafeIntegerExceeded,
Empty,
EmptySegment,
TrailingDot,
UnexpectedDot,
LeadingZero,
InvalidNumber,
MissingVersionSegment,
MissingVersionAfterOperator(&'static str),
}
impl fmt::Display for SemverErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnexpectedCharacter(ch) => write!(f, "unexpected character: '{ch}'"),
Self::MaxLengthExceeded => f.write_str("maximum length of 256 characters exceeded"),
Self::MaxSafeIntegerExceeded => f.write_str("number exceeds MAX_SAFE_INTEGER"),
Self::Empty => f.write_str("empty"),
Self::EmptySegment => f.write_str("empty segment"),
Self::TrailingDot => f.write_str("trailing dot"),
Self::UnexpectedDot => f.write_str("unexpected dot"),
Self::LeadingZero => f.write_str("leading zero"),
Self::InvalidNumber => f.write_str("invalid number"),
Self::MissingVersionSegment => f.write_str("missing version segment"),
Self::MissingVersionAfterOperator(operator) => {
write!(f, "missing version after {operator}")
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SemverError {
kind: SemverErrorKind,
}
impl fmt::Display for SemverError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.kind.fmt(f)
}
}
#[cfg(feature = "std")]
impl std::error::Error for SemverError {}
impl From<SemverErrorKind> for SemverError {
fn from(kind: SemverErrorKind) -> Self {
Self { kind }
}
}
#[cfg(test)]
mod tests {
#[cfg(not(feature = "std"))]
use alloc::string::ToString;
use super::{SemverError, SemverErrorKind};
#[test]
fn semver_error_kind_display_variants() {
let cases = [
(
SemverErrorKind::UnexpectedCharacter('x'),
"unexpected character: 'x'",
),
(
SemverErrorKind::MaxLengthExceeded,
"maximum length of 256 characters exceeded",
),
(
SemverErrorKind::MaxSafeIntegerExceeded,
"number exceeds MAX_SAFE_INTEGER",
),
(SemverErrorKind::Empty, "empty"),
(SemverErrorKind::EmptySegment, "empty segment"),
(SemverErrorKind::TrailingDot, "trailing dot"),
(SemverErrorKind::UnexpectedDot, "unexpected dot"),
(SemverErrorKind::LeadingZero, "leading zero"),
(SemverErrorKind::InvalidNumber, "invalid number"),
(
SemverErrorKind::MissingVersionSegment,
"missing version segment",
),
(
SemverErrorKind::MissingVersionAfterOperator(">="),
"missing version after >=",
),
];
for (kind, expected) in cases {
assert_eq!(kind.to_string(), expected);
let error: SemverError = kind.into();
assert_eq!(error.to_string(), expected);
}
}
}