]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/base_n.rs
librustc_data_structures: Unconfigure tests during normal build
[rust.git] / src / librustc_data_structures / 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
4 use std::str;
5
6 #[cfg(test)]
7 mod tests;
8
9 pub const MAX_BASE: usize = 64;
10 pub const ALPHANUMERIC_ONLY: usize = 62;
11 pub const CASE_INSENSITIVE: usize = 36;
12
13 const BASE_64: &[u8; MAX_BASE as usize] =
14     b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$";
15
16 #[inline]
17 pub fn push_str(mut n: u128, base: usize, output: &mut String) {
18     debug_assert!(base >= 2 && base <= MAX_BASE);
19     let mut s = [0u8; 128];
20     let mut index = 0;
21
22     let base = base as u128;
23
24     loop {
25         s[index] = BASE_64[(n % base) as usize];
26         index += 1;
27         n /= base;
28
29         if n == 0 {
30             break;
31         }
32     }
33     s[0..index].reverse();
34
35     output.push_str(str::from_utf8(&s[0..index]).unwrap());
36 }
37
38 #[inline]
39 pub fn encode(n: u128, base: usize) -> String {
40     let mut s = String::new();
41     push_str(n, base, &mut s);
42     s
43 }