Skip to content

Commit 25788f8

Browse files
committed
implement TextEncoder
1 parent deded47 commit 25788f8

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Copyright (C) 2023-2024 Lightpanda (Selecy SAS)
2+
//
3+
// Francis Bouvier <[email protected]>
4+
// Pierre Tachoire <[email protected]>
5+
//
6+
// This program is free software: you can redistribute it and/or modify
7+
// it under the terms of the GNU Affero General Public License as
8+
// published by the Free Software Foundation, either version 3 of the
9+
// License, or (at your option) any later version.
10+
//
11+
// This program is distributed in the hope that it will be useful,
12+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14+
// GNU Affero General Public License for more details.
15+
//
16+
// You should have received a copy of the GNU Affero General Public License
17+
// along with this program. If not, see <https://www.gnu.org/licenses/>.
18+
19+
const std = @import("std");
20+
21+
const SessionState = @import("../env.zig").SessionState;
22+
23+
pub const Interfaces = .{
24+
TextEncoder,
25+
};
26+
27+
// https://encoding.spec.whatwg.org/#interface-textencoder
28+
pub const TextEncoder = struct {
29+
pub fn constructor() !TextEncoder {
30+
return .{};
31+
}
32+
33+
pub fn get_encoding(_: *const TextEncoder) []const u8 {
34+
return "utf-8";
35+
}
36+
37+
pub fn _encode(_: *const TextEncoder, v: []const u8, state: *SessionState) ![]u8 {
38+
// ensure the input is a valid utf-8
39+
if (!std.unicode.utf8ValidateSlice(v)) {
40+
return error.InvalidUtf8Input;
41+
}
42+
43+
// raw copy b/c we know the input is utf-8
44+
const result = try state.arena.alloc(u16, v.len);
45+
@memcpy(result, v);
46+
return result;
47+
}
48+
};
49+
50+
const testing = @import("../../testing.zig");
51+
test "Browser.Encoding.TextEncoder" {
52+
var runner = try testing.jsRunner(testing.tracking_allocator, .{});
53+
defer runner.deinit();
54+
55+
try runner.testCases(&.{
56+
.{ "var encoder = new TextEncoder();", "undefined" },
57+
.{ "encoder.encoding;", "utf-8" },
58+
.{ "encoder.encode('€');", "Uint8Array(3) [226, 130, 172]" },
59+
}, .{});
60+
}

src/browser/env.zig

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ const WebApis = struct {
2828
@import("crypto/crypto.zig").Crypto,
2929
@import("console/console.zig").Console,
3030
@import("dom/dom.zig").Interfaces,
31+
@import("encoding/text_encoder.zig").Interfaces,
3132
@import("events/event.zig").Interfaces,
3233
@import("html/html.zig").Interfaces,
3334
@import("iterator/iterator.zig").Interfaces,

0 commit comments

Comments
 (0)