]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/base_n.rs
Rollup merge of #39039 - michaelwoerister:ignore-gdb-version, r=nrc
[rust.git] / src / librustc_data_structures / base_n.rs
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.
4 //
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.
10
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.
13
14 use std::str;
15
16 pub const MAX_BASE: u64 = 64;
17 pub const ALPHANUMERIC_ONLY: u64 = 62;
18
19 const BASE_64: &'static [u8; MAX_BASE as usize] =
20     b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$";
21
22 #[inline]
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];
26     let mut index = 0;
27
28     loop {
29         s[index] = BASE_64[(n % base) as usize];
30         index += 1;
31         n /= base;
32
33         if n == 0 {
34             break;
35         }
36     }
37     &mut s[0..index].reverse();
38     output.push_str(str::from_utf8(&s[0..index]).unwrap());
39 }
40
41 #[inline]
42 pub fn encode(n: u64, base: u64) -> String {
43     let mut s = String::with_capacity(13);
44     push_str(n, base, &mut s);
45     s
46 }
47
48 #[test]
49 fn test_encode() {
50     fn test(n: u64, base: u64) {
51         assert_eq!(Ok(n), u64::from_str_radix(&encode(n, base)[..], base as u32));
52     }
53
54     for base in 2..37 {
55         test(0, base);
56         test(1, base);
57         test(35, base);
58         test(36, base);
59         test(37, base);
60         test(u64::max_value(), base);
61
62         for i in 0 .. 1_000 {
63             test(i * 983, base);
64         }
65     }
66 }