2019-02-08 13:53:55 +00:00
|
|
|
/// Converts unsigned integers into a string representation with some base.
|
2016-11-04 21:37:42 +00:00
|
|
|
/// Bases up to and including 36 can be used for case-insensitive things.
|
|
|
|
use std::str;
|
|
|
|
|
2019-08-01 20:57:23 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests;
|
|
|
|
|
2018-01-08 11:30:52 +00:00
|
|
|
pub const MAX_BASE: usize = 64;
|
|
|
|
pub const ALPHANUMERIC_ONLY: usize = 62;
|
|
|
|
pub const CASE_INSENSITIVE: usize = 36;
|
2016-12-12 18:56:52 +00:00
|
|
|
|
2018-08-09 15:00:14 +00:00
|
|
|
const BASE_64: &[u8; MAX_BASE as usize] =
|
2016-11-04 21:37:42 +00:00
|
|
|
b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$";
|
|
|
|
|
|
|
|
#[inline]
|
2018-01-08 11:30:52 +00:00
|
|
|
pub fn push_str(mut n: u128, base: usize, output: &mut String) {
|
2016-11-04 21:37:42 +00:00
|
|
|
debug_assert!(base >= 2 && base <= MAX_BASE);
|
2018-01-08 11:30:52 +00:00
|
|
|
let mut s = [0u8; 128];
|
2016-11-04 21:37:42 +00:00
|
|
|
let mut index = 0;
|
|
|
|
|
2018-01-08 11:30:52 +00:00
|
|
|
let base = base as u128;
|
|
|
|
|
2016-11-04 21:37:42 +00:00
|
|
|
loop {
|
|
|
|
s[index] = BASE_64[(n % base) as usize];
|
|
|
|
index += 1;
|
|
|
|
n /= base;
|
|
|
|
|
|
|
|
if n == 0 {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2018-08-09 15:00:14 +00:00
|
|
|
s[0..index].reverse();
|
|
|
|
|
2016-11-04 21:37:42 +00:00
|
|
|
output.push_str(str::from_utf8(&s[0..index]).unwrap());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2018-01-08 11:30:52 +00:00
|
|
|
pub fn encode(n: u128, base: usize) -> String {
|
|
|
|
let mut s = String::new();
|
2016-11-04 21:37:42 +00:00
|
|
|
push_str(n, base, &mut s);
|
|
|
|
s
|
|
|
|
}
|