Skip to content

Commit

Permalink
fix: RangeError [ERR_BUFFER_OUT_OF_BOUNDS] "length" is outside of buf…
Browse files Browse the repository at this point in the history
…fer bounds since nodejs 22.7

call buf.utf8Write() conditionally,  it will be called in buf.write()

ref: #2025
  • Loading branch information
waitingsong committed Aug 26, 2024
1 parent 19e1fef commit 0e834b5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 16 additions & 2 deletions src/writer_buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -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;
}

0 comments on commit 0e834b5

Please sign in to comment.