@yume-chan/struct 0.0.0-20240714132542

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