Skip to content

Commit 265a7cc

Browse files
committed
Add a write_char method to std::fmt::Write
as accepted in [RFC 526](https://github.com/rust-lang/rfcs/blob/master/text/0526-fmt-text-writer.md).
1 parent 3860240 commit 265a7cc

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
@@ -1084,4 +1084,10 @@ impl fmt::Write for String {
10841084
self.push_str(s);
10851085
Ok(())
10861086
}
1087+
1088+
#[inline]
1089+
fn write_char(&mut self, c: char) -> fmt::Result {
1090+
self.push(c);
1091+
Ok(())
1092+
}
10871093
}

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 = "rust1", since = "1.0.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)