@yume-chan/struct 0.0.24 → 2.0.0

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