Skip to content

Commit 05330aa

Browse files
committed
Closer similarities.
1 parent 6a58b6a commit 05330aa

File tree

1 file changed

+16
-26
lines changed

1 file changed

+16
-26
lines changed

library/alloc/src/string.rs

+16-26
Original file line numberDiff line numberDiff line change
@@ -2228,50 +2228,40 @@ impl ToString for char {
22282228
impl ToString for u8 {
22292229
#[inline]
22302230
fn to_string(&self) -> String {
2231-
let mut result = String::with_capacity(3);
2231+
let mut buf = String::with_capacity(3);
22322232
let mut n = *self;
2233-
if n >= 100 {
2234-
result.push((b'0' + n / 100) as char);
2235-
n %= 100;
2236-
}
2237-
if !result.is_empty() || n >= 10 {
2238-
result.push((b'0' + n / 10) as char);
2233+
if n >= 10 {
2234+
if n >= 100 {
2235+
buf.push((b'0' + n / 100) as char);
2236+
n %= 100;
2237+
}
2238+
buf.push((b'0' + n / 10) as char);
22392239
n %= 10;
2240-
};
2241-
result.push((b'0' + n) as char);
2242-
result
2240+
}
2241+
buf.push((b'0' + n) as char);
2242+
buf
22432243
}
22442244
}
22452245

22462246
#[stable(feature = "i8_to_string_specialization", since = "1.999.0")]
22472247
impl ToString for i8 {
22482248
#[inline]
22492249
fn to_string(&self) -> String {
2250-
let mut vec = vec![0; 4];
2251-
let mut free = 0;
2250+
let mut buf = String::with_capacity(4);
22522251
if self.is_negative() {
2253-
vec[free] = b'-';
2254-
free += 1;
2252+
buf.push('-');
22552253
}
22562254
let mut n = self.unsigned_abs();
22572255
if n >= 10 {
22582256
if n >= 100 {
2257+
buf.push('1');
22592258
n -= 100;
2260-
vec[free] = b'1';
2261-
free += 1;
22622259
}
2263-
debug_assert!(n < 100);
2264-
vec[free] = b'0' + n / 10;
2265-
free += 1;
2260+
buf.push((b'0' + n / 10) as char);
22662261
n %= 10;
22672262
}
2268-
debug_assert!(n < 10);
2269-
vec[free] = b'0' + n;
2270-
free += 1;
2271-
vec.truncate(free);
2272-
2273-
// SAFETY: Vec only contains ascii so valid utf8
2274-
unsafe { String::from_utf8_unchecked(vec) }
2263+
buf.push((b'0' + n) as char);
2264+
buf
22752265
}
22762266
}
22772267

0 commit comments

Comments
 (0)