@yume-chan/struct 0.0.9 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.json +23 -0
  2. package/CHANGELOG.md +16 -0
  3. package/LICENSE +21 -21
  4. package/README.md +720 -709
  5. package/dts/basic/context.d.ts +10 -18
  6. package/dts/basic/context.d.ts.map +1 -1
  7. package/dts/basic/definition.d.ts +4 -4
  8. package/dts/basic/definition.d.ts.map +1 -1
  9. package/dts/basic/field-value.d.ts +3 -5
  10. package/dts/basic/field-value.d.ts.map +1 -1
  11. package/dts/basic/struct-value.d.ts.map +1 -1
  12. package/dts/struct.d.ts +16 -17
  13. package/dts/struct.d.ts.map +1 -1
  14. package/dts/syncbird.d.ts +20 -0
  15. package/dts/syncbird.d.ts.map +1 -0
  16. package/dts/types/array-buffer.d.ts +13 -12
  17. package/dts/types/array-buffer.d.ts.map +1 -1
  18. package/dts/types/number.d.ts +4 -3
  19. package/dts/types/number.d.ts.map +1 -1
  20. package/dts/types/variable-length-array-buffer.d.ts +4 -4
  21. package/dts/types/variable-length-array-buffer.d.ts.map +1 -1
  22. package/dts/utils.d.ts +3 -2
  23. package/dts/utils.d.ts.map +1 -1
  24. package/esm/basic/context.js.map +1 -1
  25. package/esm/basic/definition.js.map +1 -1
  26. package/esm/basic/field-value.js +1 -2
  27. package/esm/basic/field-value.js.map +1 -1
  28. package/esm/basic/struct-value.js +0 -6
  29. package/esm/basic/struct-value.js.map +1 -1
  30. package/esm/struct.js +27 -17
  31. package/esm/struct.js.map +1 -1
  32. package/esm/syncbird.js +25 -0
  33. package/esm/syncbird.js.map +1 -0
  34. package/esm/types/array-buffer.js +21 -20
  35. package/esm/types/array-buffer.js.map +1 -1
  36. package/esm/types/number.js +9 -8
  37. package/esm/types/number.js.map +1 -1
  38. package/esm/types/variable-length-array-buffer.js +8 -8
  39. package/esm/types/variable-length-array-buffer.js.map +1 -1
  40. package/esm/utils.js +10 -0
  41. package/esm/utils.js.map +1 -1
  42. package/package.json +47 -50
  43. package/src/basic/context.ts +32 -42
  44. package/src/basic/definition.ts +72 -69
  45. package/src/basic/field-value.ts +67 -73
  46. package/src/basic/index.ts +4 -4
  47. package/src/basic/struct-value.ts +39 -45
  48. package/src/index.ts +5 -5
  49. package/src/struct.ts +595 -575
  50. package/src/syncbird.ts +53 -0
  51. package/src/types/array-buffer.ts +194 -184
  52. package/src/types/fixed-length-array-buffer.ts +17 -17
  53. package/src/types/index.ts +4 -4
  54. package/src/types/number.ts +114 -100
  55. package/src/types/variable-length-array-buffer.ts +142 -145
  56. package/src/utils.ts +62 -51
  57. package/cjs/basic/context.js +0 -7
  58. package/cjs/basic/context.js.map +0 -1
  59. package/cjs/basic/definition.js +0 -25
  60. package/cjs/basic/definition.js.map +0 -1
  61. package/cjs/basic/field-value.js +0 -40
  62. package/cjs/basic/field-value.js.map +0 -1
  63. package/cjs/basic/index.js +0 -8
  64. package/cjs/basic/index.js.map +0 -1
  65. package/cjs/basic/struct-value.js +0 -46
  66. package/cjs/basic/struct-value.js.map +0 -1
  67. package/cjs/index.js +0 -11
  68. package/cjs/index.js.map +0 -1
  69. package/cjs/struct.js +0 -177
  70. package/cjs/struct.js.map +0 -1
  71. package/cjs/types/array-buffer.js +0 -118
  72. package/cjs/types/array-buffer.js.map +0 -1
  73. package/cjs/types/fixed-length-array-buffer.js +0 -12
  74. package/cjs/types/fixed-length-array-buffer.js.map +0 -1
  75. package/cjs/types/index.js +0 -8
  76. package/cjs/types/index.js.map +0 -1
  77. package/cjs/types/number.js +0 -52
  78. package/cjs/types/number.js.map +0 -1
  79. package/cjs/types/variable-length-array-buffer.js +0 -77
  80. package/cjs/types/variable-length-array-buffer.js.map +0 -1
  81. package/cjs/utils.js +0 -11
  82. package/cjs/utils.js.map +0 -1
  83. package/tsconfig.cjs.json +0 -11
  84. package/tsconfig.esm.json +0 -15
