| 1 | // Every field is a big-endian |
| 2 | |
| 3 | export class Cursor |
| 4 | private off = |
| 5 | |
| 6 | constructor(readonly buffer |
| 7 | |
| 8 | u8(value: |
| 9 | this.buffer.writeUInt8 |
| 10 | this.off += |
| 11 | } |
| 12 | |
| 13 | u16(value: |
| 14 | this.buffer.writeUInt16BE |
| 15 | this.off += |
| 16 | } |
| 17 | |
| 18 | u32(value: |
| 19 | this.buffer.writeUInt32BE |
| 20 | this.off += |
| 21 | } |
| 22 | |
| 23 | u64(value: |
| 24 | this.buffer.writeBigUInt64BE |
| 25 | this.off += |
| 26 | } |
| 27 | |
| 28 | bytes(value: |
| 29 | value.copy(this |
| 30 | this.off += |
| 31 | } |
| 32 | |
| 33 | str(value: |
| 34 | const encoded = |
| 35 | this.u16(encoded |
| 36 | this.bytes(encoded |
| 37 | } |
| 38 | |
| 39 | get offset() { |
| 40 | return this.off |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | export class Reader |
| 45 | constructor( |
| 46 | private readonly buffer |
| 47 | private off = |
| 48 | ) {} |
| 49 | |
| 50 | u8() { |
| 51 | const value = |
| 52 | this.off += |
| 53 | return value; |
| 54 | } |
| 55 | |
| 56 | u16() { |
| 57 | const value = |
| 58 | this.off += |
| 59 | return value; |
| 60 | } |
| 61 | |
| 62 | u32() { |
| 63 | const value = |
| 64 | this.off += |
| 65 | return value; |
| 66 | } |
| 67 | |
| 68 | u64() { |
| 69 | const value = |
| 70 | this.off += |
| 71 | return Number(value |
| 72 | } |
| 73 | |
| 74 | bytes(length: |
| 75 | if (this.off |
| 76 | throw new RangeError( |
| 77 | } |
| 78 | const value = |
| 79 | this.off += |
| 80 | return value; |
| 81 | } |
| 82 | |
| 83 | str() { |
| 84 | return this.bytes |
| 85 | } |
| 86 | |
| 87 | get offset() { |
| 88 | return this.off |
| 89 | } |
| 90 | } |