Skip to content

Commit 8fea705

Browse files
committed
Use write_char for writing padding characters
Removes some unsafe *and* saves almost half a kilobyte of code size.
1 parent 05df9ff commit 8fea705

File tree

2 files changed

+9
-23
lines changed

2 files changed

+9
-23
lines changed

src/libcore/fmt/mod.rs

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1039,24 +1039,19 @@ pub fn write(output: &mut dyn Write, args: Arguments) -> Result {
10391039
/// Padding after the end of something. Returned by `Formatter::padding`.
10401040
#[must_use = "don't forget to write the post padding"]
10411041
struct PostPadding {
1042-
fill: [u8; 4],
1043-
fill_len: u32,
1042+
fill: char,
10441043
padding: usize,
10451044
}
10461045

10471046
impl PostPadding {
1048-
/// Safety relies on `fill[..fill_len]` being a valid UTF-8 char.
1049-
unsafe fn new(fill: [u8; 4], fill_len: u32, padding: usize) -> PostPadding {
1050-
PostPadding { fill, fill_len, padding }
1047+
fn new(fill: char, padding: usize) -> PostPadding {
1048+
PostPadding { fill, padding }
10511049
}
10521050

10531051
/// Write this post padding.
10541052
fn write(self, buf: &mut dyn Write) -> Result {
1055-
let fill = unsafe {
1056-
str::from_utf8_unchecked(&self.fill.get_unchecked(..self.fill_len as usize))
1057-
};
10581053
for _ in 0..self.padding {
1059-
buf.write_str(fill)?;
1054+
buf.write_char(self.fill)?;
10601055
}
10611056
Ok(())
10621057
}
@@ -1326,20 +1321,11 @@ impl<'a> Formatter<'a> {
13261321
rt::v1::Alignment::Center => (padding / 2, (padding + 1) / 2),
13271322
};
13281323

1329-
let mut fill = [0; 4];
1330-
let fill_len = {
1331-
let fill = self.fill.encode_utf8(&mut fill);
1332-
1333-
for _ in 0..pre_pad {
1334-
self.buf.write_str(fill)?;
1335-
}
1336-
1337-
fill.len()
1338-
};
1324+
for _ in 0..pre_pad {
1325+
self.buf.write_char(self.fill)?;
1326+
}
13391327

1340-
Ok(unsafe {
1341-
PostPadding::new(fill, fill_len as u32, post_pad)
1342-
})
1328+
Ok(PostPadding::new(self.fill, post_pad))
13431329
}
13441330

13451331
/// Takes the formatted parts and applies the padding.

src/test/run-make/wasm-stringify-ints-small/Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ ifeq ($(TARGET),wasm32-unknown-unknown)
44
all:
55
$(RUSTC) foo.rs -C lto -O --target wasm32-unknown-unknown
66
wc -c < $(TMPDIR)/foo.wasm
7-
[ "`wc -c < $(TMPDIR)/foo.wasm`" -lt "21000" ]
7+
[ "`wc -c < $(TMPDIR)/foo.wasm`" -lt "20500" ]
88
else
99
all:
1010
endif

0 commit comments

Comments
 (0)