| 1 |
//! Implementations for efficiently converting a number into a [`Repr`] |
| 2 |
//! |
| 3 |
//! Adapted from the implementation in the `std` library at |
| 4 |
//! <https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L188-L266> |
| 5 |
|
| 6 |
use core::{mem, num, ptr}; |
| 7 |
|
| 8 |
use super::traits::IntoRepr; |
| 9 |
use super::{InlineBuffer, Repr, LENGTH_MASK, MAX_SIZE}; |
| 10 |
use crate::ToCompactStringError; |
| 11 |
|
| 12 |
const DEC_DIGITS_LUT: &[u8] = b"\ |
| 13 |
0001020304050607080910111213141516171819\ |
| 14 |
2021222324252627282930313233343536373839\ |
| 15 |
4041424344454647484950515253545556575859\ |
| 16 |
6061626364656667686970717273747576777879\ |
| 17 |
8081828384858687888990919293949596979899"; |
| 18 |
|
| 19 |
/// Defines the implementation of [`IntoRepr`] for integer types |
| 20 |
macro_rules! impl_IntoRepr { |
| 21 |
($t:ident, $conv_ty:ident) => { |
| 22 |
impl IntoRepr for $t { |
| 23 |
fn into_repr(self) -> Result<Repr, ToCompactStringError> { |
| 24 |
// The formatted value is at most 20 characters (`i64::MIN`). On 64-bit that always |
| 25 |
// fits inline, so we can write straight into an `InlineBuffer` and skip the |
| 26 |
// discriminant dispatch of `with_capacity`/`as_mut_ptr`/`set_len`. The only case |
| 27 |
// that doesn't fit is `u64`/`i64` on a 32-bit target (`MAX_SIZE` is 12 there); we |
| 28 |
// hand those off to `itoa` like the 128-bit types. |
| 29 |
// |
| 30 |
// `MAX_LEN` is an upper bound on the formatted length including the sign; it's `< |
| 31 |
// MAX_SIZE` (not `<=`) so the length still fits in the last byte. |
| 32 |
const MAX_LEN: usize = <$t>::MAX.ilog10() as usize + 2; |
| 33 |
|
| 34 |
if MAX_LEN >= MAX_SIZE { |
| 35 |
let mut itoa_buf = itoa::Buffer::new(); |
| 36 |
return Ok(Repr::new(itoa_buf.format(self))?); |
| 37 |
} |
| 38 |
|
| 39 |
// Number of characters to write, including a leading `-` for negatives. |
| 40 |
let num_digits = NumChars::num_chars(self); |
| 41 |
let mut buffer = [0u8; MAX_SIZE]; |
| 42 |
|
| 43 |
#[allow(unused_comparisons)] |
| 44 |
let is_nonnegative = self >= 0; |
| 45 |
let mut n = if is_nonnegative { |
| 46 |
self as $conv_ty |
| 47 |
} else { |
| 48 |
// convert the negative num to positive by summing 1 to it's 2 complement |
| 49 |
(!(self as $conv_ty)).wrapping_add(1) |
| 50 |
}; |
| 51 |
let mut curr = num_digits as isize; |
| 52 |
|
| 53 |
let buf_ptr = buffer.as_mut_ptr(); |
| 54 |
let lut_ptr = DEC_DIGITS_LUT.as_ptr(); |
| 55 |
|
| 56 |
unsafe { |
| 57 |
// need at least 16 bits for the 4-characters-at-a-time to work. |
| 58 |
if mem::size_of::<$t>() >= 2 { |
| 59 |
// eagerly decode 4 characters at a time |
| 60 |
while n >= 10000 { |
| 61 |
let rem = (n % 10000) as isize; |
| 62 |
n /= 10000; |
| 63 |
|
| 64 |
let d1 = (rem / 100) << 1; |
| 65 |
let d2 = (rem % 100) << 1; |
| 66 |
curr -= 4; |
| 67 |
ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); |
| 68 |
ptr::copy_nonoverlapping( |
| 69 |
lut_ptr.offset(d2), |
| 70 |
buf_ptr.offset(curr + 2), |
| 71 |
2, |
| 72 |
); |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
// if we reach here numbers are <= 9999, so at most 4 chars long |
| 77 |
let mut n = n as isize; // possibly reduce 64bit math |
| 78 |
|
| 79 |
// decode 2 more chars, if > 2 chars |
| 80 |
if n >= 100 { |
| 81 |
let d1 = (n % 100) << 1; |
| 82 |
n /= 100; |
| 83 |
curr -= 2; |
| 84 |
ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); |
| 85 |
} |
| 86 |
|
| 87 |
// decode last 1 or 2 chars |
| 88 |
if n < 10 { |
| 89 |
curr -= 1; |
| 90 |
*buf_ptr.offset(curr) = (n as u8) + b'0'; |
| 91 |
} else { |
| 92 |
let d1 = n << 1; |
| 93 |
curr -= 2; |
| 94 |
ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); |
| 95 |
} |
| 96 |
|
| 97 |
if !is_nonnegative { |
| 98 |
curr -= 1; |
| 99 |
*buf_ptr.offset(curr) = b'-'; |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
// we should have moved all the way down our buffer |
| 104 |
debug_assert_eq!(curr, 0); |
| 105 |
|
| 106 |
// `num_digits < MAX_SIZE`, so the length lives in the last byte, distinct from the |
| 107 |
// digits. |
| 108 |
buffer[MAX_SIZE - 1] = num_digits as u8 | LENGTH_MASK; |
| 109 |
|
| 110 |
// SAFETY: the leading `num_digits` bytes are ASCII digits (with an optional `-`), |
| 111 |
// and the last byte is a valid inline length marker. |
| 112 |
Ok(Repr::from_inline(InlineBuffer(buffer))) |
| 113 |
} |
| 114 |
} |
| 115 |
}; |
| 116 |
} |
| 117 |
|
| 118 |
impl_IntoRepr!(u8, u32); |
| 119 |
impl_IntoRepr!(i8, u32); |
| 120 |
impl_IntoRepr!(u16, u32); |
| 121 |
impl_IntoRepr!(i16, u32); |
| 122 |
impl_IntoRepr!(u32, u32); |
| 123 |
impl_IntoRepr!(i32, u32); |
| 124 |
impl_IntoRepr!(u64, u64); |
| 125 |
impl_IntoRepr!(i64, u64); |
| 126 |
|
| 127 |
#[cfg(target_pointer_width = "32")] |
| 128 |
impl_IntoRepr!(usize, u32); |
| 129 |
#[cfg(target_pointer_width = "32")] |
| 130 |
impl_IntoRepr!(isize, u32); |
| 131 |
|
| 132 |
#[cfg(target_pointer_width = "64")] |
| 133 |
impl_IntoRepr!(usize, u64); |
| 134 |
#[cfg(target_pointer_width = "64")] |
| 135 |
impl_IntoRepr!(isize, u64); |
| 136 |
|
| 137 |
/// For 128-bit integer types we use the [`itoa`] crate because writing into a buffer, and then |
| 138 |
/// copying the amount of characters we've written, is faster than determining the number of |
| 139 |
/// characters and then writing. |
| 140 |
impl IntoRepr for u128 { |
| 141 |
#[inline] |
| 142 |
fn into_repr(self) -> Result<Repr, ToCompactStringError> { |
| 143 |
let mut buffer = itoa::Buffer::new(); |
| 144 |
Ok(Repr::new(buffer.format(self))?) |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
impl IntoRepr for i128 { |
| 149 |
#[inline] |
| 150 |
fn into_repr(self) -> Result<Repr, ToCompactStringError> { |
| 151 |
let mut buffer = itoa::Buffer::new(); |
| 152 |
Ok(Repr::new(buffer.format(self))?) |
| 153 |
} |
| 154 |
} |
| 155 |
|
| 156 |
/// Defines the implementation of [`IntoRepr`] for NonZero integer types |
| 157 |
macro_rules! impl_NonZero_IntoRepr { |
| 158 |
($t:path) => { |
| 159 |
impl IntoRepr for $t { |
| 160 |
#[inline] |
| 161 |
fn into_repr(self) -> Result<Repr, ToCompactStringError> { |
| 162 |
self.get().into_repr() |
| 163 |
} |
| 164 |
} |
| 165 |
}; |
| 166 |
} |
| 167 |
|
| 168 |
impl_NonZero_IntoRepr!(num::NonZeroU8); |
| 169 |
impl_NonZero_IntoRepr!(num::NonZeroI8); |
| 170 |
impl_NonZero_IntoRepr!(num::NonZeroU16); |
| 171 |
impl_NonZero_IntoRepr!(num::NonZeroI16); |
| 172 |
impl_NonZero_IntoRepr!(num::NonZeroU32); |
| 173 |
impl_NonZero_IntoRepr!(num::NonZeroI32); |
| 174 |
impl_NonZero_IntoRepr!(num::NonZeroU64); |
| 175 |
impl_NonZero_IntoRepr!(num::NonZeroI64); |
| 176 |
impl_NonZero_IntoRepr!(num::NonZeroUsize); |
| 177 |
impl_NonZero_IntoRepr!(num::NonZeroIsize); |
| 178 |
impl_NonZero_IntoRepr!(num::NonZeroU128); |
| 179 |
impl_NonZero_IntoRepr!(num::NonZeroI128); |
| 180 |
|
| 181 |
/// All of these `num_chars(...)` methods are kind of crazy, but they are necessary. |
| 182 |
/// |
| 183 |
/// An alternate way to calculate the number of digits in a value is to do: |
| 184 |
/// ```no_run |
| 185 |
/// let val = 42; |
| 186 |
/// let num_digits = ((val as f32).log10().floor()) as usize + 1; |
| 187 |
/// assert_eq!(num_digits, 2); |
| 188 |
/// ``` |
| 189 |
/// But there are two problems with this approach: |
| 190 |
/// 1. floating point math is slow |
| 191 |
/// 2. results are dependent on floating point precision, which is too inaccurate for larger values |
| 192 |
/// |
| 193 |
/// For example, consider this relatively large value... |
| 194 |
/// |
| 195 |
/// ```no_run |
| 196 |
/// let val = 9999995; |
| 197 |
/// let num_digits = ((val as f32).log10().floor()) as usize + 1; |
| 198 |
/// |
| 199 |
/// // this is wrong! There are only 7 digits in this number! |
| 200 |
/// assert_eq!(num_digits, 8); |
| 201 |
/// ``` |
| 202 |
/// |
| 203 |
/// you can use `f64` to get better precision, e.g. |
| 204 |
/// |
| 205 |
/// ```no_run |
| 206 |
/// let val = 9999995; |
| 207 |
/// let num_digits = ((val as f64).log10().floor()) as usize + 1; |
| 208 |
/// |
| 209 |
/// // the precision is enough to get the correct value |
| 210 |
/// assert_eq!(num_digits, 7); |
| 211 |
/// ``` |
| 212 |
/// |
| 213 |
/// ...but still not precise enough! |
| 214 |
/// |
| 215 |
/// ```no_run |
| 216 |
/// let val: u64 = 9999999999999999999; |
| 217 |
/// let num_digits = ((val as f64).log10().floor()) as usize + 1; |
| 218 |
/// |
| 219 |
/// // this is wrong! the number is only 19 digits but the formula returns 20 |
| 220 |
/// assert_eq!(num_digits, 20); |
| 221 |
/// ``` |
| 222 |
trait NumChars { |
| 223 |
fn num_chars(val: Self) -> usize; |
| 224 |
} |
| 225 |
|
| 226 |
impl NumChars for u8 { |
| 227 |
#[inline(always)] |
| 228 |
fn num_chars(val: u8) -> usize { |
| 229 |
match val { |
| 230 |
u8::MIN..=9 => 1, |
| 231 |
10..=99 => 2, |
| 232 |
100..=u8::MAX => 3, |
| 233 |
} |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
impl NumChars for i8 { |
| 238 |
#[inline(always)] |
| 239 |
fn num_chars(val: i8) -> usize { |
| 240 |
match val { |
| 241 |
i8::MIN..=-100 => 4, |
| 242 |
-99..=-10 => 3, |
| 243 |
-9..=-1 => 2, |
| 244 |
0..=9 => 1, |
| 245 |
10..=99 => 2, |
| 246 |
100..=i8::MAX => 3, |
| 247 |
} |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
impl NumChars for u16 { |
| 252 |
#[inline(always)] |
| 253 |
fn num_chars(val: u16) -> usize { |
| 254 |
match val { |
| 255 |
u16::MIN..=9 => 1, |
| 256 |
10..=99 => 2, |
| 257 |
100..=999 => 3, |
| 258 |
1000..=9999 => 4, |
| 259 |
10000..=u16::MAX => 5, |
| 260 |
} |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
impl NumChars for i16 { |
| 265 |
#[inline(always)] |
| 266 |
fn num_chars(val: i16) -> usize { |
| 267 |
match val { |
| 268 |
i16::MIN..=-10000 => 6, |
| 269 |
-9999..=-1000 => 5, |
| 270 |
-999..=-100 => 4, |
| 271 |
-99..=-10 => 3, |
| 272 |
-9..=-1 => 2, |
| 273 |
0..=9 => 1, |
| 274 |
10..=99 => 2, |
| 275 |
100..=999 => 3, |
| 276 |
1000..=9999 => 4, |
| 277 |
10000..=i16::MAX => 5, |
| 278 |
} |
| 279 |
} |
| 280 |
} |
| 281 |
|
| 282 |
impl NumChars for u32 { |
| 283 |
#[inline(always)] |
| 284 |
fn num_chars(val: u32) -> usize { |
| 285 |
match val { |
| 286 |
u32::MIN..=9 => 1, |
| 287 |
10..=99 => 2, |
| 288 |
100..=999 => 3, |
| 289 |
1000..=9999 => 4, |
| 290 |
10000..=99999 => 5, |
| 291 |
100000..=999999 => 6, |
| 292 |
1000000..=9999999 => 7, |
| 293 |
10000000..=99999999 => 8, |
| 294 |
100000000..=999999999 => 9, |
| 295 |
1000000000..=u32::MAX => 10, |
| 296 |
} |
| 297 |
} |
| 298 |
} |
| 299 |
|
| 300 |
impl NumChars for i32 { |
| 301 |
#[inline(always)] |
| 302 |
fn num_chars(val: i32) -> usize { |
| 303 |
match val { |
| 304 |
i32::MIN..=-1000000000 => 11, |
| 305 |
-999999999..=-100000000 => 10, |
| 306 |
-99999999..=-10000000 => 9, |
| 307 |
-9999999..=-1000000 => 8, |
| 308 |
-999999..=-100000 => 7, |
| 309 |
-99999..=-10000 => 6, |
| 310 |
-9999..=-1000 => 5, |
| 311 |
-999..=-100 => 4, |
| 312 |
-99..=-10 => 3, |
| 313 |
-9..=-1 => 2, |
| 314 |
0..=9 => 1, |
| 315 |
10..=99 => 2, |
| 316 |
100..=999 => 3, |
| 317 |
1000..=9999 => 4, |
| 318 |
10000..=99999 => 5, |
| 319 |
100000..=999999 => 6, |
| 320 |
1000000..=9999999 => 7, |
| 321 |
10000000..=99999999 => 8, |
| 322 |
100000000..=999999999 => 9, |
| 323 |
1000000000..=i32::MAX => 10, |
| 324 |
} |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
impl NumChars for u64 { |
| 329 |
#[inline(always)] |
| 330 |
fn num_chars(val: u64) -> usize { |
| 331 |
// `checked_ilog10` is `None` only for `0`, which has one digit. Cheaper than a 20-arm |
| 332 |
// match for 64-bit values, and exact (unlike `f64::log10`). |
| 333 |
val.checked_ilog10().map_or(1, |log| log as usize + 1) |
| 334 |
} |
| 335 |
} |
| 336 |
|
| 337 |
impl NumChars for i64 { |
| 338 |
#[inline(always)] |
| 339 |
fn num_chars(val: i64) -> usize { |
| 340 |
// Digits of the magnitude plus one for the sign. `unsigned_abs` avoids `-i64::MIN`. |
| 341 |
val.unsigned_abs() |
| 342 |
.checked_ilog10() |
| 343 |
.map_or(1, |log| log as usize + 1) |
| 344 |
+ (val < 0) as usize |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
impl NumChars for usize { |
| 349 |
fn num_chars(val: usize) -> usize { |
| 350 |
#[cfg(target_pointer_width = "32")] |
| 351 |
{ |
| 352 |
u32::num_chars(val as u32) |
| 353 |
} |
| 354 |
|
| 355 |
#[cfg(target_pointer_width = "64")] |
| 356 |
{ |
| 357 |
u64::num_chars(val as u64) |
| 358 |
} |
| 359 |
} |
| 360 |
} |
| 361 |
|
| 362 |
impl NumChars for isize { |
| 363 |
fn num_chars(val: isize) -> usize { |
| 364 |
#[cfg(target_pointer_width = "32")] |
| 365 |
{ |
| 366 |
i32::num_chars(val as i32) |
| 367 |
} |
| 368 |
|
| 369 |
#[cfg(target_pointer_width = "64")] |
| 370 |
{ |
| 371 |
i64::num_chars(val as i64) |
| 372 |
} |
| 373 |
} |
| 374 |
} |
| 375 |
|
| 376 |
#[cfg(test)] |
| 377 |
mod tests { |
| 378 |
use alloc::string::ToString; |
| 379 |
|
| 380 |
use super::IntoRepr; |
| 381 |
|
| 382 |
#[test] |
| 383 |
fn test_from_u8_sanity() { |
| 384 |
let vals = [u8::MIN, 1, 0, 42, u8::MAX - 1, u8::MAX]; |
| 385 |
|
| 386 |
for x in &vals { |
| 387 |
let repr = u8::into_repr(*x).unwrap(); |
| 388 |
assert_eq!(repr.as_str(), x.to_string()); |
| 389 |
} |
| 390 |
} |
| 391 |
|
| 392 |
#[test] |
| 393 |
fn test_from_i8_sanity() { |
| 394 |
let vals = [i8::MIN, i8::MIN + 1, 0, 42, i8::MAX - 1, i8::MAX]; |
| 395 |
|
| 396 |
for x in &vals { |
| 397 |
let repr = i8::into_repr(*x).unwrap(); |
| 398 |
assert_eq!(repr.as_str(), x.to_string()); |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
#[test] |
| 403 |
fn test_from_u16_sanity() { |
| 404 |
let vals = [u16::MIN, 1, 0, 42, u16::MAX - 1, u16::MAX]; |
| 405 |
|
| 406 |
for x in &vals { |
| 407 |
let repr = u16::into_repr(*x).unwrap(); |
| 408 |
assert_eq!(repr.as_str(), x.to_string()); |
| 409 |
} |
| 410 |
} |
| 411 |
|
| 412 |
#[test] |
| 413 |
fn test_from_i16_sanity() { |
| 414 |
let vals = [i16::MIN, i16::MIN + 1, 0, 42, i16::MAX - 1, i16::MAX]; |
| 415 |
|
| 416 |
for x in &vals { |
| 417 |
let repr = i16::into_repr(*x).unwrap(); |
| 418 |
assert_eq!(repr.as_str(), x.to_string()); |
| 419 |
} |
| 420 |
} |
| 421 |
|
| 422 |
#[test] |
| 423 |
fn test_from_u32_sanity() { |
| 424 |
let vals = [u32::MIN, 1, 0, 42, u32::MAX - 1, u32::MAX]; |
| 425 |
|
| 426 |
for x in &vals { |
| 427 |
let repr = u32::into_repr(*x).unwrap(); |
| 428 |
assert_eq!(repr.as_str(), x.to_string()); |
| 429 |
} |
| 430 |
} |
| 431 |
|
| 432 |
#[test] |
| 433 |
fn test_from_i32_sanity() { |
| 434 |
let vals = [i32::MIN, i32::MIN + 1, 0, 42, i32::MAX - 1, i32::MAX]; |
| 435 |
|
| 436 |
for x in &vals { |
| 437 |
let repr = i32::into_repr(*x).unwrap(); |
| 438 |
assert_eq!(repr.as_str(), x.to_string()); |
| 439 |
} |
| 440 |
} |
| 441 |
|
| 442 |
#[test] |
| 443 |
fn test_from_u64_sanity() { |
| 444 |
let vals = [u64::MIN, 1, 0, 42, u64::MAX - 1, u64::MAX]; |
| 445 |
|
| 446 |
for x in &vals { |
| 447 |
let repr = u64::into_repr(*x).unwrap(); |
| 448 |
assert_eq!(repr.as_str(), x.to_string()); |
| 449 |
} |
| 450 |
} |
| 451 |
|
| 452 |
#[test] |
| 453 |
fn test_from_i64_sanity() { |
| 454 |
let vals = [i64::MIN, i64::MIN + 1, 0, 42, i64::MAX - 1, i64::MAX]; |
| 455 |
|
| 456 |
for x in &vals { |
| 457 |
let repr = i64::into_repr(*x).unwrap(); |
| 458 |
assert_eq!(repr.as_str(), x.to_string()); |
| 459 |
} |
| 460 |
} |
| 461 |
|
| 462 |
#[test] |
| 463 |
fn test_from_usize_sanity() { |
| 464 |
let vals = [usize::MIN, 1, 0, 42, usize::MAX - 1, usize::MAX]; |
| 465 |
|
| 466 |
for x in &vals { |
| 467 |
let repr = usize::into_repr(*x).unwrap(); |
| 468 |
assert_eq!(repr.as_str(), x.to_string()); |
| 469 |
} |
| 470 |
} |
| 471 |
|
| 472 |
#[test] |
| 473 |
fn test_from_isize_sanity() { |
| 474 |
let vals = [ |
| 475 |
isize::MIN, |
| 476 |
isize::MIN + 1, |
| 477 |
0, |
| 478 |
42, |
| 479 |
isize::MAX - 1, |
| 480 |
isize::MAX, |
| 481 |
]; |
| 482 |
|
| 483 |
for x in &vals { |
| 484 |
let repr = isize::into_repr(*x).unwrap(); |
| 485 |
assert_eq!(repr.as_str(), x.to_string()); |
| 486 |
} |
| 487 |
} |
| 488 |
|
| 489 |
#[test] |
| 490 |
fn test_from_u128_sanity() { |
| 491 |
let vals = [u128::MIN, 1, 0, 42, u128::MAX - 1, u128::MAX]; |
| 492 |
|
| 493 |
for x in &vals { |
| 494 |
let repr = u128::into_repr(*x).unwrap(); |
| 495 |
assert_eq!(repr.as_str(), x.to_string()); |
| 496 |
} |
| 497 |
} |
| 498 |
|
| 499 |
#[test] |
| 500 |
fn test_from_i128_sanity() { |
| 501 |
let vals = [i128::MIN, i128::MIN + 1, 0, 42, i128::MAX - 1, i128::MAX]; |
| 502 |
|
| 503 |
for x in &vals { |
| 504 |
let repr = i128::into_repr(*x).unwrap(); |
| 505 |
assert_eq!(repr.as_str(), x.to_string()); |
| 506 |
} |
| 507 |
} |
| 508 |
} |