From 15b028c5859f98b32cde69b81dd62468039db0be Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Wed, 22 Apr 2015 14:18:02 +0200 Subject: [PATCH] Add a write_char method to std::fmt::Formatter. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is the logical next step after #24661, but I’m less sure about this one. --- src/libcore/fmt/mod.rs | 12 ++++++++---- src/test/run-pass/ifmt.rs | 9 +++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index ee1cab4076dc5..34d635ca4ab5d 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -731,6 +731,13 @@ impl<'a> Formatter<'a> { self.buf.write_str(data) } + /// Writes a `char` to the underlying buffer contained within this + /// formatter. + #[stable(feature = "fmt_write_char", since = "1.1.0")] + pub fn write_char(&mut self, c: char) -> Result { + self.buf.write_char(c) + } + /// Writes some formatted information into this instance #[stable(feature = "rust1", since = "1.0.0")] pub fn write_fmt(&mut self, fmt: Arguments) -> Result { @@ -965,10 +972,7 @@ impl Debug for char { #[stable(feature = "rust1", since = "1.0.0")] impl Display for char { fn fmt(&self, f: &mut Formatter) -> Result { - let mut utf8 = [0; 4]; - let amt = self.encode_utf8(&mut utf8).unwrap_or(0); - let s: &str = unsafe { mem::transmute(&utf8[..amt]) }; - Display::fmt(s, f) + f.write_char(*self) } } diff --git a/src/test/run-pass/ifmt.rs b/src/test/run-pass/ifmt.rs index 240b6286c8cfc..abd1a9531130c 100644 --- a/src/test/run-pass/ifmt.rs +++ b/src/test/run-pass/ifmt.rs @@ -21,6 +21,7 @@ use std::usize; struct A; struct B; struct C; +struct D; impl fmt::LowerHex for A { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { @@ -37,6 +38,13 @@ impl fmt::Display for C { f.pad_integral(true, "☃", "123") } } +impl fmt::Binary for D { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(f.write_str("aa")); + try!(f.write_char('☃')); + f.write_str("bb") + } +} macro_rules! t { ($a:expr, $b:expr) => { assert_eq!($a, $b) } @@ -90,6 +98,7 @@ pub fn main() { t!(format!("{foo_bar}", foo_bar=1), "1"); t!(format!("{}", 5 + 5), "10"); t!(format!("{:#4}", C), "☃123"); + t!(format!("{:b}", D), "aa☃bb"); let a: &fmt::Debug = &1; t!(format!("{:?}", a), "1");