Skip to content

Commit b3c46d0

Browse files
committed
Add a write_char method to std::fmt::Formatter.
This is the logical next step after #24661, but I’m less sure about this one.
1 parent e9e9279 commit b3c46d0

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

src/libcore/fmt/mod.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -617,6 +617,13 @@ impl<'a> Formatter<'a> {
617617
self.buf.write_str(data)
618618
}
619619

620+
/// Writes a `char` to the underlying buffer contained within this
621+
/// formatter.
622+
#[stable(feature = "fmt_write_char", since = "1.1.0")]
623+
pub fn write_char(&mut self, c: char) -> Result {
624+
self.buf.write_char(c)
625+
}
626+
620627
/// Writes some formatted information into this instance
621628
#[stable(feature = "rust1", since = "1.0.0")]
622629
pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
@@ -856,10 +863,7 @@ impl Debug for char {
856863
#[stable(feature = "rust1", since = "1.0.0")]
857864
impl Display for char {
858865
fn fmt(&self, f: &mut Formatter) -> Result {
859-
let mut utf8 = [0; 4];
860-
let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
861-
let s: &str = unsafe { mem::transmute(&utf8[..amt]) };
862-
Display::fmt(s, f)
866+
f.write_char(*self)
863867
}
864868
}
865869

src/test/run-pass/ifmt.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use std::usize;
2121
struct A;
2222
struct B;
2323
struct C;
24+
struct D;
2425

2526
impl fmt::LowerHex for A {
2627
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@@ -37,6 +38,13 @@ impl fmt::Display for C {
3738
f.pad_integral(true, "☃", "123")
3839
}
3940
}
41+
impl fmt::Binary for D {
42+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43+
try!(f.write_str("aa"));
44+
try!(f.write_char('☃'));
45+
f.write_str("bb")
46+
}
47+
}
4048

4149
macro_rules! t {
4250
($a:expr, $b:expr) => { assert_eq!($a, $b) }
@@ -90,6 +98,7 @@ pub fn main() {
9098
t!(format!("{foo_bar}", foo_bar=1), "1");
9199
t!(format!("{}", 5 + 5), "10");
92100
t!(format!("{:#4}", C), "☃123");
101+
t!(format!("{:b}", D), "aa☃bb");
93102

94103
let a: &fmt::Debug = &1;
95104
t!(format!("{:?}", a), "1");

0 commit comments

Comments
 (0)