diff options
author | Valentin Popov <valentin@popov.link> | 2024-01-08 00:21:28 +0300 |
---|---|---|
committer | Valentin Popov <valentin@popov.link> | 2024-01-08 00:21:28 +0300 |
commit | 1b6a04ca5504955c571d1c97504fb45ea0befee4 (patch) | |
tree | 7579f518b23313e8a9748a88ab6173d5e030b227 /vendor/anstream/src/fmt.rs | |
parent | 5ecd8cf2cba827454317368b68571df0d13d7842 (diff) | |
download | fparkan-1b6a04ca5504955c571d1c97504fb45ea0befee4.tar.xz fparkan-1b6a04ca5504955c571d1c97504fb45ea0befee4.zip |
Initial vendor packages
Signed-off-by: Valentin Popov <valentin@popov.link>
Diffstat (limited to 'vendor/anstream/src/fmt.rs')
-rw-r--r-- | vendor/anstream/src/fmt.rs | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/vendor/anstream/src/fmt.rs b/vendor/anstream/src/fmt.rs new file mode 100644 index 0000000..e673c26 --- /dev/null +++ b/vendor/anstream/src/fmt.rs @@ -0,0 +1,54 @@ +/// A shim which allows a [`std::io::Write`] to be implemented in terms of a [`std::fmt::Write`] +/// +/// This saves off I/O errors. instead of discarding them +pub(crate) struct Adapter<W> +where + W: FnMut(&[u8]) -> std::io::Result<()>, +{ + writer: W, + error: std::io::Result<()>, +} + +impl<W> Adapter<W> +where + W: FnMut(&[u8]) -> std::io::Result<()>, +{ + pub(crate) fn new(writer: W) -> Self { + Adapter { + writer, + error: Ok(()), + } + } + + pub(crate) fn write_fmt(mut self, fmt: std::fmt::Arguments<'_>) -> std::io::Result<()> { + match std::fmt::write(&mut self, fmt) { + Ok(()) => Ok(()), + Err(..) => { + // check if the error came from the underlying `Write` or not + if self.error.is_err() { + self.error + } else { + Err(std::io::Error::new( + std::io::ErrorKind::Other, + "formatter error", + )) + } + } + } + } +} + +impl<W> std::fmt::Write for Adapter<W> +where + W: FnMut(&[u8]) -> std::io::Result<()>, +{ + fn write_str(&mut self, s: &str) -> std::fmt::Result { + match (self.writer)(s.as_bytes()) { + Ok(()) => Ok(()), + Err(e) => { + self.error = Err(e); + Err(std::fmt::Error) + } + } + } +} |