Fix Buffer *Write methods to default omitted length to remaining space#6891
Fix Buffer *Write methods to default omitted length to remaining space#6891says1117 wants to merge 1 commit into
Conversation
The encoding-specific write methods (asciiWrite, base64Write, base64urlWrite, hexWrite, latin1Write, ucs2Write, utf8Write) defaulted an omitted length argument to the full buffer size ( his.length) but then validated it against the bytes remaining after offset ( his.length - offset). As a result, any two-argument call with a non-zero offset — e.g. �uf.utf8Write(str, pos) — always threw ERR_OUT_OF_RANGE regardless of the string being written. Default the omitted length to his.length - offset instead, matching Node.js. Node briefly shipped this same bug class in v22.7.0 (nodejs/node#54523) and reverted it in v22.8.0 because it broke protobufjs and others. Adds a regression test covering all seven *Write methods. Fixes cloudflare#6875
|
All contributors have signed the CLA ✍️ ✅ |
|
I have read the CLA Document and I hereby sign the CLA |
|
Hi! This is my first contribution, so the internal build workflow didn't run automatically on my fork. Could one of the assigned reviewers kick it off when you have a chance? Quick summary of the change: the encoding-specific Buffer Thanks for taking a look! :) |
What
The encoding-specific
Bufferwrite methods (asciiWrite,base64Write,base64urlWrite,hexWrite,latin1Write,ucs2Write,utf8Write)defaulted an omitted
lengthto the full buffer size, then validated itagainst the space remaining after
offset. Any two-argument call with anon-zero offset therefore threw:
RangeError [ERR_OUT_OF_RANGE]: The value of "length" is out of range.
It must be >= 0 && <= 9. Received 10
This breaks real callers - notably protobufjs ≥ 7.6.0, which calls
buf.utf8Write(val, pos)during encoding.Fix
Default the omitted
lengthtothis.length - offsetin all sevenmethods, matching Node.js (which itself hit and reverted this exact bug
class between v22.7.0 and v22.8.0, nodejs/node#54523).
Testing
Adds
writeMethodsDefaultLengthtobuffer-nodejs-test.js, exercising allseven methods with a non-zero offset and omitted length, plus a byte-level
spot check for
utf8Write. The expected results were cross-checked againstNode.js.
Fixes #6875