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
/*
==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--

Debt64

Copyright (C) 2018-2019, 2021-2023  Anonymous

There are several releases over multiple years,
they are listed as ranges, such as: "2018-2019".

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
*/

//! Decoder

use {
    alloc::vec::Vec,
    crate::Result,
    super::{Debt64, LastChars},
};

/// # Decoder
struct Decoder<'a> {
    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,
}

impl<'a> Decoder<'a> {

    /// # 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,
        }
    }

    /// # Decodes bits
    fn decode_bits(&mut self) -> Result<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'=' => return if self.index > 1 && self.must_or_can_use_pad {
                    Ok(Some((0, true)))
                } else {
                    Err(err!("Invalid pad char: '='"))
                },
                b'\r' | b'\n' | b' ' => if self.allows_line_separators {
                    match byte {
                        b' ' => (),
                        b'\r' => {
                            if self.index >= self.len || self.bytes[self.index] != b'\n' {
                                return Err(err!("Invalid line separator: {:?}", &byte));
                            }
                            self.index += 1;
                        },
                        _ => (),
                    };
                    // Peek next byte, don't consume it
                    if self.index < self.len {
                        if matches!(self.bytes[self.index], b'\r' | b'\n') {
                            return Err(err!("Duplicate line separators"));
                        }
                    } else {
                        return Ok(None);
                    };
                } else {
                    return Err(err!("Invalid line separator: {:02x}", byte));
                },
                _ => {
                    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 {
                        if self.allows_invalid_chars == false {
                            return Err(err!("Invalid byte: {:?}", byte));
                        }
                    }
                },
            };
        }
    }

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

}

/// # Decodes
pub (super) fn decode<B>(bytes: B, debt64: &Debt64) -> Result<Vec<u8>> where B: AsRef<[u8]> {
    let bytes = bytes.as_ref();

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

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

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

    Ok(result)
}