]>
Commit | Line | Data |
---|---|---|
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 |
3 | use std::str; |
4 | ||
416331ca XL |
5 | #[cfg(test)] |
6 | mod tests; | |
7 | ||
ff7c6d11 XL |
8 | pub const MAX_BASE: usize = 64; |
9 | pub const ALPHANUMERIC_ONLY: usize = 62; | |
10 | pub const CASE_INSENSITIVE: usize = 36; | |
476ff2be | 11 | |
b7449926 | 12 | const BASE_64: &[u8; MAX_BASE as usize] = |
476ff2be SL |
13 | b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$"; |
14 | ||
15 | #[inline] | |
ff7c6d11 | 16 | pub 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 |
38 | pub 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 | } |