From 8fea7054b9c77a7dcf242ce84cfc0a58d81a9c00 Mon Sep 17 00:00:00 2001 From: Nick Fitzgerald Date: Fri, 8 Feb 2019 10:02:24 +0100 Subject: [PATCH] Use write_char for writing padding characters Removes some unsafe *and* saves almost half a kilobyte of code size. --- src/libcore/fmt/mod.rs | 30 +++++-------------- .../wasm-stringify-ints-small/Makefile | 2 +- 2 files changed, 9 insertions(+), 23 deletions(-) diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index 605779046ef51..4c0eb1eeb5530 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -1039,24 +1039,19 @@ pub fn write(output: &mut dyn Write, args: Arguments) -> Result { /// Padding after the end of something. Returned by `Formatter::padding`. #[must_use = "don't forget to write the post padding"] struct PostPadding { - fill: [u8; 4], - fill_len: u32, + fill: char, padding: usize, } impl PostPadding { - /// Safety relies on `fill[..fill_len]` being a valid UTF-8 char. - unsafe fn new(fill: [u8; 4], fill_len: u32, padding: usize) -> PostPadding { - PostPadding { fill, fill_len, padding } + fn new(fill: char, padding: usize) -> PostPadding { + PostPadding { fill, padding } } /// Write this post padding. fn write(self, buf: &mut dyn Write) -> Result { - let fill = unsafe { - str::from_utf8_unchecked(&self.fill.get_unchecked(..self.fill_len as usize)) - }; for _ in 0..self.padding { - buf.write_str(fill)?; + buf.write_char(self.fill)?; } Ok(()) } @@ -1326,20 +1321,11 @@ impl<'a> Formatter<'a> { rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2), }; - let mut fill = [0; 4]; - let fill_len = { - let fill = self.fill.encode_utf8(&mut fill); - - for _ in 0..pre_pad { - self.buf.write_str(fill)?; - } - - fill.len() - }; + for _ in 0..pre_pad { + self.buf.write_char(self.fill)?; + } - Ok(unsafe { - PostPadding::new(fill, fill_len as u32, post_pad) - }) + Ok(PostPadding::new(self.fill, post_pad)) } /// Takes the formatted parts and applies the padding. diff --git a/src/test/run-make/wasm-stringify-ints-small/Makefile b/src/test/run-make/wasm-stringify-ints-small/Makefile index 18e47242f806b..26de6a0c68990 100644 --- a/src/test/run-make/wasm-stringify-ints-small/Makefile +++ b/src/test/run-make/wasm-stringify-ints-small/Makefile @@ -4,7 +4,7 @@ ifeq ($(TARGET),wasm32-unknown-unknown) all: $(RUSTC) foo.rs -C lto -O --target wasm32-unknown-unknown wc -c < $(TMPDIR)/foo.wasm - [ "`wc -c < $(TMPDIR)/foo.wasm`" -lt "21000" ] + [ "`wc -c < $(TMPDIR)/foo.wasm`" -lt "20500" ] else all: endif