ts-error-stack 0.1.0

Simple error stacks for better reporting
Documentation
//! Simple error stacks for better reporting. Adapted from the unstable std `::std::error::Report`

#![no_std]

extern crate alloc;

use core::{error::Error, fmt};

use alloc::boxed::Box;

/// An error report that prints an error and its sources.
pub struct Report<E = Box<dyn Error>>(E);

impl<E> Report<E>
where
    Self: From<E>,
{
    /// Creates a new `Report` from an input error.
    pub fn new(error: E) -> Self {
        Self::from(error)
    }
}

impl<E> From<E> for Report<E>
where
    E: Error,
{
    fn from(error: E) -> Self {
        Self(error)
    }
}

// Debug links to display for when the report is returned from `main()`
impl<E> fmt::Debug for Report<E>
where
    Self: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl<E> fmt::Display for Report<E>
where
    E: Error,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut error: &dyn Error = &self.0;

        write!(f, "{error}")?;

        if error.source().is_some() {
            write!(f, "\n\nCaused by:")?;

            let mut index = 0;
            while let Some(cause) = error.source() {
                write!(f, "\n{index: >4}: {cause}")?;
                error = cause;
                index += 1;
            }
        }

        Ok(())
    }
}