Skip to content

Fix string with both length and zeroTerminated options - #318

Merged
keichi merged 1 commit into
masterfrom
fix-string-zero-terminated-length
Oct 18, 2026
Merged

keichi merged 1 commit into
masterfrom
fix-string-zero-terminated-length

Conversation

@keichi

@keichi keichi commented Oct 18, 2026

Copy link
Copy Markdown
Owner

Problem

generateString had two bugs when both length and zeroTerminated are set:

  1. If the NUL terminator is exactly the last byte within length, it was included in the result, because the end computation could not distinguish "hit NUL at the last byte" from "hit the length limit".
  2. length was inlined raw instead of going through ctx.generateOption, so function lengths caused a SyntaxError and field-name lengths became bare (undefined) identifiers.

Repro

new Parser().string("s", { length: 4, zeroTerminated: true }).parse(Buffer.from("abc\0")).s
// "abc\u0000" (expected "abc")

new Parser().uint8("n").string("s", { length: "n", zeroTerminated: true }) // ReferenceError at parse
new Parser().string("s", { length: () => 4, zeroTerminated: true })       // SyntaxError

Fix

Evaluate the length once via ctx.generateOption into a tmp variable, scan until the limit or a NUL (without consuming it), decode [start, offset), then skip the NUL if one was found. Offset semantics are unchanged (advances just past the NUL, or by length if none). Added regression tests.

@keichi
keichi force-pushed the fix-string-zero-terminated-length branch from 0947ad2 to 28efa80 Compare October 18, 2026 14:01
@keichi
keichi merged commit 836bb5c into master Oct 18, 2026
8 checks passed
@keichi
keichi deleted the fix-string-zero-terminated-length branch October 18, 2026 14:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant