Debian Codegraph @

.cargo/vendor/base64/src/engine/naive.rs

raw
1 use crate::{
2 alphabet::Alphabet,
3 engine::{
4 general_purpose::{self, decode_table, encode_table},
5 Config, DecodeEstimate, DecodeMetadata, DecodePaddingMode, Engine,
6 },
7 DecodeError, PAD_BYTE,
8 };
9 use std::ops::{BitAnd, BitOr, Shl, Shr};
10
11 /// Comparatively simple implementation that can be used as something to compare against in tests
12 pub struct Naive {
13 encode_table: [u8; 64],
14 decode_table: [u8; 256],
15 config: NaiveConfig,
16 }
17
18 impl Naive {
19 const ENCODE_INPUT_CHUNK_SIZE: usize = 3;
20 const DECODE_INPUT_CHUNK_SIZE: usize = 4;
21
22 pub const fn new(alphabet: &Alphabet, config: NaiveConfig) -> Self {
23 Self {
24 encode_table: encode_table(alphabet),
25 decode_table: decode_table(alphabet),
26 config,
27 }
28 }
29
30 fn decode_byte_into_u32(&self, offset: usize, byte: u8) -> Result<u32, DecodeError> {
31 let decoded = self.decode_table[byte as usize];
32
33 if decoded == general_purpose::INVALID_VALUE {
34 return Err(DecodeError::InvalidByte(offset, byte));
35 }
36
37 Ok(decoded as u32)
38 }
39 }
40
41 impl Engine for Naive {
42 type Config = NaiveConfig;
43 type DecodeEstimate = NaiveEstimate;
44
45 fn internal_encode(&self, input: &[u8], output: &mut [u8]) -> usize {
46 // complete chunks first
47
48 const LOW_SIX_BITS: u32 = 0x3F;
49
50 let rem = input.len() % Self::ENCODE_INPUT_CHUNK_SIZE;
51 // will never underflow
52 let complete_chunk_len = input.len() - rem;
53
54 let mut input_index = 0_usize;
55 let mut output_index = 0_usize;
56 if let Some(last_complete_chunk_index) =
57 complete_chunk_len.checked_sub(Self::ENCODE_INPUT_CHUNK_SIZE)
58 {
59 while input_index <= last_complete_chunk_index {
60 let chunk = &input[input_index..input_index + Self::ENCODE_INPUT_CHUNK_SIZE];
61
62 // populate low 24 bits from 3 bytes
63 let chunk_int: u32 =
64 (chunk[0] as u32).shl(16) | (chunk[1] as u32).shl(8) | (chunk[2] as u32);
65 // encode 4x 6-bit output bytes
66 output[output_index] = self.encode_table[chunk_int.shr(18) as usize];
67 output[output_index + 1] =
68 self.encode_table[chunk_int.shr(12_u8).bitand(LOW_SIX_BITS) as usize];
69 output[output_index + 2] =
70 self.encode_table[chunk_int.shr(6_u8).bitand(LOW_SIX_BITS) as usize];
71 output[output_index + 3] =
72 self.encode_table[chunk_int.bitand(LOW_SIX_BITS) as usize];
73
74 input_index += Self::ENCODE_INPUT_CHUNK_SIZE;
75 output_index += 4;
76 }
77 }
78
79 // then leftovers
80 if rem == 2 {
81 let chunk = &input[input_index..input_index + 2];
82
83 // high six bits of chunk[0]
84 output[output_index] = self.encode_table[chunk[0].shr(2) as usize];
85 // bottom 2 bits of [0], high 4 bits of [1]
86 output[output_index + 1] =
87 self.encode_table[(chunk[0].shl(4_u8).bitor(chunk[1].shr(4_u8)) as u32)
88 .bitand(LOW_SIX_BITS) as usize];
89 // bottom 4 bits of [1], with the 2 bottom bits as zero
90 output[output_index + 2] =
91 self.encode_table[(chunk[1].shl(2_u8) as u32).bitand(LOW_SIX_BITS) as usize];
92
93 output_index += 3;
94 } else if rem == 1 {
95 let byte = input[input_index];
96 output[output_index] = self.encode_table[byte.shr(2) as usize];
97 output[output_index + 1] =
98 self.encode_table[(byte.shl(4_u8) as u32).bitand(LOW_SIX_BITS) as usize];
99 output_index += 2;
100 }
101
102 output_index
103 }
104
105 fn internal_decoded_len_estimate(&self, input_len: usize) -> Self::DecodeEstimate {
106 NaiveEstimate::new(input_len)
107 }
108
109 fn internal_decode(
110 &self,
111 input: &[u8],
112 output: &mut [u8],
113 estimate: Self::DecodeEstimate,
114 ) -> Result<DecodeMetadata, DecodeError> {
115 if estimate.rem == 1 {
116 // trailing whitespace is so common that it's worth it to check the last byte to
117 // possibly return a better error message
118 if let Some(b) = input.last() {
119 if *b != PAD_BYTE
120 && self.decode_table[*b as usize] == general_purpose::INVALID_VALUE
121 {
122 return Err(DecodeError::InvalidByte(input.len() - 1, *b));
123 }
124 }
125
126 return Err(DecodeError::InvalidLength);
127 }
128
129 let mut input_index = 0_usize;
130 let mut output_index = 0_usize;
131 const BOTTOM_BYTE: u32 = 0xFF;
132
133 // can only use the main loop on non-trailing chunks
134 if input.len() > Self::DECODE_INPUT_CHUNK_SIZE {
135 // skip the last chunk, whether it's partial or full, since it might
136 // have padding, and start at the beginning of the chunk before that
137 let last_complete_chunk_start_index = estimate.complete_chunk_len
138 - if estimate.rem == 0 {
139 // Trailing chunk is also full chunk, so there must be at least 2 chunks, and
140 // this won't underflow
141 Self::DECODE_INPUT_CHUNK_SIZE * 2
142 } else {
143 // Trailing chunk is partial, so it's already excluded in
144 // complete_chunk_len
145 Self::DECODE_INPUT_CHUNK_SIZE
146 };
147
148 while input_index <= last_complete_chunk_start_index {
149 let chunk = &input[input_index..input_index + Self::DECODE_INPUT_CHUNK_SIZE];
150 let decoded_int: u32 = self.decode_byte_into_u32(input_index, chunk[0])?.shl(18)
151 | self
152 .decode_byte_into_u32(input_index + 1, chunk[1])?
153 .shl(12)
154 | self.decode_byte_into_u32(input_index + 2, chunk[2])?.shl(6)
155 | self.decode_byte_into_u32(input_index + 3, chunk[3])?;
156
157 output[output_index] = decoded_int.shr(16_u8).bitand(BOTTOM_BYTE) as u8;
158 output[output_index + 1] = decoded_int.shr(8_u8).bitand(BOTTOM_BYTE) as u8;
159 output[output_index + 2] = decoded_int.bitand(BOTTOM_BYTE) as u8;
160
161 input_index += Self::DECODE_INPUT_CHUNK_SIZE;
162 output_index += 3;
163 }
164 }
165
166 general_purpose::decode_suffix::decode_suffix(
167 input,
168 input_index,
169 output,
170 output_index,
171 &self.decode_table,
172 self.config.decode_allow_trailing_bits,
173 self.config.decode_padding_mode,
174 )
175 }
176
177 fn config(&self) -> &Self::Config {
178 &self.config
179 }
180 }
181
182 pub struct NaiveEstimate {
183 /// remainder from dividing input by `Naive::DECODE_CHUNK_SIZE`
184 rem: usize,
185 /// Length of input that is in complete `Naive::DECODE_CHUNK_SIZE`-length chunks
186 complete_chunk_len: usize,
187 }
188
189 impl NaiveEstimate {
190 fn new(input_len: usize) -> Self {
191 let rem = input_len % Naive::DECODE_INPUT_CHUNK_SIZE;
192 let complete_chunk_len = input_len - rem;
193
194 Self {
195 rem,
196 complete_chunk_len,
197 }
198 }
199 }
200
201 impl DecodeEstimate for NaiveEstimate {
202 fn decoded_len_estimate(&self) -> usize {
203 ((self.complete_chunk_len / 4) + ((self.rem > 0) as usize)) * 3
204 }
205 }
206
207 #[derive(Clone, Copy, Debug)]
208 pub struct NaiveConfig {
209 pub encode_padding: bool,
210 pub decode_allow_trailing_bits: bool,
211 pub decode_padding_mode: DecodePaddingMode,
212 }
213
214 impl Config for NaiveConfig {
215 fn encode_padding(&self) -> bool {
216 self.encode_padding
217 }
218 }