Skip to content

Commit c7017b3

Browse files
committed
rollup merge of #24661: SimonSapin/fmt-write-char
as accepted in [RFC 526](https://github.com/rust-lang/rfcs/blob/master/text/0526-fmt-text-writer.md). Note that this brand new method is marked as **stable**. I judged this safe enough: it’s simple enough that it’s very unlikely to change. Still, I can mark it unstable instead if you prefer. r? @alexcrichton
2 parents 251f8d3 + 16181e6 commit c7017b3

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/libcollections/string.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1082,4 +1082,10 @@ impl fmt::Write for String {
10821082
self.push_str(s);
10831083
Ok(())
10841084
}
1085+
1086+
#[inline]
1087+
fn write_char(&mut self, c: char) -> fmt::Result {
1088+
self.push(c);
1089+
Ok(())
1090+
}
10851091
}

src/libcore/fmt/mod.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,23 @@ pub trait Write {
8383
#[stable(feature = "rust1", since = "1.0.0")]
8484
fn write_str(&mut self, s: &str) -> Result;
8585

86+
/// Writes a `char` into this writer, returning whether the write succeeded.
87+
///
88+
/// A single `char` may be encoded as more than one byte.
89+
/// This method can only succeed if the entire byte sequence was successfully
90+
/// written, and this method will not return until all data has been
91+
/// written or an error occurs.
92+
///
93+
/// # Errors
94+
///
95+
/// This function will return an instance of `FormatError` on error.
96+
#[stable(feature = "fmt_write_char", since = "1.1.0")]
97+
fn write_char(&mut self, c: char) -> Result {
98+
let mut utf_8 = [0u8; 4];
99+
let bytes_written = c.encode_utf8(&mut utf_8).unwrap_or(0);
100+
self.write_str(unsafe { mem::transmute(&utf_8[..bytes_written]) })
101+
}
102+
86103
/// Glue for usage of the `write!` macro with implementers of this trait.
87104
///
88105
/// This method should generally not be invoked manually, but rather through

0 commit comments

Comments
 (0)