use core::error::Error;
use core::fmt;
use crate::Allocator;
use super::Location;
#[cfg(feature = "alloc")]
use rust_alloc::string::{String, ToString};
#[diagnostic::on_unimplemented(
message = "`ContextError` must be implemented for `{Self}`, or any error type captured by custom contexts",
note = "use `musli::context::ErrorMarker` to ignore errors",
note = "use `std::io::Error` and `std::string::String`, if the `std` or `alloc` features are enabled for `musli`"
)]
pub trait ContextError<A> {
fn custom<T>(alloc: A, error: T) -> Self
where
T: 'static + Send + Sync + Error;
fn message<T>(alloc: A, message: T) -> Self
where
T: fmt::Display;
#[inline]
fn traced_message<T>(alloc: A, message: T, location: &Location<'_, A>) -> Self
where
Self: Sized,
A: Allocator,
T: fmt::Display,
{
Self::message(alloc, location.with_message(message))
}
#[inline]
fn traced_custom<T>(alloc: A, error: T, location: &Location<'_, A>) -> Self
where
Self: Sized,
A: Allocator,
T: 'static + Send + Sync + Error,
{
Self::message(alloc, location.with_message(error))
}
}
#[cfg(feature = "std")]
impl<A> ContextError<A> for std::io::Error {
#[inline]
fn custom<T>(_: A, message: T) -> Self
where
T: 'static + Send + Sync + Error,
{
std::io::Error::other(message)
}
#[inline]
fn message<T>(_: A, message: T) -> Self
where
T: fmt::Display,
{
std::io::Error::other(std::format!("{message}"))
}
#[inline]
fn traced_custom<T>(_: A, error: T, location: &Location<'_, A>) -> Self
where
A: Allocator,
T: 'static + Send + Sync + Error,
{
std::io::Error::other(TracedIoError {
message: std::format!("{}", location.with_message(&error)),
source: error,
})
}
}
#[cfg(feature = "std")]
struct TracedIoError<T> {
message: String,
source: T,
}
#[cfg(feature = "std")]
impl<T> fmt::Display for TracedIoError<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.message.fmt(f)
}
}
#[cfg(feature = "std")]
impl<T> fmt::Debug for TracedIoError<T>
where
T: fmt::Debug,
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TracedIoError")
.field("message", &self.message)
.field("source", &self.source)
.finish()
}
}
#[cfg(feature = "std")]
impl<T> Error for TracedIoError<T>
where
T: 'static + Error,
{
#[inline]
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.source)
}
}
#[cfg(feature = "alloc")]
impl<A> ContextError<A> for String {
#[inline]
fn custom<T>(_: A, message: T) -> Self
where
T: fmt::Display,
{
message.to_string()
}
#[inline]
fn message<T>(_: A, message: T) -> Self
where
T: fmt::Display,
{
message.to_string()
}
}