dispair/
lib.rs

1//! # [`Dispair`]
2//! Dispair (Disp-Err) is a zero-dependency (other than `std`) library that provides a simple wrapper struct that implements `Error` for any type that implements both `Debug` and `Display`.
3//! ```rust
4//!use dispair::Dispair;
5//!use std::error::Error;
6//!
7//!#[derive(Debug)]
8//!struct TestStruct;
9//!
10//!impl core::fmt::Display for TestStruct {
11//!    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12//!        core::fmt::Debug::fmt(&self, f)
13//!    }
14//!}
15//!
16//!fn main() {
17//!    
18//!    // Wrap `TestStruct` (which doesn't implement `Error`) in `Dispair` and return it.
19//!    let err = Dispair(TestStruct);
20//!    
21//!    // Display just passes through to the wrapped value
22//!    assert_eq!(format!("{}", err), "TestStruct");
23//!    
24//!    // Debug, however, does show `Dispair`.
25//!    assert_eq!(format!("{:?}", err), "Dispair(TestStruct)");
26//!
27//!    // We should be able to convert it into a `Box<dyn Error>`
28//!    let err_boxed: Box<dyn Error> = Box::new(err);
29//!
30//!    // And this should print nicely
31//!    assert_eq!(err_boxed.to_string(), "TestStruct");
32//!}
33//!```
34#![warn(clippy::pedantic)]
35#![allow(clippy::module_name_repetitions)]
36
37use std::{fmt::{Display, Debug}, error::Error};
38
39/// # [`Dispair`]
40/// Wraps a given type that implements [`Display`] and [`Debug`] and implements [`Error`].
41#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub struct Dispair<E: Display + Debug>(pub E);
43
44impl<E: Display + Debug> Display for Dispair<E> {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        Display::fmt(&self.0, f)
47    }
48}
49
50impl<E: Display + Debug> Error for Dispair<E> {}
51