mirror of
https://github.com/rust-lang/rust.git
synced 2025-10-30 20:44:34 +00:00
This minor change removes the need to reverse resulting digits. Since reverse is O(|digit_num|) but bounded by 128, it's unlikely to be a noticeable in practice. At the same time, this code is also a 1 line shorter, so combined with tiny perf win, why not? I ran https://gist.github.com/ttsugriy/ed14860ef597ab315d4129d5f8adb191 on M1 macbook air and got a small improvement ``` Running benches/base_n_benchmark.rs (target/release/deps/base_n_benchmark-825fe5895b5c2693) push_str/old time: [14.180 µs 14.313 µs 14.462 µs] Performance has improved. Found 5 outliers among 100 measurements (5.00%) 4 (4.00%) high mild 1 (1.00%) high severe push_str/new time: [13.741 µs 13.839 µs 13.973 µs] Performance has improved. Found 8 outliers among 100 measurements (8.00%) 3 (3.00%) high mild 5 (5.00%) high severe ```
42 lines
970 B
Rust
42 lines
970 B
Rust
/// Converts unsigned integers into a string representation with some base.
|
|
/// Bases up to and including 36 can be used for case-insensitive things.
|
|
use std::str;
|
|
|
|
#[cfg(test)]
|
|
mod tests;
|
|
|
|
pub const MAX_BASE: usize = 64;
|
|
pub const ALPHANUMERIC_ONLY: usize = 62;
|
|
pub const CASE_INSENSITIVE: usize = 36;
|
|
|
|
const BASE_64: &[u8; MAX_BASE] =
|
|
b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$";
|
|
|
|
#[inline]
|
|
pub fn push_str(mut n: u128, base: usize, output: &mut String) {
|
|
debug_assert!(base >= 2 && base <= MAX_BASE);
|
|
let mut s = [0u8; 128];
|
|
let mut index = s.len();
|
|
|
|
let base = base as u128;
|
|
|
|
loop {
|
|
index -= 1;
|
|
s[index] = BASE_64[(n % base) as usize];
|
|
n /= base;
|
|
|
|
if n == 0 {
|
|
break;
|
|
}
|
|
}
|
|
|
|
output.push_str(str::from_utf8(&s[index..]).unwrap());
|
|
}
|
|
|
|
#[inline]
|
|
pub fn encode(n: u128, base: usize) -> String {
|
|
let mut s = String::new();
|
|
push_str(n, base, &mut s);
|
|
s
|
|
}
|