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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
pub const ALPHABET: &'static str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
pub enum Error {
UnknownSymbol(usize),
}
impl ::std::fmt::Display for Error {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match self {
&Error::UnknownSymbol(idx) => write!(f, "Unknown symbol at byte index {}", idx),
}
}
}
impl ::std::error::Error for Error {}
pub type Result<T> = ::std::result::Result<T, Error>;
pub fn encode(input: &[u8]) -> String {
String::from_utf8(base_encode(ALPHABET, input)).unwrap()
}
pub fn decode(input: &str) -> Result<Vec<u8>> {
base_decode(ALPHABET, input.as_bytes())
}
#[cfg(test)]
mod tests {
fn encode(input: &[u8], expected: &str) {
let encoded = super::encode(input);
assert_eq!(encoded, expected);
}
fn decode(expected: &[u8], input: &str) {
let decoded = super::decode(input).unwrap();
assert_eq!(decoded.as_slice(), expected);
}
#[test]
fn test_vector_1() {
encode(b"\0\0\0\0", "11111");
decode(b"\0\0\0\0", "11111");
}
#[test]
fn test_vector_2() {
encode(b"This is awesome!", "BRY7dK2V98Sgi7CFWiZbap");
decode(b"This is awesome!", "BRY7dK2V98Sgi7CFWiZbap");
}
#[test]
fn test_vector_3() {
encode(b"Hello World...", "TcgsE5dzphUWfjcb9i5");
decode(b"Hello World...", "TcgsE5dzphUWfjcb9i5");
}
#[test]
fn test_vector_4() {
encode(b"\0abc", "1ZiCa");
decode(b"\0abc", "1ZiCa");
}
#[test]
fn test_vector_5() {
encode(b"\0\0abc", "11ZiCa");
decode(b"\0\0abc", "11ZiCa");
}
#[test]
fn test_vector_6() {
encode(b"\0\0\0abc", "111ZiCa");
decode(b"\0\0\0abc", "111ZiCa");
}
#[test]
fn test_vector_7() {
encode(b"\0\0\0\0abc", "1111ZiCa");
decode(b"\0\0\0\0abc", "1111ZiCa");
}
#[test]
fn test_vector_8() {
encode(
b"abcdefghijklmnopqrstuvwxyz",
"3yxU3u1igY8WkgtjK92fbJQCd4BZiiT1v25f",
);
decode(
b"abcdefghijklmnopqrstuvwxyz",
"3yxU3u1igY8WkgtjK92fbJQCd4BZiiT1v25f",
);
}
}
fn base_encode(alphabet_s: &str, input: &[u8]) -> Vec<u8> {
let alphabet = alphabet_s.as_bytes();
let base = alphabet.len() as u32;
let mut digits = vec![0 as u8];
for input in input.iter() {
let mut carry = input.clone() as u32;
for j in 0..digits.len() {
carry = carry + ((digits[j] as u32) << 8);
digits[j] = (carry % base) as u8;
carry = carry / base;
}
while carry > 0 {
digits.push((carry % base) as u8);
carry = carry / base;
}
}
let mut string = vec![];
let mut k = 0;
while (k < input.len()) && (input[k] == 0) {
string.push(alphabet[0]);
k += 1;
}
for digit in digits.iter().rev() {
string.push(alphabet[digit.clone() as usize]);
}
string
}
fn base_decode(alphabet_s: &str, input: &[u8]) -> Result<Vec<u8>> {
let alphabet = alphabet_s.as_bytes();
let base = alphabet.len() as u32;
let mut bytes: Vec<u8> = vec![0];
let zcount = input.iter().take_while(|x| **x == alphabet[0]).count();
for i in zcount..input.len() {
let value = match alphabet.iter().position(|&x| x == input[i]) {
Some(idx) => idx,
None => return Err(Error::UnknownSymbol(i)),
};
let mut carry = value as u32;
for j in 0..bytes.len() {
carry = carry + (bytes[j] as u32 * base);
bytes[j] = carry as u8;
carry = carry >> 8;
}
while carry > 0 {
bytes.push(carry as u8);
carry = carry >> 8;
}
}
let leading_zeros = bytes.iter().rev().take_while(|x| **x == 0).count();
if zcount > leading_zeros {
if leading_zeros > 0 {
for _ in 0..(zcount - leading_zeros - 1) {
bytes.push(0);
}
} else {
for _ in 0..zcount {
bytes.push(0);
}
}
}
bytes.reverse();
Ok(bytes)
}