Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions lib/binary_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1202,17 +1202,18 @@ export class Parser {
const toHex = 'b => b.toString(16).padStart(2, "0")';

if (this.options.length != null && this.options.zeroTerminated) {
const len = this.options.length;
const len = ctx.generateTmpVariable();
ctx.pushCode(`var ${len} = ${ctx.generateOption(this.options.length)};`);
ctx.pushCode(`var ${start} = offset;`);
ctx.pushCode(
`while(offset - ${start} < ${len} && dataView.getUint8(offset++) !== 0);`,
`while(offset - ${start} < ${len} && dataView.getUint8(offset) !== 0) offset++;`,
);
const end = `offset - ${start} < ${len} ? offset - 1 : offset`;
ctx.pushCode(
isHex
? `${name} = Array.from(buffer.subarray(${start}, ${end}), ${toHex}).join('');`
: `${name} = new TextDecoder('${encoding}').decode(buffer.subarray(${start}, ${end}));`,
? `${name} = Array.from(buffer.subarray(${start}, offset), ${toHex}).join('');`
: `${name} = new TextDecoder('${encoding}').decode(buffer.subarray(${start}, offset));`,
);
ctx.pushCode(`if (offset - ${start} < ${len}) offset++;`);
} else if (this.options.length != null) {
const len = ctx.generateOption(this.options.length);
ctx.pushCode(
Expand Down
21 changes: 21 additions & 0 deletions test/primitive_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,27 @@ function primitiveParserTests(
c: "ij",
});
});
it("should exclude null terminator at the last byte of fixed-length string", () => {
const buffer = factory(new TextEncoder().encode("abc\u0000de"));
const parser = Parser.start()
.string("a", { length: 4, zeroTerminated: true })
.string("b", { length: 2 });

expect(parser.parse(buffer)).toStrictEqual({ a: "abc", b: "de" });
});
it("should parse zero terminated string with function/field length", () => {
const buffer = factory(new TextEncoder().encode("\u0004abcdef\u0000"));
const parser = Parser.start()
.uint8("len")
.string("a", { length: "len", zeroTerminated: true })
.string("b", { length: () => 4, zeroTerminated: true });

expect(parser.parse(buffer)).toStrictEqual({
len: 4,
a: "abcd",
b: "ef",
});
});
it("should strip trailing null characters", () => {
const buffer = hexToBuf("746573740000");
const parser1 = Parser.start().string("str", {
Expand Down
Loading