@solana/codecs-data-structures 2.0.0-preview.2 → 2.0.0-preview.2.20240417112348.42e80e05b94e649b7921049b531abab2bf637347
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.
- package/README.md +274 -70
- package/dist/index.browser.cjs +364 -223
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.js +346 -226
- package/dist/index.browser.js.map +1 -1
- package/dist/index.native.js +346 -226
- package/dist/index.native.js.map +1 -1
- package/dist/index.node.cjs +364 -223
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.js +346 -226
- package/dist/index.node.js.map +1 -1
- package/dist/types/array.d.ts.map +1 -1
- package/dist/types/boolean.d.ts +4 -4
- package/dist/types/boolean.d.ts.map +1 -1
- package/dist/types/bytes.d.ts +12 -30
- package/dist/types/bytes.d.ts.map +1 -1
- package/dist/types/constant.d.ts +16 -0
- package/dist/types/constant.d.ts.map +1 -0
- package/dist/types/discriminated-union.d.ts +97 -0
- package/dist/types/discriminated-union.d.ts.map +1 -0
- package/dist/types/enum-helpers.d.ts +51 -0
- package/dist/types/enum-helpers.d.ts.map +1 -0
- package/dist/types/enum.d.ts +57 -0
- package/dist/types/enum.d.ts.map +1 -0
- package/dist/types/hidden-prefix.d.ts +20 -0
- package/dist/types/hidden-prefix.d.ts.map +1 -0
- package/dist/types/hidden-suffix.d.ts +20 -0
- package/dist/types/hidden-suffix.d.ts.map +1 -0
- package/dist/types/index.d.ts +7 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/nullable.d.ts.map +1 -1
- package/dist/types/struct.d.ts +5 -4
- package/dist/types/struct.d.ts.map +1 -1
- package/dist/types/tuple.d.ts +13 -25
- package/dist/types/tuple.d.ts.map +1 -1
- package/dist/types/union.d.ts +32 -0
- package/dist/types/union.d.ts.map +1 -0
- package/dist/types/unit.d.ts.map +1 -1
- package/dist/types/utils.d.ts +11 -0
- package/dist/types/utils.d.ts.map +1 -1
- package/dist/types/zeroable-nullable.d.ts +38 -0
- package/dist/types/zeroable-nullable.d.ts.map +1 -0
- package/package.json +5 -5
- package/dist/types/data-enum.d.ts +0 -88
- package/dist/types/data-enum.d.ts.map +0 -1
- package/dist/types/scalar-enum.d.ts +0 -75
- package/dist/types/scalar-enum.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -93,7 +93,7 @@ const set = getSetDecoder(getU8Decoder()).decode(bytes);
|
|
|
93
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
94
|
|
|
95
95
|
```ts
|
|
96
|
-
const keyCodec =
|
|
96
|
+
const keyCodec = fixCodecSize(getUtf8Codec(), 8);
|
|
97
97
|
const valueCodec = getU8Codec();
|
|
98
98
|
const bytes = getMapCodec(keyCodec, valueCodec).encode(new Map([['alice', 42]]));
|
|
99
99
|
const map = getMapCodec(keyCodec, valueCodec).decode(bytes);
|
|
@@ -102,7 +102,7 @@ const map = getMapCodec(keyCodec, valueCodec).decode(bytes);
|
|
|
102
102
|
Just like the array codec, it uses a `u32` size prefix by default.
|
|
103
103
|
|
|
104
104
|
```ts
|
|
105
|
-
const keyCodec =
|
|
105
|
+
const keyCodec = fixCodecSize(getUtf8Codec(), 8);
|
|
106
106
|
const valueCodec = getU8Codec();
|
|
107
107
|
const myMap = new Map<string, number>();
|
|
108
108
|
myMap.set('alice', 42);
|
|
@@ -137,16 +137,16 @@ const map = getMapDecoder(keyDecoder, valueDecoder).decode(bytes);
|
|
|
137
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
138
|
|
|
139
139
|
```ts
|
|
140
|
-
const
|
|
141
|
-
const bytes =
|
|
142
|
-
const tuple =
|
|
140
|
+
const codec = getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec()), getU8Codec(), getU64Codec()]);
|
|
141
|
+
const bytes = codec.encode(['alice', 42, 123]);
|
|
142
|
+
const tuple = codec.decode(bytes);
|
|
143
143
|
```
|
|
144
144
|
|
|
145
145
|
Separate `getTupleEncoder` and `getTupleDecoder` functions are also available.
|
|
146
146
|
|
|
147
147
|
```ts
|
|
148
|
-
const bytes = getTupleEncoder(
|
|
149
|
-
const tuple = getTupleDecoder(
|
|
148
|
+
const bytes = getTupleEncoder([getU8Encoder(), getU64Encoder()]).encode([42, 123]);
|
|
149
|
+
const tuple = getTupleDecoder([getU8Decoder(), getU64Decoder()]).decode(bytes);
|
|
150
150
|
```
|
|
151
151
|
|
|
152
152
|
## Struct codec
|
|
@@ -156,7 +156,7 @@ The `getStructCodec` function accepts any number of field codecs and returns a c
|
|
|
156
156
|
```ts
|
|
157
157
|
type Person = { name: string; age: number };
|
|
158
158
|
const personCodec: Codec<Person> = getStructCodec([
|
|
159
|
-
['name',
|
|
159
|
+
['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],
|
|
160
160
|
['age', getU8Codec()],
|
|
161
161
|
]);
|
|
162
162
|
|
|
@@ -168,82 +168,148 @@ Separate `getStructEncoder` and `getStructDecoder` functions are also available.
|
|
|
168
168
|
|
|
169
169
|
```ts
|
|
170
170
|
const personEncoder: Encoder<Person> = getStructEncoder([
|
|
171
|
-
['name',
|
|
171
|
+
['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],
|
|
172
172
|
['age', getU8Encoder()],
|
|
173
173
|
]);
|
|
174
174
|
const personDecoder: Decoder<Person> = getStructDecoder([
|
|
175
|
-
['name',
|
|
175
|
+
['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],
|
|
176
176
|
['age', getU8Decoder()],
|
|
177
177
|
]);
|
|
178
178
|
const bytes = personEncoder.encode({ name: 'alice', age: 42 });
|
|
179
179
|
const person = personDecoder.decode(bytes);
|
|
180
180
|
```
|
|
181
181
|
|
|
182
|
-
##
|
|
182
|
+
## Enum codec
|
|
183
183
|
|
|
184
|
-
The `
|
|
184
|
+
The `getEnumCodec` function accepts a JavaScript enum constructor and returns a codec for encoding and decoding values of that enum.
|
|
185
185
|
|
|
186
186
|
```ts
|
|
187
187
|
enum Direction {
|
|
188
188
|
Left,
|
|
189
189
|
Right,
|
|
190
|
-
Up,
|
|
191
|
-
Down,
|
|
192
190
|
}
|
|
193
191
|
|
|
194
|
-
const bytes =
|
|
195
|
-
const direction =
|
|
192
|
+
const bytes = getEnumCodec(Direction).encode(Direction.Left);
|
|
193
|
+
const direction = getEnumCodec(Direction).decode(bytes);
|
|
196
194
|
```
|
|
197
195
|
|
|
198
|
-
When encoding
|
|
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'`.
|
|
199
197
|
|
|
200
198
|
```ts
|
|
201
199
|
enum Direction {
|
|
202
200
|
Left,
|
|
203
201
|
Right,
|
|
204
|
-
Up,
|
|
205
|
-
Down,
|
|
206
202
|
}
|
|
207
203
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
getScalarEnumCodec(Direction).encode('Left'); // 0x00
|
|
213
|
-
getScalarEnumCodec(Direction).encode('Right'); // 0x01
|
|
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
|
|
214
208
|
```
|
|
215
209
|
|
|
216
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.
|
|
217
211
|
|
|
218
212
|
```ts
|
|
219
|
-
const u32DirectionCodec =
|
|
213
|
+
const u32DirectionCodec = getEnumCodec(Direction, { size: getU32Codec() });
|
|
220
214
|
u32DirectionCodec.encode(Direction.Left); // 0x00000000
|
|
221
215
|
u32DirectionCodec.encode(Direction.Right); // 0x01000000
|
|
222
216
|
```
|
|
223
217
|
|
|
224
|
-
|
|
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.
|
|
225
219
|
|
|
226
220
|
```ts
|
|
227
|
-
enum
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
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',
|
|
232
267
|
}
|
|
268
|
+
getEnumCodec(Lexical, { useValuesAsDiscriminators: true }); // Throws an error.
|
|
269
|
+
```
|
|
233
270
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
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);
|
|
237
276
|
```
|
|
238
277
|
|
|
239
|
-
|
|
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.
|
|
240
283
|
|
|
241
284
|
```ts
|
|
242
|
-
const
|
|
243
|
-
|
|
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'
|
|
244
290
|
```
|
|
245
291
|
|
|
246
|
-
|
|
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
|
|
247
313
|
|
|
248
314
|
In Rust, enums are powerful data types whose variants can be one of the following:
|
|
249
315
|
|
|
@@ -251,9 +317,9 @@ In Rust, enums are powerful data types whose variants can be one of the followin
|
|
|
251
317
|
- A tuple variant — e.g. `enum Message { Write(String) }`.
|
|
252
318
|
- A struct variant — e.g. `enum Message { Move { x: i32, y: i32 } }`.
|
|
253
319
|
|
|
254
|
-
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
|
|
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**.
|
|
255
321
|
|
|
256
|
-
We use a special field named `__kind` to distinguish between the different variants of a
|
|
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.
|
|
257
323
|
|
|
258
324
|
```ts
|
|
259
325
|
type Message =
|
|
@@ -262,24 +328,24 @@ type Message =
|
|
|
262
328
|
| { __kind: 'Move'; x: number; y: number }; // Struct variant.
|
|
263
329
|
```
|
|
264
330
|
|
|
265
|
-
The `
|
|
331
|
+
The `getDiscriminatedUnionCodec` function helps us encode and decode these discriminated unions.
|
|
266
332
|
|
|
267
|
-
It requires the
|
|
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.
|
|
268
334
|
|
|
269
|
-
Here is how we can create a
|
|
335
|
+
Here is how we can create a discriminated union codec for our previous example.
|
|
270
336
|
|
|
271
337
|
```ts
|
|
272
|
-
const messageCodec =
|
|
338
|
+
const messageCodec = getDiscriminatedUnionCodec([
|
|
273
339
|
// Empty variant.
|
|
274
340
|
['Quit', getUnitCodec()],
|
|
275
341
|
|
|
276
342
|
// Tuple variant.
|
|
277
|
-
['Write', getStructCodec
|
|
343
|
+
['Write', getStructCodec([['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])]])],
|
|
278
344
|
|
|
279
345
|
// Struct variant.
|
|
280
346
|
[
|
|
281
347
|
'Move',
|
|
282
|
-
getStructCodec
|
|
348
|
+
getStructCodec([
|
|
283
349
|
['x', getI32Codec()],
|
|
284
350
|
['y', getI32Codec()],
|
|
285
351
|
]),
|
|
@@ -287,7 +353,7 @@ const messageCodec = getDataEnumCodec([
|
|
|
287
353
|
]);
|
|
288
354
|
```
|
|
289
355
|
|
|
290
|
-
And here’s how we can use such a codec to encode
|
|
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.
|
|
291
357
|
|
|
292
358
|
```ts
|
|
293
359
|
messageCodec.encode({ __kind: 'Quit' });
|
|
@@ -307,10 +373,10 @@ messageCodec.encode({ __kind: 'Move', x: 5, y: 6 });
|
|
|
307
373
|
// └-- 1-byte discriminator (Index 2 — the "Move" variant).
|
|
308
374
|
```
|
|
309
375
|
|
|
310
|
-
However, you may provide a number codec as the `size` option of the `
|
|
376
|
+
However, you may provide a number codec as the `size` option of the `getDiscriminatedUnionCodec` function to customise that behaviour.
|
|
311
377
|
|
|
312
378
|
```ts
|
|
313
|
-
const u32MessageCodec =
|
|
379
|
+
const u32MessageCodec = getDiscriminatedUnionCodec([...], {
|
|
314
380
|
size: getU32Codec(),
|
|
315
381
|
});
|
|
316
382
|
|
|
@@ -327,11 +393,70 @@ u32MessageCodec.encode({ __kind: 'Move', x: 5, y: 6 });
|
|
|
327
393
|
// └------┘ 4-byte discriminator (Index 2).
|
|
328
394
|
```
|
|
329
395
|
|
|
330
|
-
|
|
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.
|
|
331
456
|
|
|
332
457
|
```ts
|
|
333
|
-
const bytes =
|
|
334
|
-
const
|
|
458
|
+
const bytes = getUnionEncoder(encoders, getIndexFromValue).encode(42);
|
|
459
|
+
const value = getUnionDecoder(decoders, getIndexFromBytes).decode(bytes);
|
|
335
460
|
```
|
|
336
461
|
|
|
337
462
|
## Boolean codec
|
|
@@ -365,13 +490,15 @@ const value = getBooleanDecoder().decode(bytes); // true
|
|
|
365
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.
|
|
366
491
|
|
|
367
492
|
```ts
|
|
368
|
-
|
|
493
|
+
const stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());
|
|
494
|
+
|
|
495
|
+
getNullableCodec(stringCodec).encode('Hi');
|
|
369
496
|
// 0x01020000004869
|
|
370
497
|
// | | └-- utf8 string content ("Hi").
|
|
371
498
|
// | └-- u32 string prefix (2 characters).
|
|
372
499
|
// └-- 1-byte prefix (true — The item exists).
|
|
373
500
|
|
|
374
|
-
getNullableCodec(
|
|
501
|
+
getNullableCodec(stringCodec).encode(null);
|
|
375
502
|
// 0x00
|
|
376
503
|
// └-- 1-byte prefix (false — The item is null).
|
|
377
504
|
```
|
|
@@ -379,7 +506,7 @@ getNullableCodec(getStringCodec()).encode(null);
|
|
|
379
506
|
You may provide a number codec as the `prefix` option of the `getNullableCodec` function to configure how to store the boolean prefix.
|
|
380
507
|
|
|
381
508
|
```ts
|
|
382
|
-
const u32NullableStringCodec = getNullableCodec(
|
|
509
|
+
const u32NullableStringCodec = getNullableCodec(stringCodec, {
|
|
383
510
|
prefix: getU32Codec(),
|
|
384
511
|
});
|
|
385
512
|
|
|
@@ -396,7 +523,7 @@ Additionally, if the item is a `FixedSizeCodec`, you may set the `fixed` option
|
|
|
396
523
|
|
|
397
524
|
```ts
|
|
398
525
|
const fixedNullableStringCodec = getNullableCodec(
|
|
399
|
-
|
|
526
|
+
fixCodecSize(getUtf8Codec(), 8), // Only works with fixed-size items.
|
|
400
527
|
{ fixed: true },
|
|
401
528
|
);
|
|
402
529
|
|
|
@@ -411,13 +538,45 @@ fixedNullableStringCodec.encode(null);
|
|
|
411
538
|
// └-- 1-byte prefix (false — The item is null).
|
|
412
539
|
```
|
|
413
540
|
|
|
414
|
-
Note that you might be interested in the Rust-like alternative version of nullable codecs, available in [the
|
|
541
|
+
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).
|
|
415
542
|
|
|
416
543
|
Separate `getNullableEncoder` and `getNullableDecoder` functions are also available.
|
|
417
544
|
|
|
418
545
|
```ts
|
|
419
|
-
const bytes = getNullableEncoder(
|
|
420
|
-
const value = getNullableDecoder(
|
|
546
|
+
const bytes = getNullableEncoder(getU32Encoder()).encode(42);
|
|
547
|
+
const value = getNullableDecoder(getU32Decoder()).decode(bytes);
|
|
548
|
+
```
|
|
549
|
+
|
|
550
|
+
## Zeroable nullable codec
|
|
551
|
+
|
|
552
|
+
Similarly to the `getNullableCodec` function, The `getZeroableNullableCodec` function accepts a codec of type `T` and returns a codec of type `T | null`. However, instead of relying on a boolean prefix to determine whether the item exists, it uses a zero value to represent `null`. This means, you may only use this codec with fixed-size items.
|
|
553
|
+
|
|
554
|
+
```ts
|
|
555
|
+
const codec = getZeroableNullableCodec(getU16Codec());
|
|
556
|
+
codec.encode(42); // 0x2a00
|
|
557
|
+
codec.encode(null); // 0x0000
|
|
558
|
+
codec.decode(new Uint8Array([42, 0])); // 42
|
|
559
|
+
codec.encode(new Uint8Array([0, 0])); // null
|
|
560
|
+
```
|
|
561
|
+
|
|
562
|
+
As you can see, by default, it uses a `Uint8Array` of zeroes to represent `null`. However, you may provide a custom zero value that will be used to encode/decode null values. Note that this zero value must be a `Uint8Array` of the same length as the codec's fixed size.
|
|
563
|
+
|
|
564
|
+
```ts
|
|
565
|
+
const codec = getZeroableNullableCodec(getU16Codec(), {
|
|
566
|
+
zeroValue: new Uint8Array([255, 255]),
|
|
567
|
+
});
|
|
568
|
+
codec.encode(42); // 0x2a00
|
|
569
|
+
codec.encode(null); // 0xfffff
|
|
570
|
+
codec.encode(new Uint8Array([0, 0])); // 0
|
|
571
|
+
codec.decode(new Uint8Array([42, 0])); // 42
|
|
572
|
+
codec.decode(new Uint8Array([255, 255])); // null
|
|
573
|
+
```
|
|
574
|
+
|
|
575
|
+
Separate `getZeroableNullableEncoder` and `getZeroableNullableDecoder` functions are also available.
|
|
576
|
+
|
|
577
|
+
```ts
|
|
578
|
+
const bytes = getZeroableNullableEncoder(getU16Encoder()).encode(42);
|
|
579
|
+
const value = getZeroableNullableDecoder(getU16Decoder()).decode(bytes);
|
|
421
580
|
```
|
|
422
581
|
|
|
423
582
|
## Bytes codec
|
|
@@ -429,26 +588,24 @@ const bytes = getBytesCodec().encode(new Uint8Array([42])); // 0x2a
|
|
|
429
588
|
const value = getBytesCodec().decode(bytes); // 0x2a
|
|
430
589
|
```
|
|
431
590
|
|
|
432
|
-
|
|
591
|
+
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.
|
|
433
592
|
|
|
434
|
-
|
|
435
|
-
- `number`: When a fixed number is provided, a `FixedSizeCodec` of that size will be returned such that exactly that amount of bytes will be used to encode and decode the `Uint8Array`.
|
|
436
|
-
- `"variable"`: When the string `"variable"` is passed as a size, a `VariableSizeCodec` will be returned without any size boundary. This is the default behaviour.
|
|
593
|
+
Here are some examples of how you might use the `getBytesCodec` function.
|
|
437
594
|
|
|
438
595
|
```ts
|
|
439
|
-
//
|
|
596
|
+
// Variable size.
|
|
440
597
|
getBytesCodec().encode(new Uint8Array([42]));
|
|
441
598
|
// 0x2a
|
|
442
599
|
// └-- Uint8Array content using any bytes available.
|
|
443
600
|
|
|
444
|
-
//
|
|
445
|
-
getBytesCodec(
|
|
601
|
+
// Prefixing the size with a 2-byte u16.
|
|
602
|
+
addCodecSizePrefix(getBytesCodec(), getU16Codec()).encode(new Uint8Array([42]));
|
|
446
603
|
// 0x01002a
|
|
447
604
|
// | └-- Uint8Array content.
|
|
448
605
|
// └-- 2-byte prefix telling us to read 1 bytes
|
|
449
606
|
|
|
450
|
-
//
|
|
451
|
-
getBytesCodec(
|
|
607
|
+
// Fixing the size to 5 bytes.
|
|
608
|
+
fixCodecSize(getBytesCodec(), 5).encode(new Uint8Array([42]));
|
|
452
609
|
// 0x2a00000000
|
|
453
610
|
// └-- Uint8Array content padded to use exactly 5 bytes.
|
|
454
611
|
```
|
|
@@ -481,9 +638,28 @@ const bytes = getBitArrayEncoder(1).encode(booleans);
|
|
|
481
638
|
const decodedBooleans = getBitArrayDecoder(1).decode(bytes);
|
|
482
639
|
```
|
|
483
640
|
|
|
641
|
+
## Constant codec
|
|
642
|
+
|
|
643
|
+
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.
|
|
644
|
+
|
|
645
|
+
```ts
|
|
646
|
+
const codec = getConstantCodec(new Uint8Array([1, 2, 3]));
|
|
647
|
+
|
|
648
|
+
codec.encode(undefined); // 0x010203
|
|
649
|
+
codec.decode(new Uint8Array([1, 2, 3])); // undefined
|
|
650
|
+
codec.decode(new Uint8Array([1, 2, 4])); // Throws an error.
|
|
651
|
+
```
|
|
652
|
+
|
|
653
|
+
Separate `getConstantEncoder` and `getConstantDecoder` functions are also available.
|
|
654
|
+
|
|
655
|
+
```ts
|
|
656
|
+
getConstantEncoder(new Uint8Array([1, 2, 3])).encode(undefined);
|
|
657
|
+
getConstantDecoder(new Uint8Array([1, 2, 3])).decode(new Uint8Array([1, 2, 3]));
|
|
658
|
+
```
|
|
659
|
+
|
|
484
660
|
## Unit codec
|
|
485
661
|
|
|
486
|
-
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
|
|
662
|
+
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.
|
|
487
663
|
|
|
488
664
|
```ts
|
|
489
665
|
getUnitCodec().encode(undefined); // Empty Uint8Array
|
|
@@ -500,3 +676,31 @@ getUnitDecoder().decode(anyBytes);
|
|
|
500
676
|
---
|
|
501
677
|
|
|
502
678
|
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).
|
|
679
|
+
|
|
680
|
+
## Hidden prefix and suffix codec
|
|
681
|
+
|
|
682
|
+
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.
|
|
683
|
+
|
|
684
|
+
```ts
|
|
685
|
+
const codec: Codec<number> = getHiddenPrefixCodec(getU16Codec(), [
|
|
686
|
+
getConstantCodec(new Uint8Array([1, 2, 3])),
|
|
687
|
+
getConstantCodec(new Uint8Array([4, 5, 6])),
|
|
688
|
+
]);
|
|
689
|
+
|
|
690
|
+
codec.encode(42);
|
|
691
|
+
// 0x0102030405062a00
|
|
692
|
+
// | | └-- Our main u16 codec (value = 42).
|
|
693
|
+
// | └-- Our second hidden prefix codec.
|
|
694
|
+
// └-- Our first hidden prefix codec.
|
|
695
|
+
|
|
696
|
+
codec.decode(new Uint8Array([1, 2, 3, 4, 5, 6, 42, 0])); // 42
|
|
697
|
+
```
|
|
698
|
+
|
|
699
|
+
As usual, separate encoder and decoder functions are also available.
|
|
700
|
+
|
|
701
|
+
```ts
|
|
702
|
+
getHiddenPrefixEncoder(encoder, prefixedEncoders);
|
|
703
|
+
getHiddenPrefixEncoder(decoder, prefixedDecoders);
|
|
704
|
+
getHiddenSuffixEncoder(encoder, suffixedEncoders);
|
|
705
|
+
getHiddenSuffixEncoder(decoder, suffixedDecoders);
|
|
706
|
+
```
|