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
pub use error::DecodeError;
#[allow(missing_debug_implementations)]
pub struct DecodeBuilder<'a, I: AsRef<[u8]>> {
input: I,
alpha: &'a [u8; 58],
}
impl<'a, I: AsRef<[u8]>> DecodeBuilder<'a, I> {
pub fn new(input: I, alpha: &'a [u8; 58]) -> DecodeBuilder<'a, I> {
DecodeBuilder { input: input, alpha: alpha }
}
#[allow(needless_lifetimes)]
pub fn with_alphabet<'b>(self, alpha: &'b [u8; 58]) -> DecodeBuilder<'b, I> {
DecodeBuilder { input: self.input, alpha: alpha }
}
pub fn into_vec(self) -> Result<Vec<u8>, DecodeError> {
let input = self.input.as_ref();
let mut output = vec![0; (input.len() / 8 + 1) * 6];
decode_into(input, &mut output, self.alpha)
.map(|len| { output.truncate(len); output })
}
pub fn into<O: AsMut<[u8]>>(self, mut output: O) -> Result<usize, DecodeError> {
decode_into(self.input.as_ref(), output.as_mut(), self.alpha)
}
}
pub fn decode_into(input: &[u8], output: &mut [u8], alpha: &[u8; 58]) -> Result<usize, DecodeError> {
let mut index = 0;
let zero = alpha[0];
let alpha = {
let mut rev = [0xFF; 128];
for (i, &c) in alpha.iter().enumerate() {
rev[c as usize] = i as u8;
}
rev
};
for (i, c) in input.iter().enumerate() {
if *c > 127 {
return Err(DecodeError::NonAsciiCharacter { index: i });
}
let mut val = unsafe { *alpha.get_unchecked(*c as usize) as usize };
if val == 0xFF {
return Err(DecodeError::InvalidCharacter { character: *c as char, index: i });
} else {
for byte in &mut output[..index] {
val += (*byte as usize) * 58;
*byte = (val & 0xFF) as u8;
val >>= 8;
}
while val > 0 {
let byte = output.get_mut(index).ok_or(DecodeError::BufferTooSmall)?;
*byte = (val & 0xFF) as u8;
index += 1;
val >>= 8
}
}
}
for c in input {
if *c == zero {
let byte = output.get_mut(index).ok_or(DecodeError::BufferTooSmall)?;
*byte = 0;
index += 1;
} else {
break;
}
}
output[..index].reverse();
Ok(index)
}
#[cfg(test)]
mod tests {
use decode;
use decode::DecodeError;
#[test]
fn tests() {
for &(val, s) in super::super::TEST_CASES.iter() {
assert_eq!(val.to_vec(), decode(s).into_vec().unwrap());
}
}
#[test]
fn test_small_buffer_err() {
let mut output = [0; 2];
assert_eq!(decode("a3gV").into(&mut output), Err(DecodeError::BufferTooSmall));
}
}