about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorAlex Crichton <alex@alexcrichton.com>2014-05-10 13:52:26 -0700
committerAlex Crichton <alex@alexcrichton.com>2014-05-15 23:22:06 -0700
commit00f9263914da3d18c556d7ebc3941f9638721ac2 (patch)
tree80977a9f7f258f26d5b612646670c374fd7457d2 /src/libstd
parent3c06a0328a3c6824ff7578a6da46e133e9399854 (diff)
downloadrust-00f9263914da3d18c556d7ebc3941f9638721ac2.tar.gz
rust-00f9263914da3d18c556d7ebc3941f9638721ac2.zip
std: Add an adaptor for Writer => FormatWriter
This new method, write_fmt(), is the one way to write a formatted list of
arguments into a Writer stream. This has a special adaptor to preserve errors
which occur on the writer.

All macros will be updated to use this method explicitly.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/io/mod.rs36
1 files changed, 36 insertions, 0 deletions
diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs
index 5c9d5feab10..497213df30f 100644
--- a/src/libstd/io/mod.rs
+++ b/src/libstd/io/mod.rs
@@ -964,6 +964,42 @@ pub trait Writer {
     /// decide whether their stream needs to be buffered or not.
     fn flush(&mut self) -> IoResult<()> { Ok(()) }
 
+    /// Writes a formatted string into this writer, returning any error
+    /// encountered.
+    ///
+    /// This method is primarily used to interface with the `format_args!`
+    /// macro, but it is rare that this should explicitly be called. The
+    /// `write!` macro should be favored to invoke this method instead.
+    ///
+    /// # Errors
+    ///
+    /// This function will return any I/O error reported while formatting.
+    fn write_fmt(&mut self, fmt: &fmt::Arguments) -> IoResult<()> {
+        // Create a shim which translates a Writer to a FormatWriter and saves
+        // off I/O errors. instead of discarding them
+        struct Adaptor<'a, T> {
+            inner: &'a mut T,
+            error: IoResult<()>,
+        }
+        impl<'a, T: Writer> fmt::FormatWriter for Adaptor<'a, T> {
+            fn write(&mut self, bytes: &[u8]) -> fmt::Result {
+                match self.inner.write(bytes) {
+                    Ok(()) => Ok(()),
+                    Err(e) => {
+                        self.error = Err(e);
+                        Err(fmt::WriteError)
+                    }
+                }
+            }
+        }
+
+        let mut output = Adaptor { inner: self, error: Ok(()) };
+        match fmt::write(&mut output, fmt) {
+            Ok(()) => Ok(()),
+            Err(..) => output.error
+        }
+    }
+
     /// Write a rust string into this sink.
     ///
     /// The bytes written will be the UTF-8 encoded version of the input string.