aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/bun.js/webcore/encoding.zig10
-rw-r--r--test/js/node/buffer.test.js12
2 files changed, 15 insertions, 7 deletions
diff --git a/src/bun.js/webcore/encoding.zig b/src/bun.js/webcore/encoding.zig
index 4fa0f4ca2..9b1de838c 100644
--- a/src/bun.js/webcore/encoding.zig
+++ b/src/bun.js/webcore/encoding.zig
@@ -808,7 +808,8 @@ pub const Encoder = struct {
.utf16le => constructFromU16(input, len, .utf16le),
.ucs2 => constructFromU16(input, len, .utf16le),
.utf8 => constructFromU16(input, len, .utf8),
- .ascii => constructFromU16(input, len, .utf8),
+ .ascii => constructFromU16(input, len, .ascii),
+ .latin1 => constructFromU16(input, len, .latin1),
else => unreachable,
};
return JSC.JSValue.createBuffer(globalObject, slice, globalObject.bunVM().allocator);
@@ -1170,12 +1171,7 @@ pub const Encoder = struct {
},
.latin1, .buffer, .ascii => {
var to = allocator.alloc(u8, len) catch return &[_]u8{};
- var input_bytes = std.mem.sliceAsBytes(input[0..len]);
- @memcpy(to[0..input_bytes.len], input_bytes);
- for (to[0..len], 0..) |c, i| {
- to[i] = @as(u8, @as(u7, @truncate(c)));
- }
-
+ strings.copyU16IntoU8(to[0..len], []const u16, input[0..len]);
return to;
},
// string is already encoded, just need to copy the data
diff --git a/test/js/node/buffer.test.js b/test/js/node/buffer.test.js
index 129ceb02b..834536020 100644
--- a/test/js/node/buffer.test.js
+++ b/test/js/node/buffer.test.js
@@ -2552,3 +2552,15 @@ it("write alias", () => {
shouldBeSame("writeBigUint64BE", "writeBigUInt64BE", BigInt(1000));
shouldBeSame("writeBigUint64LE", "writeBigUInt64LE", BigInt(1000));
});
+
+it("construct buffer from UTF16, issue #3914", () => {
+ const raw = Buffer.from([0, 104, 0, 101, 0, 108, 0, 108, 0, 111]);
+ const data = new Uint16Array(raw);
+
+ const decoder = new TextDecoder("UTF-16");
+ const str = decoder.decode(data);
+ expect(str).toStrictEqual("\x00h\x00e\x00l\x00l\x00o");
+
+ const buf = Buffer.from(str, "latin1");
+ expect(buf).toStrictEqual(raw);
+});