|
2 | 2 | bigintle, |
3 | 3 | biguintle, |
4 | 4 | bool, |
| 5 | + bytes, |
5 | 6 | f16, |
6 | 7 | f32, |
7 | 8 | f64, |
@@ -488,6 +489,67 @@ test("fromDataView with setter is writable and enumerable", () => { |
488 | 489 | assert(keys.includes("val")) |
489 | 490 | }) |
490 | 491 |
|
| 492 | +test("string variable-length (no byteLength)", () => { |
| 493 | + // 4 bytes prefix + 6 bytes for variable-length string |
| 494 | + const Cls = defineStruct({ |
| 495 | + prefix: u32(0), |
| 496 | + name: string(4), |
| 497 | + }) |
| 498 | + const c = new Cls(new Uint8Array(10)) |
| 499 | + deepStrictEqual(c.name, "") |
| 500 | + c.name = "hello!" |
| 501 | + deepStrictEqual(c.name, "hello!") |
| 502 | + // trailing nulls are trimmed |
| 503 | + c.name = "hi" |
| 504 | + deepStrictEqual(c.name, "hi") |
| 505 | + // prefix field is unaffected |
| 506 | + c.prefix = 0xdeadbeef |
| 507 | + deepStrictEqual(c.prefix, 0xdeadbeef) |
| 508 | + deepStrictEqual(c.name, "hi") |
| 509 | +}) |
| 510 | + |
| 511 | +test("bytes fixed-length", () => { |
| 512 | + const buf = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]) |
| 513 | + const Cls = defineStruct({ |
| 514 | + data: bytes(2, 4), |
| 515 | + }) |
| 516 | + const c = new Cls(buf) |
| 517 | + expect(c.data).toBeInstanceOf(Uint8Array) |
| 518 | + deepStrictEqual(c.data.length, 4) |
| 519 | + // is a live view of the same underlying buffer |
| 520 | + strictEqual(c.data.buffer, buf.buffer) |
| 521 | + deepStrictEqual(c.data.byteOffset, 2) |
| 522 | + // mutations through the Uint8Array are reflected in buf |
| 523 | + c.data[0] = 0xff |
| 524 | + deepStrictEqual(buf[2], 0xff) |
| 525 | + // is read-only (no setter) |
| 526 | + throws(() => { |
| 527 | + // @ts-expect-error assigning to readonly property |
| 528 | + c.data = new Uint8Array(4) |
| 529 | + }) |
| 530 | +}) |
| 531 | + |
| 532 | +test("bytes variable-length (no byteLength)", () => { |
| 533 | + const buf = new Uint8Array([10, 20, 30, 40, 50]) |
| 534 | + const Cls = defineStruct({ |
| 535 | + data: bytes(2), |
| 536 | + }) |
| 537 | + const c = new Cls(buf) |
| 538 | + expect(c.data).toBeInstanceOf(Uint8Array) |
| 539 | + // extends from offset 2 to end of struct |
| 540 | + deepStrictEqual(c.data.length, 3) |
| 541 | + strictEqual(c.data.buffer, buf.buffer) |
| 542 | + deepStrictEqual(c.data.byteOffset, 2) |
| 543 | + // mutations through the Uint8Array are reflected in buf |
| 544 | + c.data[1] = 0xab |
| 545 | + deepStrictEqual(buf[3], 0xab) |
| 546 | + // is read-only (no setter) |
| 547 | + throws(() => { |
| 548 | + // @ts-expect-error assigning to readonly property |
| 549 | + c.data = new Uint8Array(3) |
| 550 | + }) |
| 551 | +}) |
| 552 | + |
491 | 553 | function hexToUint8Array(hex: string): Uint8Array { |
492 | 554 | if (hex.length % 2 !== 0) { |
493 | 555 | throw new TypeError("Hex input must have an even length") |
|
0 commit comments