Use write_char for writing padding characters

Removes some unsafe *and* saves almost half a kilobyte of code size.
This commit is contained in:
Nick Fitzgerald 2019-02-08 10:02:24 +01:00
parent 05df9ff415
commit 8fea7054b9
2 changed files with 9 additions and 23 deletions

View File

@ -1039,24 +1039,19 @@ pub fn write(output: &mut dyn Write, args: Arguments) -> Result {
/// Padding after the end of something. Returned by `Formatter::padding`. /// Padding after the end of something. Returned by `Formatter::padding`.
#[must_use = "don't forget to write the post padding"] #[must_use = "don't forget to write the post padding"]
struct PostPadding { struct PostPadding {
fill: [u8; 4], fill: char,
fill_len: u32,
padding: usize, padding: usize,
} }
impl PostPadding { impl PostPadding {
/// Safety relies on `fill[..fill_len]` being a valid UTF-8 char. fn new(fill: char, padding: usize) -> PostPadding {
unsafe fn new(fill: [u8; 4], fill_len: u32, padding: usize) -> PostPadding { PostPadding { fill, padding }
PostPadding { fill, fill_len, padding }
} }
/// Write this post padding. /// Write this post padding.
fn write(self, buf: &mut dyn Write) -> Result { 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 { for _ in 0..self.padding {
buf.write_str(fill)?; buf.write_char(self.fill)?;
} }
Ok(()) Ok(())
} }
@ -1326,20 +1321,11 @@ impl<'a> Formatter<'a> {
rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2), rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
}; };
let mut fill = [0; 4]; for _ in 0..pre_pad {
let fill_len = { self.buf.write_char(self.fill)?;
let fill = self.fill.encode_utf8(&mut fill); }
for _ in 0..pre_pad { Ok(PostPadding::new(self.fill, post_pad))
self.buf.write_str(fill)?;
}
fill.len()
};
Ok(unsafe {
PostPadding::new(fill, fill_len as u32, post_pad)
})
} }
/// Takes the formatted parts and applies the padding. /// Takes the formatted parts and applies the padding.

View File

@ -4,7 +4,7 @@ ifeq ($(TARGET),wasm32-unknown-unknown)
all: all:
$(RUSTC) foo.rs -C lto -O --target wasm32-unknown-unknown $(RUSTC) foo.rs -C lto -O --target wasm32-unknown-unknown
wc -c < $(TMPDIR)/foo.wasm wc -c < $(TMPDIR)/foo.wasm
[ "`wc -c < $(TMPDIR)/foo.wasm`" -lt "21000" ] [ "`wc -c < $(TMPDIR)/foo.wasm`" -lt "20500" ]
else else
all: all:
endif endif