use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct StateTransitionError<S> {
pub from: S,
pub to: S,
}
impl<S> StateTransitionError<S> {
#[inline]
pub const fn new(from: S, to: S) -> Self {
Self { from, to }
}
}
impl<S: fmt::Display> fmt::Display for StateTransitionError<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid state transition from {} to {}", self.from, self.to)
}
}
impl<S: fmt::Debug> fmt::Debug for StateTransitionError<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StateTransitionError")
.field("from", &self.from)
.field("to", &self.to)
.finish()
}
}
impl<S: fmt::Debug + fmt::Display> std::error::Error for StateTransitionError<S> {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GotExpected<T> {
pub got: T,
pub expected: T,
}
impl<T> GotExpected<T> {
#[inline]
pub const fn new(got: T, expected: T) -> Self {
Self { got, expected }
}
}
impl<T: fmt::Display> fmt::Display for GotExpected<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "expected {}, got {}", self.expected, self.got)
}
}
impl<T: fmt::Debug + fmt::Display> std::error::Error for GotExpected<T> {}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
Pending,
Active,
Closed,
}
impl fmt::Display for Status {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Pending => write!(f, "pending"),
Self::Active => write!(f, "active"),
Self::Closed => write!(f, "closed"),
}
}
}
#[test]
fn transition_error_display() {
let err = StateTransitionError::new(Status::Pending, Status::Closed);
assert_eq!(err.to_string(), "invalid state transition from pending to closed");
}
#[test]
fn transition_error_debug() {
let err = StateTransitionError::new(Status::Active, Status::Pending);
let debug = format!("{:?}", err);
assert!(debug.contains("StateTransitionError"));
assert!(debug.contains("Active"));
assert!(debug.contains("Pending"));
}
#[test]
fn transition_error_fields() {
let err = StateTransitionError::new(Status::Active, Status::Closed);
assert_eq!(err.from, Status::Active);
assert_eq!(err.to, Status::Closed);
}
#[test]
fn got_expected_display() {
let ge = GotExpected { got: 3, expected: 5 };
assert_eq!(ge.to_string(), "expected 5, got 3");
}
#[test]
fn got_expected_with_strings() {
let ge = GotExpected { got: "foo".to_string(), expected: "bar".to_string() };
assert_eq!(ge.to_string(), "expected bar, got foo");
}
}