use core::error::Error;
use core::fmt;
use super::{Format, Formatted, OneLine};
pub type MainResult<E, F = OneLine> = core::result::Result<(), DisplaySwapDebug<Formatted<E, F>>>;
#[derive(Copy, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DisplaySwapDebug<T>(T);
impl<T> From<T> for DisplaySwapDebug<T> {
fn from(value: T) -> Self {
DisplaySwapDebug(value)
}
}
impl<T> DisplaySwapDebug<T> {
pub fn new(value: T) -> Self {
DisplaySwapDebug(value)
}
}
impl<D: fmt::Debug> fmt::Display for DisplaySwapDebug<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl<D: fmt::Display> fmt::Debug for DisplaySwapDebug<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl<E: Error, F: Format> From<E> for DisplaySwapDebug<Formatted<E, F>> {
fn from(value: E) -> Self {
DisplaySwapDebug::new(Formatted::new(value))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::Error;
struct Foo;
impl fmt::Debug for Foo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Debug")
}
}
impl fmt::Display for Foo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Display")
}
}
fn test_return() -> MainResult<Error> {
Err(Error::One)?;
Ok(())
}
#[test]
fn test_swap() {
let result = DisplaySwapDebug::new(Foo);
assert_eq!(format!("{result:?}"), "Display");
assert_eq!(result.to_string(), "Debug");
}
#[test]
fn test_swap_with_formatted() {
let inner = Formatted::<_, OneLine>::new(Error::Two(crate::tests::ErrorInner::One));
let wrapped = DisplaySwapDebug::new(inner);
assert_eq!(format!("{wrapped:?}"), "Two: One");
assert_eq!(wrapped.to_string(), "Two(One)");
}
#[test]
fn test_main_result() {
assert_eq!(
DisplaySwapDebug::new(test_return().unwrap_err()).to_string(),
"One"
);
assert_eq!(
DisplaySwapDebug::new(&DisplaySwapDebug::new(Formatted::<_, OneLine>::new(
Error::One
)))
.to_string(),
"One"
);
}
}