Skip to content

Commit d07c43a

Browse files
committed
Alternative LUT rather than dividing.
1 parent a69960a commit d07c43a

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

library/alloc/src/string.rs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2224,7 +2224,7 @@ impl ToString for char {
22242224
}
22252225
}
22262226

2227-
#[stable(feature = "u8_to_string_specialization", since="1.999.0")]
2227+
#[stable(feature = "u8_to_string_specialization", since = "1.999.0")]
22282228
impl ToString for u8 {
22292229
#[inline]
22302230
fn to_string(&self) -> String {
@@ -2243,6 +2243,39 @@ impl ToString for u8 {
22432243
}
22442244
}
22452245

2246+
// 2 digit decimal look up table
2247+
static DEC_DIGITS_LUT: &[u8; 200] = b"0001020304050607080910111213141516171819\
2248+
2021222324252627282930313233343536373839\
2249+
4041424344454647484950515253545556575859\
2250+
6061626364656667686970717273747576777879\
2251+
8081828384858687888990919293949596979899";
2252+
2253+
#[stable(feature = "i8_to_string_specialization", since = "1.999.0")]
2254+
impl ToString for i8 {
2255+
#[inline]
2256+
fn to_string(&self) -> String {
2257+
let mut vec: Vec<u8> = if *self < 0 {
2258+
let mut v = Vec::with_capacity(4);
2259+
v.push(b'-');
2260+
v
2261+
} else {
2262+
Vec::with_capacity(3)
2263+
};
2264+
let mut n = self.abs();
2265+
if n >= 10 {
2266+
if n >= 100 {
2267+
n -= 100;
2268+
vec.push(b'1');
2269+
}
2270+
let nn = n * 2;
2271+
vec.extend_from_slice(&DEC_DIGITS_LUT[nn as usize..=nn as usize + 1]);
2272+
} else {
2273+
vec.push(b'0' + (n as u8));
2274+
}
2275+
unsafe { String::from_utf8_unchecked(vec) }
2276+
}
2277+
}
2278+
22462279
#[stable(feature = "str_to_string_specialization", since = "1.9.0")]
22472280
impl ToString for str {
22482281
#[inline]

0 commit comments

Comments
 (0)