use std::{
convert::Infallible,
fmt::{self},
marker::PhantomData,
};
use crate::fmt::encoding::{Encoder, LossyUtf8Encoder};
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum WriteError<E> {
Fmt(fmt::Error),
Encoding(E),
}
impl<E> From<fmt::Error> for WriteError<E> {
fn from(value: fmt::Error) -> Self {
Self::Fmt(value)
}
}
impl<E> fmt::Display for WriteError<E>
where
E: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
WriteError::Fmt(error) => error.fmt(f),
WriteError::Encoding(error) => error.fmt(f),
}
}
}
impl<E> std::error::Error for WriteError<E> where E: std::error::Error {}
pub type WriteResult<E> = std::result::Result<(), WriteError<E>>;
pub trait WriteEncoded {
fn fmt_to<E>(&self, writer: &mut impl fmt::Write) -> WriteResult<E::Err>
where
E: Encoder,
for<'a> E::Str<'a>: fmt::Display;
}
pub struct Displayed<'a, T: ?Sized, E = LossyUtf8Encoder> {
inner: &'a T,
_encoder: PhantomData<E>,
}
impl<T, E> fmt::Display for Displayed<'_, T, E>
where
T: WriteEncoded,
E: Encoder,
for<'a> E::Str<'a>: fmt::Display,
E::Err: Into<Infallible>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.inner.fmt_to::<E>(f) {
Ok(()) => Ok(()),
Err(WriteError::Fmt(e)) => Err(e),
#[allow(unreachable_code)]
Err(WriteError::Encoding(e)) => match e.into() {},
}
}
}
pub trait FormatToExt: WriteEncoded {
fn display(&self) -> Displayed<'_, Self> {
Displayed {
inner: self,
_encoder: PhantomData,
}
}
fn display_as<E: Encoder>(&self) -> Displayed<'_, Self, E>
where
E::Err: Into<Infallible>,
{
Displayed {
inner: self,
_encoder: PhantomData,
}
}
}
impl<T: WriteEncoded + ?Sized> FormatToExt for T {}