Skip to content

Commit 2bb5b5c

Browse files
committed
core: Remove an implicit panic from Formatter::pad
The expression `&s[..i]` in general can panic if `i` is out of bounds or not on a character boundary for a string, and this caused the codegen for `Formatter::pad` to be a bit larger than it otherwise needed to be. This commit replaces this with `s.get(..i).unwrap_or(&s)` which while having different behavior if `i` is out of bounds has a much smaller code footprint and otherwise avoids the need for `unsafe` code.
1 parent 66c5e3f commit 2bb5b5c

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

src/libcore/fmt/mod.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -1212,7 +1212,11 @@ impl<'a> Formatter<'a> {
12121212
// truncation. However other flags like `fill`, `width` and `align`
12131213
// must act as always.
12141214
if let Some((i, _)) = s.char_indices().skip(max).next() {
1215-
&s[..i]
1215+
// LLVM here can't prove that `..i` won't panic `&s[..i]`, but
1216+
// we know that it can't panic. Use `get` + `unwrap_or` to avoid
1217+
// `unsafe` and otherwise don't emit any panic-related code
1218+
// here.
1219+
s.get(..i).unwrap_or(&s)
12161220
} else {
12171221
&s
12181222
}

0 commit comments

Comments
 (0)