@solana/codecs-data-structures 2.0.0-canary-20240731173615

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 (53) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +728 -0
  3. package/dist/index.browser.cjs +709 -0
  4. package/dist/index.browser.cjs.map +1 -0
  5. package/dist/index.browser.mjs +653 -0
  6. package/dist/index.browser.mjs.map +1 -0
  7. package/dist/index.native.mjs +653 -0
  8. package/dist/index.native.mjs.map +1 -0
  9. package/dist/index.node.cjs +709 -0
  10. package/dist/index.node.cjs.map +1 -0
  11. package/dist/index.node.mjs +653 -0
  12. package/dist/index.node.mjs.map +1 -0
  13. package/dist/types/array.d.ts +62 -0
  14. package/dist/types/array.d.ts.map +1 -0
  15. package/dist/types/assertions.d.ts +3 -0
  16. package/dist/types/assertions.d.ts.map +1 -0
  17. package/dist/types/bit-array.d.ts +31 -0
  18. package/dist/types/bit-array.d.ts.map +1 -0
  19. package/dist/types/boolean.d.ts +41 -0
  20. package/dist/types/boolean.d.ts.map +1 -0
  21. package/dist/types/bytes.d.ts +23 -0
  22. package/dist/types/bytes.d.ts.map +1 -0
  23. package/dist/types/constant.d.ts +16 -0
  24. package/dist/types/constant.d.ts.map +1 -0
  25. package/dist/types/discriminated-union.d.ts +97 -0
  26. package/dist/types/discriminated-union.d.ts.map +1 -0
  27. package/dist/types/enum-helpers.d.ts +51 -0
  28. package/dist/types/enum-helpers.d.ts.map +1 -0
  29. package/dist/types/enum.d.ts +57 -0
  30. package/dist/types/enum.d.ts.map +1 -0
  31. package/dist/types/hidden-prefix.d.ts +20 -0
  32. package/dist/types/hidden-prefix.d.ts.map +1 -0
  33. package/dist/types/hidden-suffix.d.ts +20 -0
  34. package/dist/types/hidden-suffix.d.ts.map +1 -0
  35. package/dist/types/index.d.ts +18 -0
  36. package/dist/types/index.d.ts.map +1 -0
  37. package/dist/types/map.d.ts +54 -0
  38. package/dist/types/map.d.ts.map +1 -0
  39. package/dist/types/nullable.d.ts +95 -0
  40. package/dist/types/nullable.d.ts.map +1 -0
  41. package/dist/types/set.d.ts +51 -0
  42. package/dist/types/set.d.ts.map +1 -0
  43. package/dist/types/struct.d.ts +33 -0
  44. package/dist/types/struct.d.ts.map +1 -0
  45. package/dist/types/tuple.d.ts +31 -0
  46. package/dist/types/tuple.d.ts.map +1 -0
  47. package/dist/types/union.d.ts +32 -0
  48. package/dist/types/union.d.ts.map +1 -0
  49. package/dist/types/unit.d.ts +14 -0
  50. package/dist/types/unit.d.ts.map +1 -0
  51. package/dist/types/utils.d.ts +24 -0
  52. package/dist/types/utils.d.ts.map +1 -0
  53. package/package.json +83 -0
