1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 /// Convert unsigned integers into a string representation with some base.
12 /// Bases up to and including 36 can be used for case-insensitive things.
16 pub const MAX_BASE: usize = 64;
17 pub const ALPHANUMERIC_ONLY: usize = 62;
18 pub const CASE_INSENSITIVE: usize = 36;
20 const BASE_64: &[u8; MAX_BASE as usize] =
21 b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$";
24 pub fn push_str(mut n: u128, base: usize, output: &mut String) {
25 debug_assert!(base >= 2 && base <= MAX_BASE);
26 let mut s = [0u8; 128];
29 let base = base as u128;
32 s[index] = BASE_64[(n % base) as usize];
40 s[0..index].reverse();
42 output.push_str(str::from_utf8(&s[0..index]).unwrap());
46 pub fn encode(n: u128, base: usize) -> String {
47 let mut s = String::new();
48 push_str(n, base, &mut s);
54 fn test(n: u128, base: usize) {
55 assert_eq!(Ok(n), u128::from_str_radix(&encode(n, base), base as u32));
64 test(u64::max_value() as u128, base);
65 test(u128::max_value(), base);