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: u64 = 64;
17 pub const ALPHANUMERIC_ONLY: u64 = 62;
19 const BASE_64: &'static [u8; MAX_BASE as usize] =
20 b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$";
23 pub fn push_str(mut n: u64, base: u64, output: &mut String) {
24 debug_assert!(base >= 2 && base <= MAX_BASE);
25 let mut s = [0u8; 64];
29 s[index] = BASE_64[(n % base) as usize];
37 &mut s[0..index].reverse();
38 output.push_str(str::from_utf8(&s[0..index]).unwrap());
42 pub fn encode(n: u64, base: u64) -> String {
43 let mut s = String::with_capacity(13);
44 push_str(n, base, &mut s);
50 fn test(n: u64, base: u64) {
51 assert_eq!(Ok(n), u64::from_str_radix(&encode(n, base)[..], base as u32));
60 test(u64::max_value(), base);