]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_data_structures/src/base_n.rs
New upstream version 1.57.0+dfsg1
[rustc.git] / compiler / rustc_data_structures / src / base_n.rs
CommitLineData
9fa01778 1/// Converts unsigned integers into a string representation with some base.
476ff2be 2/// Bases up to and including 36 can be used for case-insensitive things.
476ff2be
SL
3use std::str;
4
416331ca
XL
5#[cfg(test)]
6mod tests;
7
ff7c6d11
XL
8pub const MAX_BASE: usize = 64;
9pub const ALPHANUMERIC_ONLY: usize = 62;
10pub const CASE_INSENSITIVE: usize = 36;
476ff2be 11
b7449926 12const BASE_64: &[u8; MAX_BASE as usize] =
476ff2be
SL
13 b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$";
14
15#[inline]
ff7c6d11 16pub fn push_str(mut n: u128, base: usize, output: &mut String) {
c295e0f8 17 debug_assert!((2..=MAX_BASE).contains(&base));
ff7c6d11 18 let mut s = [0u8; 128];
476ff2be
SL
19 let mut index = 0;
20
ff7c6d11
XL
21 let base = base as u128;
22
476ff2be
SL
23 loop {
24 s[index] = BASE_64[(n % base) as usize];
25 index += 1;
26 n /= base;
27
28 if n == 0 {
29 break;
30 }
31 }
b7449926
XL
32 s[0..index].reverse();
33
476ff2be
SL
34 output.push_str(str::from_utf8(&s[0..index]).unwrap());
35}
36
37#[inline]
ff7c6d11
XL
38pub fn encode(n: u128, base: usize) -> String {
39 let mut s = String::new();
476ff2be
SL
40 push_str(n, base, &mut s);
41 s
42}