|
11 | 11 | namespace node { |
12 | 12 | //// Base 64 //// |
13 | 13 | static inline constexpr size_t base64_encoded_size(size_t size) { |
14 | | - return ((size + 2 - ((size + 2) % 3)) / 3 * 4); |
| 14 | + return ((size + 2) / 3 * 4); |
15 | 15 | } |
16 | 16 |
|
17 | 17 | // Doesn't check for padding at the end. Can be 1-2 bytes over. |
18 | | -static inline size_t base64_decoded_size_fast(size_t size) { |
19 | | - size_t remainder = size % 4; |
20 | | - |
21 | | - size = (size / 4) * 3; |
22 | | - if (remainder) { |
23 | | - if (size == 0 && remainder == 1) { |
24 | | - // special case: 1-byte input cannot be decoded |
25 | | - size = 0; |
26 | | - } else { |
27 | | - // non-padded input, add 1 or 2 extra bytes |
28 | | - size += 1 + (remainder == 3); |
29 | | - } |
30 | | - } |
31 | | - |
32 | | - return size; |
| 18 | +static inline constexpr size_t base64_decoded_size_fast(size_t size) { |
| 19 | + // 1-byte input cannot be decoded |
| 20 | + return size > 1 ? (size / 4) * 3 + (size % 4 + 1) / 2 : 0; |
33 | 21 | } |
34 | 22 |
|
35 | 23 | template <typename TypeName> |
36 | 24 | size_t base64_decoded_size(const TypeName* src, size_t size) { |
37 | | - if (size == 0) |
| 25 | + // 1-byte input cannot be decoded |
| 26 | + if (size < 2) |
38 | 27 | return 0; |
39 | 28 |
|
40 | | - if (src[size - 1] == '=') |
| 29 | + if (src[size - 1] == '=') { |
41 | 30 | size--; |
42 | | - if (size > 0 && src[size - 1] == '=') |
43 | | - size--; |
44 | | - |
| 31 | + if (src[size - 1] == '=') |
| 32 | + size--; |
| 33 | + } |
45 | 34 | return base64_decoded_size_fast(size); |
46 | 35 | } |
47 | 36 |
|
@@ -166,25 +155,22 @@ static size_t base64_encode(const char* src, |
166 | 155 | k += 4; |
167 | 156 | } |
168 | 157 |
|
169 | | - if (n != slen) { |
170 | | - switch (slen - n) { |
171 | | - case 1: |
172 | | - a = src[i + 0] & 0xff; |
173 | | - dst[k + 0] = table[a >> 2]; |
174 | | - dst[k + 1] = table[(a & 3) << 4]; |
175 | | - dst[k + 2] = '='; |
176 | | - dst[k + 3] = '='; |
177 | | - break; |
178 | | - |
179 | | - case 2: |
180 | | - a = src[i + 0] & 0xff; |
181 | | - b = src[i + 1] & 0xff; |
182 | | - dst[k + 0] = table[a >> 2]; |
183 | | - dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; |
184 | | - dst[k + 2] = table[(b & 0x0f) << 2]; |
185 | | - dst[k + 3] = '='; |
186 | | - break; |
187 | | - } |
| 158 | + switch (slen - n) { |
| 159 | + case 1: |
| 160 | + a = src[i + 0] & 0xff; |
| 161 | + dst[k + 0] = table[a >> 2]; |
| 162 | + dst[k + 1] = table[(a & 3) << 4]; |
| 163 | + dst[k + 2] = '='; |
| 164 | + dst[k + 3] = '='; |
| 165 | + break; |
| 166 | + case 2: |
| 167 | + a = src[i + 0] & 0xff; |
| 168 | + b = src[i + 1] & 0xff; |
| 169 | + dst[k + 0] = table[a >> 2]; |
| 170 | + dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; |
| 171 | + dst[k + 2] = table[(b & 0x0f) << 2]; |
| 172 | + dst[k + 3] = '='; |
| 173 | + break; |
188 | 174 | } |
189 | 175 |
|
190 | 176 | return dlen; |
|
0 commit comments