dedicated sink newtypes for fmt::Write and io::Write

main
pantonshire 2 years ago
parent 3dcb61021f
commit 706e8ca22a

@ -12,45 +12,42 @@ pub trait StrSink {
}
}
impl<W> StrSink for W
where
W: fmt::Write,
{
pub trait FmtSink: StrSink {
fn sink_fmt<'a>(&mut self, args: Arguments<'a>) -> Result<(), <Self as StrSink>::Error>;
}
#[macro_export]
macro_rules! sink_fmt {
($dst:expr, $($arg:tt)*) => {
FmtSink::sink_fmt($dst, core::format_args!($($arg)*))
};
}
pub use sink_fmt;
pub struct FmtWriteSink<W: fmt::Write>(pub W);
impl<W: fmt::Write> StrSink for FmtWriteSink<W> {
type Error = fmt::Error;
#[inline]
fn sink_str(&mut self, s: &str) -> Result<(), Self::Error> {
self.write_str(s)
self.0.write_str(s)
}
#[inline]
fn sink_char(&mut self, c: char) -> Result<(), Self::Error> {
self.write_char(c)
self.0.write_char(c)
}
}
pub trait FmtSink: StrSink {
fn sink_fmt<'a>(&mut self, args: Arguments<'a>) -> Result<(), <Self as StrSink>::Error>;
}
impl<W> FmtSink for W
where
W: fmt::Write,
{
impl<W: fmt::Write> FmtSink for FmtWriteSink<W> {
#[inline]
fn sink_fmt<'a>(&mut self, args: Arguments<'a>) -> Result<(), <Self as StrSink>::Error> {
self.write_fmt(args)
self.0.write_fmt(args)
}
}
#[macro_export]
macro_rules! sink_fmt {
($dst:expr, $($arg:tt)*) => {
FmtSink::sink_fmt($dst, core::format_args!($($arg)*))
};
}
pub use sink_fmt;
#[cfg(feature = "alloc")]
pub use string_sink::SinkString;
@ -138,3 +135,33 @@ mod string_sink {
}
}
}
#[cfg(feature = "std")]
pub use io_sink::IoWriteSink;
#[cfg(feature = "std")]
mod io_sink {
use core::fmt::Arguments;
use std::io;
use super::{StrSink, FmtSink};
#[repr(transparent)]
pub struct IoWriteSink<W: io::Write>(pub W);
impl<W: io::Write> StrSink for IoWriteSink<W> {
type Error = io::Error;
#[inline]
fn sink_str(&mut self, s: &str) -> Result<(), Self::Error> {
self.0.write_all(s.as_bytes())
}
}
impl<W: io::Write> FmtSink for IoWriteSink<W> {
#[inline]
fn sink_fmt<'a>(&mut self, args: Arguments<'a>) -> Result<(), <Self as StrSink>::Error> {
self.0.write_fmt(args)
}
}
}

Loading…
Cancel
Save