package/README.md ADDED
@@ -0,0 +1,728 @@
1
+ [![npm][npm-image]][npm-url]
2
+ [![npm-downloads][npm-downloads-image]][npm-url]
3
+ [![semantic-release][semantic-release-image]][semantic-release-url]
4
+ <br />
5
+ [![code-style-prettier][code-style-prettier-image]][code-style-prettier-url]
6
+
7
+ [code-style-prettier-image]: https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square
8
+ [code-style-prettier-url]: https://github.com/prettier/prettier
9
+ [npm-downloads-image]: https://img.shields.io/npm/dm/@solana/codecs-data-structures/experimental.svg?style=flat
10
+ [npm-image]: https://img.shields.io/npm/v/@solana/codecs-data-structures/experimental.svg?style=flat
11
+ [npm-url]: https://www.npmjs.com/package/@solana/codecs-data-structures/v/experimental
12
+ [semantic-release-image]: https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg
13
+ [semantic-release-url]: https://github.com/semantic-release/semantic-release
14
+
15
+ # @solana/codecs-data-structures
16
+
17
+ This package contains codecs for various data structures such as arrays, maps, structs, tuples, enums, etc. It can be used standalone, but it is also exported as part of the Solana JavaScript SDK [`@solana/web3.js@experimental`](https://github.com/solana-labs/solana-web3.js/tree/master/packages/library).
18
+
19
+ This package is also part of the [`@solana/codecs` package](https://github.com/solana-labs/solana-web3.js/tree/master/packages/codecs) which acts as an entry point for all codec packages as well as for their documentation.
20
+
21
+ ## Array codec
22
+
23
+ The `getArrayCodec` function accepts any codec of type `T` and returns a codec of type `Array<T>`. For instance, here’s how we can create a codec for arrays of numbers that each fit in a single byte.
24
+
25
+ ```ts
26
+ const bytes = getArrayCodec(getU8Codec()).encode([1, 2, 3]);
27
+ const array = getArrayCodec(getU8Codec()).decode(bytes);
28
+ ```
29
+
30
+ By default, the size of the array is stored as a `u32` prefix before encoding the items.
31
+
32
+ ```ts
33
+ getArrayCodec(getU8Codec()).encode([1, 2, 3]);
34
+ // 0x03000000010203
35
+ // | └-- 3 items of 1 byte each.
36
+ // └-- 4-byte prefix telling us to read 3 items.
37
+ ```
38
+
39
+ However, you may use the `size` option to configure this behaviour. It can be one of the following three strategies:
40
+
41
+ - `Codec<number>`: When a number codec is provided, that codec will be used to encode and decode the size prefix.
42
+ - `number`: When a number is provided, the codec will expect a fixed number of items in the array. An error will be thrown when trying to encode an array of a different length.
43
+ - `"remainder"`: When the string `"remainder"` is passed as a size, the codec will use the remainder of the bytes to encode/decode its items. This means the size is not stored or known in advance but simply inferred from the rest of the buffer. For instance, if we have an array of `u16` numbers and 10 bytes remaining, we know there are 5 items in this array.
44
+
45
+ ```ts
46
+ getArrayCodec(getU8Codec(), { size: getU16Codec() }).encode([1, 2, 3]);
47
+ // 0x0300010203
48
+ // | └-- 3 items of 1 byte each.
49
+ // └-- 2-byte prefix telling us to read 3 items.
50
+
51
+ getArrayCodec(getU8Codec(), { size: 3 }).encode([1, 2, 3]);
52
+ // 0x010203
53
+ // └-- 3 items of 1 byte each. There must always be 3 items in the array.
54
+
55
+ getArrayCodec(getU8Codec(), { size: 'remainder' }).encode([1, 2, 3]);
56
+ // 0x010203
57
+ // └-- 3 items of 1 byte each. The size is inferred from the remainder of the bytes.
58
+ ```
59
+
60
+ Separate `getArrayEncoder` and `getArrayDecoder` functions are also available.
61
+
62
+ ```ts
63
+ const bytes = getArrayEncoder(getU8Encoder()).encode([1, 2, 3]);
64
+ const array = getArrayDecoder(getU8Decoder()).decode(bytes);
65
+ ```
66
+
67
+ ## Set codec
68
+
69
+ The `getSetCodec` function accepts any codec of type `T` and returns a codec of type `Set<T>`. For instance, here’s how we can create a codec for sets of numbers that each fit in a single byte.
70
+
71
+ ```ts
72
+ const bytes = getSetCodec(getU8Codec()).encode(new Set([1, 2, 3]));
73
+ const set = getSetCodec(getU8Codec()).decode(bytes);
74
+ ```
75
+
76
+ Just like the array codec, it uses a `u32` size prefix by default but can be configured using the `size` option. [See the array codec](#array-codec) for more details.
77
+
78
+ ```ts
79
+ getSetCodec(getU8Codec(), { size: getU16Codec() }).encode(new Set([1, 2, 3]));
80
+ getSetCodec(getU8Codec(), { size: 3 }).encode(new Set([1, 2, 3]));
81
+ getSetCodec(getU8Codec(), { size: 'remainder' }).encode(new Set([1, 2, 3]));
82
+ ```
83
+
84
+ Separate `getSetEncoder` and `getSetDecoder` functions are also available.
85
+
86
+ ```ts
87
+ const bytes = getSetEncoder(getU8Encoder()).encode(new Set([1, 2, 3]));
88
+ const set = getSetDecoder(getU8Decoder()).decode(bytes);
89
+ ```
90
+
91
+ ## Map codec
92
+
93
+ The `getMapCodec` function accepts two codecs of type `K` and `V` and returns a codec of type `Map<K, V>`. For instance, here’s how we can create a codec for maps such that the keys are fixed strings of 8 bytes and the values are `u8` numbers.
94
+
95
+ ```ts
96
+ const keyCodec = fixCodecSize(getUtf8Codec(), 8);
97
+ const valueCodec = getU8Codec();
98
+ const bytes = getMapCodec(keyCodec, valueCodec).encode(new Map([['alice', 42]]));
99
+ const map = getMapCodec(keyCodec, valueCodec).decode(bytes);
100
+ ```
101
+
102
+ Just like the array codec, it uses a `u32` size prefix by default.
103
+
104
+ ```ts
105
+ const keyCodec = fixCodecSize(getUtf8Codec(), 8);
106
+ const valueCodec = getU8Codec();
107
+ const myMap = new Map<string, number>();
108
+ myMap.set('alice', 42);
109
+ myMap.set('bob', 5);
110
+
111
+ getMapCodec(keyCodec, valueCodec).encode(myMap);
112
+ // 0x02000000616c6963650000002a626f62000000000005
113
+ // | | | | └-- 2nd entry value (5).
114
+ // | | | └-- 2nd entry key ("bob").
115
+ // | | └-- 1st entry value (42).
116
+ // | └-- 1st entry key ("alice").
117
+ // └-- 4-byte prefix telling us to read 2 map entries.
118
+ ```
119
+
120
+ However, it can be configured using the `size` option. [See the `size` option of the array codec](#array-codec) for more details.
121
+
122
+ ```ts
123
+ getMapCodec(keyCodec, valueCodec, { size: getU16Codec() }).encode(myMap);
124
+ getMapCodec(keyCodec, valueCodec, { size: 3 }).encode(myMap);
125
+ getMapCodec(keyCodec, valueCodec, { size: 'remainder' }).encode(myMap);
126
+ ```
127
+
128
+ Separate `getMapEncoder` and `getMapDecoder` functions are also available.
129
+
130
+ ```ts
131
+ const bytes = getMapEncoder(keyEncoder, valueEncoder).encode(myMap);
132
+ const map = getMapDecoder(keyDecoder, valueDecoder).decode(bytes);
133
+ ```
134
+
135
+ ## Tuple codec
136
+
137
+ The `getTupleCodec` function accepts any number of codecs — `T`, `U`, `V`, etc. — and returns a tuple codec of type `[T, U, V, …]` such that each item is in the order of the provided codecs.
138
+
139
+ ```ts
140
+ const codec = getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec()), getU8Codec(), getU64Codec()]);
141
+ const bytes = codec.encode(['alice', 42, 123]);
142
+ const tuple = codec.decode(bytes);
143
+ ```
144
+
145
+ Separate `getTupleEncoder` and `getTupleDecoder` functions are also available.
146
+
147
+ ```ts
148
+ const bytes = getTupleEncoder([getU8Encoder(), getU64Encoder()]).encode([42, 123]);
149
+ const tuple = getTupleDecoder([getU8Decoder(), getU64Decoder()]).decode(bytes);
150
+ ```
151
+
152
+ ## Struct codec
153
+
154
+ The `getStructCodec` function accepts any number of field codecs and returns a codec for an object containing all these fields. Each provided field is an array such that the first item is the name of the field and the second item is the codec used to encode and decode that field type.
155
+
156
+ ```ts
157
+ type Person = { name: string; age: number };
158
+ const personCodec: Codec<Person> = getStructCodec([
159
+ ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],
160
+ ['age', getU8Codec()],
161
+ ]);
162
+
163
+ const bytes = personCodec.encode({ name: 'alice', age: 42 });
164
+ const person = personCodec.decode(bytes);
165
+ ```
166
+
167
+ Separate `getStructEncoder` and `getStructDecoder` functions are also available.
168
+
169
+ ```ts
170
+ const personEncoder: Encoder<Person> = getStructEncoder([
171
+ ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],
172
+ ['age', getU8Encoder()],
173
+ ]);
174
+ const personDecoder: Decoder<Person> = getStructDecoder([
175
+ ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],
176
+ ['age', getU8Decoder()],
177
+ ]);
178
+ const bytes = personEncoder.encode({ name: 'alice', age: 42 });
179
+ const person = personDecoder.decode(bytes);
180
+ ```
181
+
182
+ ## Enum codec
183
+
184
+ The `getEnumCodec` function accepts a JavaScript enum constructor and returns a codec for encoding and decoding values of that enum.
185
+
186
+ ```ts
187
+ enum Direction {
188
+ Left,
189
+ Right,
190
+ }
191
+
192
+ const bytes = getEnumCodec(Direction).encode(Direction.Left);
193
+ const direction = getEnumCodec(Direction).decode(bytes);
194
+ ```
195
+
196
+ When encoding an enum, you may either provide the value of the enum variant — e.g. `Direction.Left` — or its key — e.g. `'Left'`.
197
+
198
+ ```ts
199
+ enum Direction {
200
+ Left,
201
+ Right,
202
+ }
203
+
204
+ getEnumCodec(Direction).encode(Direction.Left); // 0x00
205
+ getEnumCodec(Direction).encode(Direction.Right); // 0x01
206
+ getEnumCodec(Direction).encode('Left'); // 0x00
207
+ getEnumCodec(Direction).encode('Right'); // 0x01
208
+ ```
209
+
210
+ As you can see, by default, a `u8` number is being used to store the enum value. However, a number codec may be passed as the `size` option to configure that behaviour.
211
+
212
+ ```ts
213
+ const u32DirectionCodec = getEnumCodec(Direction, { size: getU32Codec() });
214
+ u32DirectionCodec.encode(Direction.Left); // 0x00000000
215
+ u32DirectionCodec.encode(Direction.Right); // 0x01000000
216
+ ```
217
+
218
+ This function also works with lexical enums — e.g. `enum Direction { Left = '←' }` — explicit numerical enums — e.g. `enum Speed { Left = 50 }` — and hybrid enums with a mix of both.
219
+
220
+ ```ts
221
+ enum Numbers {
222
+ One,
223
+ Five = 5,
224
+ Six,
225
+ Nine = 'nine',
226
+ }
227
+
228
+ getEnumCodec(Numbers).encode(Direction.One); // 0x00
229
+ getEnumCodec(Numbers).encode(Direction.Five); // 0x01
230
+ getEnumCodec(Numbers).encode(Direction.Six); // 0x02
231
+ getEnumCodec(Numbers).encode(Direction.Nine); // 0x03
232
+ getEnumCodec(Numbers).encode('One'); // 0x00
233
+ getEnumCodec(Numbers).encode('Five'); // 0x01
234
+ getEnumCodec(Numbers).encode('Six'); // 0x02
235
+ getEnumCodec(Numbers).encode('Nine'); // 0x03
236
+ ```
237
+
238
+ Notice how, by default, the index of the enum variant is used to encode the value of the enum. For instance, in the example above, `Numbers.Five` is encoded as `0x01` even though its value is `5`. This is also true for lexical enums.
239
+
240
+ However, when dealing with numerical enums that have explicit values, you may use the `useValuesAsDiscriminators` option to encode the value of the enum variant instead of its index.
241
+
242
+ ```ts
243
+ enum Numbers {
244
+ One,
245
+ Five = 5,
246
+ Six,
247
+ Nine = 9,
248
+ }
249
+
250
+ const codec = getEnumCodec(Numbers, { useValuesAsDiscriminators: true });
251
+ codec.encode(Direction.One); // 0x00
252
+ codec.encode(Direction.Five); // 0x05
253
+ codec.encode(Direction.Six); // 0x06
254
+ codec.encode(Direction.Nine); // 0x09
255
+ codec.encode('One'); // 0x00
256
+ codec.encode('Five'); // 0x05
257
+ codec.encode('Six'); // 0x06
258
+ codec.encode('Nine'); // 0x09
259
+ ```
260
+
261
+ Note that when using the `useValuesAsDiscriminators` option on an enum that contains a lexical value, an error will be thrown.
262
+
263
+ ```ts
264
+ enum Lexical {
265
+ One,
266
+ Two = 'two',
267
+ }
268
+ getEnumCodec(Lexical, { useValuesAsDiscriminators: true }); // Throws an error.
269
+ ```
270
+
271
+ Separate `getEnumEncoder` and `getEnumDecoder` functions are also available.
272
+
273
+ ```ts
274
+ const bytes = getEnumEncoder(Direction).encode(Direction.Left);
275
+ const direction = getEnumDecoder(Direction).decode(bytes);
276
+ ```
277
+
278
+ ## Literal union codec
279
+
280
+ The `getLiteralUnionCodec` function works similarly to the `getUnionCodec` function but does not require a JavaScript `enum` to exist.
281
+
282
+ It accepts an array of literal values — such as `string`, `number`, `boolean`, etc. — and returns a codec that encodes and decodes such values using by using their index in the array. It uses TypeScript unions to represent all the possible values.
283
+
284
+ ```ts
285
+ const codec = getLiteralUnionCodec(['left', 'right', 'up', 'down']);
286
+ // ^? FixedSizeCodec<"left" | "right" | "up" | "down">
287
+
288
+ const bytes = codec.encode('left'); // 0x00
289
+ const value = codec.decode(bytes); // 'left'
290
+ ```
291
+
292
+ As you can see, it uses a `u8` number by default to store the index of the value. However, you may provide a number codec as the `size` option of the `getLiteralUnionCodec` function to customise that behaviour.
293
+
294
+ ```ts
295
+ const codec = getLiteralUnionCodec(['left', 'right', 'up', 'down'], {
296
+ size: getU32Codec(),
297
+ });
298
+
299
+ codec.encode('left'); // 0x00000000
300
+ codec.encode('right'); // 0x01000000
301
+ codec.encode('up'); // 0x02000000
302
+ codec.encode('down'); // 0x03000000
303
+ ```
304
+
305
+ Separate `getLiteralUnionEncoder` and `getLiteralUnionDecoder` functions are also available.
306
+
307
+ ```ts
308
+ const bytes = getLiteralUnionEncoder(['left', 'right']).encode('left'); // 0x00
309
+ const value = getLiteralUnionDecoder(['left', 'right']).decode(bytes); // 'left'
310
+ ```
311
+
312
+ ## Discriminated union codec
313
+
314
+ In Rust, enums are powerful data types whose variants can be one of the following:
315
+
316
+ - An empty variant — e.g. `enum Message { Quit }`.
317
+ - A tuple variant — e.g. `enum Message { Write(String) }`.
318
+ - A struct variant — e.g. `enum Message { Move { x: i32, y: i32 } }`.
319
+
320
+ Whilst we do not have such powerful enums in JavaScript, we can emulate them in TypeScript using a union of objects such that each object is differentiated by a specific field. **We call this a discriminated union**.
321
+
322
+ We use a special field named `__kind` to distinguish between the different variants of a discriminated union. Additionally, since all variants are objects, we can use a `fields` property to wrap the array of tuple variants. Here is an example.
323
+
324
+ ```ts
325
+ type Message =
326
+ | { __kind: 'Quit' } // Empty variant.
327
+ | { __kind: 'Write'; fields: [string] } // Tuple variant.
328
+ | { __kind: 'Move'; x: number; y: number }; // Struct variant.
329
+ ```
330
+
331
+ The `getDiscriminatedUnionCodec` function helps us encode and decode these discriminated unions.
332
+
333
+ It requires the discriminator and codec of each variant as a first argument. Similarly to the struct codec, these are defined as an array of variant tuples where the first item is the discriminator of the variant and the second item is its codec. Since empty variants do not have data to encode, they simply use the unit codec — documented below — which does nothing.
334
+
335
+ Here is how we can create a discriminated union codec for our previous example.
336
+
337
+ ```ts
338
+ const messageCodec = getDiscriminatedUnionCodec([
339
+ // Empty variant.
340
+ ['Quit', getUnitCodec()],
341
+
342
+ // Tuple variant.
343
+ ['Write', getStructCodec([['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])]])],
344
+
345
+ // Struct variant.
346
+ [
347
+ 'Move',
348
+ getStructCodec([
349
+ ['x', getI32Codec()],
350
+ ['y', getI32Codec()],
351
+ ]),
352
+ ],
353
+ ]);
354
+ ```
355
+
356
+ And here’s how we can use such a codec to encode discriminated unions. Notice that by default, they use a `u8` number prefix to distinguish between the different types of variants.
357
+
358
+ ```ts
359
+ messageCodec.encode({ __kind: 'Quit' });
360
+ // 0x00
361
+ // └-- 1-byte discriminator (Index 0 — the "Quit" variant).
362
+
363
+ messageCodec.encode({ __kind: 'Write', fields: ['Hi'] });
364
+ // 0x01020000004869
365
+ // | | └-- utf8 string content ("Hi").
366
+ // | └-- u32 string prefix (2 characters).
367
+ // └-- 1-byte discriminator (Index 1 — the "Write" variant).
368
+
369
+ messageCodec.encode({ __kind: 'Move', x: 5, y: 6 });
370
+ // 0x020500000006000000
371
+ // | | └-- Field y (6).
372
+ // | └-- Field x (5).
373
+ // └-- 1-byte discriminator (Index 2 — the "Move" variant).
374
+ ```
375
+
376
+ However, you may provide a number codec as the `size` option of the `getDiscriminatedUnionCodec` function to customise that behaviour.
377
+
378
+ ```ts
379
+ const u32MessageCodec = getDiscriminatedUnionCodec([...], {
380
+ size: getU32Codec(),
381
+ });
382
+
383
+ u32MessageCodec.encode({ __kind: 'Quit' });
384
+ // 0x00000000
385
+ // └------┘ 4-byte discriminator (Index 0).
386
+
387
+ u32MessageCodec.encode({ __kind: 'Write', fields: ['Hi'] });
388
+ // 0x01000000020000004869
389
+ // └------┘ 4-byte discriminator (Index 1).
390
+
391
+ u32MessageCodec.encode({ __kind: 'Move', x: 5, y: 6 });
392
+ // 0x020000000500000006000000
393
+ // └------┘ 4-byte discriminator (Index 2).
394
+ ```
395
+
396
+ You may also customize the discriminator property — which defaults to `__kind` — by providing the desired property name as the `discriminator` option like so:
397
+
398
+ ```ts
399
+ const messageCodec = getDiscriminatedUnionCodec([...], {
400
+ discriminator: 'message',
401
+ });
402
+
403
+ messageCodec.encode({ message: 'Quit' });
404
+ messageCodec.encode({ message: 'Write', fields: ['Hi'] });
405
+ messageCodec.encode({ message: 'Move', x: 5, y: 6 });
406
+ ```
407
+
408
+ Note that, the discriminator value of a variant may be any scalar value — such as `number`, `bigint`, `boolean`, a JavaScript `enum`, etc. For instance, the following is also valid:
409
+
410
+ ```ts
411
+ enum Message {
412
+ Quit,
413
+ Write,
414
+ Move,
415
+ }
416
+ const messageCodec = getDiscriminatedUnionCodec([
417
+ [Message.Quit, getUnitCodec()],
418
+ [Message.Write, getStructCodec([...])],
419
+ [Message.Move, getStructCodec([...])],
420
+ ]);
421
+
422
+ codec.encode({ __kind: Message.Quit });
423
+ codec.encode({ __kind: Message.Write, fields: ['Hi'] });
424
+ codec.encode({ __kind: Message.Move, x: 5, y: 6 });
425
+ ```
426
+
427
+ Finally, note that separate `getDiscriminatedUnionEncoder` and `getDiscriminatedUnionDecoder` functions are available.
428
+
429
+ ```ts
430
+ const bytes = getDiscriminatedUnionEncoder(variantEncoders).encode({ __kind: 'Quit' });
431
+ const message = getDiscriminatedUnionDecoder(variantDecoders).decode(bytes);
432
+ ```
433
+
434
+ ## Union codec
435
+
436
+ The `getUnionCodec` is a lower-lever codec helper that can be used to encode/decode any TypeScript union.
437
+
438
+ It accepts the following arguments:
439
+
440
+ - An array of codecs, each defining a variant of the union.
441
+ - A `getIndexFromValue` function which, given a value of the union, returns the index of the codec that should be used to encode that value.
442
+ - A `getIndexFromBytes` function which, given the byte array to decode at a given offset, returns the index of the codec that should be used to decode the next bytes.
443
+
444
+ ```ts
445
+ const codec: Codec<number | boolean> = getUnionCodec(
446
+ [getU16Codec(), getBooleanCodec()],
447
+ value => (typeof value === 'number' ? 0 : 1),
448
+ (bytes, offset) => (bytes.slice(offset).length > 1 ? 0 : 1),
449
+ );
450
+
451
+ codec.encode(42); // 0x2a00
452
+ codec.encode(true); // 0x01
453
+ ```
454
+
455
+ As usual, separate `getUnionEncoder` and `getUnionDecoder` functions are also available.
456
+
457
+ ```ts
458
+ const bytes = getUnionEncoder(encoders, getIndexFromValue).encode(42);
459
+ const value = getUnionDecoder(decoders, getIndexFromBytes).decode(bytes);
460
+ ```
461
+
462
+ ## Boolean codec
463
+
464
+ The `getBooleanCodec` function returns a `Codec<boolean>` that stores the boolean as `0` or `1` using a `u8` number by default.
465
+
466
+ ```ts
467
+ const bytes = getBooleanCodec().encode(true); // 0x01
468
+ const value = getBooleanCodec().decode(bytes); // true
469
+ ```
470
+
471
+ You may configure that behaviour by providing an explicit number codec as the `size` option of the `getBooleanCodec` function. That number codec will then be used to encode and decode the values `0` and `1` accordingly.
472
+
473
+ ```ts
474
+ getBooleanCodec({ size: getU16Codec() }).encode(false); // 0x0000
475
+ getBooleanCodec({ size: getU16Codec() }).encode(true); // 0x0100
476
+
477
+ getBooleanCodec({ size: getU32Codec() }).encode(false); // 0x00000000
478
+ getBooleanCodec({ size: getU32Codec() }).encode(true); // 0x01000000
479
+ ```
480
+
481
+ Separate `getBooleanEncoder` and `getBooleanDecoder` functions are also available.
482
+
483
+ ```ts
484
+ const bytes = getBooleanEncoder().encode(true); // 0x01
485
+ const value = getBooleanDecoder().decode(bytes); // true
486
+ ```
487
+
488
+ ## Nullable codec
489
+
490
+ The `getNullableCodec` function accepts a codec of type `T` and returns a codec of type `T | null`. It stores whether or not the item exists as a boolean prefix using a `u8` by default.
491
+
492
+ ```ts
493
+ const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());
494
+
495
+ getNullableCodec(stringCodec).encode('Hi');
496
+ // 0x01020000004869
497
+ // | | └-- utf8 string content ("Hi").
498
+ // | └-- u32 string prefix (2 characters).
499
+ // └-- 1-byte prefix (true — The item exists).
500
+
501
+ getNullableCodec(stringCodec).encode(null);
502
+ // 0x00
503
+ // └-- 1-byte prefix (false — The item is null).
504
+ ```
505
+
506
+ You may provide a number codec as the `prefix` option of the `getNullableCodec` function to configure how to store the boolean prefix.
507
+
508
+ ```ts
509
+ const u32NullableStringCodec = getNullableCodec(stringCodec, {
510
+ prefix: getU32Codec(),
511
+ });
512
+
513
+ u32NullableStringCodec.encode('Hi');
514
+ // 0x01000000020000004869
515
+ // └------┘ 4-byte prefix (true).
516
+
517
+ u32NullableStringCodec.encode(null);
518
+ // 0x00000000
519
+ // └------┘ 4-byte prefix (false).
520
+ ```
521
+
522
+ Additionally, if the item is a `FixedSizeCodec`, you may set the `noneValue` option to `"zeroes"` to also make the returned nullable codec a `FixedSizeCodec`. To do so, it will pad `null` values with zeroes to match the length of existing values.
523
+
524
+ ```ts
525
+ const fixedNullableStringCodec = getNullableCodec(
526
+ fixCodecSize(getUtf8Codec(), 8), // Only works with fixed-size items.
527
+ { noneValue: 'zeroes' },
528
+ );
529
+
530
+ fixedNullableStringCodec.encode('Hi');
531
+ // 0x014869000000000000
532
+ // | └-- 8-byte utf8 string content ("Hi").
533
+ // └-- 1-byte prefix (true — The item exists).
534
+
535
+ fixedNullableStringCodec.encode(null);
536
+ // 0x000000000000000000
537
+ // | └-- 8-byte of padding to make a fixed-size codec.
538
+ // └-- 1-byte prefix (false — The item is null).
539
+ ```
540
+
541
+ The `noneValue` option can also be set to an explicit byte array to use as the padding for `null` values. Note that, in this case, the returned codec will not be a `FixedSizeCodec` as the byte array representing `null` values may be of any length.
542
+
543
+ ```ts
544
+ const codec = getNullableCodec(getUtf8Codec(), {
545
+ noneValue: new Uint8Array([255]), // 0xff means null.
546
+ });
547
+
548
+ codec.encode('Hi');
549
+ // 0x014869
550
+ // | └-- 2-byte utf8 string content ("Hi").
551
+ // └-- 1-byte prefix (true — The item exists).
552
+
553
+ codec.encode(null);
554
+ // 0x00ff
555
+ // | └-- 1-byte representing null (0xff).
556
+ // └-- 1-byte prefix (false — The item is null).
557
+ ```
558
+
559
+ Last but not least, the `prefix` option of the `getNullableCodec` function can also be set to `null`, meaning no prefix will be used to determine whether the item exists. In this case, the codec will rely on the `noneValue` option to determine whether the item is `null`.
560
+
561
+ ```ts
562
+ const codecWithZeroNoneValue = getNullableCodec(getU16Codec(), {
563
+ noneValue: 'zeroes', // 0x0000 means null.
564
+ prefix: null,
565
+ });
566
+ codecWithZeroNoneValue.encode(42); // 0x2a00
567
+ codecWithZeroNoneValue.encode(null); // 0x0000
568
+
569
+ const codecWithCustomNoneValue = getNullableCodec(getU16Codec(), {
570
+ noneValue: new Uint8Array([255]), // 0xff means null.
571
+ prefix: null,
572
+ });
573
+ codecWithCustomNoneValue.encode(42); // 0x2a00
574
+ codecWithCustomNoneValue.encode(null); // 0xff
575
+ ```
576
+
577
+ Finally, note that if `prefix` is set to `null` and no `noneValue` is provided, the codec assume that the item exists if and only if some remaining bytes are available to decode. This could be useful to describe data structures that may or may not have additional data to the end of the buffer.
578
+
579
+ ```ts
580
+ const codec = getNullableCodec(getU16Codec(), { prefix: null });
581
+ codec.encode(42); // 0x2a00
582
+ codec.encode(null); // Encodes nothing.
583
+ codec.decode(new Uint8Array([42, 0])); // 42
584
+ codec.decode(new Uint8Array([])); // null
585
+ ```
586
+
587
+ To recap, here are all the possible configurations of the `getNullableCodec` function, using a `u16` codec as an example.
588
+
589
+ | `encode(42)` / `encode(null)` | No `noneValue` (default) | `noneValue: "zeroes"` | Custom `noneValue` (`0xff`) |
590
+ | ----------------------------- | ------------------------ | --------------------------- | --------------------------- |
591
+ | `u8` prefix (default) | `0x012a00` / `0x00` | `0x012a00` / `0x000000` | `0x012a00` / `0x00ff` |
592
+ | Custom `prefix` (`u16`) | `0x01002a00` / `0x0000` | `0x01002a00` / `0x00000000` | `0x01002a00` / `0x0000ff` |
593
+ | No `prefix` | `0x2a00` / `0x` | `0x2a00` / `0x0000` | `0x2a00` / `0xff` |
594
+
595
+ Note that you might be interested in the Rust-like alternative version of nullable codecs, available in [the `@solana/options` package](https://github.com/solana-labs/solana-web3.js/tree/master/packages/options).
596
+
597
+ Separate `getNullableEncoder` and `getNullableDecoder` functions are also available.
598
+
599
+ ```ts
600
+ const bytes = getNullableEncoder(getU32Encoder()).encode(42);
601
+ const value = getNullableDecoder(getU32Decoder()).decode(bytes);
602
+ ```
603
+
604
+ ## Bytes codec
605
+
606
+ The `getBytesCodec` function returns a `Codec<Uint8Array>` meaning it converts `Uint8Arrays` to and from… `Uint8Arrays`! Whilst this might seem a bit useless, it can be useful when composed into other codecs. For example, you could use it in a struct codec to say that a particular field should be left unserialised.
607
+
608
+ ```ts
609
+ const bytes = getBytesCodec().encode(new Uint8Array([42])); // 0x2a
610
+ const value = getBytesCodec().decode(bytes); // 0x2a
611
+ ```
612
+
613
+ The `getBytesCodec` function will encode and decode `Uint8Arrays` using as much bytes as necessary. If you'd like to restrict the number of bytes used by this codec, you may combine it with the [`fixCodecSize`](https://github.com/solana-labs/solana-web3.js/tree/master/packages/codecs-core#fixing-the-size-of-codecs) or [`addCodecSizePrefix`](https://github.com/solana-labs/solana-web3.js/tree/master/packages/codecs-core#prefixing-the-size-of-codecs) primitives.
614
+
615
+ Here are some examples of how you might use the `getBytesCodec` function.
616
+
617
+ ```ts
618
+ // Variable size.
619
+ getBytesCodec().encode(new Uint8Array([42]));
620
+ // 0x2a
621
+ // └-- Uint8Array content using any bytes available.
622
+
623
+ // Prefixing the size with a 2-byte u16.
624
+ addCodecSizePrefix(getBytesCodec(), getU16Codec()).encode(new Uint8Array([42]));
625
+ // 0x01002a
626
+ // | └-- Uint8Array content.
627
+ // └-- 2-byte prefix telling us to read 1 bytes
628
+
629
+ // Fixing the size to 5 bytes.
630
+ fixCodecSize(getBytesCodec(), 5).encode(new Uint8Array([42]));
631
+ // 0x2a00000000
632
+ // └-- Uint8Array content padded to use exactly 5 bytes.
633
+ ```
634
+
635
+ Separate `getBytesEncoder` and `getBytesDecoder` functions are also available.
636
+
637
+ ```ts
638
+ const bytes = getBytesEncoder().encode(new Uint8Array([42]));
639
+ const value = getBytesDecoder().decode(bytes);
640
+ ```
641
+
642
+ ## Bit array codec
643
+
644
+ The `getBitArrayCodec` function returns a codec that encodes and decodes an array of booleans such that each boolean is represented by a single bit. It requires the size of the codec in bytes and an optional `backward` flag that can be used to reverse the order of the bits.
645
+
646
+ ```ts
647
+ const booleans = [true, false, true, false, true, false, true, false];
648
+
649
+ getBitArrayCodec(1).encode(booleans);
650
+ // 0xaa or 0b10101010
651
+
652
+ getBitArrayCodec(1, { backward: true }).encode(booleans);
653
+ // 0x55 or 0b01010101
654
+ ```
655
+
656
+ Separate `getBitArrayEncoder` and `getBitArrayDecoder` functions are also available.
657
+
658
+ ```ts
659
+ const bytes = getBitArrayEncoder(1).encode(booleans);
660
+ const decodedBooleans = getBitArrayDecoder(1).decode(bytes);
661
+ ```
662
+
663
+ ## Constant codec
664
+
665
+ The `getConstantCodec` function accepts any `Uint8Array` and returns a `Codec<void>`. When encoding, it will set the provided `Uint8Array` as-is. When decoding, it will assert that the next bytes contain the provided `Uint8Array` and move the offset forward.
666
+
667
+ ```ts
668
+ const codec = getConstantCodec(new Uint8Array([1, 2, 3]));
669
+
670
+ codec.encode(undefined); // 0x010203
671
+ codec.decode(new Uint8Array([1, 2, 3])); // undefined
672
+ codec.decode(new Uint8Array([1, 2, 4])); // Throws an error.
673
+ ```
674
+
675
+ Separate `getConstantEncoder` and `getConstantDecoder` functions are also available.
676
+
677
+ ```ts
678
+ getConstantEncoder(new Uint8Array([1, 2, 3])).encode(undefined);
679
+ getConstantDecoder(new Uint8Array([1, 2, 3])).decode(new Uint8Array([1, 2, 3]));
680
+ ```
681
+
682
+ ## Unit codec
683
+
684
+ The `getUnitCodec` function returns a `Codec<void>` that encodes `undefined` into an empty `Uint8Array` and returns `undefined` without consuming any bytes when decoding. This is more of a low-level codec that can be used internally by other codecs. For instance, this is how discriminated union codecs describe the codecs of empty variants.
685
+
686
+ ```ts
687
+ getUnitCodec().encode(undefined); // Empty Uint8Array
688
+ getUnitCodec().decode(anyBytes); // undefined
689
+ ```
690
+
691
+ Separate `getUnitEncoder` and `getUnitDecoder` functions are also available.
692
+
693
+ ```ts
694
+ getUnitEncoder().encode(undefined);
695
+ getUnitDecoder().decode(anyBytes);
696
+ ```
697
+
698
+ ---
699
+
700
+ To read more about the available codecs and how to use them, check out the documentation of the main [`@solana/codecs` package](https://github.com/solana-labs/solana-web3.js/tree/master/packages/codecs).
701
+
702
+ ## Hidden prefix and suffix codec
703
+
704
+ The `getHiddenPrefixCodec` and `getHiddenSuffixCodec` functions allow us to respectively prepend or append a list of hidden `Codec<void>` to a given codec. When encoding, the hidden codecs will be encoded before or after the main codec and the offset will be moved accordingly. When decoding, the hidden codecs will be decoded but only the result of the main codec will be returned. This is particularly helpful when creating data structures that include constant values that should not be included in the final type.
705
+
706
+ ```ts
707
+ const codec: Codec<number> = getHiddenPrefixCodec(getU16Codec(), [
708
+ getConstantCodec(new Uint8Array([1, 2, 3])),
709
+ getConstantCodec(new Uint8Array([4, 5, 6])),
710
+ ]);
711
+
712
+ codec.encode(42);
713
+ // 0x0102030405062a00
714
+ // | | └-- Our main u16 codec (value = 42).
715
+ // | └-- Our second hidden prefix codec.
716
+ // └-- Our first hidden prefix codec.
717
+
718
+ codec.decode(new Uint8Array([1, 2, 3, 4, 5, 6, 42, 0])); // 42
719
+ ```
720
+
721
+ As usual, separate encoder and decoder functions are also available.
722
+
723
+ ```ts
724
+ getHiddenPrefixEncoder(encoder, prefixedEncoders);
725
+ getHiddenPrefixEncoder(decoder, prefixedDecoders);
726
+ getHiddenSuffixEncoder(encoder, suffixedEncoders);
727
+ getHiddenSuffixEncoder(decoder, suffixedDecoders);
728
+ ```