1
Fork 0

std: Enforce Unicode in fmt::Writer

This commit is an implementation of [RFC 526][rfc] which is a change to alter
the definition of the old `fmt::FormatWriter`. The new trait, renamed to
`Writer`, now only exposes one method `write_str` in order to guarantee that all
implementations of the formatting traits can only produce valid Unicode.

[rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0526-fmt-text-writer.md

One of the primary improvements of this patch is the performance of the
`.to_string()` method by avoiding an almost-always redundant UTF-8 check. This
is a breaking change due to the renaming of the trait as well as the loss of the
`write` method, but migration paths should be relatively easy:

* All usage of `write` should move to `write_str`. If truly binary data was
  being written in an implementation of `Show`, then it will need to use a
  different trait or an altogether different code path.

* All usage of `write!` should continue to work as-is with no modifications.

* All usage of `Show` where implementations just delegate to another should
  continue to work as-is.

[breaking-change]

Closes #20352
This commit is contained in:
Alex Crichton 2014-12-12 10:59:41 -08:00
parent cd614164e6
commit e423fcf0e0
25 changed files with 320 additions and 359 deletions

View file

@ -29,7 +29,7 @@ impl<'a> fmt::Show for Escape<'a> {
for (i, ch) in s.bytes().enumerate() {
match ch as char {
'<' | '>' | '&' | '\'' | '"' => {
try!(fmt.write(pile_o_bits.slice(last, i).as_bytes()));
try!(fmt.write_str(pile_o_bits.slice(last, i)));
let s = match ch as char {
'>' => "&gt;",
'<' => "&lt;",
@ -38,7 +38,7 @@ impl<'a> fmt::Show for Escape<'a> {
'"' => "&quot;",
_ => unreachable!()
};
try!(fmt.write(s.as_bytes()));
try!(fmt.write_str(s));
last = i + 1;
}
_ => {}
@ -46,7 +46,7 @@ impl<'a> fmt::Show for Escape<'a> {
}
if last < s.len() {
try!(fmt.write(pile_o_bits.slice_from(last).as_bytes()));
try!(fmt.write_str(pile_o_bits.slice_from(last)));
}
Ok(())
}