Skip to content
Open
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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,8 @@ the following keys:
function. Use number for statically sized arrays, string to reference
another variable and function to do some calculation.
- `zeroTerminated` - (Optional, defaults to `false`) If true, then this parser
reads until it reaches zero.
reads until it reaches zero. UTF-16 encodings consume a two-byte null code
unit; other encodings consume one null byte. `length` remains a byte limit.
- `greedy` - (Optional, defaults to `false`) If true, then this parser reads
until it reaches the end of the buffer. Will consume zero-bytes.
- `stripNull` - (Optional, must be used with `length`) If true, then strip
Expand Down
22 changes: 16 additions & 6 deletions lib/binary_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1406,6 +1406,11 @@ export class Parser {
const name = ctx.generateVariable(this.varName);
const start = ctx.generateTmpVariable();
const decoder = this.options.decoder;
const unitSize =
decoder?.encoding === "utf-16le" || decoder?.encoding === "utf-16be"
? 2
: 1;
const readUnit = `dataView.getUint${unitSize * 8}(offset)`;
const latin1 = (bytes: string) =>
`${ctx.addImport(bytesToLatin1)}(${bytes})`;
const decode = (bytes: string) => {
Expand All @@ -1430,10 +1435,16 @@ export class Parser {
ctx.pushCode(`var ${len} = ${ctx.generateOption(this.options.length)};`);
ctx.pushCode(`var ${start} = offset;`);
ctx.pushCode(
`while(offset - ${start} < ${len} && dataView.getUint8(offset) !== 0) offset++;`,
`while(offset - ${start} + ${unitSize} <= ${len} && ${readUnit} !== 0) offset += ${unitSize};`,
);
if (unitSize === 2) {
// A byte limit can end partway through a UTF-16 code unit.
ctx.pushCode(
`if (offset - ${start} + 2 > ${len}) offset = ${start} + ${len};`,
);
}
ctx.pushCode(`${name} = ${decode(`buffer.subarray(${start}, offset)`)};`);
ctx.pushCode(`if (offset - ${start} < ${len}) offset++;`);
ctx.pushCode(`if (offset - ${start} < ${len}) offset += ${unitSize};`);
} else if (this.options.length != null) {
const len = ctx.generateOption(this.options.length);
ctx.pushCode(
Expand All @@ -1442,10 +1453,9 @@ export class Parser {
ctx.pushCode(`offset += ${len};`);
} else if (this.options.zeroTerminated) {
ctx.pushCode(`var ${start} = offset;`);
ctx.pushCode("while(dataView.getUint8(offset++) !== 0);");
ctx.pushCode(
`${name} = ${decode(`buffer.subarray(${start}, offset - 1)`)};`,
);
ctx.pushCode(`while(${readUnit} !== 0) offset += ${unitSize};`);
ctx.pushCode(`${name} = ${decode(`buffer.subarray(${start}, offset)`)};`);
ctx.pushCode(`offset += ${unitSize};`);
} else if (this.options.greedy) {
ctx.pushCode(`var ${start} = offset;`);
ctx.pushCode("offset = buffer.length;");
Expand Down
66 changes: 66 additions & 0 deletions test/primitive_parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,72 @@ function primitiveParserTests(
});

describe("String parser", () => {
for (const encoding of ["utf-16le", "utf-16be", "utf-16"]) {
const textBytes =
encoding === "utf-16be" ? [0, 0x41, 1, 0] : [0x41, 0, 0, 1];

for (const length of [undefined, 8]) {
it(`should read a UTF-16 terminator (${encoding}, length ${length})`, () => {
const parser = new Parser()
.uint8("prefix")
.string("text", { encoding, zeroTerminated: true, length })
.saveOffset("offset")
.uint8("tail");

expect(
parser.parse(factory([17, ...textBytes, 0, 0, 42])),
).toStrictEqual({
prefix: 17,
text: "A\u0100",
offset: 7,
tail: 42,
});
});
}

it(`should consume a complete empty UTF-16 terminator (${encoding})`, () => {
const parser = new Parser()
.string("text", { encoding, zeroTerminated: true })
.uint8("tail");
expect(parser.parse(factory([0, 0, 42]))).toStrictEqual({
text: "",
tail: 42,
});
});

it(`should respect a UTF-16 byte limit without a terminator (${encoding})`, () => {
const parser = new Parser()
.string("text", { encoding, zeroTerminated: true, length: 4 })
.uint8("tail");
expect(parser.parse(factory([...textBytes, 42]))).toStrictEqual({
text: "A\u0100",
tail: 42,
});
});

it(`should keep an odd UTF-16 byte limit (${encoding})`, () => {
const parser = new Parser()
.string("text", { encoding, zeroTerminated: true, length: 3 })
.uint8("tail");
expect(
parser.parse(factory([...textBytes.slice(0, 3), 42])),
).toStrictEqual({
text: "A\ufffd",
tail: 42,
});
});

it(`should reject a truncated UTF-16 terminator (${encoding})`, () => {
const parser = new Parser().string("text", {
encoding,
zeroTerminated: true,
});
expect(() => parser.parse(factory([...textBytes, 0]))).toThrow(
RangeError,
);
});
}

it("should parse string with length 0", () => {
const parser = Parser.start()
.string("a", { length: 0 })
Expand Down