]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/base_n.rs
Merge commit '4a053f206fd6799a25823c307f7d7f9d897be118' into sync-rustfmt-subtree
[rust.git] / compiler / rustc_data_structures / src / base_n.rs
1 /// Converts unsigned integers into a string representation with some base.
2 /// Bases up to and including 36 can be used for case-insensitive things.
3 use std::str;
4
5 #[cfg(test)]
6 mod tests;
7
8 pub const MAX_BASE: usize = 64;
9 pub const ALPHANUMERIC_ONLY: usize = 62;
10 pub const CASE_INSENSITIVE: usize = 36;
11
12 const BASE_64: &[u8; MAX_BASE as usize] =
13     b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$";
14
15 #[inline]
16 pub fn push_str(mut n: u128, base: usize, output: &mut String) {
17     debug_assert!(base >= 2 && base <= MAX_BASE);
18     let mut s = [0u8; 128];
19     let mut index = 0;
20
21     let base = base as u128;
22
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     }
32     s[0..index].reverse();
33
34     output.push_str(str::from_utf8(&s[0..index]).unwrap());
35 }
36
37 #[inline]
38 pub fn encode(n: u128, base: usize) -> String {
39     let mut s = String::new();
40     push_str(n, base, &mut s);
41     s
42 }