authorgravatar for 124872+jedisct1@users.noreply.github.comFrank Denis <124872+jedisct1@users.noreply.github.com> 2021-03-19 19:26:30+01:00
committergravatar for 124872+jedisct1@users.noreply.github.comFrank Denis <124872+jedisct1@users.noreply.github.com> 2021-03-28 14:32:34+02:00
logb8c019ef49be54d76acc6721d5d8d493193bcf5d
treef6607c0cc2f6c31736da8bb59b838f13506684dc
parentab9324e604068d4afb4e65a8e587bea95ab1051a

std/base64: cleanups & support url-safe and other non-padded variants

This makes a few changes to the base64 codecs. * The padding character is optional. The common "URL-safe" variant, in particular, is generally not used with padding. This is also the case for password hashes, so having this will avoid code duplication with bcrypt, scrypt and other functions. * The URL-safe variant is added. Instead of having individual constants for each parameter of each variant, we are now grouping these in a struct. So, `standard_pad_char` just becomes `standard.pad_char`. * Types are not `snake_case`'d any more. So, `standard_encoder` becomes `standard.Encoder`, as it is a type. * Creating a decoder with ignored characters required the alphabet and padding. Now, `standard.decoderWithIgnore(<ignored chars>)` returns a decoder with the standard parameters and the set of ignored chars. * Whatever applies to `standard.*` obviously also works with `url_safe.*` * the `calcSize()` interface was inconsistent, taking a length in the encoder, and a slice in the encoder. Rename the variant that takes a slice to `calcSizeForSlice()`. * In the decoder with ignored characters, add `calcSizeUpperBound()`, which is more useful than the one that takes a slice in order to size a fixed buffer before we have the data. * Return `error.InvalidCharacter` when the input actually contains characters that are neither padding nor part of the alphabet. If we hit a padding issue (which includes extra bits at the end), consistently return `error.InvalidPadding`. * Don't keep the `char_in_alphabet` array permanently in a decoder; it is only required for sanity checks during initialization. * Tests are unchanged, but now cover both the standard (padded) and the url-safe (non-padded) variants. * Add an error set, rename `OutputTooSmallError` to `NoSpaceLeft` to match the `hex2bin` equivalent.

5 files changed, 337 insertions(+), 275 deletions(-)

