diff options
| author | Giles Cope <gilescope@gmail.com> | 2021-03-04 22:11:04 +0000 |
|---|---|---|
| committer | Giles Cope <gilescope@gmail.com> | 2021-03-04 22:11:04 +0000 |
| commit | a678b9a2ae6fdca2bfa7aed8f73723a7cf238d16 (patch) | |
| tree | 69ff9f98b354d06c90b8e31bd0dc3c6fa38701f0 /library/alloc/src/string.rs | |
| parent | d07c43af3129c8e160bb62d98ebcb8b9cf6f3ccd (diff) | |
| download | rust-a678b9a2ae6fdca2bfa7aed8f73723a7cf238d16.tar.gz rust-a678b9a2ae6fdca2bfa7aed8f73723a7cf238d16.zip | |
less uB in i8
Diffstat (limited to 'library/alloc/src/string.rs')
| -rw-r--r-- | library/alloc/src/string.rs | 8 |
1 files changed, 6 insertions, 2 deletions
diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 714c24a7665..e80f14eaca8 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -2254,14 +2254,18 @@ static DEC_DIGITS_LUT: &[u8; 200] = b"0001020304050607080910111213141516171819\ impl ToString for i8 { #[inline] fn to_string(&self) -> String { - let mut vec: Vec<u8> = if *self < 0 { + let mut n = *self; + let mut vec: Vec<u8> = if n < 0 { + // convert the negative num to positive by summing 1 to it's 2 complement + // ( -128u8.abs() would panic ) + n = (!n).wrapping_add(1); let mut v = Vec::with_capacity(4); v.push(b'-'); v } else { Vec::with_capacity(3) }; - let mut n = self.abs(); + let mut n = n as u8; if n >= 10 { if n >= 100 { n -= 100; |
