diff --git a/README.md b/README.md index dc8e9ad..cf4ccf5 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/lib/binary_parser.ts b/lib/binary_parser.ts index 230d16b..2a9a964 100644 --- a/lib/binary_parser.ts +++ b/lib/binary_parser.ts @@ -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) => { @@ -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( @@ -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;"); diff --git a/test/primitive_parser.ts b/test/primitive_parser.ts index 0d67482..9932a3a 100644 --- a/test/primitive_parser.ts +++ b/test/primitive_parser.ts @@ -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 })