doc/langref.html.in+2-2
......@@ -9952,8 +9952,8 @@ export fn decode_base_64(
99529952) usize {
99539953 const src = source_ptr[0..source_len];
99549954 const dest = dest_ptr[0..dest_len];
9955 const base64_decoder = base64.standard_decoder_unsafe;
9956 const decoded_size = base64_decoder.calcSize(src);
9955 const base64_decoder = base64.standard.DecoderUnsafe;
9956 const decoded_size = base64_decoder.calcSizeForSlice(src) catch unreachable;
99579957 base64_decoder.decode(dest[0..decoded_size], src);
99589958 return decoded_size;
99599959}
lib/std/base64.zig+327-265
......@@ -8,308 +8,339 @@ const assert = std.debug.assert;
88const testing = std.testing;
99const mem = std.mem;
1010
11pub const standard_alphabet_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
12pub const standard_pad_char = '=';
13pub const standard_encoder = Base64Encoder.init(standard_alphabet_chars, standard_pad_char);
11pub const Error = error{
12 InvalidCharacter,
13 InvalidPadding,
14 NoSpaceLeft,
15};
16
17/// Base64 codecs
18pub const Codecs = struct {
19 alphabet_chars: [64]u8,
20 pad_char: ?u8,
21 decoderWithIgnore: fn (ignore: []const u8) Base64DecoderWithIgnore,
22 Encoder: Base64Encoder,
23 Decoder: Base64Decoder,
24 DecoderUnsafe: Base64DecoderUnsafe,
25};
26
27pub const standard_alphabet_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".*;
28fn standardBase64DecoderWithIgnore(ignore: []const u8) Base64DecoderWithIgnore {
29 return Base64DecoderWithIgnore.init(standard_alphabet_chars, '=', ignore);
30}
31
32/// Standard Base64 codecs, with padding
33pub const standard = Codecs{
34 .alphabet_chars = standard_alphabet_chars,
35 .pad_char = '=',
36 .decoderWithIgnore = standardBase64DecoderWithIgnore,
37 .Encoder = Base64Encoder.init(standard_alphabet_chars, '='),
38 .Decoder = Base64Decoder.init(standard_alphabet_chars, '='),
39 .DecoderUnsafe = Base64DecoderUnsafe.init(standard_alphabet_chars, '='),
40};
41
42pub const url_safe_alphabet_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".*;
43fn urlSafeBase64DecoderWithIgnore(ignore: []const u8) Base64DecoderWithIgnore {
44 return Base64DecoderWithIgnore.init(url_safe_alphabet_chars, null, ignore);
45}
46
47/// URL-safe Base64 codecs, without padding
48pub const url_safe = Codecs{
49 .alphabet_chars = url_safe_alphabet_chars,
50 .pad_char = null,
51 .decoderWithIgnore = urlSafeBase64DecoderWithIgnore,
52 .Encoder = Base64Encoder.init(url_safe_alphabet_chars, null),
53 .Decoder = Base64Decoder.init(url_safe_alphabet_chars, null),
54 .DecoderUnsafe = Base64DecoderUnsafe.init(url_safe_alphabet_chars, null),
55};
56
57// Backwards compatibility
58
59/// Deprecated - Use `standard.pad_char`
60pub const standard_pad_char = standard.pad_char;
61/// Deprecated - Use `standard.Encoder`
62pub const standard_encoder = standard.Encoder;
63/// Deprecated - Use `standard.Decoder`
64pub const standard_decoder = standard.Decoder;
65/// Deprecated - Use `standard.DecoderUnsafe`
66pub const standard_decoder_unsafe = standard.DecoderUnsafe;
1467
1568pub const Base64Encoder = struct {
16 alphabet_chars: []const u8,
17 pad_char: u8,
69 alphabet_chars: [64]u8,
70 pad_char: ?u8,
1871
19 /// a bunch of assertions, then simply pass the data right through.
20 pub fn init(alphabet_chars: []const u8, pad_char: u8) Base64Encoder {
72 /// A bunch of assertions, then simply pass the data right through.
73 pub fn init(alphabet_chars: [64]u8, pad_char: ?u8) Base64Encoder {
2174 assert(alphabet_chars.len == 64);
2275 var char_in_alphabet = [_]bool{false} ** 256;
2376 for (alphabet_chars) |c| {
2477 assert(!char_in_alphabet[c]);
25 assert(c != pad_char);
78 assert(pad_char == null or c != pad_char.?);
2679 char_in_alphabet[c] = true;
2780 }
28
2981 return Base64Encoder{
3082 .alphabet_chars = alphabet_chars,
3183 .pad_char = pad_char,
3284 };
3385 }
3486
35 /// ceil(source_len * 4/3)
36 pub fn calcSize(source_len: usize) usize {
37 return @divTrunc(source_len + 2, 3) * 4;
87 /// Compute the encoded length
88 pub fn calcSize(encoder: *const Base64Encoder, source_len: usize) usize {
89 if (encoder.pad_char != null) {
90 return @divTrunc(source_len + 2, 3) * 4;
91 } else {
92 const leftover = source_len % 3;
93 return @divTrunc(source_len, 3) * 4 + @divTrunc(leftover * 4 + 2, 3);
94 }
3895 }
3996
40 /// dest.len must be what you get from ::calcSize.
97 /// dest.len must at least be what you get from ::calcSize.
4198 pub fn encode(encoder: *const Base64Encoder, dest: []u8, source: []const u8) []const u8 {
42 assert(dest.len >= Base64Encoder.calcSize(source.len));
43
44 var i: usize = 0;
45 var out_index: usize = 0;
46 while (i + 2 < source.len) : (i += 3) {
47 dest[out_index] = encoder.alphabet_chars[(source[i] >> 2) & 0x3f];
48 out_index += 1;
49
50 dest[out_index] = encoder.alphabet_chars[((source[i] & 0x3) << 4) | ((source[i + 1] & 0xf0) >> 4)];
51 out_index += 1;
52
53 dest[out_index] = encoder.alphabet_chars[((source[i + 1] & 0xf) << 2) | ((source[i + 2] & 0xc0) >> 6)];
54 out_index += 1;
55
56 dest[out_index] = encoder.alphabet_chars[source[i + 2] & 0x3f];
57 out_index += 1;
99 const out_len = encoder.calcSize(source.len);
100 assert(dest.len >= out_len);
101
102 const nibbles = source.len / 3;
103 const leftover = source.len - 3 * nibbles;
104
105 var acc: u12 = 0;
106 var acc_len: u4 = 0;
107 var out_idx: usize = 0;
108 for (source) |v| {
109 acc = (acc << 8) + v;
110 acc_len += 8;
111 while (acc_len >= 6) {
112 acc_len -= 6;
113 dest[out_idx] = encoder.alphabet_chars[@truncate(u6, (acc >> acc_len))];
114 out_idx += 1;
115 }
58116 }
59
60 if (i < source.len) {
61 dest[out_index] = encoder.alphabet_chars[(source[i] >> 2) & 0x3f];
62 out_index += 1;
63
64 if (i + 1 == source.len) {
65 dest[out_index] = encoder.alphabet_chars[(source[i] & 0x3) << 4];
66 out_index += 1;
67
68 dest[out_index] = encoder.pad_char;
69 out_index += 1;
70 } else {
71 dest[out_index] = encoder.alphabet_chars[((source[i] & 0x3) << 4) | ((source[i + 1] & 0xf0) >> 4)];
72 out_index += 1;
73
74 dest[out_index] = encoder.alphabet_chars[(source[i + 1] & 0xf) << 2];
75 out_index += 1;
117 if (acc_len > 0) {
118 dest[out_idx] = encoder.alphabet_chars[@truncate(u6, (acc << 6 - acc_len))];
119 out_idx += 1;
120 }
121 if (encoder.pad_char) |pad_char| {
122 for (dest[out_idx..]) |*pad| {
123 pad.* = pad_char;
76124 }
77
78 dest[out_index] = encoder.pad_char;
79 out_index += 1;
80125 }
81 return dest[0..out_index];
126 return dest[0..out_len];
82127 }
83128};
84129
85pub const standard_decoder = Base64Decoder.init(standard_alphabet_chars, standard_pad_char);
86
87130pub const Base64Decoder = struct {
131 const invalid_char: u8 = 0xff;
132
88133 /// e.g. 'A' => 0.
89 /// undefined for any value not in the 64 alphabet chars.
134 /// `invalid_char` for any value not in the 64 alphabet chars.
90135 char_to_index: [256]u8,
136 pad_char: ?u8,
91137
92 /// true only for the 64 chars in the alphabet, not the pad char.
93 char_in_alphabet: [256]bool,
94 pad_char: u8,
95
96 pub fn init(alphabet_chars: []const u8, pad_char: u8) Base64Decoder {
97 assert(alphabet_chars.len == 64);
98
138 pub fn init(alphabet_chars: [64]u8, pad_char: ?u8) Base64Decoder {
99139 var result = Base64Decoder{
100 .char_to_index = undefined,
101 .char_in_alphabet = [_]bool{false} ** 256,
140 .char_to_index = [_]u8{invalid_char} ** 256,
102141 .pad_char = pad_char,
103142 };
104143
144 var char_in_alphabet = [_]bool{false} ** 256;
105145 for (alphabet_chars) |c, i| {
106 assert(!result.char_in_alphabet[c]);
107 assert(c != pad_char);
146 assert(!char_in_alphabet[c]);
147 assert(pad_char == null or c != pad_char.?);
108148
109149 result.char_to_index[c] = @intCast(u8, i);
110 result.char_in_alphabet[c] = true;
150 char_in_alphabet[c] = true;
111151 }
152 return result;
153 }
112154
155 /// Return the maximum possible decoded size for a given input length - The actual length may be less if the input includes padding.
156 /// `InvalidPadding` is returned if the input length is not valid.
157 pub fn calcSizeUpperBound(decoder: *const Base64Decoder, source_len: usize) Error!usize {
158 var result = source_len / 4 * 3;
159 const leftover = source_len % 4;
160 if (decoder.pad_char != null) {
161 if (leftover % 4 != 0) return error.InvalidPadding;
162 } else {
163 if (leftover % 4 == 1) return error.InvalidPadding;
164 result += leftover * 3 / 4;
165 }
113166 return result;
114167 }
115168
116 /// If the encoded buffer is detected to be invalid, returns error.InvalidPadding.
117 pub fn calcSize(decoder: *const Base64Decoder, source: []const u8) !usize {
118 if (source.len % 4 != 0) return error.InvalidPadding;
119 return calcDecodedSizeExactUnsafe(source, decoder.pad_char);
169 /// Return the exact decoded size for a slice.
170 /// `InvalidPadding` is returned if the input length is not valid.
171 pub fn calcSizeForSlice(decoder: *const Base64Decoder, source: []const u8) Error!usize {
172 const source_len = source.len;
173 var result = try decoder.calcSizeUpperBound(source_len);
174 if (decoder.pad_char) |pad_char| {
175 if (source_len >= 1 and source[source_len - 1] == pad_char) result -= 1;
176 if (source_len >= 2 and source[source_len - 2] == pad_char) result -= 1;
177 }
178 return result;
120179 }
121180
122181 /// dest.len must be what you get from ::calcSize.
123182 /// invalid characters result in error.InvalidCharacter.
124183 /// invalid padding results in error.InvalidPadding.
125 pub fn decode(decoder: *const Base64Decoder, dest: []u8, source: []const u8) !void {
126 assert(dest.len == (decoder.calcSize(source) catch unreachable));
127 assert(source.len % 4 == 0);
128
129 var src_cursor: usize = 0;
130 var dest_cursor: usize = 0;
131
132 while (src_cursor < source.len) : (src_cursor += 4) {
133 if (!decoder.char_in_alphabet[source[src_cursor + 0]]) return error.InvalidCharacter;
134 if (!decoder.char_in_alphabet[source[src_cursor + 1]]) return error.InvalidCharacter;
135 if (src_cursor < source.len - 4 or source[src_cursor + 3] != decoder.pad_char) {
136 // common case
137 if (!decoder.char_in_alphabet[source[src_cursor + 2]]) return error.InvalidCharacter;
138 if (!decoder.char_in_alphabet[source[src_cursor + 3]]) return error.InvalidCharacter;
139 dest[dest_cursor + 0] = decoder.char_to_index[source[src_cursor + 0]] << 2 | decoder.char_to_index[source[src_cursor + 1]] >> 4;
140 dest[dest_cursor + 1] = decoder.char_to_index[source[src_cursor + 1]] << 4 | decoder.char_to_index[source[src_cursor + 2]] >> 2;
141 dest[dest_cursor + 2] = decoder.char_to_index[source[src_cursor + 2]] << 6 | decoder.char_to_index[source[src_cursor + 3]];
142 dest_cursor += 3;
143 } else if (source[src_cursor + 2] != decoder.pad_char) {
144 // one pad char
145 if (!decoder.char_in_alphabet[source[src_cursor + 2]]) return error.InvalidCharacter;
146 dest[dest_cursor + 0] = decoder.char_to_index[source[src_cursor + 0]] << 2 | decoder.char_to_index[source[src_cursor + 1]] >> 4;
147 dest[dest_cursor + 1] = decoder.char_to_index[source[src_cursor + 1]] << 4 | decoder.char_to_index[source[src_cursor + 2]] >> 2;
148 if (decoder.char_to_index[source[src_cursor + 2]] << 6 != 0) return error.InvalidPadding;
149 dest_cursor += 2;
150 } else {
151 // two pad chars
152 dest[dest_cursor + 0] = decoder.char_to_index[source[src_cursor + 0]] << 2 | decoder.char_to_index[source[src_cursor + 1]] >> 4;
153 if (decoder.char_to_index[source[src_cursor + 1]] << 4 != 0) return error.InvalidPadding;
154 dest_cursor += 1;
184 pub fn decode(decoder: *const Base64Decoder, dest: []u8, source: []const u8) Error!void {
185 if (decoder.pad_char != null and source.len % 4 != 0) return error.InvalidPadding;
186 var acc: u12 = 0;
187 var acc_len: u4 = 0;
188 var dest_idx: usize = 0;
189 var leftover_idx: ?usize = null;
190 for (source) |c, src_idx| {
191 const d = decoder.char_to_index[c];
192 if (d == invalid_char) {
193 if (decoder.pad_char == null or c != decoder.pad_char.?) return error.InvalidCharacter;
194 leftover_idx = src_idx;
195 break;
196 }
197 acc = (acc << 6) + d;
198 acc_len += 6;
199 if (acc_len >= 8) {
200 acc_len -= 8;
201 dest[dest_idx] = @truncate(u8, acc >> acc_len);
202 dest_idx += 1;
155203 }
156204 }
157
158 assert(src_cursor == source.len);
159 assert(dest_cursor == dest.len);
205 if (acc_len > 4 or (acc & (@as(u12, 1) << acc_len) - 1) != 0) {
206 return error.InvalidPadding;
207 }
208 if (leftover_idx == null) return;
209 var leftover = source[leftover_idx.?..];
210 if (decoder.pad_char) |pad_char| {
211 const padding_len = acc_len / 2;
212 var padding_chars: usize = 0;
213 var i: usize = 0;
214 for (leftover) |c| {
215 if (c != pad_char) {
216 return if (c == Base64Decoder.invalid_char) error.InvalidCharacter else error.InvalidPadding;
217 }
218 padding_chars += 1;
219 }
220 if (padding_chars != padding_len) return error.InvalidPadding;
221 }
160222 }
161223};
162224
163225pub const Base64DecoderWithIgnore = struct {
164226 decoder: Base64Decoder,
165227 char_is_ignored: [256]bool,
166 pub fn init(alphabet_chars: []const u8, pad_char: u8, ignore_chars: []const u8) Base64DecoderWithIgnore {
228
229 pub fn init(alphabet_chars: [64]u8, pad_char: ?u8, ignore_chars: []const u8) Base64DecoderWithIgnore {
167230 var result = Base64DecoderWithIgnore{
168231 .decoder = Base64Decoder.init(alphabet_chars, pad_char),
169232 .char_is_ignored = [_]bool{false} ** 256,
170233 };
171
172234 for (ignore_chars) |c| {
173 assert(!result.decoder.char_in_alphabet[c]);
235 assert(result.decoder.char_to_index[c] == Base64Decoder.invalid_char);
174236 assert(!result.char_is_ignored[c]);
175237 assert(result.decoder.pad_char != c);
176238 result.char_is_ignored[c] = true;
177239 }
178
179240 return result;
180241 }
181242
182 /// If no characters end up being ignored or padding, this will be the exact decoded size.
183 pub fn calcSizeUpperBound(encoded_len: usize) usize {
184 return @divTrunc(encoded_len, 4) * 3;
243 /// Return the maximum possible decoded size for a given input length - The actual length may be less if the input includes padding
244 /// `InvalidPadding` is returned if the input length is not valid.
245 pub fn calcSizeUpperBound(decoder_with_ignore: *const Base64DecoderWithIgnore, source_len: usize) Error!usize {
246 var result = source_len / 4 * 3;
247 if (decoder_with_ignore.decoder.pad_char == null) {
248 const leftover = source_len % 4;
249 result += leftover * 3 / 4;
250 }
251 return result;
185252 }
186253
187254 /// Invalid characters that are not ignored result in error.InvalidCharacter.
188255 /// Invalid padding results in error.InvalidPadding.
189 /// Decoding more data than can fit in dest results in error.OutputTooSmall. See also ::calcSizeUpperBound.
256 /// Decoding more data than can fit in dest results in error.NoSpaceLeft. See also ::calcSizeUpperBound.
190257 /// Returns the number of bytes written to dest.
191 pub fn decode(decoder_with_ignore: *const Base64DecoderWithIgnore, dest: []u8, source: []const u8) !usize {
258 pub fn decode(decoder_with_ignore: *const Base64DecoderWithIgnore, dest: []u8, source: []const u8) Error!usize {
192259 const decoder = &decoder_with_ignore.decoder;
193
194 var src_cursor: usize = 0;
195 var dest_cursor: usize = 0;
196
197 while (true) {
198 // get the next 4 chars, if available
199 var next_4_chars: [4]u8 = undefined;
200 var available_chars: usize = 0;
201 var pad_char_count: usize = 0;
202 while (available_chars < 4 and src_cursor < source.len) {
203 var c = source[src_cursor];
204 src_cursor += 1;
205
206 if (decoder.char_in_alphabet[c]) {
207 // normal char
208 next_4_chars[available_chars] = c;
209 available_chars += 1;
210 } else if (decoder_with_ignore.char_is_ignored[c]) {
211 // we're told to skip this one
212 continue;
213 } else if (c == decoder.pad_char) {
214 // the padding has begun. count the pad chars.
215 pad_char_count += 1;
216 while (src_cursor < source.len) {
217 c = source[src_cursor];
218 src_cursor += 1;
219 if (c == decoder.pad_char) {
220 pad_char_count += 1;
221 if (pad_char_count > 2) return error.InvalidCharacter;
222 } else if (decoder_with_ignore.char_is_ignored[c]) {
223 // we can even ignore chars during the padding
224 continue;
225 } else return error.InvalidCharacter;
226 }
227 break;
228 } else return error.InvalidCharacter;
260 var acc: u12 = 0;
261 var acc_len: u4 = 0;
262 var dest_idx: usize = 0;
263 var leftover_idx: ?usize = null;
264 for (source) |c, src_idx| {
265 if (decoder_with_ignore.char_is_ignored[c]) continue;
266 const d = decoder.char_to_index[c];
267 if (d == Base64Decoder.invalid_char) {
268 if (decoder.pad_char == null or c != decoder.pad_char.?) return error.InvalidCharacter;
269 leftover_idx = src_idx;
270 break;
229271 }
230
231 switch (available_chars) {
232 4 => {
233 // common case
234 if (dest_cursor + 3 > dest.len) return error.OutputTooSmall;
235 assert(pad_char_count == 0);
236 dest[dest_cursor + 0] = decoder.char_to_index[next_4_chars[0]] << 2 | decoder.char_to_index[next_4_chars[1]] >> 4;
237 dest[dest_cursor + 1] = decoder.char_to_index[next_4_chars[1]] << 4 | decoder.char_to_index[next_4_chars[2]] >> 2;
238 dest[dest_cursor + 2] = decoder.char_to_index[next_4_chars[2]] << 6 | decoder.char_to_index[next_4_chars[3]];
239 dest_cursor += 3;
240 continue;
241 },
242 3 => {
243 if (dest_cursor + 2 > dest.len) return error.OutputTooSmall;
244 if (pad_char_count != 1) return error.InvalidPadding;
245 dest[dest_cursor + 0] = decoder.char_to_index[next_4_chars[0]] << 2 | decoder.char_to_index[next_4_chars[1]] >> 4;
246 dest[dest_cursor + 1] = decoder.char_to_index[next_4_chars[1]] << 4 | decoder.char_to_index[next_4_chars[2]] >> 2;
247 if (decoder.char_to_index[next_4_chars[2]] << 6 != 0) return error.InvalidPadding;
248 dest_cursor += 2;
249 break;
250 },
251 2 => {
252 if (dest_cursor + 1 > dest.len) return error.OutputTooSmall;
253 if (pad_char_count != 2) return error.InvalidPadding;
254 dest[dest_cursor + 0] = decoder.char_to_index[next_4_chars[0]] << 2 | decoder.char_to_index[next_4_chars[1]] >> 4;
255 if (decoder.char_to_index[next_4_chars[1]] << 4 != 0) return error.InvalidPadding;
256 dest_cursor += 1;
257 break;
258 },
259 1 => {
260 return error.InvalidPadding;
261 },
262 0 => {
263 if (pad_char_count != 0) return error.InvalidPadding;
264 break;
265 },
266 else => unreachable,
272 acc = (acc << 6) + d;
273 acc_len += 6;
274 if (acc_len >= 8) {
275 if (dest_idx == dest.len) return error.NoSpaceLeft;
276 acc_len -= 8;
277 dest[dest_idx] = @truncate(u8, acc >> acc_len);
278 dest_idx += 1;
267279 }
268280 }
269
270 assert(src_cursor == source.len);
271
272 return dest_cursor;
281 if (acc_len > 4 or (acc & (@as(u12, 1) << acc_len) - 1) != 0) {
282 return error.InvalidPadding;
283 }
284 const padding_len = acc_len / 2;
285 if (leftover_idx == null) {
286 if (decoder.pad_char != null and padding_len != 0) return error.InvalidPadding;
287 return dest_idx;
288 }
289 var leftover = source[leftover_idx.?..];
290 if (decoder.pad_char) |pad_char| {
291 var padding_chars: usize = 0;
292 var i: usize = 0;
293 for (leftover) |c| {
294 if (decoder_with_ignore.char_is_ignored[c]) continue;
295 if (c != pad_char) {
296 return if (c == Base64Decoder.invalid_char) error.InvalidCharacter else error.InvalidPadding;
297 }
298 padding_chars += 1;
299 }
300 if (padding_chars != padding_len) return error.InvalidPadding;
301 }
302 return dest_idx;
273303 }
274304};
275305
276pub const standard_decoder_unsafe = Base64DecoderUnsafe.init(standard_alphabet_chars, standard_pad_char);
277
278306pub const Base64DecoderUnsafe = struct {
279307 /// e.g. 'A' => 0.
280308 /// undefined for any value not in the 64 alphabet chars.
281309 char_to_index: [256]u8,
282 pad_char: u8,
310 pad_char: ?u8,
283311
284 pub fn init(alphabet_chars: []const u8, pad_char: u8) Base64DecoderUnsafe {
285 assert(alphabet_chars.len == 64);
312 pub fn init(alphabet_chars: [64]u8, pad_char: ?u8) Base64DecoderUnsafe {
286313 var result = Base64DecoderUnsafe{
287314 .char_to_index = undefined,
288315 .pad_char = pad_char,
289316 };
290317 for (alphabet_chars) |c, i| {
291 assert(c != pad_char);
318 assert(pad_char == null or c != pad_char.?);
292319 result.char_to_index[c] = @intCast(u8, i);
293320 }
294321 return result;
295322 }
296323
297 /// The source buffer must be valid.
298 pub fn calcSize(decoder: *const Base64DecoderUnsafe, source: []const u8) usize {
299 return calcDecodedSizeExactUnsafe(source, decoder.pad_char);
324 /// Return the exact decoded size for a slice.
325 /// `InvalidPadding` is returned if the input length is not valid.
326 pub fn calcSizeForSlice(decoder: *const Base64DecoderUnsafe, source: []const u8) Error!usize {
327 const safe_decoder = Base64Decoder{ .char_to_index = undefined, .pad_char = decoder.pad_char };
328 return safe_decoder.calcSizeForSlice(source);
300329 }
301330
302331 /// dest.len must be what you get from ::calcDecodedSizeExactUnsafe.
303332 /// invalid characters or padding will result in undefined values.
304333 pub fn decode(decoder: *const Base64DecoderUnsafe, dest: []u8, source: []const u8) void {
305 assert(dest.len == decoder.calcSize(source));
334 assert(dest.len == decoder.calcSizeForSlice(source) catch unreachable);
306335
307336 var src_index: usize = 0;
308337 var dest_index: usize = 0;
309338 var in_buf_len: usize = source.len;
310339
311 while (in_buf_len > 0 and source[in_buf_len - 1] == decoder.pad_char) {
312 in_buf_len -= 1;
340 if (decoder.pad_char) |pad_char| {
341 while (in_buf_len > 0 and source[in_buf_len - 1] == pad_char) {
342 in_buf_len -= 1;
343 }
313344 }
314345
315346 while (in_buf_len > 4) {
......@@ -341,80 +372,111 @@ pub const Base64DecoderUnsafe = struct {
341372 }
342373};
343374
344fn calcDecodedSizeExactUnsafe(source: []const u8, pad_char: u8) usize {
345 if (source.len == 0) return 0;
346 var result = @divExact(source.len, 4) * 3;
347 if (source[source.len - 1] == pad_char) {
348 result -= 1;
349 if (source[source.len - 2] == pad_char) {
350 result -= 1;
351 }
352 }
353 return result;
354}
355
356375test "base64" {
357376 @setEvalBranchQuota(8000);
358377 testBase64() catch unreachable;
359 comptime (testBase64() catch unreachable);
378 comptime testAllApis(standard, "comptime", "Y29tcHRpbWU=") catch unreachable;
379}
380
381test "base64 url_safe" {
382 @setEvalBranchQuota(8000);
383 testBase64UrlSafe() catch unreachable;
384 comptime testAllApis(url_safe, "comptime", "Y29tcHRpbWU") catch unreachable;
360385}
361386
362387fn testBase64() !void {
363 try testAllApis("", "");
364 try testAllApis("f", "Zg==");
365 try testAllApis("fo", "Zm8=");
366 try testAllApis("foo", "Zm9v");
367 try testAllApis("foob", "Zm9vYg==");
368 try testAllApis("fooba", "Zm9vYmE=");
369 try testAllApis("foobar", "Zm9vYmFy");
370
371 try testDecodeIgnoreSpace("", " ");
372 try testDecodeIgnoreSpace("f", "Z g= =");
373 try testDecodeIgnoreSpace("fo", " Zm8=");
374 try testDecodeIgnoreSpace("foo", "Zm9v ");
375 try testDecodeIgnoreSpace("foob", "Zm9vYg = = ");
376 try testDecodeIgnoreSpace("fooba", "Zm9v YmE=");
377 try testDecodeIgnoreSpace("foobar", " Z m 9 v Y m F y ");
388 const codecs = standard;
389
390 try testAllApis(codecs, "", "");
391 try testAllApis(codecs, "f", "Zg==");
392 try testAllApis(codecs, "fo", "Zm8=");
393 try testAllApis(codecs, "foo", "Zm9v");
394 try testAllApis(codecs, "foob", "Zm9vYg==");
395 try testAllApis(codecs, "fooba", "Zm9vYmE=");
396 try testAllApis(codecs, "foobar", "Zm9vYmFy");
397
398 try testDecodeIgnoreSpace(codecs, "", " ");
399 try testDecodeIgnoreSpace(codecs, "f", "Z g= =");
400 try testDecodeIgnoreSpace(codecs, "fo", " Zm8=");
401 try testDecodeIgnoreSpace(codecs, "foo", "Zm9v ");
402 try testDecodeIgnoreSpace(codecs, "foob", "Zm9vYg = = ");
403 try testDecodeIgnoreSpace(codecs, "fooba", "Zm9v YmE=");
404 try testDecodeIgnoreSpace(codecs, "foobar", " Z m 9 v Y m F y ");
405
406 // test getting some api errors
407 try testError(codecs, "A", error.InvalidPadding);
408 try testError(codecs, "AA", error.InvalidPadding);
409 try testError(codecs, "AAA", error.InvalidPadding);
410 try testError(codecs, "A..A", error.InvalidCharacter);
411 try testError(codecs, "AA=A", error.InvalidPadding);
412 try testError(codecs, "AA/=", error.InvalidPadding);
413 try testError(codecs, "A/==", error.InvalidPadding);
414 try testError(codecs, "A===", error.InvalidPadding);
415 try testError(codecs, "====", error.InvalidPadding);
416
417 try testNoSpaceLeftError(codecs, "AA==");
418 try testNoSpaceLeftError(codecs, "AAA=");
419 try testNoSpaceLeftError(codecs, "AAAA");
420 try testNoSpaceLeftError(codecs, "AAAAAA==");
421}
422
423fn testBase64UrlSafe() !void {
424 const codecs = url_safe;
425
426 try testAllApis(codecs, "", "");
427 try testAllApis(codecs, "f", "Zg");
428 try testAllApis(codecs, "fo", "Zm8");
429 try testAllApis(codecs, "foo", "Zm9v");
430 try testAllApis(codecs, "foob", "Zm9vYg");
431 try testAllApis(codecs, "fooba", "Zm9vYmE");
432 try testAllApis(codecs, "foobar", "Zm9vYmFy");
433
434 try testDecodeIgnoreSpace(codecs, "", " ");
435 try testDecodeIgnoreSpace(codecs, "f", "Z g ");
436 try testDecodeIgnoreSpace(codecs, "fo", " Zm8");
437 try testDecodeIgnoreSpace(codecs, "foo", "Zm9v ");
438 try testDecodeIgnoreSpace(codecs, "foob", "Zm9vYg ");
439 try testDecodeIgnoreSpace(codecs, "fooba", "Zm9v YmE");
440 try testDecodeIgnoreSpace(codecs, "foobar", " Z m 9 v Y m F y ");
378441
379442 // test getting some api errors
380 try testError("A", error.InvalidPadding);
381 try testError("AA", error.InvalidPadding);
382 try testError("AAA", error.InvalidPadding);
383 try testError("A..A", error.InvalidCharacter);
384 try testError("AA=A", error.InvalidCharacter);
385 try testError("AA/=", error.InvalidPadding);
386 try testError("A/==", error.InvalidPadding);
387 try testError("A===", error.InvalidCharacter);
388 try testError("====", error.InvalidCharacter);
389
390 try testOutputTooSmallError("AA==");
391 try testOutputTooSmallError("AAA=");
392 try testOutputTooSmallError("AAAA");
393 try testOutputTooSmallError("AAAAAA==");
443 try testError(codecs, "A", error.InvalidPadding);
444 try testError(codecs, "AAA=", error.InvalidCharacter);
445 try testError(codecs, "A..A", error.InvalidCharacter);
446 try testError(codecs, "AA=A", error.InvalidCharacter);
447 try testError(codecs, "AA/=", error.InvalidCharacter);
448 try testError(codecs, "A/==", error.InvalidCharacter);
449 try testError(codecs, "A===", error.InvalidCharacter);
450 try testError(codecs, "====", error.InvalidCharacter);
451
452 try testNoSpaceLeftError(codecs, "AA");
453 try testNoSpaceLeftError(codecs, "AAA");
454 try testNoSpaceLeftError(codecs, "AAAA");
455 try testNoSpaceLeftError(codecs, "AAAAAA");
394456}
395457
396fn testAllApis(expected_decoded: []const u8, expected_encoded: []const u8) !void {
458fn testAllApis(codecs: Codecs, expected_decoded: []const u8, expected_encoded: []const u8) !void {
397459 // Base64Encoder
398460 {
399461 var buffer: [0x100]u8 = undefined;
400 const encoded = standard_encoder.encode(&buffer, expected_decoded);
462 const encoded = codecs.Encoder.encode(&buffer, expected_decoded);
401463 testing.expectEqualSlices(u8, expected_encoded, encoded);
402464 }
403465
404466 // Base64Decoder
405467 {
406468 var buffer: [0x100]u8 = undefined;
407 var decoded = buffer[0..try standard_decoder.calcSize(expected_encoded)];
408 try standard_decoder.decode(decoded, expected_encoded);
469 var decoded = buffer[0..try codecs.Decoder.calcSizeForSlice(expected_encoded)];
470 try codecs.Decoder.decode(decoded, expected_encoded);
409471 testing.expectEqualSlices(u8, expected_decoded, decoded);
410472 }
411473
412474 // Base64DecoderWithIgnore
413475 {
414 const standard_decoder_ignore_nothing = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, "");
476 const decoder_ignore_nothing = codecs.decoderWithIgnore("");
415477 var buffer: [0x100]u8 = undefined;
416 var decoded = buffer[0..Base64DecoderWithIgnore.calcSizeUpperBound(expected_encoded.len)];
417 var written = try standard_decoder_ignore_nothing.decode(decoded, expected_encoded);
478 var decoded = buffer[0..try decoder_ignore_nothing.calcSizeUpperBound(expected_encoded.len)];
479 var written = try decoder_ignore_nothing.decode(decoded, expected_encoded);
418480 testing.expect(written <= decoded.len);
419481 testing.expectEqualSlices(u8, expected_decoded, decoded[0..written]);
420482 }
......@@ -422,40 +484,40 @@ fn testAllApis(expected_decoded: []const u8, expected_encoded: []const u8) !void
422484 // Base64DecoderUnsafe
423485 {
424486 var buffer: [0x100]u8 = undefined;
425 var decoded = buffer[0..standard_decoder_unsafe.calcSize(expected_encoded)];
426 standard_decoder_unsafe.decode(decoded, expected_encoded);
487 var decoded = buffer[0..try codecs.DecoderUnsafe.calcSizeForSlice(expected_encoded)];
488 codecs.DecoderUnsafe.decode(decoded, expected_encoded);
427489 testing.expectEqualSlices(u8, expected_decoded, decoded);
428490 }
429491}
430492
431fn testDecodeIgnoreSpace(expected_decoded: []const u8, encoded: []const u8) !void {
432 const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, " ");
493fn testDecodeIgnoreSpace(codecs: Codecs, expected_decoded: []const u8, encoded: []const u8) !void {
494 const decoder_ignore_space = codecs.decoderWithIgnore(" ");
433495 var buffer: [0x100]u8 = undefined;
434 var decoded = buffer[0..Base64DecoderWithIgnore.calcSizeUpperBound(encoded.len)];
435 var written = try standard_decoder_ignore_space.decode(decoded, encoded);
496 var decoded = buffer[0..try decoder_ignore_space.calcSizeUpperBound(encoded.len)];
497 var written = try decoder_ignore_space.decode(decoded, encoded);
436498 testing.expectEqualSlices(u8, expected_decoded, decoded[0..written]);
437499}
438500
439fn testError(encoded: []const u8, expected_err: anyerror) !void {
440 const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, " ");
501fn testError(codecs: Codecs, encoded: []const u8, expected_err: anyerror) !void {
502 const decoder_ignore_space = codecs.decoderWithIgnore(" ");
441503 var buffer: [0x100]u8 = undefined;
442 if (standard_decoder.calcSize(encoded)) |decoded_size| {
504 if (codecs.Decoder.calcSizeForSlice(encoded)) |decoded_size| {
443505 var decoded = buffer[0..decoded_size];
444 if (standard_decoder.decode(decoded, encoded)) |_| {
506 if (codecs.Decoder.decode(decoded, encoded)) |_| {
445507 return error.ExpectedError;
446508 } else |err| if (err != expected_err) return err;
447509 } else |err| if (err != expected_err) return err;
448510
449 if (standard_decoder_ignore_space.decode(buffer[0..], encoded)) |_| {
511 if (decoder_ignore_space.decode(buffer[0..], encoded)) |_| {
450512 return error.ExpectedError;
451513 } else |err| if (err != expected_err) return err;
452514}
453515
454fn testOutputTooSmallError(encoded: []const u8) !void {
455 const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, " ");
516fn testNoSpaceLeftError(codecs: Codecs, encoded: []const u8) !void {
517 const decoder_ignore_space = codecs.decoderWithIgnore(" ");
456518 var buffer: [0x100]u8 = undefined;
457 var decoded = buffer[0 .. calcDecodedSizeExactUnsafe(encoded, standard_pad_char) - 1];
458 if (standard_decoder_ignore_space.decode(decoded, encoded)) |_| {
519 var decoded = buffer[0 .. (try codecs.Decoder.calcSizeForSlice(encoded)) - 1];
520 if (decoder_ignore_space.decode(decoded, encoded)) |_| {
459521 return error.ExpectedError;
460 } else |err| if (err != error.OutputTooSmall) return err;
522 } else |err| if (err != error.NoSpaceLeft) return err;
461523}
lib/std/fs.zig+5-5
......@@ -50,13 +50,13 @@ pub const MAX_PATH_BYTES = switch (builtin.os.tag) {
5050 else => @compileError("Unsupported OS"),
5151};
5252
53pub const base64_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
53pub const base64_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".*;
5454
5555/// Base64 encoder, replacing the standard `+/` with `-_` so that it can be used in a file name on any filesystem.
56pub const base64_encoder = base64.Base64Encoder.init(base64_alphabet, base64.standard_pad_char);
56pub const base64_encoder = base64.Base64Encoder.init(base64_alphabet, null);
5757
5858/// Base64 decoder, replacing the standard `+/` with `-_` so that it can be used in a file name on any filesystem.
59pub const base64_decoder = base64.Base64Decoder.init(base64_alphabet, base64.standard_pad_char);
59pub const base64_decoder = base64.Base64Decoder.init(base64_alphabet, null);
6060
6161/// Whether or not async file system syscalls need a dedicated thread because the operating
6262/// system does not support non-blocking I/O on the file system.
......@@ -77,7 +77,7 @@ pub fn atomicSymLink(allocator: *Allocator, existing_path: []const u8, new_path:
7777 const dirname = path.dirname(new_path) orelse ".";
7878
7979 var rand_buf: [AtomicFile.RANDOM_BYTES]u8 = undefined;
80 const tmp_path = try allocator.alloc(u8, dirname.len + 1 + base64.Base64Encoder.calcSize(rand_buf.len));
80 const tmp_path = try allocator.alloc(u8, dirname.len + 1 + base64_encoder.calcSize(rand_buf.len));
8181 defer allocator.free(tmp_path);
8282 mem.copy(u8, tmp_path[0..], dirname);
8383 tmp_path[dirname.len] = path.sep;
......@@ -142,7 +142,7 @@ pub const AtomicFile = struct {
142142 const InitError = File.OpenError;
143143
144144 const RANDOM_BYTES = 12;
145 const TMP_PATH_LEN = base64.Base64Encoder.calcSize(RANDOM_BYTES);
145 const TMP_PATH_LEN = base64_encoder.calcSize(RANDOM_BYTES);
146146
147147 /// Note that the `Dir.atomicFile` API may be more handy than this lower-level function.
148148 pub fn init(
lib/std/testing.zig+1-1
......@@ -298,7 +298,7 @@ pub const TmpDir = struct {
298298 sub_path: [sub_path_len]u8,
299299
300300 const random_bytes_count = 12;
301 const sub_path_len = std.base64.Base64Encoder.calcSize(random_bytes_count);
301 const sub_path_len = std.fs.base64_encoder.calcSize(random_bytes_count);
302302
303303 pub fn cleanup(self: *TmpDir) void {
304304 self.dir.close();
test/standalone/mix_o_files/base64.zig+2-2
......@@ -3,8 +3,8 @@ const base64 = @import("std").base64;
33export fn decode_base_64(dest_ptr: [*]u8, dest_len: usize, source_ptr: [*]const u8, source_len: usize) usize {
44 const src = source_ptr[0..source_len];
55 const dest = dest_ptr[0..dest_len];
6 const base64_decoder = base64.standard_decoder_unsafe;
7 const decoded_size = base64_decoder.calcSize(src);
6 const base64_decoder = base64.standard.DecoderUnsafe;
7 const decoded_size = base64_decoder.calcSizeForSlice(src) catch unreachable;
88 base64_decoder.decode(dest[0..decoded_size], src);
99 return decoded_size;
1010}