From 0e834b5028e7decc56782183a2c7faa8575a817a Mon Sep 17 00:00:00 2001 From: waiting <1661926154@qq.com> Date: Sun, 25 Aug 2024 23:57:08 +0800 Subject: [PATCH] fix: RangeError [ERR_BUFFER_OUT_OF_BOUNDS] "length" is outside of buffer bounds since nodejs 22.7 call buf.utf8Write() conditionally, it will be called in buf.write() ref: https://github.com/protobufjs/protobuf.js/issues/2025 --- .github/workflows/test.yml | 2 +- src/writer_buffer.js | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b6795f91c..98df36e9a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -23,7 +23,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node_version: ["12", "14", "16", "18"] + node_version: ["12", "14", "16", "18", "20", "22"] steps: - uses: actions/checkout@v1 - uses: actions/setup-node@v1 diff --git a/src/writer_buffer.js b/src/writer_buffer.js index 09a4a912a..a7cd9e87e 100644 --- a/src/writer_buffer.js +++ b/src/writer_buffer.js @@ -54,11 +54,14 @@ BufferWriter.prototype.bytes = function write_bytes_buffer(value) { return this; }; +const isOlderVer = compareVersions(process.version.slice(1), targetVersion) < 0 ? true : false; + function writeStringBuffer(val, buf, pos) { + const targetVersion = '22.7.0'; if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) util.utf8.write(val, buf, pos); - else if (buf.utf8Write) - buf.utf8Write(val, pos); + else if (isOlderVer && buf.utf8Write) + buf.utf8Write(val, pos); // node less than 22.7.0 else buf.write(val, pos); } @@ -83,3 +86,14 @@ BufferWriter.prototype.string = function write_string_buffer(value) { */ BufferWriter._configure(); + +function compareVersions(version1, version2) { + const v1Parts = version1.split('.').map(Number); + const v2Parts = version2.split('.').map(Number); + + for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i+=1) { + if ((v1Parts[i] || 0) < (v2Parts[i] || 0)) { return -1 } + if ((v1Parts[i] || 0) > (v2Parts[i] || 0)) { return 1 } + } + return 0; +}