@solana/options 2.0.0-experimental.f57da91 → 2.0.0-experimental.f5d64e6
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/LICENSE +1 -1
- 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/option-codec.d.ts +29 -11
- package/dist/types/option-codec.d.ts.map +1 -1
- package/dist/types/unwrap-option-recursively.d.ts +1 -1
- package/dist/types/unwrap-option-recursively.d.ts.map +1 -1
- package/dist/types/unwrap-option.d.ts +1 -1
- package/package.json +14 -14
- package/dist/index.development.js +0 -252
- package/dist/index.development.js.map +0 -1
- package/dist/index.production.min.js +0 -21
package/LICENSE
CHANGED
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, "Fixed options can only be used with fixed-size codecs.");
|
|
28
|
+
codecsCore.assertIsFixedSize(prefix, "Fixed options can only be used with fixed-size 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, "Fixed options can only be used with fixed-size codecs.");
|
|
65
|
+
codecsCore.assertIsFixedSize(prefix, "Fixed options can only be used with fixed-size 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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AO;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,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,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAMA;AAAA,EACA;AAAA,OAIG;AACP;AAAA,EAII;AAAA,EACA;AAAA,OAIG;;;AClBA,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;;;ADoDzG,SAAS,iBACZ,MACA,SAA2C,CAAC,GACZ;AAChC,QAAM,SAAS,OAAO,UAAU,aAAa;AAC7C,QAAM,QAAQ,OAAO,SAAS;AAE9B,QAAM,iBAAiB,YAAY,IAAI,KAAK,YAAY,MAAM,KAAK,KAAK,cAAc;AACtF,MAAI,SAAS,gBAAgB;AACzB,sBAAkB,MAAM,wDAAwD;AAChF,sBAAkB,QAAQ,wDAAwD;AAClF,UAAM,YAAY,OAAO,YAAY,KAAK;AAC1C,WAAO,cAAc;AAAA,MACjB;AAAA,MACA,OAAO,CAAC,kBAA2C,OAAO,WAAW;AACjE,cAAM,SAAS,SAAgB,gBAAgB,IAAI,mBAAmB,aAAa,gBAAgB;AACnG,cAAM,eAAe,OAAO,MAAM,OAAO,OAAO,MAAM,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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 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 | NumberEncoder | NumberDecoder> = {\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\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, 'Fixed options can only be used with fixed-size codecs.');\n assertIsFixedSize(prefix, 'Fixed options can only be used with fixed-size 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, 'Fixed options can only be used with fixed-size codecs.');\n assertIsFixedSize(prefix, 'Fixed options can only be used with fixed-size 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 | 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"]}
|
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, "Fixed options can only be used with fixed-size codecs.");
|
|
26
|
+
assertIsFixedSize(prefix, "Fixed options can only be used with fixed-size 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, "Fixed options can only be used with fixed-size codecs.");
|
|
63
|
+
assertIsFixedSize(prefix, "Fixed options can only be used with fixed-size 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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AI,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,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,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAMA;AAAA,EACA;AAAA,OAIG;AACP;AAAA,EAII;AAAA,EACA;AAAA,OAIG;;;AClBA,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;;;ADoDzG,SAAS,iBACZ,MACA,SAA2C,CAAC,GACZ;AAChC,QAAM,SAAS,OAAO,UAAU,aAAa;AAC7C,QAAM,QAAQ,OAAO,SAAS;AAE9B,QAAM,iBAAiB,YAAY,IAAI,KAAK,YAAY,MAAM,KAAK,KAAK,cAAc;AACtF,MAAI,SAAS,gBAAgB;AACzB,sBAAkB,MAAM,wDAAwD;AAChF,sBAAkB,QAAQ,wDAAwD;AAClF,UAAM,YAAY,OAAO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AI,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 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 | NumberEncoder | NumberDecoder> = {\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\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, 'Fixed options can only be used with fixed-size codecs.');\n assertIsFixedSize(prefix, 'Fixed options can only be used with fixed-size 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, 'Fixed options can only be used with fixed-size codecs.');\n assertIsFixedSize(prefix, 'Fixed options can only be used with fixed-size 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 | 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"]}
|
package/dist/index.native.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, "Fixed options can only be used with fixed-size codecs.");
|
|
26
|
+
assertIsFixedSize(prefix, "Fixed options can only be used with fixed-size 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, "Fixed options can only be used with fixed-size codecs.");
|
|
63
|
+
assertIsFixedSize(prefix, "Fixed options can only be used with fixed-size 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
|
package/dist/index.native.js.map
CHANGED
|
@@ -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,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AAG,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,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,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAMA;AAAA,EACA;AAAA,OAIG;AACP;AAAA,EAII;AAAA,EACA;AAAA,OAIG;;;AClBA,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;;;ADoDzG,SAAS,iBACZ,MACA,SAA2C,CAAC,GACZ;AAChC,QAAM,SAAS,OAAO,UA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O,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 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 | NumberEncoder | NumberDecoder> = {\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\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, 'Fixed options can only be used with fixed-size codecs.');\n assertIsFixedSize(prefix, 'Fixed options can only be used with fixed-size 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, 'Fixed options can only be used with fixed-size codecs.');\n assertIsFixedSize(prefix, 'Fixed options can only be used with fixed-size 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 | 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"]}
|