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