Skip to content

Commit a678b9a

Browse files
committed
less uB in i8
1 parent d07c43a commit a678b9a

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

library/alloc/src/string.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2254,14 +2254,18 @@ static DEC_DIGITS_LUT: &[u8; 200] = b"0001020304050607080910111213141516171819\
22542254
impl ToString for i8 {
22552255
#[inline]
22562256
fn to_string(&self) -> String {
2257-
let mut vec: Vec<u8> = if *self < 0 {
2257+
let mut n = *self;
2258+
let mut vec: Vec<u8> = if n < 0 {
2259+
// convert the negative num to positive by summing 1 to it's 2 complement
2260+
// ( -128u8.abs() would panic )
2261+
n = (!n).wrapping_add(1);
22582262
let mut v = Vec::with_capacity(4);
22592263
v.push(b'-');
22602264
v
22612265
} else {
22622266
Vec::with_capacity(3)
22632267
};
2264-
let mut n = self.abs();
2268+
let mut n = n as u8;
22652269
if n >= 10 {
22662270
if n >= 100 {
22672271
n -= 100;

0 commit comments

Comments
 (0)