From 8e1eae7dae43fa83d043a907f9e52815917be210 Mon Sep 17 00:00:00 2001 From: Ai Hoshino Date: Mon, 23 Oct 2023 04:42:05 +0800 Subject: [PATCH] fix(node:buffer): fix Buffer.write stuck (#6651) --- src/string_immutable.zig | 14 +++++++++----- test/js/node/buffer.test.js | 28 +++++++++++++++++++++++----- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/string_immutable.zig b/src/string_immutable.zig index 00ee8d8355..8e6dc0ab2a 100644 --- a/src/string_immutable.zig +++ b/src/string_immutable.zig @@ -2079,12 +2079,16 @@ pub fn copyLatin1IntoUTF8StopOnNonASCII(buf_: []u8, comptime Type: type, latin1_ } } - if (latin1.len > 0 and buf.len >= 2) { - if (comptime stop) return .{ .written = std.math.maxInt(u32), .read = std.math.maxInt(u32) }; + if (latin1.len > 0) { + if (buf.len >= 2) { + if (comptime stop) return .{ .written = std.math.maxInt(u32), .read = std.math.maxInt(u32) }; - buf[0..2].* = latin1ToCodepointBytesAssumeNotASCII(latin1[0]); - latin1 = latin1[1..]; - buf = buf[2..]; + buf[0..2].* = latin1ToCodepointBytesAssumeNotASCII(latin1[0]); + latin1 = latin1[1..]; + buf = buf[2..]; + } else { + break; + } } } diff --git a/test/js/node/buffer.test.js b/test/js/node/buffer.test.js index 450129b0ec..e178a65095 100644 --- a/test/js/node/buffer.test.js +++ b/test/js/node/buffer.test.js @@ -211,11 +211,29 @@ it("only top level parent propagates from a non-pooled instance", () => { }); it("UTF-8 write() & slice()", () => { - const testValue = "\u00F6\u65E5\u672C\u8A9E"; // ö日本語 - const buffer = Buffer.allocUnsafe(32); - const size = buffer.write(testValue, 0, "utf8"); - const slice = buffer.toString("utf8", 0, size); - expect(slice).toBe(testValue); + { + const testValue = "\u00F6\u65E5\u672C\u8A9E"; // ö日本語 + const buffer = Buffer.allocUnsafe(32); + const size = buffer.write(testValue, 0, "utf8"); + const slice = buffer.toString("utf8", 0, size); + expect(slice).toBe(testValue); + } + { + const buffer = Buffer.allocUnsafe(1); + buffer.write("\x61"); + buffer.write("\xFF"); + expect(buffer).toStrictEqual(Buffer.from([0x61])); + } + { + const buffer = Buffer.alloc(5); + buffer.write("\x61\xFF\x62\xFF\x63", "utf8"); + expect(buffer).toStrictEqual(Buffer.from([0x61, 0xc3, 0xbf, 0x62, 0x00])); + } + { + const buffer = Buffer.alloc(5); + buffer.write("\xFF\x61\xFF\x62\xFF", "utf8"); + expect(buffer).toStrictEqual(Buffer.from([0xc3, 0xbf, 0x61, 0xc3, 0xbf])); + } }); it("triple slice", () => {