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
// License: see LICENSE file at root directory of `master` branch

//! Decoder

use alloc::vec::Vec;
use core::marker::PhantomData;
use crate::{Error, Result};
use super::{Kind, LastChars};

/// # Decoder
///
/// ## Lifetimes
///
/// - `'a` is used for input data.
/// - `'e` is used for returning errors.
struct Decoder<'a, 'e> {
    bytes: &'a [u8],
    index: usize,
    len: usize,
    allows_line_separators: bool,
    must_or_can_use_pad: bool,
    allows_invalid_chars: bool,
    last_chars: &'a LastChars,
    phantom_data: PhantomData<&'e ()>,
}

impl<'a, 'e> Decoder<'a, 'e> {

    /// # Makes new instance
    fn new(bytes: &'a [u8], allows_line_separators: bool, must_or_can_use_pad: bool, allows_invalid_chars: bool, last_chars: &'a LastChars)
    -> Self {
        Self {
            bytes,
            index: 0,
            len: bytes.len(),
            allows_line_separators,
            must_or_can_use_pad,
            allows_invalid_chars,
            last_chars,
            phantom_data: PhantomData,
        }
    }

    /// # Decodes bits
    fn decode_bits(&mut self) -> Result<'e, Option<(u8, bool)>> {
        loop {
            if self.index >= self.len {
                return Ok(None);
            }

            let byte = self.bytes[self.index];
            self.index += 1;

            match byte {
                b'A'...b'Z' => return Ok(Some((byte - b'A', false))),
                b'a'...b'z' => return Ok(Some((byte - b'a' + 26, false))),
                b'0'...b'9' => return Ok(Some((byte - b'0' + 52, false))),
                b'=' => match self.index > 1 && self.must_or_can_use_pad {
                    true => return Ok(Some((0, true))),
                    false => return Err(Error::new("Invalid pad char: '='").into()),
                },
                b'\r' | b'\n' | b' ' => match self.allows_line_separators {
                    true => {
                        match byte {
                            b' ' => (),
                            b'\r' => {
                                if self.index >= self.len || self.bytes[self.index] != b'\n' {
                                    return Err(Error::new(alloc::format!("Invalid line separator: {:?}", &byte)).into());
                                }
                                self.index += 1;
                            },
                            _ => (),
                        };
                        // Peek next byte, don't consume it
                        match self.index < self.len {
                            true => match self.bytes[self.index] {
                                b'\r' | b'\n' => return Err(Error::new("Duplicate line separators").into()),
                                _ => (),
                            },
                            false => return Ok(None),
                        };
                    },
                    false => return Err(Error::new(alloc::format!("Invalid line separator: {:02x}", byte)).into()),
                },
                _ => {
                    if self.last_chars.first == byte as char {
                        return Ok(Some((62, false)));
                    } else if self.last_chars.last == byte as char {
                        return Ok(Some((63, false)));
                    } else {
                        match self.allows_invalid_chars {
                            true => (),
                            false => return Err(Error::new(alloc::format!("Invalid byte: {:?}", byte)).into()),
                        };
                    }
                },
            };
        }
    }

    /// # Checks if there are more bytes
    fn has_more_bytes(&self) -> bool {
        self.index < self.len
    }

}

/// # Decodes
pub fn decode<'a, B>(bytes: B, kind: Kind) -> Result<'a, Vec<u8>> where B: AsRef<[u8]> {
    let bytes = bytes.as_ref();

    let mut result = Vec::with_capacity(kind.estimate_decoding_capacity(bytes));

    let must_use_pad = kind.must_use_pad();
    let mut decoder = Decoder::new(
        bytes, kind.line_separators().is_some(), must_use_pad || kind.can_use_pad(), kind.allows_invalid_chars(), kind.last_chars()
    );

    loop {
        let first_bits = match decoder.decode_bits()? {
            Some((first_bits, is_pad_char)) => match is_pad_char {
                true => return Err(Error::new("Invalid pad character at first byte").into()),
                false => first_bits,
            },
            None => break,
        };
        let second_bits = match decoder.decode_bits()? {
            Some((second_bits, is_pad_char)) => match is_pad_char {
                true => return Err(Error::new("Invalid pad character at second byte").into()),
                false => {
                    result.push((first_bits << 2) | (second_bits >> 4));
                    second_bits
                },
            },
            None => return Err(Error::new("Missing second byte").into()),
        };
        let (third_bits, third_byte_is_pad_char) = match decoder.decode_bits()? {
            Some((third_bits, is_pad_char)) => {
                if is_pad_char == false {
                    result.push((second_bits << 4) | (third_bits >> 2));
                }
                (third_bits, is_pad_char)
            },
            None => match must_use_pad {
                true => return Err(Error::new("Missing pad char '=' for third byte").into()),
                false => break,
            },
        };
        match decoder.decode_bits()? {
            Some((fourth_bits, is_pad_char)) => {
                match third_byte_is_pad_char {
                    true => if is_pad_char == false {
                        return Err(Error::new("Invalid character after first pad character").into());
                    },
                    false => if is_pad_char == false {
                        result.push((third_bits << 6) | fourth_bits);
                    },
                };
                if is_pad_char {
                    match decoder.has_more_bytes() {
                        true => return Err(Error::new("Invalid character after ending").into()),
                        false => break,
                    };
                }
            },
            None => match must_use_pad {
                true => return Err(Error::new("Missing pad char '=' for fourth byte").into()),
                false => break,
            },
        };
    }

    Ok(result)
}

/// # Decodes bytes via [`Standard`][debt64::Kind::Standard]
///
/// [debt64::Kind::Standard]: enum.Kind.html#variant.Standard
pub fn decode_standard<'a, B>(bytes: B) -> Result<'a, Vec<u8>> where B: AsRef<[u8]> {
    decode(bytes, Kind::Standard)
}

/// # Decodes bytes via [`IMAP`][debt64::Kind::IMAP]
///
/// [debt64::Kind::IMAP]: enum.Kind.html#variant.IMAP
pub fn decode_imap<'a, B>(bytes: B) -> Result<'a, Vec<u8>> where B: AsRef<[u8]> {
    decode(bytes, Kind::IMAP)
}

/// # Decodes bytes via [`MIME`][debt64::Kind::MIME]
///
/// [debt64::Kind::MIME]: enum.Kind.html#variant.MIME
pub fn decode_mime<'a, B>(bytes: B) -> Result<'a, Vec<u8>> where B: AsRef<[u8]> {
    decode(bytes, Kind::MIME)
}

/// # Decodes bytes via [`URL`][debt64::Kind::URL]
///
/// [debt64::Kind::URL]: enum.Kind.html#variant.URL
pub fn decode_url<'a, B>(bytes: B) -> Result<'a, Vec<u8>> where B: AsRef<[u8]> {
    decode(bytes, Kind::URL)
}

/// # Decodes bytes via [`FreenetURL`][debt64::Kind::FreenetURL]
///
/// [debt64::Kind::FreenetURL]: enum.Kind.html#variant.FreenetURL
pub fn decode_freenet_url<'a, B>(bytes: B) -> Result<'a, Vec<u8>> where B: AsRef<[u8]> {
    decode(bytes, Kind::FreenetURL)
}