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
#![deny(missing_docs)]
use std::io;
const SHIFT: u8 = 5;
const MASK: u8 = (1 << SHIFT) - 1;
const CONTINUED: u8 = 1 << SHIFT;
#[derive(Debug)]
pub enum Error {
InvalidBase64,
IOError(io::Error),
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Error {
Error::IOError(e)
}
}
pub type Result<T> = std::result::Result<T, Error>;
fn decode64(input: u8) -> Result<u8> {
match input {
b'A'...b'Z' => Ok(input - b'A'),
b'a'...b'z' => Ok(input - b'a' + 26),
b'0'...b'9' => Ok(input - b'0' + 52),
b'+' => Ok(62),
b'-' => Ok(63),
_ => Err(Error::InvalidBase64)
}
}
pub fn decode(input: &mut io::Read) -> Result<i64> {
let mut accum = 0;
let mut shift = 0;
let mut keep_going = true;
while keep_going {
let mut byte = [0; 1];
input.read_exact(&mut byte[..])?;
let digit = decode64(byte[0])?;
keep_going = (digit & CONTINUED) != 0;
accum += ((digit & MASK) as u64) << shift;
shift += SHIFT;
}
let negate = (accum & 1) != 0;
accum >>= 1;
if negate {
accum = accum.wrapping_neg();
}
Ok(accum as i64)
}
fn encode64(value: u8) -> u8 {
debug_assert!(value < 64);
if value < 26 {
value + b'A'
} else if value < 52 {
value - 26 + b'a'
} else if value < 62 {
value - 52 + b'0'
} else if value == 62 {
b'+'
} else {
assert!(value == 63);
b'-'
}
}
pub fn encode(value: i64, output: &mut io::Write) -> io::Result<()> {
let signed = value < 0;
let mut value = (value.wrapping_abs() as u64) << 1;
if signed {
value |= 1;
}
loop {
let mut digit = value as u8 & MASK;
value >>= SHIFT;
if value > 0 {
digit |= CONTINUED;
}
let bytes = [encode64(digit)];
output.write_all(&bytes[..])?;
if value == 0 {
break;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
fn decode_tester_ok(input: &[u8], expect: i64) {
let mut cursor = ::io::Cursor::new(input);
match ::decode(&mut cursor) {
Ok(x) => {
assert_eq!(x, expect);
assert_eq!(cursor.position(), input.len() as u64);
},
_ => assert!(false)
}
}
#[test]
fn test_decode() {
decode_tester_ok("A".as_bytes(), 0);
decode_tester_ok("B".as_bytes(), 0);
decode_tester_ok("C".as_bytes(), 1);
decode_tester_ok("D".as_bytes(), -1);
}
#[test]
fn test_roundtrip() {
for val in -512..512 {
let mut buf = Vec::<u8>::new();
match ::encode(val, &mut buf) {
Ok(()) => assert!(buf.len() > 0),
_ => assert!(false)
}
decode_tester_ok(&buf, val);
}
}
}