use num::cast::NumCast;
use num::Integer;
const ALPHABET: [char; 62] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z',
];
pub trait ToBase62 {
fn to_base62(&self) -> String;
}
impl<T: Copy + Integer + NumCast> ToBase62 for T {
fn to_base62(&self) -> String {
let len: T = NumCast::from(ALPHABET.len()).unwrap();
let mut encoded = String::new();
let mut n = *self;
while n > T::zero() {
let (quo, rem) = n.div_rem(&len);
n = quo;
encoded.insert(0, ALPHABET[rem.to_usize().unwrap()])
}
encoded
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encode_to_base62() {
assert_eq!(1.to_base62(), "1");
assert_eq!(2.to_base62(), "2");
assert_eq!(3.to_base62(), "3");
assert_eq!(62.to_base62(), "10");
assert_eq!(63.to_base62(), "11");
assert_eq!(64.to_base62(), "12");
}
}