use core::error::Error;
use core::fmt;
#[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;
}
#[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}"))
}
}
#[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()
}
}