| ... | ... | @@ -8,308 +8,339 @@ const assert = std.debug.assert; |
| 8 | 8 | const testing = std.testing; |
| 9 | 9 | const mem = std.mem; |
| 10 | 10 | |
| 11 | | pub const standard_alphabet_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 12 | | pub const standard_pad_char = '='; |
| 13 | | pub const standard_encoder = Base64Encoder.init(standard_alphabet_chars, standard_pad_char); |
| 11 | pub const Error = error{ |
| 12 | InvalidCharacter, |
| 13 | InvalidPadding, |
| 14 | NoSpaceLeft, |
| 15 | }; |
| 16 | |
| 17 | /// Base64 codecs |
| 18 | pub 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 | |
| 27 | pub const standard_alphabet_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".*; |
| 28 | fn standardBase64DecoderWithIgnore(ignore: []const u8) Base64DecoderWithIgnore { |
| 29 | return Base64DecoderWithIgnore.init(standard_alphabet_chars, '=', ignore); |
| 30 | } |
| 31 | |
| 32 | /// Standard Base64 codecs, with padding |
| 33 | pub 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 | |
| 42 | pub const url_safe_alphabet_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".*; |
| 43 | fn urlSafeBase64DecoderWithIgnore(ignore: []const u8) Base64DecoderWithIgnore { |
| 44 | return Base64DecoderWithIgnore.init(url_safe_alphabet_chars, null, ignore); |
| 45 | } |
| 46 | |
| 47 | /// URL-safe Base64 codecs, without padding |
| 48 | pub 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` |
| 60 | pub const standard_pad_char = standard.pad_char; |
| 61 | /// Deprecated - Use `standard.Encoder` |
| 62 | pub const standard_encoder = standard.Encoder; |
| 63 | /// Deprecated - Use `standard.Decoder` |
| 64 | pub const standard_decoder = standard.Decoder; |
| 65 | /// Deprecated - Use `standard.DecoderUnsafe` |
| 66 | pub const standard_decoder_unsafe = standard.DecoderUnsafe; |
| 14 | 67 | |
| 15 | 68 | pub const Base64Encoder = struct { |
| 16 | | alphabet_chars: []const u8, |
| 17 | | pad_char: u8, |
| 69 | alphabet_chars: [64]u8, |
| 70 | pad_char: ?u8, |
| 18 | 71 | |
| 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 { |
| 21 | 74 | assert(alphabet_chars.len == 64); |
| 22 | 75 | var char_in_alphabet = [_]bool{false} ** 256; |
| 23 | 76 | for (alphabet_chars) |c| { |
| 24 | 77 | assert(!char_in_alphabet[c]); |
| 25 | | assert(c != pad_char); |
| 78 | assert(pad_char == null or c != pad_char.?); |
| 26 | 79 | char_in_alphabet[c] = true; |
| 27 | 80 | } |
| 28 | | |
| 29 | 81 | return Base64Encoder{ |
| 30 | 82 | .alphabet_chars = alphabet_chars, |
| 31 | 83 | .pad_char = pad_char, |
| 32 | 84 | }; |
| 33 | 85 | } |
| 34 | 86 | |
| 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 | } |
| 38 | 95 | } |
| 39 | 96 | |
| 40 | | /// dest.len must be what you get from ::calcSize. |
| 97 | /// dest.len must at least be what you get from ::calcSize. |
| 41 | 98 | 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 | } |
| 58 | 116 | } |
| 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; |
| 76 | 124 | } |
| 77 | | |
| 78 | | dest[out_index] = encoder.pad_char; |
| 79 | | out_index += 1; |
| 80 | 125 | } |
| 81 | | return dest[0..out_index]; |
| 126 | return dest[0..out_len]; |
| 82 | 127 | } |
| 83 | 128 | }; |
| 84 | 129 | |
| 85 | | pub const standard_decoder = Base64Decoder.init(standard_alphabet_chars, standard_pad_char); |
| 86 | | |
| 87 | 130 | pub const Base64Decoder = struct { |
| 131 | const invalid_char: u8 = 0xff; |
| 132 | |
| 88 | 133 | /// 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. |
| 90 | 135 | char_to_index: [256]u8, |
| 136 | pad_char: ?u8, |
| 91 | 137 | |
| 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 { |
| 99 | 139 | var result = Base64Decoder{ |
| 100 | | .char_to_index = undefined, |
| 101 | | .char_in_alphabet = [_]bool{false} ** 256, |
| 140 | .char_to_index = [_]u8{invalid_char} ** 256, |
| 102 | 141 | .pad_char = pad_char, |
| 103 | 142 | }; |
| 104 | 143 | |
| 144 | var char_in_alphabet = [_]bool{false} ** 256; |
| 105 | 145 | 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.?); |
| 108 | 148 | |
| 109 | 149 | result.char_to_index[c] = @intCast(u8, i); |
| 110 | | result.char_in_alphabet[c] = true; |
| 150 | char_in_alphabet[c] = true; |
| 111 | 151 | } |
| 152 | return result; |
| 153 | } |
| 112 | 154 | |
| 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 | } |
| 113 | 166 | return result; |
| 114 | 167 | } |
| 115 | 168 | |
| 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; |
| 120 | 179 | } |
| 121 | 180 | |
| 122 | 181 | /// dest.len must be what you get from ::calcSize. |
| 123 | 182 | /// invalid characters result in error.InvalidCharacter. |
| 124 | 183 | /// 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; |
| 155 | 203 | } |
| 156 | 204 | } |
| 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 | } |
| 160 | 222 | } |
| 161 | 223 | }; |
| 162 | 224 | |
| 163 | 225 | pub const Base64DecoderWithIgnore = struct { |
| 164 | 226 | decoder: Base64Decoder, |
| 165 | 227 | 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 { |
| 167 | 230 | var result = Base64DecoderWithIgnore{ |
| 168 | 231 | .decoder = Base64Decoder.init(alphabet_chars, pad_char), |
| 169 | 232 | .char_is_ignored = [_]bool{false} ** 256, |
| 170 | 233 | }; |
| 171 | | |
| 172 | 234 | for (ignore_chars) |c| { |
| 173 | | assert(!result.decoder.char_in_alphabet[c]); |
| 235 | assert(result.decoder.char_to_index[c] == Base64Decoder.invalid_char); |
| 174 | 236 | assert(!result.char_is_ignored[c]); |
| 175 | 237 | assert(result.decoder.pad_char != c); |
| 176 | 238 | result.char_is_ignored[c] = true; |
| 177 | 239 | } |
| 178 | | |
| 179 | 240 | return result; |
| 180 | 241 | } |
| 181 | 242 | |
| 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; |
| 185 | 252 | } |
| 186 | 253 | |
| 187 | 254 | /// Invalid characters that are not ignored result in error.InvalidCharacter. |
| 188 | 255 | /// 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. |
| 190 | 257 | /// 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 { |
| 192 | 259 | 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; |
| 229 | 271 | } |
| 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; |
| 267 | 279 | } |
| 268 | 280 | } |
| 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; |
| 273 | 303 | } |
| 274 | 304 | }; |
| 275 | 305 | |
| 276 | | pub const standard_decoder_unsafe = Base64DecoderUnsafe.init(standard_alphabet_chars, standard_pad_char); |
| 277 | | |
| 278 | 306 | pub const Base64DecoderUnsafe = struct { |
| 279 | 307 | /// e.g. 'A' => 0. |
| 280 | 308 | /// undefined for any value not in the 64 alphabet chars. |
| 281 | 309 | char_to_index: [256]u8, |
| 282 | | pad_char: u8, |
| 310 | pad_char: ?u8, |
| 283 | 311 | |
| 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 { |
| 286 | 313 | var result = Base64DecoderUnsafe{ |
| 287 | 314 | .char_to_index = undefined, |
| 288 | 315 | .pad_char = pad_char, |
| 289 | 316 | }; |
| 290 | 317 | for (alphabet_chars) |c, i| { |
| 291 | | assert(c != pad_char); |
| 318 | assert(pad_char == null or c != pad_char.?); |
| 292 | 319 | result.char_to_index[c] = @intCast(u8, i); |
| 293 | 320 | } |
| 294 | 321 | return result; |
| 295 | 322 | } |
| 296 | 323 | |
| 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); |
| 300 | 329 | } |
| 301 | 330 | |
| 302 | 331 | /// dest.len must be what you get from ::calcDecodedSizeExactUnsafe. |
| 303 | 332 | /// invalid characters or padding will result in undefined values. |
| 304 | 333 | 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); |
| 306 | 335 | |
| 307 | 336 | var src_index: usize = 0; |
| 308 | 337 | var dest_index: usize = 0; |
| 309 | 338 | var in_buf_len: usize = source.len; |
| 310 | 339 | |
| 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 | } |
| 313 | 344 | } |
| 314 | 345 | |
| 315 | 346 | while (in_buf_len > 4) { |
| ... | ... | @@ -341,80 +372,111 @@ pub const Base64DecoderUnsafe = struct { |
| 341 | 372 | } |
| 342 | 373 | }; |
| 343 | 374 | |
| 344 | | fn 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 | | |
| 356 | 375 | test "base64" { |
| 357 | 376 | @setEvalBranchQuota(8000); |
| 358 | 377 | testBase64() catch unreachable; |
| 359 | | comptime (testBase64() catch unreachable); |
| 378 | comptime testAllApis(standard, "comptime", "Y29tcHRpbWU=") catch unreachable; |
| 379 | } |
| 380 | |
| 381 | test "base64 url_safe" { |
| 382 | @setEvalBranchQuota(8000); |
| 383 | testBase64UrlSafe() catch unreachable; |
| 384 | comptime testAllApis(url_safe, "comptime", "Y29tcHRpbWU") catch unreachable; |
| 360 | 385 | } |
| 361 | 386 | |
| 362 | 387 | fn 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 | |
| 423 | fn 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 "); |
| 378 | 441 | |
| 379 | 442 | // 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"); |
| 394 | 456 | } |
| 395 | 457 | |
| 396 | | fn testAllApis(expected_decoded: []const u8, expected_encoded: []const u8) !void { |
| 458 | fn testAllApis(codecs: Codecs, expected_decoded: []const u8, expected_encoded: []const u8) !void { |
| 397 | 459 | // Base64Encoder |
| 398 | 460 | { |
| 399 | 461 | var buffer: [0x100]u8 = undefined; |
| 400 | | const encoded = standard_encoder.encode(&buffer, expected_decoded); |
| 462 | const encoded = codecs.Encoder.encode(&buffer, expected_decoded); |
| 401 | 463 | testing.expectEqualSlices(u8, expected_encoded, encoded); |
| 402 | 464 | } |
| 403 | 465 | |
| 404 | 466 | // Base64Decoder |
| 405 | 467 | { |
| 406 | 468 | 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); |
| 409 | 471 | testing.expectEqualSlices(u8, expected_decoded, decoded); |
| 410 | 472 | } |
| 411 | 473 | |
| 412 | 474 | // Base64DecoderWithIgnore |
| 413 | 475 | { |
| 414 | | const standard_decoder_ignore_nothing = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, ""); |
| 476 | const decoder_ignore_nothing = codecs.decoderWithIgnore(""); |
| 415 | 477 | 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); |
| 418 | 480 | testing.expect(written <= decoded.len); |
| 419 | 481 | testing.expectEqualSlices(u8, expected_decoded, decoded[0..written]); |
| 420 | 482 | } |
| ... | ... | @@ -422,40 +484,40 @@ fn testAllApis(expected_decoded: []const u8, expected_encoded: []const u8) !void |
| 422 | 484 | // Base64DecoderUnsafe |
| 423 | 485 | { |
| 424 | 486 | 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); |
| 427 | 489 | testing.expectEqualSlices(u8, expected_decoded, decoded); |
| 428 | 490 | } |
| 429 | 491 | } |
| 430 | 492 | |
| 431 | | fn testDecodeIgnoreSpace(expected_decoded: []const u8, encoded: []const u8) !void { |
| 432 | | const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, " "); |
| 493 | fn testDecodeIgnoreSpace(codecs: Codecs, expected_decoded: []const u8, encoded: []const u8) !void { |
| 494 | const decoder_ignore_space = codecs.decoderWithIgnore(" "); |
| 433 | 495 | 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); |
| 436 | 498 | testing.expectEqualSlices(u8, expected_decoded, decoded[0..written]); |
| 437 | 499 | } |
| 438 | 500 | |
| 439 | | fn testError(encoded: []const u8, expected_err: anyerror) !void { |
| 440 | | const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, " "); |
| 501 | fn testError(codecs: Codecs, encoded: []const u8, expected_err: anyerror) !void { |
| 502 | const decoder_ignore_space = codecs.decoderWithIgnore(" "); |
| 441 | 503 | var buffer: [0x100]u8 = undefined; |
| 442 | | if (standard_decoder.calcSize(encoded)) |decoded_size| { |
| 504 | if (codecs.Decoder.calcSizeForSlice(encoded)) |decoded_size| { |
| 443 | 505 | var decoded = buffer[0..decoded_size]; |
| 444 | | if (standard_decoder.decode(decoded, encoded)) |_| { |
| 506 | if (codecs.Decoder.decode(decoded, encoded)) |_| { |
| 445 | 507 | return error.ExpectedError; |
| 446 | 508 | } else |err| if (err != expected_err) return err; |
| 447 | 509 | } else |err| if (err != expected_err) return err; |
| 448 | 510 | |
| 449 | | if (standard_decoder_ignore_space.decode(buffer[0..], encoded)) |_| { |
| 511 | if (decoder_ignore_space.decode(buffer[0..], encoded)) |_| { |
| 450 | 512 | return error.ExpectedError; |
| 451 | 513 | } else |err| if (err != expected_err) return err; |
| 452 | 514 | } |
| 453 | 515 | |
| 454 | | fn testOutputTooSmallError(encoded: []const u8) !void { |
| 455 | | const standard_decoder_ignore_space = Base64DecoderWithIgnore.init(standard_alphabet_chars, standard_pad_char, " "); |
| 516 | fn testNoSpaceLeftError(codecs: Codecs, encoded: []const u8) !void { |
| 517 | const decoder_ignore_space = codecs.decoderWithIgnore(" "); |
| 456 | 518 | 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)) |_| { |
| 459 | 521 | return error.ExpectedError; |
| 460 | | } else |err| if (err != error.OutputTooSmall) return err; |
| 522 | } else |err| if (err != error.NoSpaceLeft) return err; |
| 461 | 523 | } |