diff options
| author | Giles Cope <gilescope@gmail.com> | 2021-03-08 22:35:37 +0000 |
|---|---|---|
| committer | Giles Cope <gilescope@gmail.com> | 2021-03-08 22:35:37 +0000 |
| commit | 05330aaf42c794d441a91dc261e3202f965e0ce2 (patch) | |
| tree | 69e23bb902fecd5565d0556bcaac0d94d6525c42 /library/alloc/src/string.rs | |
| parent | 6a58b6af3231505344d450fba99a50c1d5c5ec01 (diff) | |
| download | rust-05330aaf42c794d441a91dc261e3202f965e0ce2.tar.gz rust-05330aaf42c794d441a91dc261e3202f965e0ce2.zip | |
Closer similarities.
Diffstat (limited to 'library/alloc/src/string.rs')
| -rw-r--r-- | library/alloc/src/string.rs | 42 |
1 files changed, 16 insertions, 26 deletions
diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 7292ebdaeec..8b0f3047a0a 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -2228,18 +2228,18 @@ impl ToString for char { impl ToString for u8 { #[inline] fn to_string(&self) -> String { - let mut result = String::with_capacity(3); + let mut buf = String::with_capacity(3); let mut n = *self; - if n >= 100 { - result.push((b'0' + n / 100) as char); - n %= 100; - } - if !result.is_empty() || n >= 10 { - result.push((b'0' + n / 10) as char); + if n >= 10 { + if n >= 100 { + buf.push((b'0' + n / 100) as char); + n %= 100; + } + buf.push((b'0' + n / 10) as char); n %= 10; - }; - result.push((b'0' + n) as char); - result + } + buf.push((b'0' + n) as char); + buf } } @@ -2247,31 +2247,21 @@ impl ToString for u8 { impl ToString for i8 { #[inline] fn to_string(&self) -> String { - let mut vec = vec![0; 4]; - let mut free = 0; + let mut buf = String::with_capacity(4); if self.is_negative() { - vec[free] = b'-'; - free += 1; + buf.push('-'); } let mut n = self.unsigned_abs(); if n >= 10 { if n >= 100 { + buf.push('1'); n -= 100; - vec[free] = b'1'; - free += 1; } - debug_assert!(n < 100); - vec[free] = b'0' + n / 10; - free += 1; + buf.push((b'0' + n / 10) as char); n %= 10; } - debug_assert!(n < 10); - vec[free] = b'0' + n; - free += 1; - vec.truncate(free); - - // SAFETY: Vec only contains ascii so valid utf8 - unsafe { String::from_utf8_unchecked(vec) } + buf.push((b'0' + n) as char); + buf } } |
