Skip to content

Commit 6937c8e

Browse files
Merge pull request #823 from lightpanda-io/atob_btoa
add atob and btoa
2 parents 476fb7e + f02b956 commit 6937c8e

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/browser/html/window.zig

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,21 @@ pub const Window = struct {
217217
};
218218
}
219219

220+
pub fn _btoa(_: *const Window, value: []const u8, page: *Page) ![]const u8 {
221+
const Encoder = std.base64.standard.Encoder;
222+
const out = try page.call_arena.alloc(u8, Encoder.calcSize(value.len));
223+
return Encoder.encode(out, value);
224+
}
225+
226+
pub fn _atob(_: *const Window, value: []const u8, page: *Page) ![]const u8 {
227+
const Decoder = std.base64.standard.Decoder;
228+
const size = Decoder.calcSizeForSlice(value) catch return error.InvalidCharacterError;
229+
230+
const out = try page.call_arena.alloc(u8, size);
231+
Decoder.decode(out, value) catch return error.InvalidCharacterError;
232+
return out;
233+
}
234+
220235
const CreateTimeoutOpts = struct {
221236
repeat: bool = false,
222237
animation_frame: bool = false,
@@ -414,4 +429,12 @@ test "Browser.HTML.Window" {
414429
"true",
415430
},
416431
}, .{});
432+
433+
try runner.testCases(&.{
434+
.{ "const b64 = btoa('https://ziglang.org/documentation/master/std/#std.base64.Base64Decoder')", "undefined" },
435+
.{ "b64", "aHR0cHM6Ly96aWdsYW5nLm9yZy9kb2N1bWVudGF0aW9uL21hc3Rlci9zdGQvI3N0ZC5iYXNlNjQuQmFzZTY0RGVjb2Rlcg==" },
436+
.{ "const str = atob(b64)", "undefined" },
437+
.{ "str", "https://ziglang.org/documentation/master/std/#std.base64.Base64Decoder" },
438+
.{ "try { atob('b') } catch (e) { e } ", "Error: InvalidCharacterError" },
439+
}, .{});
417440
}

0 commit comments

Comments
 (0)