diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:02:58 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:02:58 +0000 |
commit | 698f8c2f01ea549d77d7dc3338a12e04c11057b9 (patch) | |
tree | 173a775858bd501c378080a10dca74132f05bc50 /compiler/rustc_data_structures/src/base_n.rs | |
parent | Initial commit. (diff) | |
download | rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.tar.xz rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.zip |
Adding upstream version 1.64.0+dfsg1.upstream/1.64.0+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'compiler/rustc_data_structures/src/base_n.rs')
-rw-r--r-- | compiler/rustc_data_structures/src/base_n.rs | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/compiler/rustc_data_structures/src/base_n.rs b/compiler/rustc_data_structures/src/base_n.rs new file mode 100644 index 000000000..3c7bea271 --- /dev/null +++ b/compiler/rustc_data_structures/src/base_n.rs @@ -0,0 +1,42 @@ +/// 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 as usize] = + 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 = 0; + + let base = base as u128; + + loop { + s[index] = BASE_64[(n % base) as usize]; + index += 1; + n /= base; + + if n == 0 { + break; + } + } + s[0..index].reverse(); + + output.push_str(str::from_utf8(&s[0..index]).unwrap()); +} + +#[inline] +pub fn encode(n: u128, base: usize) -> String { + let mut s = String::new(); + push_str(n, base, &mut s); + s +} |