diff --git a/src/sink.rs b/src/sink.rs index 959dd8d..239b55a 100644 --- a/src/sink.rs +++ b/src/sink.rs @@ -12,45 +12,42 @@ pub trait StrSink { } } -impl StrSink for W -where - W: fmt::Write, -{ +pub trait FmtSink: StrSink { + fn sink_fmt<'a>(&mut self, args: Arguments<'a>) -> Result<(), ::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(pub W); + +impl StrSink for FmtWriteSink { 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<(), ::Error>; -} - -impl FmtSink for W -where - W: fmt::Write, -{ +impl FmtSink for FmtWriteSink { + #[inline] fn sink_fmt<'a>(&mut self, args: Arguments<'a>) -> Result<(), ::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(pub W); + + impl StrSink for IoWriteSink { + type Error = io::Error; + + #[inline] + fn sink_str(&mut self, s: &str) -> Result<(), Self::Error> { + self.0.write_all(s.as_bytes()) + } + } + + impl FmtSink for IoWriteSink { + #[inline] + fn sink_fmt<'a>(&mut self, args: Arguments<'a>) -> Result<(), ::Error> { + self.0.write_fmt(args) + } + } +}