@solana/options 2.0.0-experimental.ffeddf6 → 2.0.0-preview.1
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 +153 -4
- package/dist/index.browser.cjs +58 -44
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.js +59 -45
- package/dist/index.browser.js.map +1 -1
- package/dist/index.native.js +59 -45
- package/dist/index.native.js.map +1 -1
- package/dist/index.node.cjs +58 -44
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.js +59 -45
- package/dist/index.node.js.map +1 -1
- package/dist/types/index.d.ts +4 -4
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/option-codec.d.ts +34 -16
- package/dist/types/option-codec.d.ts.map +1 -0
- package/dist/types/option.d.ts +1 -1
- package/dist/types/option.d.ts.map +1 -0
- package/dist/types/unwrap-option-recursively.d.ts +2 -2
- package/dist/types/unwrap-option-recursively.d.ts.map +1 -0
- package/dist/types/unwrap-option.d.ts +1 -1
- package/dist/types/unwrap-option.d.ts.map +1 -0
- package/package.json +12 -33
- package/dist/index.development.js +0 -252
- package/dist/index.development.js.map +0 -1
- package/dist/index.production.min.js +0 -21
package/README.md
CHANGED
|
@@ -16,10 +16,159 @@
|
|
|
16
16
|
|
|
17
17
|
This package allows us to manage and serialize Rust-like Option types in JavaScript. 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
18
|
|
|
19
|
-
|
|
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
20
|
|
|
21
|
-
|
|
21
|
+
## Creating options
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
In Rust, we define optional values as an `Option<T>` type which can either be `Some(T)` or `None`. This is usually represented as `T | null` in the JavaScript world. The issue with this approach is it doesn't work with nested options. For instance, an `Option<Option<T>>` in Rust would become a `T | null | null` in JavaScript which is equivalent to `T | null`. That means, there is no way for us to represent the `Some(None)` value in JavaScript or any other nested option.
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
To solve this issue, this library provides an `Option<T>` union type that works very similarly to the Rust `Option<T>` type. It is defined as follows:
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
type Option<T> = Some<T> | None;
|
|
29
|
+
type Some<T> = { __option: 'Some'; value: T };
|
|
30
|
+
type None = { __option: 'None' };
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
To improve the developer experience, helper functions are available to help you create options. The type `T` of the option can either be inferred by TypeScript or explicitly provided.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
// Create an option with a value.
|
|
37
|
+
some('Hello World');
|
|
38
|
+
some<number | string>(123);
|
|
39
|
+
|
|
40
|
+
// Create an empty option.
|
|
41
|
+
none();
|
|
42
|
+
none<number | string>();
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Option helpers
|
|
46
|
+
|
|
47
|
+
This library also provides helper functions to help us identify and manage `Option` types.
|
|
48
|
+
|
|
49
|
+
For instance, you can use the `isSome` and `isNone` type guards to check whether a given `Option` is of the desired type.
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
isSome(some('Hello World')); // true
|
|
53
|
+
isSome(none()); // false
|
|
54
|
+
|
|
55
|
+
isNone(some('Hello World')); // false
|
|
56
|
+
isNone(none()); // true
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
If you are given a type `T | null`, you may also use the `wrapNullable` helper function to transform it into an `Option<T>` type.
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
wrapNullable('Hello world'); // Some<string>
|
|
63
|
+
wrapNullable(null); // None
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Unwrapping options
|
|
67
|
+
|
|
68
|
+
Several helpers are available to help you unwrap your options and access their potential value. For instance, the `unwrapOption` function transforms an `Option<T>` type into `T` if the value exits and `null` otherwise.
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
unwrapOption(some('Hello World')); // "Hello World"
|
|
72
|
+
unwrapOption(none()); // null
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
If `null` isn’t the value you want to use for `None` options, you may provide a custom fallback function as the second argument. Its return value will be assigned to `None` options.
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
unwrapOption(some('Hello World'), () => 'Default'); // "Hello World"
|
|
79
|
+
unwrapOption(none(), () => 'Default'); // "Default"
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Note that this `unwrapOption` function does not recursively unwrap nested options. You may use the `unwrapOptionRecursively` function for that purpose instead.
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
unwrapOptionRecursively(some(some(some('Hello World')))); // "Hello World"
|
|
86
|
+
unwrapOptionRecursively(some(some(none<string>()))); // null
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The `unwrapOptionRecursively` function also walks any object and array it encounters and recursively unwraps any option it identifies in its journey without mutating any object or array.
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
unwrapOptionRecursively({
|
|
93
|
+
a: 'hello',
|
|
94
|
+
b: none(),
|
|
95
|
+
c: [{ c1: some(42) }, { c2: none() }],
|
|
96
|
+
});
|
|
97
|
+
// { a: "hello", b: null, c: [{ c1: 42 }, { c2: null }] }
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The `unwrapOptionRecursively` also accepts a fallback function as a second argument to provide custom values for `None` options.
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
unwrapOptionRecursively(
|
|
104
|
+
{
|
|
105
|
+
a: 'hello',
|
|
106
|
+
b: none(),
|
|
107
|
+
c: [{ c1: some(42) }, { c2: none() }],
|
|
108
|
+
},
|
|
109
|
+
() => 'Default',
|
|
110
|
+
);
|
|
111
|
+
// { a: "hello", b: "Default", c: [{ c1: 42 }, { c2: "Default" }] }
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## Option codec
|
|
115
|
+
|
|
116
|
+
The `getOptionCodec` function behaves exactly the same as the [`getNullableCodec`](https://github.com/solana-labs/solana-web3.js/tree/master/packages/codecs-data-structures#nullable-codec) except that it encodes `Option<T>` types instead of `T | null` types.
|
|
117
|
+
|
|
118
|
+
Namely, it accepts a codec of type `T` and returns a codec of type `Option<T>`. It stores whether or not the item exists as a boolean prefix using a `u8` by default.
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
getOptionCodec(getStringCodec()).encode(some('Hi'));
|
|
122
|
+
// 0x01020000004869
|
|
123
|
+
// | | └-- utf8 string content ("Hi").
|
|
124
|
+
// | └-- u32 string prefix (2 characters).
|
|
125
|
+
// └-- 1-byte prefix (Some).
|
|
126
|
+
|
|
127
|
+
getOptionCodec(getStringCodec()).encode(none());
|
|
128
|
+
// 0x00
|
|
129
|
+
// └-- 1-byte prefix (None).
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
You may provide a number codec as the `prefix` option of the `getOptionCodec` function to configure how to store the boolean prefix.
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
const u32OptionStringCodec = getOptionCodec(getStringCodec(), {
|
|
136
|
+
prefix: getU32Codec(),
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
u32OptionStringCodec.encode(some('Hi'));
|
|
140
|
+
// 0x01000000020000004869
|
|
141
|
+
// └------┘ 4-byte prefix (Some).
|
|
142
|
+
|
|
143
|
+
u32OptionStringCodec.encode(none());
|
|
144
|
+
// 0x00000000
|
|
145
|
+
// └------┘ 4-byte prefix (None).
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Additionally, if the item is a `FixedSizeCodec`, you may set the `fixed` option to `true` to also make the returned option codec a `FixedSizeCodec`. To do so, it will pad `null` values with zeroes to match the length of existing values.
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
const fixedOptionStringCodec = getOptionCodec(
|
|
152
|
+
getStringCodec({ size: 8 }), // Only works with fixed-size items.
|
|
153
|
+
{ fixed: true },
|
|
154
|
+
);
|
|
155
|
+
|
|
156
|
+
fixedOptionStringCodec.encode(some('Hi'));
|
|
157
|
+
// 0x014869000000000000
|
|
158
|
+
// | └-- 8-byte utf8 string content ("Hi").
|
|
159
|
+
// └-- 1-byte prefix (Some).
|
|
160
|
+
|
|
161
|
+
fixedOptionStringCodec.encode(none());
|
|
162
|
+
// 0x000000000000000000
|
|
163
|
+
// | └-- 8-byte of padding to make a fixed-size codec.
|
|
164
|
+
// └-- 1-byte prefix (None).
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Separate `getOptionEncoder` and `getOptionDecoder` functions are also available.
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
const bytes = getOptionEncoder(getStringEncoder()).encode(some('Hi'));
|
|
171
|
+
const value = getOptionDecoder(getStringDecoder()).decode(bytes);
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
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).
|
package/dist/index.browser.cjs
CHANGED
|
@@ -19,61 +19,75 @@ function unwrapOption(option, fallback) {
|
|
|
19
19
|
var wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
|
|
20
20
|
|
|
21
21
|
// src/option-codec.ts
|
|
22
|
-
function
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
codecsCore.
|
|
31
|
-
|
|
32
|
-
|
|
22
|
+
function getOptionEncoder(item, config = {}) {
|
|
23
|
+
const prefix = config.prefix ?? codecsNumbers.getU8Encoder();
|
|
24
|
+
const fixed = config.fixed ?? false;
|
|
25
|
+
const isZeroSizeItem = codecsCore.isFixedSize(item) && codecsCore.isFixedSize(prefix) && item.fixedSize === 0;
|
|
26
|
+
if (fixed || isZeroSizeItem) {
|
|
27
|
+
codecsCore.assertIsFixedSize(item);
|
|
28
|
+
codecsCore.assertIsFixedSize(prefix);
|
|
29
|
+
const fixedSize = prefix.fixedSize + item.fixedSize;
|
|
30
|
+
return codecsCore.createEncoder({
|
|
31
|
+
fixedSize,
|
|
32
|
+
write: (optionOrNullable, bytes, offset) => {
|
|
33
|
+
const option = isOption(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);
|
|
34
|
+
const prefixOffset = prefix.write(Number(isSome(option)), bytes, offset);
|
|
35
|
+
if (isSome(option)) {
|
|
36
|
+
item.write(option.value, bytes, prefixOffset);
|
|
37
|
+
}
|
|
38
|
+
return offset + fixedSize;
|
|
39
|
+
}
|
|
40
|
+
});
|
|
33
41
|
}
|
|
34
|
-
return {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const prefix = options.prefix ?? codecsNumbers.getU8Encoder();
|
|
42
|
-
const fixed = options.fixed ?? false;
|
|
43
|
-
return {
|
|
44
|
-
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
45
|
-
encode: (optionOrNullable) => {
|
|
42
|
+
return codecsCore.createEncoder({
|
|
43
|
+
getSizeFromValue: (optionOrNullable) => {
|
|
44
|
+
const option = isOption(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);
|
|
45
|
+
return codecsCore.getEncodedSize(Number(isSome(option)), prefix) + (isSome(option) ? codecsCore.getEncodedSize(option.value, item) : 0);
|
|
46
|
+
},
|
|
47
|
+
maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? void 0,
|
|
48
|
+
write: (optionOrNullable, bytes, offset) => {
|
|
46
49
|
const option = isOption(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
50
|
+
offset = prefix.write(Number(isSome(option)), bytes, offset);
|
|
51
|
+
if (isSome(option)) {
|
|
52
|
+
offset = item.write(option.value, bytes, offset);
|
|
53
|
+
}
|
|
54
|
+
return offset;
|
|
51
55
|
}
|
|
52
|
-
};
|
|
56
|
+
});
|
|
53
57
|
}
|
|
54
|
-
function getOptionDecoder(item,
|
|
55
|
-
const prefix =
|
|
56
|
-
const fixed =
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
58
|
+
function getOptionDecoder(item, config = {}) {
|
|
59
|
+
const prefix = config.prefix ?? codecsNumbers.getU8Decoder();
|
|
60
|
+
const fixed = config.fixed ?? false;
|
|
61
|
+
let fixedSize = null;
|
|
62
|
+
const isZeroSizeItem = codecsCore.isFixedSize(item) && codecsCore.isFixedSize(prefix) && item.fixedSize === 0;
|
|
63
|
+
if (fixed || isZeroSizeItem) {
|
|
64
|
+
codecsCore.assertIsFixedSize(item);
|
|
65
|
+
codecsCore.assertIsFixedSize(prefix);
|
|
66
|
+
fixedSize = prefix.fixedSize + item.fixedSize;
|
|
67
|
+
}
|
|
68
|
+
return codecsCore.createDecoder({
|
|
69
|
+
...fixedSize === null ? { maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? void 0 } : { fixedSize },
|
|
70
|
+
read: (bytes, offset) => {
|
|
60
71
|
if (bytes.length - offset <= 0) {
|
|
61
72
|
return [none(), offset];
|
|
62
73
|
}
|
|
63
|
-
const
|
|
64
|
-
const [isSome2, prefixOffset] = prefix.decode(bytes, offset);
|
|
65
|
-
offset = prefixOffset;
|
|
74
|
+
const [isSome2, prefixOffset] = prefix.read(bytes, offset);
|
|
66
75
|
if (isSome2 === 0) {
|
|
67
|
-
return [none(),
|
|
76
|
+
return [none(), fixedSize !== null ? offset + fixedSize : prefixOffset];
|
|
68
77
|
}
|
|
69
|
-
const [value, newOffset] = item.
|
|
70
|
-
offset
|
|
71
|
-
return [some(value), fixed ? fixedOffset : offset];
|
|
78
|
+
const [value, newOffset] = item.read(bytes, prefixOffset);
|
|
79
|
+
return [some(value), fixedSize !== null ? offset + fixedSize : newOffset];
|
|
72
80
|
}
|
|
73
|
-
};
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
function getOptionCodec(item, config = {}) {
|
|
84
|
+
return codecsCore.combineCodec(getOptionEncoder(item, config), getOptionDecoder(item, config));
|
|
85
|
+
}
|
|
86
|
+
function sumCodecSizes(sizes) {
|
|
87
|
+
return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
|
|
74
88
|
}
|
|
75
|
-
function
|
|
76
|
-
return codecsCore.
|
|
89
|
+
function getMaxSize(codec) {
|
|
90
|
+
return codecsCore.isFixedSize(codec) ? codec.fixedSize : codec.maxSize ?? null;
|
|
77
91
|
}
|
|
78
92
|
|
|
79
93
|
// src/unwrap-option-recursively.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/option.ts","../src/option-codec.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":["isSome"],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAAc,UAClC,CAAC,EACG,SACA,OAAO,UAAU,YACjB,cAAc,UACZ,MAAM,aAAa,UAAU,WAAW,SAAU,MAAM,aAAa;AAMxE,IAAM,SAAS,CAAI,WAAyC,OAAO,aAAa;AAKhF,IAAM,SAAS,CAAI,WAAsC,OAAO,aAAa;;;AC9DpF;AAAA,EACI;AAAA,EAIA;AAAA,EAGA;AAAA,EACA;AAAA,OACG;AACP,SAAS,cAAc,oBAA+D;;;ACH/E,SAAS,aAA0B,QAAmB,UAA2B;AACpF,MAAI,OAAO,MAAM;AAAG,WAAO,OAAO;AAClC,SAAO,WAAW,SAAS,IAAK;AACpC;AAKO,IAAM,eAAe,CAAI,aAAmC,aAAa,OAAO,KAAK,QAAQ,IAAI,KAAQ;;;ADmBhH,SAAS,cAAc,OAAyC;AAC5D,SAAO,MAAM,OAAO,CAAC,KAAK,SAAU,QAAQ,QAAQ,SAAS,OAAO,OAAO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M;AACvC,UAAI,MAAM,SAAS,UAAU,GAAG;AAC5B,eAAO,CAAC,KAAK,GAAG,MAAM;AAAA,MAC1B;AACA,YAAM,cAAc,UAAU,OAAO,aAAa,MAAM,KAAK,aAAa;AAC1E,YAAM,CAACA,SAAQ,YAAY,IAAI,OAAO,OAAO,OAAO,MAAM;AAC1D,eAAS;AACT,UAAIA,YAAW,GAAG;AACd,eAAO,CAAC,KAAK,GAAG,QAAQ,cAAc,MAAM;AAAA,MAChD;AACA,YAAM,CAAC,OAAO,SAAS,IAAI,KAAK,OAAO,OAAO,MAAM;AACpD,eAAS;AACT,aAAO,CAAC,KAAK,KAAK,GAAG,QAAQ,cAAc,MAAM;AAAA,IACrD;AAAA,EACJ;AACJ;AAQO,SAAS,eACZ,MACA,UAA2C,CAAC,GACP;AACrC,SAAO,aAAa,iBAAoB,MAAM,OAAO,GAAG,iBAAoB,MAAM,OAAO,CAAC;AAC9F;;;AErEO,SAAS,wBAAqC,OAAU,UAA2C;AAEtG,MAAI,CAAC,SAAS,YAAY,OAAO,KAAK,GAAG;AACrC,WAAO;AAAA,EACX;AAEA,QAAM,OAAO,CAAI,MACZ,WAAW,wBAAwB,GAAG,QAAQ,IAAI,wBAAwB,CAAC;AAGhF,MAAI,SAAS,KAAK,GAAG;AACjB,QAAI,OAAO,KAAK;AAAG,aAAO,KAAK,MAAM,KAAK;AAC1C,WAAQ,WAAW,SAAS,IAAI;AAAA,EACpC;AAGA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACtB,WAAO,MAAM,IAAI,IAAI;AAAA,EACzB;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import {\n assertFixedSizeCodec,\n BaseCodecOptions,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n fixBytes,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { isOption, isSome, none, Option, OptionOrNullable, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/** Defines the options for option codecs. */\nexport type OptionCodecOptions<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `None` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n};\n\nfunction sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nfunction optionCodecHelper(item: CodecData, prefix: CodecData, fixed: boolean, description?: string): CodecData {\n let descriptionSuffix = `; ${prefix.description}`;\n let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;\n if (fixed) {\n assertFixedSizeCodec(item, 'Fixed options can only be used with fixed-size codecs.');\n assertFixedSizeCodec(prefix, 'Fixed options can only be used with fixed-size prefix.');\n descriptionSuffix += '; fixed';\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n\n return {\n description: description ?? `option(${item.description + descriptionSuffix})`,\n fixedSize,\n maxSize: sumCodecSizes([prefix.maxSize, item.maxSize]),\n };\n}\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param options - A set of options for the encoder.\n */\nexport function getOptionEncoder<T>(\n item: Encoder<T>,\n options: OptionCodecOptions<NumberEncoder> = {}\n): Encoder<OptionOrNullable<T>> {\n const prefix = options.prefix ?? getU8Encoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n encode: (optionOrNullable: OptionOrNullable<T>) => {\n const option = isOption<T>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n const prefixByte = prefix.encode(Number(isSome(option)));\n let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();\n itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize as number) : itemBytes;\n return mergeBytes([prefixByte, itemBytes]);\n },\n };\n}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param options - A set of options for the decoder.\n */\nexport function getOptionDecoder<T>(\n item: Decoder<T>,\n options: OptionCodecOptions<NumberDecoder> = {}\n): Decoder<Option<T>> {\n const prefix = options.prefix ?? getU8Decoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n if (bytes.length - offset <= 0) {\n return [none(), offset];\n }\n const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);\n const [isSome, prefixOffset] = prefix.decode(bytes, offset);\n offset = prefixOffset;\n if (isSome === 0) {\n return [none(), fixed ? fixedOffset : offset];\n }\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n return [some(value), fixed ? fixedOffset : offset];\n },\n };\n}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param options - A set of options for the codec.\n */\nexport function getOptionCodec<T, U extends T = T>(\n item: Codec<T, U>,\n options: OptionCodecOptions<NumberCodec> = {}\n): Codec<OptionOrNullable<T>, Option<U>> {\n return combineCodec(getOptionEncoder<T>(item, options), getOptionDecoder<U>(item, options));\n}\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/option.ts","../src/option-codec.ts","../src/unwrap-option.ts","../src/unwr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AC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = None | Some<T>;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { isOption, isSome, none, Option, OptionOrNullable, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/** Defines the config for option codecs. */\nexport type OptionCodecConfig<TPrefix extends NumberCodec | NumberDecoder | NumberEncoder> = {\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `None` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n};\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param config - A set of config for the encoder.\n */\nexport function getOptionEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: OptionCodecConfig<FixedSizeNumberEncoder> & { fixed: true },\n): FixedSizeEncoder<OptionOrNullable<TFrom>>;\nexport function getOptionEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom, 0>,\n config?: OptionCodecConfig<FixedSizeNumberEncoder>,\n): FixedSizeEncoder<OptionOrNullable<TFrom>>;\nexport function getOptionEncoder<TFrom>(\n item: Encoder<TFrom>,\n config?: OptionCodecConfig<NumberEncoder> & { fixed?: false },\n): VariableSizeEncoder<OptionOrNullable<TFrom>>;\nexport function getOptionEncoder<TFrom>(\n item: Encoder<TFrom>,\n config: OptionCodecConfig<NumberEncoder> = {},\n): Encoder<OptionOrNullable<TFrom>> {\n const prefix = config.prefix ?? getU8Encoder();\n const fixed = config.fixed ?? false;\n\n const isZeroSizeItem = isFixedSize(item) && isFixedSize(prefix) && item.fixedSize === 0;\n if (fixed || isZeroSizeItem) {\n assertIsFixedSize(item);\n assertIsFixedSize(prefix);\n const fixedSize = prefix.fixedSize + item.fixedSize;\n return createEncoder({\n fixedSize,\n write: (optionOrNullable: OptionOrNullable<TFrom>, bytes, offset) => {\n const option = isOption<TFrom>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n const prefixOffset = prefix.write(Number(isSome(option)), bytes, offset);\n if (isSome(option)) {\n item.write(option.value, bytes, prefixOffset);\n }\n return offset + fixedSize;\n },\n });\n }\n\n return createEncoder({\n getSizeFromValue: (optionOrNullable: OptionOrNullable<TFrom>) => {\n const option = isOption<TFrom>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n return (\n getEncodedSize(Number(isSome(option)), prefix) +\n (isSome(option) ? getEncodedSize(option.value, item) : 0)\n );\n },\n maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? undefined,\n write: (optionOrNullable: OptionOrNullable<TFrom>, bytes, offset) => {\n const option = isOption<TFrom>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n offset = prefix.write(Number(isSome(option)), bytes, offset);\n if (isSome(option)) {\n offset = item.write(option.value, bytes, offset);\n }\n return offset;\n },\n });\n}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param config - A set of config for the decoder.\n */\nexport function getOptionDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: OptionCodecConfig<FixedSizeNumberDecoder> & { fixed: true },\n): FixedSizeDecoder<Option<TTo>>;\nexport function getOptionDecoder<TTo>(\n item: FixedSizeDecoder<TTo, 0>,\n config?: OptionCodecConfig<FixedSizeNumberDecoder>,\n): FixedSizeDecoder<Option<TTo>>;\nexport function getOptionDecoder<TTo>(\n item: Decoder<TTo>,\n config?: OptionCodecConfig<NumberDecoder> & { fixed?: false },\n): VariableSizeDecoder<Option<TTo>>;\nexport function getOptionDecoder<TTo>(\n item: Decoder<TTo>,\n config: OptionCodecConfig<NumberDecoder> = {},\n): Decoder<Option<TTo>> {\n const prefix = config.prefix ?? getU8Decoder();\n const fixed = config.fixed ?? false;\n\n let fixedSize: number | null = null;\n const isZeroSizeItem = isFixedSize(item) && isFixedSize(prefix) && item.fixedSize === 0;\n if (fixed || isZeroSizeItem) {\n assertIsFixedSize(item);\n assertIsFixedSize(prefix);\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n\n return createDecoder({\n ...(fixedSize === null\n ? { maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? undefined }\n : { fixedSize }),\n read: (bytes: Uint8Array, offset) => {\n if (bytes.length - offset <= 0) {\n return [none(), offset];\n }\n const [isSome, prefixOffset] = prefix.read(bytes, offset);\n if (isSome === 0) {\n return [none(), fixedSize !== null ? offset + fixedSize : prefixOffset];\n }\n const [value, newOffset] = item.read(bytes, prefixOffset);\n return [some(value), fixedSize !== null ? offset + fixedSize : newOffset];\n },\n });\n}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param config - A set of config for the codec.\n */\nexport function getOptionCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: OptionCodecConfig<FixedSizeNumberCodec> & { fixed: true },\n): FixedSizeCodec<OptionOrNullable<TFrom>, Option<TTo>>;\nexport function getOptionCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo, 0>,\n config?: OptionCodecConfig<FixedSizeNumberCodec>,\n): FixedSizeCodec<OptionOrNullable<TFrom>, Option<TTo>>;\nexport function getOptionCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config?: OptionCodecConfig<NumberCodec> & { fixed?: false },\n): VariableSizeCodec<OptionOrNullable<TFrom>, Option<TTo>>;\nexport function getOptionCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config: OptionCodecConfig<NumberCodec> = {},\n): Codec<OptionOrNullable<TFrom>, Option<TTo>> {\n return combineCodec(getOptionEncoder<TFrom>(item, config as object), getOptionDecoder<TTo>(item, config as object));\n}\n\nfunction sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nfunction getMaxSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : codec.maxSize ?? null;\n}\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | Date\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint16Array\n | Uint32Array\n | bigint\n | boolean\n | number\n | string\n | symbol\n | null\n | undefined;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> =\n T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
package/dist/index.browser.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isFixedSize, assertIsFixedSize, createEncoder, getEncodedSize, createDecoder, combineCodec } from '@solana/codecs-core';
|
|
2
2
|
import { getU8Encoder, getU8Decoder } from '@solana/codecs-numbers';
|
|
3
3
|
|
|
4
4
|
// src/option.ts
|
|
@@ -17,61 +17,75 @@ function unwrapOption(option, fallback) {
|
|
|
17
17
|
var wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
|
|
18
18
|
|
|
19
19
|
// src/option-codec.ts
|
|
20
|
-
function
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
20
|
+
function getOptionEncoder(item, config = {}) {
|
|
21
|
+
const prefix = config.prefix ?? getU8Encoder();
|
|
22
|
+
const fixed = config.fixed ?? false;
|
|
23
|
+
const isZeroSizeItem = isFixedSize(item) && isFixedSize(prefix) && item.fixedSize === 0;
|
|
24
|
+
if (fixed || isZeroSizeItem) {
|
|
25
|
+
assertIsFixedSize(item);
|
|
26
|
+
assertIsFixedSize(prefix);
|
|
27
|
+
const fixedSize = prefix.fixedSize + item.fixedSize;
|
|
28
|
+
return createEncoder({
|
|
29
|
+
fixedSize,
|
|
30
|
+
write: (optionOrNullable, bytes, offset) => {
|
|
31
|
+
const option = isOption(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);
|
|
32
|
+
const prefixOffset = prefix.write(Number(isSome(option)), bytes, offset);
|
|
33
|
+
if (isSome(option)) {
|
|
34
|
+
item.write(option.value, bytes, prefixOffset);
|
|
35
|
+
}
|
|
36
|
+
return offset + fixedSize;
|
|
37
|
+
}
|
|
38
|
+
});
|
|
31
39
|
}
|
|
32
|
-
return {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const prefix = options.prefix ?? getU8Encoder();
|
|
40
|
-
const fixed = options.fixed ?? false;
|
|
41
|
-
return {
|
|
42
|
-
...optionCodecHelper(item, prefix, fixed, options.description),
|
|
43
|
-
encode: (optionOrNullable) => {
|
|
40
|
+
return createEncoder({
|
|
41
|
+
getSizeFromValue: (optionOrNullable) => {
|
|
42
|
+
const option = isOption(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);
|
|
43
|
+
return getEncodedSize(Number(isSome(option)), prefix) + (isSome(option) ? getEncodedSize(option.value, item) : 0);
|
|
44
|
+
},
|
|
45
|
+
maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? void 0,
|
|
46
|
+
write: (optionOrNullable, bytes, offset) => {
|
|
44
47
|
const option = isOption(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
48
|
+
offset = prefix.write(Number(isSome(option)), bytes, offset);
|
|
49
|
+
if (isSome(option)) {
|
|
50
|
+
offset = item.write(option.value, bytes, offset);
|
|
51
|
+
}
|
|
52
|
+
return offset;
|
|
49
53
|
}
|
|
50
|
-
};
|
|
54
|
+
});
|
|
51
55
|
}
|
|
52
|
-
function getOptionDecoder(item,
|
|
53
|
-
const prefix =
|
|
54
|
-
const fixed =
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
56
|
+
function getOptionDecoder(item, config = {}) {
|
|
57
|
+
const prefix = config.prefix ?? getU8Decoder();
|
|
58
|
+
const fixed = config.fixed ?? false;
|
|
59
|
+
let fixedSize = null;
|
|
60
|
+
const isZeroSizeItem = isFixedSize(item) && isFixedSize(prefix) && item.fixedSize === 0;
|
|
61
|
+
if (fixed || isZeroSizeItem) {
|
|
62
|
+
assertIsFixedSize(item);
|
|
63
|
+
assertIsFixedSize(prefix);
|
|
64
|
+
fixedSize = prefix.fixedSize + item.fixedSize;
|
|
65
|
+
}
|
|
66
|
+
return createDecoder({
|
|
67
|
+
...fixedSize === null ? { maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? void 0 } : { fixedSize },
|
|
68
|
+
read: (bytes, offset) => {
|
|
58
69
|
if (bytes.length - offset <= 0) {
|
|
59
70
|
return [none(), offset];
|
|
60
71
|
}
|
|
61
|
-
const
|
|
62
|
-
const [isSome2, prefixOffset] = prefix.decode(bytes, offset);
|
|
63
|
-
offset = prefixOffset;
|
|
72
|
+
const [isSome2, prefixOffset] = prefix.read(bytes, offset);
|
|
64
73
|
if (isSome2 === 0) {
|
|
65
|
-
return [none(),
|
|
74
|
+
return [none(), fixedSize !== null ? offset + fixedSize : prefixOffset];
|
|
66
75
|
}
|
|
67
|
-
const [value, newOffset] = item.
|
|
68
|
-
offset
|
|
69
|
-
return [some(value), fixed ? fixedOffset : offset];
|
|
76
|
+
const [value, newOffset] = item.read(bytes, prefixOffset);
|
|
77
|
+
return [some(value), fixedSize !== null ? offset + fixedSize : newOffset];
|
|
70
78
|
}
|
|
71
|
-
};
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
function getOptionCodec(item, config = {}) {
|
|
82
|
+
return combineCodec(getOptionEncoder(item, config), getOptionDecoder(item, config));
|
|
83
|
+
}
|
|
84
|
+
function sumCodecSizes(sizes) {
|
|
85
|
+
return sizes.reduce((all, size) => all === null || size === null ? null : all + size, 0);
|
|
72
86
|
}
|
|
73
|
-
function
|
|
74
|
-
return
|
|
87
|
+
function getMaxSize(codec) {
|
|
88
|
+
return isFixedSize(codec) ? codec.fixedSize : codec.maxSize ?? null;
|
|
75
89
|
}
|
|
76
90
|
|
|
77
91
|
// src/unwrap-option-recursively.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/option.ts","../src/option-codec.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":["isSome"],"mappings":";AAkCO,IAAM,OAAO,CAAI,WAAyB,EAAE,UAAU,QAAQ,MAAM;AAOpE,IAAM,OAAO,OAAqB,EAAE,UAAU,OAAO;AAKrD,IAAM,WAAW,CAAc,UAClC,CAAC,EACG,SACA,OAAO,UAAU,YACjB,cAAc,UACZ,MAAM,aAAa,UAAU,WAAW,SAAU,MAAM,aAAa;AAMxE,IAAM,SAAS,CAAI,WAAyC,OAAO,aAAa;AAKhF,IAAM,SAAS,CAAI,WAAsC,OAAO,aAAa;;;AC9DpF;AAAA,EACI;AAAA,EAIA;AAAA,EAGA;AAAA,EACA;AAAA,OACG;AACP,SAAS,cAAc,oBAA+D;;;ACH/E,SAAS,aAA0B,QAAmB,UAA2B;AACpF,MAAI,OAAO,MAAM;AAAG,WAAO,OAAO;AAClC,SAAO,WAAW,SAAS,IAAK;AACpC;AAKO,IAAM,eAAe,CAAI,aAAmC,aAAa,OAAO,KAAK,QAAQ,IAAI,KAAQ;;;ADmBhH,SAAS,cAAc,OAAyC;AAC5D,SAAO,MAAM,OAAO,CAAC,KAAK,SAAU,QAAQ,QAAQ,SAAS,OAAO,OAAO,MAAM,MAAO,CAAkB;AAC9G;AAEA,SAAS,kB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5B,eAAO,CAAC,KAAK,GAAG,MAAM;AAAA,MAC1B;AACA,YAAM,cAAc,UAAU,OAAO,aAAa,MAAM,KAAK,aAAa;AAC1E,YAAM,CAACA,SAAQ,YAAY,IAAI,OAAO,OAAO,OAAO,MAAM;AAC1D,eAAS;AACT,UAAIA,YAAW,GAAG;AACd,eAAO,CAAC,KAAK,GAAG,QAAQ,cAAc,MAAM;AAAA,MAChD;AACA,YAAM,CAAC,OAAO,SAAS,IAAI,KAAK,OAAO,OAAO,MAAM;AACpD,eAAS;AACT,aAAO,CAAC,KAAK,KAAK,GAAG,QAAQ,cAAc,MAAM;AAAA,IACrD;AAAA,EACJ;AACJ;AAQO,SAAS,eACZ,MACA,UAA2C,CAAC,GACP;AACrC,SAAO,aAAa,iBAAoB,MAAM,OAAO,GAAG,iBAAoB,MAAM,OAAO,CAAC;AAC9F;;;AErEO,SAAS,wBAAqC,OAAU,UAA2C;AAEtG,MAAI,CAAC,SAAS,YAAY,OAAO,KAAK,GAAG;AACrC,WAAO;AAAA,EACX;AAEA,QAAM,OAAO,CAAI,MACZ,WAAW,wBAAwB,GAAG,QAAQ,IAAI,wBAAwB,CAAC;AAGhF,MAAI,SAAS,KAAK,GAAG;AACjB,QAAI,OAAO,KAAK;AAAG,aAAO,KAAK,MAAM,KAAK;AAC1C,WAAQ,WAAW,SAAS,IAAI;AAAA,EACpC;AAGA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACtB,WAAO,MAAM,IAAI,IAAI;AAAA,EACzB;AACA,MAAI,OAAO,UAAU,UAAU;AAC3B,WAAO,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAAA,EACjF;AACA,SAAO;AACX","sourcesContent":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = Some<T> | None;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import {\n assertFixedSizeCodec,\n BaseCodecOptions,\n Codec,\n CodecData,\n combineCodec,\n Decoder,\n Encoder,\n fixBytes,\n mergeBytes,\n} from '@solana/codecs-core';\nimport { getU8Decoder, getU8Encoder, NumberCodec, NumberDecoder, NumberEncoder } from '@solana/codecs-numbers';\n\nimport { isOption, isSome, none, Option, OptionOrNullable, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/** Defines the options for option codecs. */\nexport type OptionCodecOptions<TPrefix extends NumberCodec | NumberEncoder | NumberDecoder> = BaseCodecOptions & {\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `None` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n};\n\nfunction sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nfunction optionCodecHelper(item: CodecData, prefix: CodecData, fixed: boolean, description?: string): CodecData {\n let descriptionSuffix = `; ${prefix.description}`;\n let fixedSize = item.fixedSize === 0 ? prefix.fixedSize : null;\n if (fixed) {\n assertFixedSizeCodec(item, 'Fixed options can only be used with fixed-size codecs.');\n assertFixedSizeCodec(prefix, 'Fixed options can only be used with fixed-size prefix.');\n descriptionSuffix += '; fixed';\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n\n return {\n description: description ?? `option(${item.description + descriptionSuffix})`,\n fixedSize,\n maxSize: sumCodecSizes([prefix.maxSize, item.maxSize]),\n };\n}\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param options - A set of options for the encoder.\n */\nexport function getOptionEncoder<T>(\n item: Encoder<T>,\n options: OptionCodecOptions<NumberEncoder> = {}\n): Encoder<OptionOrNullable<T>> {\n const prefix = options.prefix ?? getU8Encoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n encode: (optionOrNullable: OptionOrNullable<T>) => {\n const option = isOption<T>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n const prefixByte = prefix.encode(Number(isSome(option)));\n let itemBytes = isSome(option) ? item.encode(option.value) : new Uint8Array();\n itemBytes = fixed ? fixBytes(itemBytes, item.fixedSize as number) : itemBytes;\n return mergeBytes([prefixByte, itemBytes]);\n },\n };\n}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param options - A set of options for the decoder.\n */\nexport function getOptionDecoder<T>(\n item: Decoder<T>,\n options: OptionCodecOptions<NumberDecoder> = {}\n): Decoder<Option<T>> {\n const prefix = options.prefix ?? getU8Decoder();\n const fixed = options.fixed ?? false;\n return {\n ...optionCodecHelper(item, prefix, fixed, options.description),\n decode: (bytes: Uint8Array, offset = 0) => {\n if (bytes.length - offset <= 0) {\n return [none(), offset];\n }\n const fixedOffset = offset + (prefix.fixedSize ?? 0) + (item.fixedSize ?? 0);\n const [isSome, prefixOffset] = prefix.decode(bytes, offset);\n offset = prefixOffset;\n if (isSome === 0) {\n return [none(), fixed ? fixedOffset : offset];\n }\n const [value, newOffset] = item.decode(bytes, offset);\n offset = newOffset;\n return [some(value), fixed ? fixedOffset : offset];\n },\n };\n}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param options - A set of options for the codec.\n */\nexport function getOptionCodec<T, U extends T = T>(\n item: Codec<T, U>,\n options: OptionCodecOptions<NumberCodec> = {}\n): Codec<OptionOrNullable<T>, Option<U>> {\n return combineCodec(getOptionEncoder<T>(item, options), getOptionDecoder<U>(item, options));\n}\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | undefined\n | null\n | Uint8Array\n | Int8Array\n | Uint16Array\n | Int16Array\n | Uint32Array\n | Int32Array\n | Date;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> = T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/option.ts","../src/option-codec.ts","../src/unwrap-option.ts","../src/unwrap-option-recursively.ts"],"names":["isSome"],"mappings":";AAkCO,IA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Content":["/**\n * An implementation of the Rust Option type in JavaScript.\n * It can be one of the following:\n * - <code>{@link Some}<T></code>: Meaning there is a value of type T.\n * - <code>{@link None}</code>: Meaning there is no value.\n */\nexport type Option<T> = None | Some<T>;\n\n/**\n * Defines a looser type that can be used when serializing an {@link Option}.\n * This allows us to pass null or the Option value directly whilst still\n * supporting the Option type for use-cases that need more type safety.\n */\nexport type OptionOrNullable<T> = Option<T> | T | null;\n\n/**\n * Represents an option of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport type Some<T> = Readonly<{ __option: 'Some'; value: T }>;\n\n/**\n * Represents an option of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport type None = Readonly<{ __option: 'None' }>;\n\n/**\n * Creates a new {@link Option} of type `T` that has a value.\n *\n * @see {@link Option}\n */\nexport const some = <T>(value: T): Option<T> => ({ __option: 'Some', value });\n\n/**\n * Creates a new {@link Option} of type `T` that has no value.\n *\n * @see {@link Option}\n */\nexport const none = <T>(): Option<T> => ({ __option: 'None' });\n\n/**\n * Whether the given data is an {@link Option}.\n */\nexport const isOption = <T = unknown>(input: unknown): input is Option<T> =>\n !!(\n input &&\n typeof input === 'object' &&\n '__option' in input &&\n ((input.__option === 'Some' && 'value' in input) || input.__option === 'None')\n );\n\n/**\n * Whether the given {@link Option} is a {@link Some}.\n */\nexport const isSome = <T>(option: Option<T>): option is Some<T> => option.__option === 'Some';\n\n/**\n * Whether the given {@link Option} is a {@link None}.\n */\nexport const isNone = <T>(option: Option<T>): option is None => option.__option === 'None';\n","import {\n assertIsFixedSize,\n Codec,\n combineCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n getEncodedSize,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from '@solana/codecs-core';\nimport {\n FixedSizeNumberCodec,\n FixedSizeNumberDecoder,\n FixedSizeNumberEncoder,\n getU8Decoder,\n getU8Encoder,\n NumberCodec,\n NumberDecoder,\n NumberEncoder,\n} from '@solana/codecs-numbers';\n\nimport { isOption, isSome, none, Option, OptionOrNullable, some } from './option';\nimport { wrapNullable } from './unwrap-option';\n\n/** Defines the config for option codecs. */\nexport type OptionCodecConfig<TPrefix extends NumberCodec | NumberDecoder | NumberEncoder> = {\n /**\n * Whether the item codec should be of fixed size.\n *\n * When this is true, a `None` value will skip the bytes that would\n * have been used for the item. Note that this will only work if the\n * item codec is of fixed size.\n * @defaultValue `false`\n */\n fixed?: boolean;\n\n /**\n * The codec to use for the boolean prefix.\n * @defaultValue u8 prefix.\n */\n prefix?: TPrefix;\n};\n\n/**\n * Creates a encoder for an optional value using `null` as the `None` value.\n *\n * @param item - The encoder to use for the value that may be present.\n * @param config - A set of config for the encoder.\n */\nexport function getOptionEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom>,\n config: OptionCodecConfig<FixedSizeNumberEncoder> & { fixed: true },\n): FixedSizeEncoder<OptionOrNullable<TFrom>>;\nexport function getOptionEncoder<TFrom>(\n item: FixedSizeEncoder<TFrom, 0>,\n config?: OptionCodecConfig<FixedSizeNumberEncoder>,\n): FixedSizeEncoder<OptionOrNullable<TFrom>>;\nexport function getOptionEncoder<TFrom>(\n item: Encoder<TFrom>,\n config?: OptionCodecConfig<NumberEncoder> & { fixed?: false },\n): VariableSizeEncoder<OptionOrNullable<TFrom>>;\nexport function getOptionEncoder<TFrom>(\n item: Encoder<TFrom>,\n config: OptionCodecConfig<NumberEncoder> = {},\n): Encoder<OptionOrNullable<TFrom>> {\n const prefix = config.prefix ?? getU8Encoder();\n const fixed = config.fixed ?? false;\n\n const isZeroSizeItem = isFixedSize(item) && isFixedSize(prefix) && item.fixedSize === 0;\n if (fixed || isZeroSizeItem) {\n assertIsFixedSize(item);\n assertIsFixedSize(prefix);\n const fixedSize = prefix.fixedSize + item.fixedSize;\n return createEncoder({\n fixedSize,\n write: (optionOrNullable: OptionOrNullable<TFrom>, bytes, offset) => {\n const option = isOption<TFrom>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n const prefixOffset = prefix.write(Number(isSome(option)), bytes, offset);\n if (isSome(option)) {\n item.write(option.value, bytes, prefixOffset);\n }\n return offset + fixedSize;\n },\n });\n }\n\n return createEncoder({\n getSizeFromValue: (optionOrNullable: OptionOrNullable<TFrom>) => {\n const option = isOption<TFrom>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n return (\n getEncodedSize(Number(isSome(option)), prefix) +\n (isSome(option) ? getEncodedSize(option.value, item) : 0)\n );\n },\n maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? undefined,\n write: (optionOrNullable: OptionOrNullable<TFrom>, bytes, offset) => {\n const option = isOption<TFrom>(optionOrNullable) ? optionOrNullable : wrapNullable(optionOrNullable);\n offset = prefix.write(Number(isSome(option)), bytes, offset);\n if (isSome(option)) {\n offset = item.write(option.value, bytes, offset);\n }\n return offset;\n },\n });\n}\n\n/**\n * Creates a decoder for an optional value using `null` as the `None` value.\n *\n * @param item - The decoder to use for the value that may be present.\n * @param config - A set of config for the decoder.\n */\nexport function getOptionDecoder<TTo>(\n item: FixedSizeDecoder<TTo>,\n config: OptionCodecConfig<FixedSizeNumberDecoder> & { fixed: true },\n): FixedSizeDecoder<Option<TTo>>;\nexport function getOptionDecoder<TTo>(\n item: FixedSizeDecoder<TTo, 0>,\n config?: OptionCodecConfig<FixedSizeNumberDecoder>,\n): FixedSizeDecoder<Option<TTo>>;\nexport function getOptionDecoder<TTo>(\n item: Decoder<TTo>,\n config?: OptionCodecConfig<NumberDecoder> & { fixed?: false },\n): VariableSizeDecoder<Option<TTo>>;\nexport function getOptionDecoder<TTo>(\n item: Decoder<TTo>,\n config: OptionCodecConfig<NumberDecoder> = {},\n): Decoder<Option<TTo>> {\n const prefix = config.prefix ?? getU8Decoder();\n const fixed = config.fixed ?? false;\n\n let fixedSize: number | null = null;\n const isZeroSizeItem = isFixedSize(item) && isFixedSize(prefix) && item.fixedSize === 0;\n if (fixed || isZeroSizeItem) {\n assertIsFixedSize(item);\n assertIsFixedSize(prefix);\n fixedSize = prefix.fixedSize + item.fixedSize;\n }\n\n return createDecoder({\n ...(fixedSize === null\n ? { maxSize: sumCodecSizes([prefix, item].map(getMaxSize)) ?? undefined }\n : { fixedSize }),\n read: (bytes: Uint8Array, offset) => {\n if (bytes.length - offset <= 0) {\n return [none(), offset];\n }\n const [isSome, prefixOffset] = prefix.read(bytes, offset);\n if (isSome === 0) {\n return [none(), fixedSize !== null ? offset + fixedSize : prefixOffset];\n }\n const [value, newOffset] = item.read(bytes, prefixOffset);\n return [some(value), fixedSize !== null ? offset + fixedSize : newOffset];\n },\n });\n}\n\n/**\n * Creates a codec for an optional value using `null` as the `None` value.\n *\n * @param item - The codec to use for the value that may be present.\n * @param config - A set of config for the codec.\n */\nexport function getOptionCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo>,\n config: OptionCodecConfig<FixedSizeNumberCodec> & { fixed: true },\n): FixedSizeCodec<OptionOrNullable<TFrom>, Option<TTo>>;\nexport function getOptionCodec<TFrom, TTo extends TFrom = TFrom>(\n item: FixedSizeCodec<TFrom, TTo, 0>,\n config?: OptionCodecConfig<FixedSizeNumberCodec>,\n): FixedSizeCodec<OptionOrNullable<TFrom>, Option<TTo>>;\nexport function getOptionCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config?: OptionCodecConfig<NumberCodec> & { fixed?: false },\n): VariableSizeCodec<OptionOrNullable<TFrom>, Option<TTo>>;\nexport function getOptionCodec<TFrom, TTo extends TFrom = TFrom>(\n item: Codec<TFrom, TTo>,\n config: OptionCodecConfig<NumberCodec> = {},\n): Codec<OptionOrNullable<TFrom>, Option<TTo>> {\n return combineCodec(getOptionEncoder<TFrom>(item, config as object), getOptionDecoder<TTo>(item, config as object));\n}\n\nfunction sumCodecSizes(sizes: (number | null)[]): number | null {\n return sizes.reduce((all, size) => (all === null || size === null ? null : all + size), 0 as number | null);\n}\n\nfunction getMaxSize(codec: { fixedSize: number } | { maxSize?: number }): number | null {\n return isFixedSize(codec) ? codec.fixedSize : codec.maxSize ?? null;\n}\n","import { isSome, none, Option, some } from './option';\n\n/**\n * Unwraps the value of an {@link Option} of type `T`\n * or returns a fallback value that defaults to `null`.\n */\nexport function unwrapOption<T>(option: Option<T>): T | null;\nexport function unwrapOption<T, U>(option: Option<T>, fallback: () => U): T | U;\nexport function unwrapOption<T, U = null>(option: Option<T>, fallback?: () => U): T | U {\n if (isSome(option)) return option.value;\n return fallback ? fallback() : (null as U);\n}\n\n/**\n * Wraps a nullable value into an {@link Option}.\n */\nexport const wrapNullable = <T>(nullable: T | null): Option<T> => (nullable !== null ? some(nullable) : none<T>());\n","import { isOption, isSome, None, Some } from './option';\n\n/**\n * Lists all types that should not be recursively unwrapped.\n *\n * @see {@link UnwrappedOption}\n */\ntype UnUnwrappables =\n | Date\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint16Array\n | Uint32Array\n | bigint\n | boolean\n | number\n | string\n | symbol\n | null\n | undefined;\n\n/**\n * A type that defines the recursive unwrapping of a type `T`\n * such that all nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns the type of its value, otherwise, it returns the provided\n * fallback type `U` which defaults to `null`.\n */\nexport type UnwrappedOption<T, U = null> =\n T extends Some<infer TValue>\n ? UnwrappedOption<TValue, U>\n : T extends None\n ? U\n : T extends UnUnwrappables\n ? T\n : T extends object\n ? { [key in keyof T]: UnwrappedOption<T[key], U> }\n : T extends Array<infer TItem>\n ? Array<UnwrappedOption<TItem, U>>\n : T;\n\n/**\n * Recursively go through a type `T` such that all\n * nested {@link Option} types are unwrapped.\n *\n * For each nested {@link Option} type, if the option is a {@link Some},\n * it returns its value, otherwise, it returns the provided fallback value\n * which defaults to `null`.\n */\nexport function unwrapOptionRecursively<T>(input: T): UnwrappedOption<T>;\nexport function unwrapOptionRecursively<T, U>(input: T, fallback: () => U): UnwrappedOption<T, U>;\nexport function unwrapOptionRecursively<T, U = null>(input: T, fallback?: () => U): UnwrappedOption<T, U> {\n // Types to bypass.\n if (!input || ArrayBuffer.isView(input)) {\n return input as UnwrappedOption<T, U>;\n }\n\n const next = <X>(x: X) =>\n (fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x)) as UnwrappedOption<X, U>;\n\n // Handle Option.\n if (isOption(input)) {\n if (isSome(input)) return next(input.value) as UnwrappedOption<T, U>;\n return (fallback ? fallback() : null) as UnwrappedOption<T, U>;\n }\n\n // Walk.\n if (Array.isArray(input)) {\n return input.map(next) as UnwrappedOption<T, U>;\n }\n if (typeof input === 'object') {\n return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)])) as UnwrappedOption<T, U>;\n }\n return input as UnwrappedOption<T, U>;\n}\n"]}
|