package/README.md CHANGED
@@ -1,709 +1,720 @@
1
- # @yume-chan/struct
2
-
3
- ![license](https://img.shields.io/npm/l/@yume-chan/struct)
4
- ![npm type definitions](https://img.shields.io/npm/types/@yume-chan/struct)
5
- [![npm version](https://img.shields.io/npm/v/@yume-chan/struct)](https://www.npmjs.com/package/@yume-chan/struct)
6
- ![npm bundle size](https://img.shields.io/bundlephobia/min/@yume-chan/struct)
7
- ![Codecov](https://img.shields.io/codecov/c/github/yume-chan/ya-webadb?flag=struct&token=2fU3Cx2Edq)
8
-
9
- A C-style structure serializer and deserializer. Written in TypeScript and highly takes advantage of its type system.
10
-
11
- ## Installation
12
-
13
- ```sh
14
- $ npm i @yume-chan/struct
15
- ```
16
-
17
- ## Quick Start
18
-
19
- ```ts
20
- import Struct from '@yume-chan/struct';
21
-
22
- const MyStruct =
23
- new Struct({ littleEndian: true })
24
- .int8('foo')
25
- .int64('bar')
26
- .int32('bazLength')
27
- .string('baz', { lengthField: 'bazLength' });
28
-
29
- const value = await MyStruct.deserialize(stream);
30
- value.foo // number
31
- value.bar // bigint
32
- value.bazLength // number
33
- value.baz // string
34
-
35
- const buffer = MyStruct.serialize({
36
- foo: 42,
37
- bar: 42n,
38
- // `bazLength` automatically set to `baz.length`
39
- baz: 'Hello, World!',
40
- });
41
- ```
42
-
43
- - [Installation](#installation)
44
- - [Quick Start](#quick-start)
45
- - [Compatibility](#compatibility)
46
- - [API](#api)
47
- - [`placeholder`](#placeholder)
48
- - [`Struct`](#struct)
49
- - [`int8`/`uint8`/`int16`/`uint16`/`int32`/`uint32`](#int8uint8int16uint16int32uint32)
50
- - [`int64`/`uint64`](#int64uint64)
51
- - [`arraybuffer`/`uint8ClampedArray`/`string`](#arraybufferuint8clampedarraystring)
52
- - [`fields`](#fields)
53
- - [`extra`](#extra)
54
- - [`postDeserialize`](#postdeserialize)
55
- - [`deserialize`](#deserialize)
56
- - [`serialize`](#serialize)
57
- - [Custom field type](#custom-field-type)
58
- - [`Struct#field`](#structfield)
59
- - [`StructFieldDefinition`](#structfielddefinition)
60
- - [`TValue`/`TOmitInitKey`](#tvaluetomitinitkey)
61
- - [`getSize`](#getsize)
62
- - [`create`](#create)
63
- - [`deserialize`](#deserialize-1)
64
- - [`StructFieldValue`](#structfieldvalue)
65
- - [`getSize`](#getsize-1)
66
- - [`get`/`set`](#getset)
67
- - [`serialize`](#serialize-1)
68
-
69
- ## Compatibility
70
-
71
- | | Chrome | Edge | Firefox | Internet Explorer | Safari | Node.js |
72
- | ---------------------------------------------------- | ------ | ---- | ------- | ----------------- | -------------- | ------- |
73
- | [`Promise`][MDN_Promise] | 32 | 12 | 29 | No<sup>1</sup> | 8 | 0.12 |
74
- | [`ArrayBuffer`][MDN_ArrayBuffer] | 7 | 12 | 4 | 10 | 5.1 | 0.10 |
75
- | [`Uint8Array`][MDN_Uint8Array] | 7 | 12 | 4 | 10 | 5.1 | 0.10 |
76
- | [`DataView`][MDN_DataView] | 9 | 12 | 15 | 10 | 5.1 | 0.10 |
77
- | **Basic usage** | 32 | 12 | 29 | 10<sup>1</sup> | 8 | 0.12 |
78
- | [`BigInt`][MDN_BigInt] | 67 | 79 | 68 | No | 14 | 10.4 |
79
- | [`DataView#getBigUint64`][MDN_DataView_getBigUint64] | 67 | 79 | 68 | No | No<sup>2</sup> | 10.4 |
80
- | [`DataView#setBigUint64`][MDN_DataView_setBigUint64] | 67 | 79 | 68 | No | No<sup>2</sup> | 10.4 |
81
- | **Use [`int64/uint64`](#int64uint64) API** | 67 | 79 | 68 | No | 14<sup>2</sup> | 10.4 |
82
-
83
- <sup>1</sup> Requires a polyfill for Promise (e.g. [promise-polyfill](https://www.npmjs.com/package/promise-polyfill))
84
-
85
- <sup>2</sup> Requires a polyfill for `DataView#getBigUint64` and `DataView#setBigUint64`
86
-
87
- [MDN_Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
88
- [MDN_ArrayBuffer]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
89
- [MDN_Uint8Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
90
- [MDN_DataView]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
91
- [MDN_BigInt]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt
92
- [MDN_DataView_getBigUint64]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getBigUint64
93
- [MDN_DataView_setBigUint64]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setBigUint64
94
-
95
- ## API
96
-
97
- ### `placeholder`
98
-
99
- ```ts
100
- function placeholder<T>(): T {
101
- return undefined as unknown as T;
102
- }
103
- ```
104
-
105
- Returns a (fake) value of the given type. It's only useful in TypeScript, if you are using JavaScript, you shouldn't care about it.
106
-
107
- Many methods in this library have multiple generic parameters, but TypeScript only allows users to specify none (let TypeScript inference all of them from arguments), or all generic arguments. ([Microsoft/TypeScript#26242](https://github.com/microsoft/TypeScript/issues/26242))
108
-
109
- <details>
110
- <summary>Detail explanation (click to expand)</summary>
111
-
112
- When you have a generic method, where half generic parameters can be inferred.
113
-
114
- ```ts
115
- declare function fn<A, B>(a: A): [A, B];
116
- fn(42); // Expected 2 type arguments, but got 1. ts(2558)
117
- ```
118
-
119
- Rather than force users repeat the type `A`, I declare a parameter for `B`.
120
-
121
- ```ts
122
- declare function fn2<A, B>(a: A, b: B): [A, B];
123
- ```
124
-
125
- I don't really need a value of type `B`, I only require its type information
126
-
127
- ```ts
128
- fn2(42, placeholder<boolean>()) // fn2<number, boolean>
129
- ```
130
- </details>
131
-
132
- To workaround this issue, these methods have an extra `_typescriptType` parameter, to let you specify a generic parameter, without passing all other generic arguments manually. The actual value of `_typescriptType` argument is never used, so you can pass any value, as long as it has the correct type, including values produced by this `placeholder` method.
133
-
134
- **With that said, I don't expect you to specify any generic arguments manually when using this library.**
135
-
136
- ### `Struct`
137
-
138
- ```ts
139
- class Struct<
140
- TFields extends object = {},
141
- TOmitInitKey extends string | number | symbol = never,
142
- TExtra extends object = {},
143
- TPostDeserialized = undefined
144
- > {
145
- public constructor(options: Partial<StructOptions> = StructDefaultOptions);
146
- }
147
- ```
148
-
149
- Creates a new structure declaration.
150
-
151
- <details>
152
- <summary>Generic parameters (click to expand)</summary>
153
-
154
- This information was added to help you understand how does it work. These are considered as "internal state" so don't specify them manually.
155
-
156
- 1. `TFields`: Type of the Struct value. Modified when new fields are added.
157
- 2. `TOmitInitKey`: When serializing a structure containing variable length arrays, the length field can be calculate from the array field, so they doesn't need to be provided explicitly.
158
- 3. `TExtra`: Type of extra fields. Modified when `extra` is called.
159
- 4. `TPostDeserialized`: State of the `postDeserialize` function. Modified when `postDeserialize` is called. Affects return type of `deserialize`
160
- </details>
161
-
162
- **Parameters**
163
-
164
- 1. `options`:
165
- * `littleEndian:boolean = false`: Whether all multi-byte fields in this struct are [little-endian encoded][Wikipeida_Endianess].
166
-
167
- [Wikipeida_Endianess]: https://en.wikipedia.org/wiki/Endianness
168
-
169
- #### `int8`/`uint8`/`int16`/`uint16`/`int32`/`uint32`
170
-
171
- ```ts
172
- int32<
173
- TName extends string | number | symbol,
174
- TTypeScriptType = number
175
- >(
176
- name: TName,
177
- _typescriptType?: TTypeScriptType
178
- ): Struct<
179
- TFields & Record<TName, TTypeScriptType>,
180
- TOmitInitKey,
181
- TExtra,
182
- TPostDeserialized
183
- >;
184
- ```
185
-
186
- Appends an `int8`/`uint8`/`int16`/`uint16`/`int32`/`uint32` field to the `Struct`.
187
-
188
- <details>
189
- <summary>Generic parameters (click to expand)</summary>
190
-
191
- 1. `TName`: Literal type of the field's name.
192
- 2. `TTypeScriptType = number`: Type of the field in the result object. For example you can declare it as a number literal type, or some enum type.
193
- </details>
194
-
195
- **Parameters**
196
-
197
- 1. `name`: (Required) Field name. Must have a [literal type](https://www.typescriptlang.org/docs/handbook/literal-types.html).
198
- 2. `_typescriptType`: Set field's type. See examples below.
199
-
200
- **Note**
201
-
202
- There is no generic constraints on the `TTypeScriptType`, because TypeScript doesn't allow casting enum types to `number`.
203
-
204
- So it's technically possible to pass in an incompatible type (e.g. `string`). But obviously, it's a bad idea.
205
-
206
- **Examples**
207
-
208
- 1. Append an `int32` field named `foo`
209
-
210
- ```ts
211
- const struct = new Struct()
212
- .int32('foo');
213
-
214
- const value = await struct.deserialize(stream);
215
- value.foo; // number
216
-
217
- struct.serialize({ }, context) // error: 'foo' is required
218
- struct.serialize({ foo: 'bar' }, context) // error: 'foo' must be a number
219
- struct.serialize({ foo: 42 }, context) // ok
220
- ```
221
-
222
- 2. Set fields' type (can be used with [`placeholder` method](#placeholder))
223
-
224
- ```ts
225
- enum MyEnum {
226
- a,
227
- b,
228
- }
229
-
230
- const struct = new Struct()
231
- .int32('foo', placeholder<MyEnum>())
232
- .int32('bar', MyEnum.a as const);
233
-
234
- const value = await struct.deserialize(stream);
235
- value.foo; // MyEnum
236
- value.bar; // MyEnum.a
237
-
238
- struct.serialize({ foo: 42, bar: MyEnum.a }, context); // error: 'foo' must be of type `MyEnum`
239
- struct.serialize({ foo: MyEnum.a, bar: MyEnum.b }, context); // error: 'bar' must be of type `MyEnum.a`
240
- struct.serialize({ foo: MyEnum.a, bar: MyEnum.b }, context); // ok
241
- ```
242
-
243
- #### `int64`/`uint64`
244
-
245
- ```ts
246
- int64<
247
- TName extends string | number | symbol,
248
- TTypeScriptType = bigint
249
- >(
250
- name: TName,
251
- _typescriptType?: TTypeScriptType
252
- ): Struct<
253
- TFields & Record<TName, TTypeScriptType>,
254
- TOmitInitKey,
255
- TExtra,
256
- TPostDeserialized
257
- >;
258
- ```
259
-
260
- Appends an `int64`/`uint64` field to the `Struct`.
261
-
262
- Requires native support for `BigInt`. Check [compatibility table](#compatibility) for more information.
263
-
264
- #### `arraybuffer`/`uint8ClampedArray`/`string`
265
-
266
- ```ts
267
- arraybuffer<
268
- TName extends string | number | symbol,
269
- TTypeScriptType = ArrayBuffer
270
- >(
271
- name: TName,
272
- options: FixedLengthArrayBufferLikeFieldOptions,
273
- _typescriptType?: TTypeScriptType,
274
- ): Struct<
275
- TFields & Record<TName, TTypeScriptType>,
276
- TOmitInitKey,
277
- TExtra,
278
- TPostDeserialized
279
- >;
280
-
281
- arraybuffer<
282
- TName extends string | number | symbol,
283
- TOptions extends VariableLengthArrayBufferLikeFieldOptions<TFields>,
284
- TTypeScriptType = ArrayBuffer,
285
- >(
286
- name: TName,
287
- options: TOptions,
288
- _typescriptType?: TTypeScriptType,
289
- ): Struct<
290
- TFields & Record<TName, TTypeScriptType>,
291
- TOmitInitKey | TOptions['lengthField'],
292
- TExtra,
293
- TPostDeserialized
294
- >;
295
- ```
296
-
297
- Appends an `ArrayBuffer`/`Uint8ClampedArray`/`string` field to the `Struct`.
298
-
299
- The `options` parameter defines its length, it can be in two formats:
300
-
301
- * `{ length: number }`: Presence of the `length` option indicates that it's a fixed length array.
302
- * `{ lengthField: string }`: Presence of the `lengthField` option indicates it's a variable length array. The `lengthField` options must refers to a `number` or `string` typed field that's already defined in this `Struct`. When deserializing, it will use that field's value as its length. And when serializing, it will write its length to that field.
303
-
304
- All these three are actually deserialized to `ArrayBuffer`, then converted to `Uint8ClampedArray` or `string` for ease of use.
305
-
306
- #### `fields`
307
-
308
- ```ts
309
- fields<
310
- TOther extends Struct<any, any, any, any>
311
- >(
312
- other: TOther
313
- ): Struct<
314
- TFields & TOther['fieldsType'],
315
- TOmitInitKey | TOther['omitInitType'],
316
- TExtra & TOther['extraType'],
317
- TPostDeserialized
318
- >;
319
- ```
320
-
321
- Merges (flats) another `Struct`'s fields and extra fields into the current one.
322
-
323
- **Examples**
324
-
325
- 1. Extending another `Struct`
326
-
327
- ```ts
328
- const MyStructV1 =
329
- new Struct()
330
- .int32('field1');
331
-
332
- const MyStructV2 =
333
- new Struct()
334
- .fields(MyStructV1)
335
- .int32('field2');
336
-
337
- const structV2 = await MyStructV2.deserialize(context);
338
- structV2.field1; // number
339
- structV2.field2; // number
340
- // Fields are flatten
341
- ```
342
-
343
- 2. Also possible in any order
344
-
345
- ```ts
346
- const MyStructV1 =
347
- new Struct()
348
- .int32('field1');
349
-
350
- const MyStructV2 =
351
- new Struct()
352
- .int32('field2')
353
- .fields(MyStructV1);
354
-
355
- const structV2 = await MyStructV2.deserialize(context);
356
- structV2.field1; // number
357
- structV2.field2; // number
358
- // Same result as above, but serialize/deserialize order is reversed
359
- ```
360
-
361
- #### `extra`
362
-
363
- ```ts
364
- extra<
365
- T extends Record<
366
- Exclude<
367
- keyof T,
368
- Exclude<
369
- keyof T,
370
- keyof TFields
371
- >
372
- >,
373
- never
374
- >
375
- >(
376
- value: T & ThisType<Overwrite<Overwrite<TExtra, T>, TFields>>
377
- ): Struct<
378
- TFields,
379
- TInit,
380
- Overwrite<TExtra, T>,
381
- TPostDeserialized
382
- >;
383
- ```
384
-
385
- Adds extra fields into the `Struct`. Extra fields will be defined on prototype of each Struct values, so they don't affect serialize and deserialize process, and deserialized fields will overwrite extra fields.
386
-
387
- Multiple calls merge all extra fields together.
388
-
389
- **Generic Parameters**
390
-
391
- 1. `T`: Type of the extra fields. The scary looking generic constraint is used to forbid overwriting any already existed fields.
392
-
393
- **Parameters**
394
-
395
- 1. `value`: An object containing anything you want to add to Struct values. Accessors and methods are also allowed.
396
-
397
- **Examples**
398
-
399
- 1. Add an extra field
400
-
401
- ```ts
402
- const struct = new Struct()
403
- .int32('foo')
404
- .extra({
405
- bar: 'hello',
406
- });
407
-
408
- const value = await struct.deserialize(stream);
409
- value.foo; // number
410
- value.bar; // 'hello'
411
-
412
- struct.serialize({ foo: 42 }, context); // ok
413
- struct.serialize({ foo: 42, bar: 'hello' }, context); // error: 'bar' is redundant
414
- ```
415
-
416
- 2. Add getters and methods. `this` in functions refers to the result object.
417
-
418
- ```ts
419
- const struct = new Struct()
420
- .int32('foo')
421
- .extra({
422
- get bar() {
423
- // `this` is the result Struct value
424
- return this.foo + 1;
425
- },
426
- logBar() {
427
- // `this` also contains other extra fields
428
- console.log(this.bar);
429
- },
430
- });
431
-
432
- const value = await struct.deserialize(stream);
433
- value.foo; // number
434
- value.bar; // number
435
- value.logBar();
436
- ```
437
-
438
- #### `postDeserialize`
439
-
440
- ```ts
441
- postDeserialize(): Struct<TFields, TOmitInitKey, TExtra, undefined>;
442
- ```
443
-
444
- Remove any registered post deserialization callback.
445
-
446
- ```ts
447
- postDeserialize(
448
- callback: (this: TFields, object: TFields) => never
449
- ): Struct<TFields, TOmitInitKey, TExtra, never>;
450
- postDeserialize(
451
- callback: (this: TFields, object: TFields) => void
452
- ): Struct<TFields, TOmitInitKey, TExtra, undefined>;
453
- ```
454
-
455
- Registers (or replaces) a custom callback to be run after deserialized.
456
-
457
- `this` in `callback`, along with the first parameter `object` will both be the deserialized Struct value.
458
-
459
- A callback returning `never` (always throws errors) will change the return type of `deserialize` to `never`.
460
-
461
- A callback returning `void` means it modify the result object in-place (or doesn't modify it at all), so `deserialize` will still return the result object.
462
-
463
- ```ts
464
- postDeserialize<TPostSerialize>(
465
- callback: (this: TFields, object: TFields) => TPostSerialize
466
- ): Struct<TFields, TOmitInitKey, TExtra, TPostSerialize>;
467
- ```
468
-
469
- Registers (or replaces) a custom callback to be run after deserialized.
470
-
471
- A callback returning anything other than `undefined` will cause `deserialize` to return that value instead.
472
-
473
- **Generic Parameters**
474
-
475
- 1. `TPostSerialize`: Type of the new result.
476
-
477
- **Parameters**
478
-
479
- 1. `callback`: An function contains the custom logic to be run, optionally returns a new result. Or `undefined`, to remove any previously set `postDeserialize` callback.
480
-
481
- **Examples**
482
-
483
- 1. Handle an "error" packet
484
-
485
- ```ts
486
- // Say your protocol have an error packet,
487
- // You want to throw a JavaScript Error when received such a packet,
488
- // But you don't want to modify all receiving path
489
-
490
- const struct = new Struct()
491
- .int32('messageLength')
492
- .string('message', { lengthField: 'messageLength' })
493
- .postDeserialize(value => {
494
- throw new Error(value.message);
495
- });
496
- ```
497
-
498
- 2. Do anything you want
499
-
500
- ```ts
501
- // I think this one doesn't need any code example
502
- ```
503
-
504
- 3. Replace result object
505
-
506
- ```ts
507
- const struct1 = new Struct()
508
- .int32('foo')
509
- .postDeserialize(value => {
510
- return {
511
- bar: value.foo,
512
- };
513
- });
514
-
515
- const value = await struct.deserialize(stream);
516
- value.foo // error: not exist
517
- value.bar; // number
518
- ```
519
-
520
- #### `deserialize`
521
-
522
- ```ts
523
- interface StructDeserializationContext {
524
- decodeUtf8(buffer: ArrayBuffer): string;
525
-
526
- read(length: number): ArrayBuffer | Promise<ArrayBuffer>;
527
- }
528
-
529
- deserialize(
530
- context: StructDeserializationContext
531
- ): Promise<
532
- TPostDeserialized extends undefined
533
- ? Overwrite<TExtra, TValue>
534
- : TPostDeserialized
535
- >;
536
- ```
537
-
538
- Deserialize a Struct value from `context`.
539
-
540
- As the signature shows, if the `postDeserialize` callback returns any value, `deserialize` will return that value instead.
541
-
542
- The `read` method of `context`, when being called, should returns exactly `length` bytes of data (or throw an `Error` if it can't).
543
-
544
- #### `serialize`
545
-
546
- ```ts
547
- interface StructSerializationContext {
548
- encodeUtf8(input: string): ArrayBuffer;
549
- }
550
-
551
- serialize(
552
- init: Omit<TFields, TOmitInitKey>,
553
- context: StructSerializationContext
554
- ): ArrayBuffer;
555
- ```
556
-
557
- Serialize a Struct value into an `ArrayBuffer`.
558
-
559
- ## Custom field type
560
-
561
- This library supports adding fields of user defined types.
562
-
563
- ### `Struct#field`
564
-
565
- ```ts
566
- field<
567
- TName extends string | number | symbol,
568
- TDefinition extends StructFieldDefinition<any, any, any>
569
- >(
570
- name: TName,
571
- definition: TDefinition
572
- ): Struct<
573
- TFields & Record<TName, TDefinition['TValue']>,
574
- TOmitInitKey | TDefinition['TOmitInitKey'],
575
- TExtra,
576
- TPostDeserialized
577
- >;
578
- ```
579
-
580
- Appends a `StructFieldDefinition` to the `Struct`.
581
-
582
- Actually, all built-in field type methods are aliases of `field`. For example, calling
583
-
584
- ```ts
585
- struct.int8('foo')
586
- ```
587
-
588
- is same as
589
-
590
- ```ts
591
- struct.field(
592
- 'foo',
593
- new NumberFieldDefinition(
594
- NumberFieldType.Int8
595
- )
596
- )
597
- ```
598
-
599
-
600
- ### `StructFieldDefinition`
601
-
602
- ```ts
603
- abstract class StructFieldDefinition<
604
- TOptions = void,
605
- TValue = unknown,
606
- TOmitInitKey extends PropertyKey = never,
607
- > {
608
- public readonly options: TOptions;
609
-
610
- public constructor(options: TOptions);
611
- }
612
- ```
613
-
614
- A `StructFieldDefinition` describes type, size and runtime semantics of a field.
615
-
616
- It's an `abstract` class, means it lacks some method implementations, so it shouldn't be constructed.
617
-
618
- #### `TValue`/`TOmitInitKey`
619
-
620
- These two fields are used to provide type information to TypeScript. Their values will always be `undefined`, but having correct types is enough. You don't need to care about them.
621
-
622
- #### `getSize`
623
-
624
- ```ts
625
- abstract getSize(): number;
626
- ```
627
-
628
- Derived classes must implement this method to return size (or minimal size if it's dynamic) of this field.
629
-
630
- Actual size should be returned from `StructFieldValue#getSize`
631
-
632
- #### `create`
633
-
634
- ```ts
635
- abstract create(
636
- options: Readonly<StructOptions>,
637
- context: StructSerializationContext,
638
- struct: StructValue,
639
- value: TValue,
640
- ): StructFieldValue<this>;
641
- ```
642
-
643
- Derived classes must implement this method to create its own field value instance for the current definition.
644
-
645
- `Struct#serialize` will call this method, then call `StructFieldValue#serialize` to serialize one field value.
646
-
647
- #### `deserialize`
648
-
649
- ```ts
650
- abstract deserialize(
651
- options: Readonly<StructOptions>,
652
- context: StructDeserializationContext,
653
- struct: StructValue,
654
- ): ValueOrPromise<StructFieldValue<this>>;
655
- ```
656
-
657
- Derived classes must implement this method to define how to deserialize a value from `context`. Can also return a `Promise`.
658
-
659
- Usually implementations should be:
660
-
661
- 1. Somehow parse the value from `context`
662
- 2. Pass the value into its `create` method
663
-
664
- Sometimes, some metadata is present when deserializing, but need to be calculated when serializing, for example a UTF-8 encoded string may have different length between itself (character count) and serialized form (byte length). So `deserialize` can save those metadata on the `StructFieldValue` instance for later use.
665
-
666
- ### `StructFieldValue`
667
-
668
- ```ts
669
- abstract class StructFieldValue<
670
- TDefinition extends StructFieldDefinition<any, any, any>
671
- >
672
- ```
673
-
674
- To define a custom type, one must create their own `StructFieldValue` type to define the runtime semantics.
675
-
676
- Each `StructFieldValue` is linked to a `StructFieldDefinition`.
677
-
678
- #### `getSize`
679
-
680
- ```ts
681
- getSize(): number;
682
- ```
683
-
684
- Gets size of this field. By default, it returns its `definition`'s size.
685
-
686
- If this field's size can change based on some criteria, one must override `getSize` to return its actual size.
687
-
688
- #### `get`/`set`
689
-
690
- ```ts
691
- get(): TDefinition['TValue'];
692
- set(value: TDefinition['TValue']): void;
693
- ```
694
-
695
- Defines how to get or set this field's value. By default, it store its value in `value` field.
696
-
697
- If one needs to manipulate other states when getting/setting values, they can override these methods.
698
-
699
- #### `serialize`
700
-
701
- ```ts
702
- abstract serialize(
703
- dataView: DataView,
704
- offset: number,
705
- context: StructSerializationContext
706
- ): void;
707
- ```
708
-
709
- Derived classes must implement this method to serialize current value into `dataView`, from `offset`. It must not write more bytes than what its `getSize` returned.
1
+ # @yume-chan/struct
2
+
3
+ ![license](https://img.shields.io/npm/l/@yume-chan/struct)
4
+ ![npm type definitions](https://img.shields.io/npm/types/@yume-chan/struct)
5
+ [![npm version](https://img.shields.io/npm/v/@yume-chan/struct)](https://www.npmjs.com/package/@yume-chan/struct)
6
+ ![npm bundle size](https://img.shields.io/bundlephobia/min/@yume-chan/struct)
7
+ ![Codecov](https://img.shields.io/codecov/c/github/yume-chan/ya-webadb?flag=struct&token=2fU3Cx2Edq)
8
+
9
+ A C-style structure serializer and deserializer. Written in TypeScript and highly takes advantage of its type system.
10
+
11
+ **WARNING:** The public API is UNSTABLE. If you have any questions, please open an issue.
12
+
13
+ ## Installation
14
+
15
+ ```sh
16
+ $ npm i @yume-chan/struct
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ```ts
22
+ import Struct from '@yume-chan/struct';
23
+
24
+ const MyStruct =
25
+ new Struct({ littleEndian: true })
26
+ .int8('foo')
27
+ .int64('bar')
28
+ .int32('bazLength')
29
+ .string('baz', { lengthField: 'bazLength' });
30
+
31
+ const value = await MyStruct.deserialize(stream);
32
+ value.foo // number
33
+ value.bar // bigint
34
+ value.bazLength // number
35
+ value.baz // string
36
+
37
+ const buffer = MyStruct.serialize({
38
+ foo: 42,
39
+ bar: 42n,
40
+ // `bazLength` automatically set to `baz.length`
41
+ baz: 'Hello, World!',
42
+ });
43
+ ```
44
+
45
+ - [Installation](#installation)
46
+ - [Quick Start](#quick-start)
47
+ - [Compatibility](#compatibility)
48
+ - [API](#api)
49
+ - [`placeholder`](#placeholder)
50
+ - [`Struct`](#struct)
51
+ - [`int8`/`uint8`/`int16`/`uint16`/`int32`/`uint32`](#int8uint8int16uint16int32uint32)
52
+ - [`int64`/`uint64`](#int64uint64)
53
+ - [`arraybuffer`/`uint8ClampedArray`/`string`](#arraybufferuint8clampedarraystring)
54
+ - [`fields`](#fields)
55
+ - [`extra`](#extra)
56
+ - [`postDeserialize`](#postdeserialize)
57
+ - [`deserialize`](#deserialize)
58
+ - [`serialize`](#serialize)
59
+ - [Custom field type](#custom-field-type)
60
+ - [`Struct#field`](#structfield)
61
+ - [`StructFieldDefinition`](#structfielddefinition)
62
+ - [`TValue`/`TOmitInitKey`](#tvaluetomitinitkey)
63
+ - [`getSize`](#getsize)
64
+ - [`create`](#create)
65
+ - [`deserialize`](#deserialize-1)
66
+ - [`StructFieldValue`](#structfieldvalue)
67
+ - [`getSize`](#getsize-1)
68
+ - [`get`/`set`](#getset)
69
+ - [`serialize`](#serialize-1)
70
+
71
+ ## Compatibility
72
+
73
+ | | Chrome | Edge | Firefox | Internet Explorer | Safari | Node.js |
74
+ | ---------------------------------------------------- | ------ | ---- | ------- | ----------------- | -------------- | ------- |
75
+ | [`Promise`][MDN_Promise] | 32 | 12 | 29 | No<sup>1</sup> | 8 | 0.12 |
76
+ | [`ArrayBuffer`][MDN_ArrayBuffer] | 7 | 12 | 4 | 10 | 5.1 | 0.10 |
77
+ | [`Uint8Array`][MDN_Uint8Array] | 7 | 12 | 4 | 10 | 5.1 | 0.10 |
78
+ | [`DataView`][MDN_DataView] | 9 | 12 | 15 | 10 | 5.1 | 0.10 |
79
+ | **Basic usage** | 32 | 12 | 29 | 10<sup>1</sup> | 8 | 0.12 |
80
+ | [`BigInt`][MDN_BigInt] | 67 | 79 | 68 | No | 14 | 10.4 |
81
+ | [`DataView#getBigUint64`][MDN_DataView_getBigUint64] | 67 | 79 | 68 | No | No<sup>2</sup> | 10.4 |
82
+ | [`DataView#setBigUint64`][MDN_DataView_setBigUint64] | 67 | 79 | 68 | No | No<sup>2</sup> | 10.4 |
83
+ | **Use [`int64/uint64`](#int64uint64) API** | 67 | 79 | 68 | No | 14<sup>2</sup> | 10.4 |
84
+
85
+ <sup>1</sup> Requires a polyfill for Promise (e.g. [promise-polyfill](https://www.npmjs.com/package/promise-polyfill))
86
+
87
+ <sup>2</sup> Requires a polyfill for `DataView#getBigUint64` and `DataView#setBigUint64`
88
+
89
+ [MDN_Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
90
+ [MDN_ArrayBuffer]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
91
+ [MDN_Uint8Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
92
+ [MDN_DataView]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
93
+ [MDN_BigInt]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt
94
+ [MDN_DataView_getBigUint64]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/getBigUint64
95
+ [MDN_DataView_setBigUint64]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView/setBigUint64
96
+
97
+ ## API
98
+
99
+ ### `placeholder`
100
+
101
+ ```ts
102
+ function placeholder<T>(): T {
103
+ return undefined as unknown as T;
104
+ }
105
+ ```
106
+
107
+ Returns a (fake) value of the given type. It's only useful in TypeScript, if you are using JavaScript, you shouldn't care about it.
108
+
109
+ Many methods in this library have multiple generic parameters, but TypeScript only allows users to specify none (let TypeScript inference all of them from arguments), or all generic arguments. ([Microsoft/TypeScript#26242](https://github.com/microsoft/TypeScript/issues/26242))
110
+
111
+ <details>
112
+ <summary>Detail explanation (click to expand)</summary>
113
+
114
+ When you have a generic method, where half generic parameters can be inferred.
115
+
116
+ ```ts
117
+ declare function fn<A, B>(a: A): [A, B];
118
+ fn(42); // Expected 2 type arguments, but got 1. ts(2558)
119
+ ```
120
+
121
+ Rather than force users repeat the type `A`, I declare a parameter for `B`.
122
+
123
+ ```ts
124
+ declare function fn2<A, B>(a: A, b: B): [A, B];
125
+ ```
126
+
127
+ I don't really need a value of type `B`, I only require its type information
128
+
129
+ ```ts
130
+ fn2(42, placeholder<boolean>()) // fn2<number, boolean>
131
+ ```
132
+ </details>
133
+
134
+ To workaround this issue, these methods have an extra `_typescriptType` parameter, to let you specify a generic parameter, without passing all other generic arguments manually. The actual value of `_typescriptType` argument is never used, so you can pass any value, as long as it has the correct type, including values produced by this `placeholder` method.
135
+
136
+ **With that said, I don't expect you to specify any generic arguments manually when using this library.**
137
+
138
+ ### `Struct`
139
+
140
+ ```ts
141
+ class Struct<
142
+ TFields extends object = {},
143
+ TOmitInitKey extends string | number | symbol = never,
144
+ TExtra extends object = {},
145
+ TPostDeserialized = undefined
146
+ > {
147
+ public constructor(options: Partial<StructOptions> = StructDefaultOptions);
148
+ }
149
+ ```
150
+
151
+ Creates a new structure declaration.
152
+
153
+ <details>
154
+ <summary>Generic parameters (click to expand)</summary>
155
+
156
+ This information was added to help you understand how does it work. These are considered as "internal state" so don't specify them manually.
157
+
158
+ 1. `TFields`: Type of the Struct value. Modified when new fields are added.
159
+ 2. `TOmitInitKey`: When serializing a structure containing variable length arrays, the length field can be calculate from the array field, so they doesn't need to be provided explicitly.
160
+ 3. `TExtra`: Type of extra fields. Modified when `extra` is called.
161
+ 4. `TPostDeserialized`: State of the `postDeserialize` function. Modified when `postDeserialize` is called. Affects return type of `deserialize`
162
+ </details>
163
+
164
+ **Parameters**
165
+
166
+ 1. `options`:
167
+ * `littleEndian:boolean = false`: Whether all multi-byte fields in this struct are [little-endian encoded][Wikipeida_Endianess].
168
+
169
+ [Wikipeida_Endianess]: https://en.wikipedia.org/wiki/Endianness
170
+
171
+ #### `int8`/`uint8`/`int16`/`uint16`/`int32`/`uint32`
172
+
173
+ ```ts
174
+ int32<
175
+ TName extends string | number | symbol,
176
+ TTypeScriptType = number
177
+ >(
178
+ name: TName,
179
+ _typescriptType?: TTypeScriptType
180
+ ): Struct<
181
+ TFields & Record<TName, TTypeScriptType>,
182
+ TOmitInitKey,
183
+ TExtra,
184
+ TPostDeserialized
185
+ >;
186
+ ```
187
+
188
+ Appends an `int8`/`uint8`/`int16`/`uint16`/`int32`/`uint32` field to the `Struct`.
189
+
190
+ <details>
191
+ <summary>Generic parameters (click to expand)</summary>
192
+
193
+ 1. `TName`: Literal type of the field's name.
194
+ 2. `TTypeScriptType = number`: Type of the field in the result object. For example you can declare it as a number literal type, or some enum type.
195
+ </details>
196
+
197
+ **Parameters**
198
+
199
+ 1. `name`: (Required) Field name. Must have a [literal type](https://www.typescriptlang.org/docs/handbook/literal-types.html).
200
+ 2. `_typescriptType`: Set field's type. See examples below.
201
+
202
+ **Note**
203
+
204
+ There is no generic constraints on the `TTypeScriptType`, because TypeScript doesn't allow casting enum types to `number`.
205
+
206
+ So it's technically possible to pass in an incompatible type (e.g. `string`). But obviously, it's a bad idea.
207
+
208
+ **Examples**
209
+
210
+ 1. Append an `int32` field named `foo`
211
+
212
+ ```ts
213
+ const struct = new Struct()
214
+ .int32('foo');
215
+
216
+ const value = await struct.deserialize(stream);
217
+ value.foo; // number
218
+
219
+ struct.serialize({ }) // error: 'foo' is required
220
+ struct.serialize({ foo: 'bar' }) // error: 'foo' must be a number
221
+ struct.serialize({ foo: 42 }) // ok
222
+ ```
223
+
224
+ 2. Set fields' type (can be used with [`placeholder` method](#placeholder))
225
+
226
+ ```ts
227
+ enum MyEnum {
228
+ a,
229
+ b,
230
+ }
231
+
232
+ const struct = new Struct()
233
+ .int32('foo', placeholder<MyEnum>())
234
+ .int32('bar', MyEnum.a as const);
235
+
236
+ const value = await struct.deserialize(stream);
237
+ value.foo; // MyEnum
238
+ value.bar; // MyEnum.a
239
+
240
+ struct.serialize({ foo: 42, bar: MyEnum.a }); // error: 'foo' must be of type `MyEnum`
241
+ struct.serialize({ foo: MyEnum.a, bar: MyEnum.b }); // error: 'bar' must be of type `MyEnum.a`
242
+ struct.serialize({ foo: MyEnum.a, bar: MyEnum.b }); // ok
243
+ ```
244
+
245
+ #### `int64`/`uint64`
246
+
247
+ ```ts
248
+ int64<
249
+ TName extends string | number | symbol,
250
+ TTypeScriptType = bigint
251
+ >(
252
+ name: TName,
253
+ _typescriptType?: TTypeScriptType
254
+ ): Struct<
255
+ TFields & Record<TName, TTypeScriptType>,
256
+ TOmitInitKey,
257
+ TExtra,
258
+ TPostDeserialized
259
+ >;
260
+ ```
261
+
262
+ Appends an `int64`/`uint64` field to the `Struct`.
263
+
264
+ Requires native support for `BigInt`. Check [compatibility table](#compatibility) for more information.
265
+
266
+ #### `arraybuffer`/`uint8ClampedArray`/`string`
267
+
268
+ ```ts
269
+ arraybuffer<
270
+ TName extends string | number | symbol,
271
+ TTypeScriptType = ArrayBuffer
272
+ >(
273
+ name: TName,
274
+ options: FixedLengthArrayBufferLikeFieldOptions,
275
+ _typescriptType?: TTypeScriptType,
276
+ ): Struct<
277
+ TFields & Record<TName, TTypeScriptType>,
278
+ TOmitInitKey,
279
+ TExtra,
280
+ TPostDeserialized
281
+ >;
282
+
283
+ arraybuffer<
284
+ TName extends string | number | symbol,
285
+ TOptions extends VariableLengthArrayBufferLikeFieldOptions<TFields>,
286
+ TTypeScriptType = ArrayBuffer,
287
+ >(
288
+ name: TName,
289
+ options: TOptions,
290
+ _typescriptType?: TTypeScriptType,
291
+ ): Struct<
292
+ TFields & Record<TName, TTypeScriptType>,
293
+ TOmitInitKey | TOptions['lengthField'],
294
+ TExtra,
295
+ TPostDeserialized
296
+ >;
297
+ ```
298
+
299
+ Appends an `ArrayBuffer`/`Uint8ClampedArray`/`string` field to the `Struct`.
300
+
301
+ The `options` parameter defines its length, it can be in two formats:
302
+
303
+ * `{ length: number }`: Presence of the `length` option indicates that it's a fixed length array.
304
+ * `{ lengthField: string }`: Presence of the `lengthField` option indicates it's a variable length array. The `lengthField` options must refers to a `number` or `string` typed field that's already defined in this `Struct`. When deserializing, it will use that field's value as its length. And when serializing, it will write its length to that field.
305
+
306
+ All these three are actually deserialized to `ArrayBuffer`, then converted to `Uint8ClampedArray` or `string` for ease of use.
307
+
308
+ #### `fields`
309
+
310
+ ```ts
311
+ fields<
312
+ TOther extends Struct<any, any, any, any>
313
+ >(
314
+ other: TOther
315
+ ): Struct<
316
+ TFields & TOther['fieldsType'],
317
+ TOmitInitKey | TOther['omitInitType'],
318
+ TExtra & TOther['extraType'],
319
+ TPostDeserialized
320
+ >;
321
+ ```
322
+
323
+ Merges (flats) another `Struct`'s fields and extra fields into the current one.
324
+
325
+ **Examples**
326
+
327
+ 1. Extending another `Struct`
328
+
329
+ ```ts
330
+ const MyStructV1 =
331
+ new Struct()
332
+ .int32('field1');
333
+
334
+ const MyStructV2 =
335
+ new Struct()
336
+ .fields(MyStructV1)
337
+ .int32('field2');
338
+
339
+ const structV2 = await MyStructV2.deserialize(stream);
340
+ structV2.field1; // number
341
+ structV2.field2; // number
342
+ // Fields are flatten
343
+ ```
344
+
345
+ 2. Also possible in any order
346
+
347
+ ```ts
348
+ const MyStructV1 =
349
+ new Struct()
350
+ .int32('field1');
351
+
352
+ const MyStructV2 =
353
+ new Struct()
354
+ .int32('field2')
355
+ .fields(MyStructV1);
356
+
357
+ const structV2 = await MyStructV2.deserialize(stream);
358
+ structV2.field1; // number
359
+ structV2.field2; // number
360
+ // Same result as above, but serialize/deserialize order is reversed
361
+ ```
362
+
363
+ #### `extra`
364
+
365
+ ```ts
366
+ extra<
367
+ T extends Record<
368
+ Exclude<
369
+ keyof T,
370
+ Exclude<
371
+ keyof T,
372
+ keyof TFields
373
+ >
374
+ >,
375
+ never
376
+ >
377
+ >(
378
+ value: T & ThisType<Overwrite<Overwrite<TExtra, T>, TFields>>
379
+ ): Struct<
380
+ TFields,
381
+ TInit,
382
+ Overwrite<TExtra, T>,
383
+ TPostDeserialized
384
+ >;
385
+ ```
386
+
387
+ Adds extra fields into the `Struct`. Extra fields will be defined on prototype of each Struct values, so they don't affect serialize and deserialize process, and deserialized fields will overwrite extra fields.
388
+
389
+ Multiple calls merge all extra fields together.
390
+
391
+ **Generic Parameters**
392
+
393
+ 1. `T`: Type of the extra fields. The scary looking generic constraint is used to forbid overwriting any already existed fields.
394
+
395
+ **Parameters**
396
+
397
+ 1. `value`: An object containing anything you want to add to Struct values. Accessors and methods are also allowed.
398
+
399
+ **Examples**
400
+
401
+ 1. Add an extra field
402
+
403
+ ```ts
404
+ const struct = new Struct()
405
+ .int32('foo')
406
+ .extra({
407
+ bar: 'hello',
408
+ });
409
+
410
+ const value = await struct.deserialize(stream);
411
+ value.foo; // number
412
+ value.bar; // 'hello'
413
+
414
+ struct.serialize({ foo: 42 }); // ok
415
+ struct.serialize({ foo: 42, bar: 'hello' }); // error: 'bar' is redundant
416
+ ```
417
+
418
+ 2. Add getters and methods. `this` in functions refers to the result object.
419
+
420
+ ```ts
421
+ const struct = new Struct()
422
+ .int32('foo')
423
+ .extra({
424
+ get bar() {
425
+ // `this` is the result Struct value
426
+ return this.foo + 1;
427
+ },
428
+ logBar() {
429
+ // `this` also contains other extra fields
430
+ console.log(this.bar);
431
+ },
432
+ });
433
+
434
+ const value = await struct.deserialize(stream);
435
+ value.foo; // number
436
+ value.bar; // number
437
+ value.logBar();
438
+ ```
439
+
440
+ #### `postDeserialize`
441
+
442
+ ```ts
443
+ postDeserialize(): Struct<TFields, TOmitInitKey, TExtra, undefined>;
444
+ ```
445
+
446
+ Remove any registered post deserialization callback.
447
+
448
+ ```ts
449
+ postDeserialize(
450
+ callback: (this: TFields, object: TFields) => never
451
+ ): Struct<TFields, TOmitInitKey, TExtra, never>;
452
+ postDeserialize(
453
+ callback: (this: TFields, object: TFields) => void
454
+ ): Struct<TFields, TOmitInitKey, TExtra, undefined>;
455
+ ```
456
+
457
+ Registers (or replaces) a custom callback to be run after deserialized.
458
+
459
+ `this` in `callback`, along with the first parameter `object` will both be the deserialized Struct value.
460
+
461
+ A callback returning `never` (always throws errors) will change the return type of `deserialize` to `never`.
462
+
463
+ A callback returning `void` means it modify the result object in-place (or doesn't modify it at all), so `deserialize` will still return the result object.
464
+
465
+ ```ts
466
+ postDeserialize<TPostSerialize>(
467
+ callback: (this: TFields, object: TFields) => TPostSerialize
468
+ ): Struct<TFields, TOmitInitKey, TExtra, TPostSerialize>;
469
+ ```
470
+
471
+ Registers (or replaces) a custom callback to be run after deserialized.
472
+
473
+ A callback returning anything other than `undefined` will cause `deserialize` to return that value instead.
474
+
475
+ **Generic Parameters**
476
+
477
+ 1. `TPostSerialize`: Type of the new result.
478
+
479
+ **Parameters**
480
+
481
+ 1. `callback`: An function contains the custom logic to be run, optionally returns a new result. Or `undefined`, to remove any previously set `postDeserialize` callback.
482
+
483
+ **Examples**
484
+
485
+ 1. Handle an "error" packet
486
+
487
+ ```ts
488
+ // Say your protocol have an error packet,
489
+ // You want to throw a JavaScript Error when received such a packet,
490
+ // But you don't want to modify all receiving path
491
+
492
+ const struct = new Struct()
493
+ .int32('messageLength')
494
+ .string('message', { lengthField: 'messageLength' })
495
+ .postDeserialize(value => {
496
+ throw new Error(value.message);
497
+ });
498
+ ```
499
+
500
+ 2. Do anything you want
501
+
502
+ ```ts
503
+ // I think this one doesn't need any code example
504
+ ```
505
+
506
+ 3. Replace result object
507
+
508
+ ```ts
509
+ const struct1 = new Struct()
510
+ .int32('foo')
511
+ .postDeserialize(value => {
512
+ return {
513
+ bar: value.foo,
514
+ };
515
+ });
516
+
517
+ const value = await struct.deserialize(stream);
518
+ value.foo // error: not exist
519
+ value.bar; // number
520
+ ```
521
+
522
+ #### `deserialize`
523
+
524
+ ```ts
525
+ interface StructDeserializeStream {
526
+ /**
527
+ * Read data from the underlying data source.
528
+ *
529
+ * Stream must return exactly `length` bytes or data. If that's not possible
530
+ * (due to end of file or other error condition), it must throw an error.
531
+ */
532
+ read(length: number): ArrayBuffer;
533
+ }
534
+
535
+ deserialize(
536
+ stream: StructDeserializeStream,
537
+ ): TPostDeserialized extends undefined
538
+ ? Overwrite<TExtra, TValue>
539
+ : TPostDeserialized
540
+ >;
541
+ deserialize(
542
+ stream: StructAsyncDeserializeStream,
543
+ ): Promise<
544
+ TPostDeserialized extends undefined
545
+ ? Overwrite<TExtra, TValue>
546
+ : TPostDeserialized
547
+ >
548
+ >;
549
+ ```
550
+
551
+ Deserialize a Struct value from `stream`.
552
+
553
+ As the signature shows, if the `postDeserialize` callback returns any value, `deserialize` will return that value instead.
554
+
555
+ The `read` method of `stream`, when being called, should returns exactly `length` bytes of data (or throw an `Error` if it can't).
556
+
557
+ #### `serialize`
558
+
559
+ ```ts
560
+ serialize(
561
+ init: Omit<TFields, TOmitInitKey>
562
+ ): ArrayBuffer;
563
+ ```
564
+
565
+ Serialize a Struct value into an `ArrayBuffer`.
566
+
567
+ ## Custom field type
568
+
569
+ This library supports adding fields of user defined types.
570
+
571
+ ### `Struct#field`
572
+
573
+ ```ts
574
+ field<
575
+ TName extends string | number | symbol,
576
+ TDefinition extends StructFieldDefinition<any, any, any>
577
+ >(
578
+ name: TName,
579
+ definition: TDefinition
580
+ ): Struct<
581
+ TFields & Record<TName, TDefinition['TValue']>,
582
+ TOmitInitKey | TDefinition['TOmitInitKey'],
583
+ TExtra,
584
+ TPostDeserialized
585
+ >;
586
+ ```
587
+
588
+ Appends a `StructFieldDefinition` to the `Struct`.
589
+
590
+ Actually, all built-in field type methods are aliases of `field`. For example, calling
591
+
592
+ ```ts
593
+ struct.int8('foo')
594
+ ```
595
+
596
+ is same as
597
+
598
+ ```ts
599
+ struct.field(
600
+ 'foo',
601
+ new NumberFieldDefinition(
602
+ NumberFieldType.Int8
603
+ )
604
+ )
605
+ ```
606
+
607
+
608
+ ### `StructFieldDefinition`
609
+
610
+ ```ts
611
+ abstract class StructFieldDefinition<
612
+ TOptions = void,
613
+ TValue = unknown,
614
+ TOmitInitKey extends PropertyKey = never,
615
+ > {
616
+ public readonly options: TOptions;
617
+
618
+ public constructor(options: TOptions);
619
+ }
620
+ ```
621
+
622
+ A `StructFieldDefinition` describes type, size and runtime semantics of a field.
623
+
624
+ It's an `abstract` class, means it lacks some method implementations, so it shouldn't be constructed.
625
+
626
+ #### `TValue`/`TOmitInitKey`
627
+
628
+ These two fields are used to provide type information to TypeScript. Their values will always be `undefined`, but having correct types is enough. You don't need to care about them.
629
+
630
+ #### `getSize`
631
+
632
+ ```ts
633
+ abstract getSize(): number;
634
+ ```
635
+
636
+ Derived classes must implement this method to return size (or minimal size if it's dynamic) of this field.
637
+
638
+ Actual size should be returned from `StructFieldValue#getSize`
639
+
640
+ #### `create`
641
+
642
+ ```ts
643
+ abstract create(
644
+ options: Readonly<StructOptions>,
645
+ struct: StructValue,
646
+ value: TValue,
647
+ ): StructFieldValue<this>;
648
+ ```
649
+
650
+ Derived classes must implement this method to create its own field value instance for the current definition.
651
+
652
+ `Struct#serialize` will call this method, then call `StructFieldValue#serialize` to serialize one field value.
653
+
654
+ #### `deserialize`
655
+
656
+ ```ts
657
+ abstract deserialize(
658
+ options: Readonly<StructOptions>,
659
+ stream: StructDeserializeStream,
660
+ struct: StructValue,
661
+ ): StructFieldValue<this>;
662
+ abstract deserialize(
663
+ options: Readonly<StructOptions>,
664
+ stream: StructAsyncDeserializeStream,
665
+ struct: StructValue,
666
+ ): Promise<StructFieldValue<this>>;
667
+ ```
668
+
669
+ Derived classes must implement this method to define how to deserialize a value from `stream`. Can also return a `Promise`.
670
+
671
+ Usually implementations should be:
672
+
673
+ 1. Somehow parse the value from `stream`
674
+ 2. Pass the value into its `create` method
675
+
676
+ Sometimes, some metadata is present when deserializing, but need to be calculated when serializing, for example a UTF-8 encoded string may have different length between itself (character count) and serialized form (byte length). So `deserialize` can save those metadata on the `StructFieldValue` instance for later use.
677
+
678
+ ### `StructFieldValue`
679
+
680
+ ```ts
681
+ abstract class StructFieldValue<
682
+ TDefinition extends StructFieldDefinition<any, any, any>
683
+ >
684
+ ```
685
+
686
+ To define a custom type, one must create their own `StructFieldValue` type to define the runtime semantics.
687
+
688
+ Each `StructFieldValue` is linked to a `StructFieldDefinition`.
689
+
690
+ #### `getSize`
691
+
692
+ ```ts
693
+ getSize(): number;
694
+ ```
695
+
696
+ Gets size of this field. By default, it returns its `definition`'s size.
697
+
698
+ If this field's size can change based on some criteria, one must override `getSize` to return its actual size.
699
+
700
+ #### `get`/`set`
701
+
702
+ ```ts
703
+ get(): TDefinition['TValue'];
704
+ set(value: TDefinition['TValue']): void;
705
+ ```
706
+
707
+ Defines how to get or set this field's value. By default, it store its value in `value` field.
708
+
709
+ If one needs to manipulate other states when getting/setting values, they can override these methods.
710
+
711
+ #### `serialize`
712
+
713
+ ```ts
714
+ abstract serialize(
715
+ dataView: DataView,
716
+ offset: number
717
+ ): void;
718
+ ```
719
+
720
+ Derived classes must implement this method to serialize current value into `dataView`, from `offset`. It must not write more bytes than what its `getSize` returned.