use core::fmt::{self, Arguments, Debug};
use crate::{IntoTryWriteFn, WriteBytes, WriteStr};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FmtTryWriter<F1>(F1);
pub trait IntoFmtWriteResult {
fn into_fmt_write_result(self) -> fmt::Result;
}
impl<F1> FmtTryWriter<F1>
where
F1: WriteStr,
{
pub fn new(write: F1) -> Self {
Self(write)
}
pub fn from_closure<F, Ts>(closure: F) -> Self
where
F: IntoTryWriteFn<Ts, TryWriteFn = F1>,
{
Self(closure.into_try_write_fn())
}
}
impl<F1> FmtTryWriter<F1>
where
Self: fmt::Write,
{
pub fn write_fmt(&mut self, args: Arguments<'_>) -> fmt::Result {
fmt::Write::write_fmt(self, args)
}
}
impl<F1> fmt::Write for FmtTryWriter<F1>
where
Self: WriteStr<Output = fmt::Result>,
{
fn write_str(&mut self, buf: &str) -> fmt::Result {
WriteStr::write_str(self, buf)
}
}
impl<F1> WriteStr for FmtTryWriter<F1>
where
F1: WriteStr,
F1::Output: IntoFmtWriteResult,
{
type Output = fmt::Result;
fn write_str(&mut self, buf: &str) -> Self::Output {
self.0.write_str(buf).into_fmt_write_result()
}
}
impl<F1> WriteBytes for FmtTryWriter<F1>
where
F1: WriteBytes,
F1::Output: IntoFmtWriteResult,
{
type Output = fmt::Result;
fn write_bytes(&mut self, buf: &[u8]) -> Self::Output {
self.0.write_bytes(buf).into_fmt_write_result()
}
}
impl IntoFmtWriteResult for () {
fn into_fmt_write_result(self) -> fmt::Result {
Ok(())
}
}
impl<E: Debug> IntoFmtWriteResult for Result<(), E> {
fn into_fmt_write_result(self) -> fmt::Result {
self.map_err(|_| fmt::Error)
}
}