use alloc::{fmt, fmt::Debug};
use core::panic::Location;
use std::fmt::Display;
use crate::{error::StackedError, Error, ErrorKind};
pub struct DisplayStr<'a>(pub &'a str);
impl<'a> Debug for DisplayStr<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("{}", self.0))
}
}
pub struct DisplayShortLocation<'a>(pub &'a Location<'a>);
impl<'a> Debug for DisplayShortLocation<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s = self.0.file();
#[cfg(not(windows))]
{
let find = "/.cargo/registry/src/";
if let Some(i) = s.find(find) {
s = &s[(i + find.len())..];
if let Some(i) = s.find('/') {
s = &s[(i + 1)..];
}
}
}
#[cfg(windows)]
{
let find = "\\.cargo\\registry\\src\\";
if let Some(i) = s.find(find) {
s = &s[(i + find.len())..];
if let Some(i) = s.find('\\') {
s = &s[(i + 1)..];
}
}
}
f.write_fmt(format_args!(
"Location {{ file: \"{}\", line: {}, col: {} }}",
s,
self.0.line(),
self.0.column()
))
}
}
impl Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("Error {{ stack: [\n"))?;
for (error, location) in self.stack.iter().rev() {
if let Some(location) = location {
let location = DisplayShortLocation(location);
f.write_fmt(format_args!("{location:?},\n"))?;
}
match error {
ErrorKind::UnitError => (),
ErrorKind::StrError(s) => {
f.write_fmt(format_args!("{s}\n"))?;
}
ErrorKind::StringError(s) => {
f.write_fmt(format_args!("{s}\n"))?;
}
_ => {
f.write_fmt(format_args!("{error:?},\n"))?;
}
}
}
f.write_fmt(format_args!("] }}"))
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("{:?}", self))
}
}
impl Display for StackedError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("{:?}", self))
}
}