-
Notifications
You must be signed in to change notification settings - Fork 1
/
base62.rs
80 lines (64 loc) · 2.16 KB
/
base62.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Based on code from https://github.com/fbernier/base62
use crate::error::DecodeError;
use crate::error::DecodeError::{ArithmeticOverflow, InvalidBase62Byte};
const BASE: u128 = 62;
const ALPHABET: [u8; BASE as usize] = [b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9',
b'A', b'B', b'C', b'D', b'E', b'F', b'G', b'H', b'I', b'J',
b'K', b'L', b'M', b'N', b'O', b'P', b'Q', b'R', b'S', b'T',
b'U', b'V', b'W', b'X', b'Y', b'Z', b'a', b'b', b'c', b'd',
b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', b'n',
b'o', b'p', b'q', b'r', b's', b't', b'u', b'v', b'w', b'x',
b'y', b'z'];
pub fn encode(mut num: u128) -> String {
if num == 0 {
return "0".to_owned();
}
let mut bytes = Vec::new();
while num > 0 {
bytes.push(ALPHABET[(num % BASE) as usize]);
num /= BASE
}
bytes.reverse();
String::from_utf8(bytes).unwrap()
}
pub fn decode(string: &str) -> Result<u128, DecodeError> {
let mut result = 0;
for (i, c) in string.as_bytes().iter().rev().enumerate() {
let num = BASE.pow(i as u32);
match ALPHABET.binary_search(c) {
Ok(v) => {
match (v as u128).checked_mul(num) {
Some(z) => result += z,
None => return Err(ArithmeticOverflow),
}
}
Err(_e) => {
return Err(InvalidBase62Byte(c.to_owned() as char, string.len() - i));
}
}
}
Ok(result)
}
#[cfg(test)]
mod tests {
use crate::base62;
#[test]
fn test_encode() {
assert_eq!(base62::encode(852751187393), "F0ob4rZ");
}
#[test]
fn test_decode() {
assert_eq!(base62::decode("F0ob4rZ").unwrap(), 852751187393);
}
#[test]
fn test_decode_invalid_char() {
assert!(base62::decode("ds{Z455f").is_err());
println!("{}", base62::decode("ds{Z455f").unwrap_err());
}
#[test]
fn test_decode_long_string() {
assert!(base62::decode("dsZ455fzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")
.is_err());
}
}