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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
use core::fmt;
use core::marker::PhantomData;
use core::mem;
use crate::step::{In, Out, Over};
use crate::then::{Then, Cont, Done, Fail};
use crate::input::{Input, AsInput};
use crate::output::{Output, IntoOutput};
use crate::decoder::Decoder;
use crate::encoder::Encoder;

pub trait DecodeBase64: Sized {
    fn decode_base64_input<I>(input: &mut I) -> Result<Self, Base64Error> where I: Input<Token=char>;

    fn decode_base64(string: &str) -> Result<Self, Base64Error> {
        Self::decode_base64_input(&mut string.as_input())
    }
}

pub trait EncodeBase64 {
    fn encode_base64_output<O>(&self, output: O, alphabet: Base64Alphabet)
        -> Result<O::Out, O::Err> where O: Output<Token=char>;

    fn encode_base64<I, O>(&self, output: I) -> O::Out
        where I: IntoOutput<IntoOut=O>, O: Output<Token=char>, O::Err: fmt::Debug {
        let output = output.into_output();
        self.encode_base64_output(output, Base64).unwrap()
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Base64Alphabet {
    Base64,
    Base64Url,
}
pub use self::Base64Alphabet::{Base64, Base64Url};

impl Base64Alphabet {
    pub fn as_str(self) -> &'static [u8; 64] {
        let alphabet = match self {
            Base64    => "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
            Base64Url => "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
        };
        unsafe { mem::transmute(alphabet.as_ptr()) }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Base64Error {
    Unexpected,
    Unpadded,
}

pub struct Base64Decoder<I: Input<Token=char>, O: Output<Token=u8>> {
    pub output: O,
    p: u8,
    q: u8,
    r: u8,
    padded: bool,
    state: u32,
    input: PhantomData<I>,
}

pub struct Base64Encoder<I: Input<Token=u8>, O: Output<Token=char>> {
    alphabet: &'static [u8; 64],
    pub input: I,
    x: u8,
    y: u8,
    z: u8,
    padded: bool,
    state: u32,
    output: PhantomData<O>,
}

impl<I, O> Base64Decoder<I, O> where I: Input<Token=char>, O: Output<Token=u8> {
    pub fn new(output: O) -> Self {
        Self {
            output: output,
            p: 0,
            q: 0,
            r: 0,
            padded: true,
            state: 1,
            input: PhantomData,
        }
    }

    pub fn padded(mut self, padded: bool) -> Self {
        self.padded = padded;
        self
    }

    pub fn consume(mut self, input: &mut I) -> Result<O::Out, Base64Error> where O::Err: fmt::Debug {
        loop {
            match self.decode(input) {
                Done(output) => return Ok(output),
                Fail(error) => return Err(error),
                Cont(next) => {
                    if input.is_out() {
                        input.over();
                        self = next;
                    } else {
                        return Err(Base64Error::Unexpected);
                    }
                },
            }
        }
    }
}

impl<I, O> Decoder for Base64Decoder<I, O>
    where I: Input<Token=char>,
          O: Output<Token=u8>,
          O::Err: fmt::Debug {

    type Input = I;
    type Output = O::Out;
    type Error = Base64Error;

    fn decode(mut self, input: &mut I) -> Then<Self, O::Out, Base64Error> {
        loop {
            match self.state {
                1 => {
                    match input.head() {
                        In(c) if is_base64_char(c) => {
                            input.step();
                            self.p = decode_base64_char(c);
                            self.state = 2;
                        },
                        In(_) | Over => return Done(self.output.take_out().unwrap()),
                        Out => return Cont(self),
                    };
                },
                2 => {
                    match input.head() {
                        In(c) if is_base64_char(c) => {
                            input.step();
                            self.q = decode_base64_char(c);
                            self.state = 3;
                        },
                        In(_) | Over => return Fail(Base64Error::Unexpected),
                        Out => return Cont(self),
                    };
                },
                3 => {
                    match input.head() {
                        In(c) if is_base64_char(c) || c == '=' => {
                            input.step();
                            self.r = decode_base64_char(c);
                            if c != '=' {
                                self.state = 4;
                            } else {
                                self.state = 5;
                            }
                        },
                        In(_) | Over if !self.padded => {
                            decode_base64_quantum(self.p, self.q, 255, 255, &mut self.output);
                            return Done(self.output.take_out().unwrap());
                        },
                        In(_) | Over => return Fail(Base64Error::Unpadded),
                        Out => return Cont(self),
                    };
                },
                4 => {
                    match input.head() {
                        In(c) if is_base64_char(c) || c == '=' => {
                            input.step();
                            let s = decode_base64_char(c);
                            decode_base64_quantum(self.p, self.q, self.r, s, &mut self.output);
                            self.r = 0;
                            self.q = 0;
                            self.p = 0;
                            if c != '=' {
                                self.state = 1;
                            } else {
                                return Done(self.output.take_out().unwrap());
                            }
                        },
                        In(_) | Over if !self.padded => {
                            decode_base64_quantum(self.p, self.q, self.r, 255, &mut self.output);
                            return Done(self.output.take_out().unwrap());
                        }
                        In(_) | Over => return Fail(Base64Error::Unpadded),
                        Out => return Cont(self),
                    };
                },
                5 => {
                    match input.head() {
                        In('=') => {
                            input.step();
                            decode_base64_quantum(self.p, self.q, self.r, 255, &mut self.output);
                            self.r = 0;
                            self.q = 0;
                            self.p = 0;
                            return Done(self.output.take_out().unwrap());
                        },
                        In(_) | Over => return Fail(Base64Error::Unpadded),
                        Out => return Cont(self),
                    }
                },
                _ => unreachable!(),
            };
        }
    }
}

impl<I, O> Base64Encoder<I, O> where I: Input<Token=u8>, O: Output<Token=char> {
    pub fn new(input: I, alphabet: Base64Alphabet) -> Self {
        Self {
            alphabet: alphabet.as_str(),
            input: input,
            x: 0,
            y: 0,
            z: 0,
            padded: true,
            state: 1,
            output: PhantomData,
        }
    }

    pub fn padded(mut self, padded: bool) -> Self {
        self.padded = padded;
        self
    }

    pub fn produce(mut self, mut output: O) -> Result<O::Out, O::Err> {
        loop {
            match self.encode(&mut output) {
                Done(_) => return output.take_out(),
                Fail(_) => unreachable!(),
                Cont(next) => {
                    self = next;
                    self.input.over();
                }
            }
        }
    }

    fn encode_base64_digit(&self, x: u8) -> char {
        debug_assert!(x < 64);
        unsafe { (*self.alphabet.get_unchecked(x as usize)) as char }
    }
}

impl<I, O> Encoder for Base64Encoder<I, O> where I: Input<Token=u8>, O: Output<Token=char> {
    type Input = I;
    type Output = O;
    type Error = ();

    fn encode(mut self, output: &mut O) -> Then<Self, I, ()> {
        while !output.is_full() {
            match self.state {
                1 => {
                    match self.input.head() {
                        In(x) => {
                            self.input.step();
                            self.x = x;
                            self.state = 2;
                            output.push(self.encode_base64_digit(x >> 2));
                        },
                        Over => return Done(self.input),
                        Out => break,
                    };
                },
                2 => {
                    match self.input.head() {
                        In(y) => {
                            self.input.step();
                            self.y = y;
                            self.state = 3;
                            output.push(self.encode_base64_digit((self.x << 4 | y >> 4) & 0x3F));
                        },
                        Over => {
                            output.push(self.encode_base64_digit(self.x << 4 & 0x3F));
                            if self.padded {
                                self.state = 5;
                            } else {
                                return Done(self.input);
                            }
                        },
                        Out => break,
                    };
                },
                3 => {
                    match self.input.head() {
                        In(z) => {
                            self.input.step();
                            self.z = z;
                            self.state = 4;
                            output.push(self.encode_base64_digit((self.y << 2 | z >> 6) & 0x3F));
                        },
                        Over => {
                            output.push(self.encode_base64_digit(self.y << 2 & 0x3F));
                            if self.padded {
                                self.state = 6;
                            } else {
                                return Done(self.input);
                            }
                        },
                        Out => break,
                    }
                },
                4 => {
                    output.push(self.encode_base64_digit(self.z & 0x3F));
                    self.z = 0;
                    self.y = 0;
                    self.x = 0;
                    self.state = 1;
                },
                5 => {
                    output.push('=');
                    self.state = 6;
                },
                6 => {
                    output.push('=');
                    return Done(self.input);
                },
                _ => unreachable!(),
            };
        }
        return Cont(self);
    }
}

#[inline]
fn is_base64_char(c: char) -> bool {
    c >= '0' && c <= '9' ||
    c >= 'A' && c <= 'Z' ||
    c >= 'a' && c <= 'z' ||
    c == '+' || c == '-' ||
    c == '/' || c == '_'
}

#[inline]
fn decode_base64_char(c: char) -> u8 {
    if c >= 'A' && c <= 'Z' {
        c as u8 - 'A' as u8
    } else if c >= 'a' && c <= 'z' {
        26 + (c as u8 - 'a' as u8)
    } else if c >= '0' && c <= '9' {
        52 + (c as u8 - '0' as u8)
    } else if c == '+' || c == '-' {
        62
    } else if c == '/' || c == '_' {
        63
    } else if c == '=' {
        255
    } else {
      unreachable!()
    }
}

fn decode_base64_quantum<O>(p: u8, q: u8, r: u8, s: u8, output: &mut O)
    where O: Output<Token=u8> {
    if r < 64 {
        if s < 64 {
            output.push(p << 2 | q >> 4);
            output.push(q << 4 | r >> 2);
            output.push(r << 6 | s);
        } else {
            output.push(p << 2 | q >> 4);
            output.push(q << 4 | r >> 2);
        }
    } else {
        debug_assert_eq!(s, 255);
        output.push((p << 2) | (q >> 4));
    }
}

#[cfg(test)]
mod tests {
    use crate::output::{SliceOutput, StrOutput};
    use super::*;

    fn assert_transcodes(encoded: &str, decoded: &[u8]) {
        let mut buffer = [0u8; 1024];
        let decoder = Base64Decoder::new(SliceOutput::new(&mut buffer));
        assert_eq!(decoder.consume(&mut encoded.as_input()).unwrap(), decoded);
        let mut buffer = [0u8; 1024];
        let encoder = Base64Encoder::new(decoded.as_input(), Base64);
        assert_eq!(encoder.produce(StrOutput::new(&mut buffer)).unwrap(), encoded);
    }

    #[test]
    fn test_base64_transcode() {
        assert_transcodes("AA==", &[0]);
        assert_transcodes("AAA=", &[0, 0]);
        assert_transcodes("AAAA", &[0, 0, 0]);
        assert_transcodes("+w==", &[251]);
        assert_transcodes("++8=", &[251, 239]);
        assert_transcodes("++++", &[251, 239, 190]);
        assert_transcodes("ABCDabcd12/+", &[0, 16, 131, 105, 183, 29, 215, 111, 254]);
        assert_transcodes("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/+",
                          &[0, 16, 131, 16, 81, 135, 32, 146, 139, 48, 211, 143, 65, 20,
                            147, 81, 85, 151, 97, 150, 155, 113, 215, 159, 130, 24, 163,
                            146, 89, 167, 162, 154, 171, 178, 219, 175, 195, 28, 179, 211,
                            93, 183, 227, 158, 187, 243, 223, 254]);
    }
}