|
| 1 | +const std = @import("std"); |
| 2 | +const Allocator = std.mem.Allocator; |
| 3 | + |
| 4 | +// Parses data:[<media-type>][;base64],<data> |
| 5 | +pub fn parse(allocator: Allocator, src: []const u8) !?[]const u8 { |
| 6 | + if (!std.mem.startsWith(u8, src, "data:")) { |
| 7 | + return null; |
| 8 | + } |
| 9 | + |
| 10 | + const uri = src[5..]; |
| 11 | + const data_starts = std.mem.indexOfScalar(u8, uri, ',') orelse return null; |
| 12 | + |
| 13 | + var data = uri[data_starts + 1 ..]; |
| 14 | + |
| 15 | + // Extract the encoding. |
| 16 | + const metadata = uri[0..data_starts]; |
| 17 | + if (std.mem.endsWith(u8, metadata, ";base64")) { |
| 18 | + const decoder = std.base64.standard.Decoder; |
| 19 | + const decoded_size = try decoder.calcSizeForSlice(data); |
| 20 | + |
| 21 | + const buffer = try allocator.alloc(u8, decoded_size); |
| 22 | + errdefer allocator.free(buffer); |
| 23 | + |
| 24 | + try decoder.decode(buffer, data); |
| 25 | + data = buffer; |
| 26 | + } |
| 27 | + |
| 28 | + return data; |
| 29 | +} |
| 30 | + |
| 31 | +const testing = @import("../testing.zig"); |
| 32 | +test "DataURI: parse valid" { |
| 33 | + try test_valid("data:text/javascript; charset=utf-8;base64,Zm9v", "foo"); |
| 34 | + try test_valid("data:text/javascript; charset=utf-8;,foo", "foo"); |
| 35 | + try test_valid("data:,foo", "foo"); |
| 36 | +} |
| 37 | + |
| 38 | +test "DataURI: parse invalid" { |
| 39 | + try test_cannot_parse("atad:,foo"); |
| 40 | + try test_cannot_parse("data:foo"); |
| 41 | + try test_cannot_parse("data:"); |
| 42 | +} |
| 43 | + |
| 44 | +fn test_valid(uri: []const u8, expected: []const u8) !void { |
| 45 | + defer testing.reset(); |
| 46 | + const data_uri = try parse(testing.arena_allocator, uri) orelse return error.TestFailed; |
| 47 | + try testing.expectEqual(expected, data_uri); |
| 48 | +} |
| 49 | + |
| 50 | +fn test_cannot_parse(uri: []const u8) !void { |
| 51 | + try testing.expectEqual(null, parse(undefined, uri)); |
| 52 | +} |
0 commit comments