{"_id":"@atlaschain/codecs-data-structures","name":"@atlaschain/codecs-data-structures","dist-tags":{"latest":"3.0.0"},"versions":{"3.0.0":{"name":"@atlaschain/codecs-data-structures","version":"3.0.0","description":"Codecs for various data structures","exports":{"edge-light":{"import":"./dist/index.node.mjs","require":"./dist/index.node.cjs"},"workerd":{"import":"./dist/index.node.mjs","require":"./dist/index.node.cjs"},"browser":{"import":"./dist/index.browser.mjs","require":"./dist/index.browser.cjs"},"node":{"import":"./dist/index.node.mjs","require":"./dist/index.node.cjs"},"react-native":"./dist/index.native.mjs","types":"./dist/types/index.d.ts"},"browser":{"./dist/index.node.cjs":"./dist/index.browser.cjs","./dist/index.node.mjs":"./dist/index.browser.mjs"},"main":"./dist/index.node.cjs","module":"./dist/index.node.mjs","react-native":"./dist/index.native.mjs","types":"./dist/types/index.d.ts","type":"commonjs","sideEffects":false,"keywords":["blockchain","atlas","web3"],"scripts":{"compile:docs":"typedoc","compile:js":"tsup --config build-scripts/tsup.config.package.ts","compile:typedefs":"tsc -p ./tsconfig.declarations.json","dev":"jest -c ../../node_modules/@atlas/test-config/jest-dev.config.ts --rootDir . --watch","prepublishOnly":"pnpm pkg delete devDependencies","publish-impl":"npm view $npm_package_name@$npm_package_version > /dev/null 2>&1 || (pnpm publish --tag ${PUBLISH_TAG:-canary} --access public --no-git-checks && (([ -n \"${GITHUB_OUTPUT:-}\" ] && echo 'published=true' >> \"$GITHUB_OUTPUT\") || true) && (([ \"$PUBLISH_TAG\" != \"canary\" ] && ../build-scripts/maybe-tag-latest.ts $npm_package_name@$npm_package_version) || true))","publish-packages":"pnpm prepublishOnly && pnpm publish-impl","style:fix":"pnpm eslint --fix src && pnpm prettier --log-level warn --ignore-unknown --write ./*","test:lint":"TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@atlas/test-config/jest-lint.config.ts --rootDir . --silent","test:prettier":"TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@atlas/test-config/jest-prettier.config.ts --rootDir . --silent","test:treeshakability:browser":"agadoo dist/index.browser.mjs","test:treeshakability:native":"agadoo dist/index.native.mjs","test:treeshakability:node":"agadoo dist/index.node.mjs","test:typecheck":"tsc --noEmit","test:unit:browser":"TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@atlas/test-config/jest-unit.config.browser.ts --rootDir . --silent","test:unit:node":"TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@atlas/test-config/jest-unit.config.node.ts --rootDir . --silent"},"author":{"name":"Atlas Chain Foundation"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/anza-xyz/kit.git"},"bugs":{"url":"https://github.com/anza-xyz/kit/issues"},"browserslist":["supports bigint and not dead","maintained node versions"],"dependencies":{"@atlaschain/codecs-core":"workspace:*","@atlaschain/codecs-numbers":"workspace:*","@atlaschain/errors":"workspace:*"},"peerDependencies":{"typescript":">=5.3.3"},"engines":{"node":">=20.18.0"},"_id":"@atlaschain/codecs-data-structures@3.0.0","homepage":"https://github.com/anza-xyz/kit#readme","_nodeVersion":"22.12.0","_npmVersion":"10.9.0","dist":{"integrity":"sha512-tkqk8IbYAS7PjecXRFe4fj4+hoGpbk6RCtRgTNU12Pr3217tYs3BmrFF6ZSKT+GQ0VbYxjfl8+HmLKFF5K41dw==","shasum":"53fcf88cba51d2a67835e3515f5c46ed37ccef55","tarball":"https://registry.npmjs.org/@atlaschain/codecs-data-structures/-/codecs-data-structures-3.0.0.tgz","fileCount":5,"unpackedSize":63746,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIEU5hRbjLJUnYDwvLLd7Q9VsZfWS/GzXOoN6p+pFfRKxAiEAr9CkLfVw0TKj64sMvovcEVuZ+EKXK6mHb/GADkhXNOw="}]},"_npmUser":{"name":"atlaschain","email":"jq@atlaschain.org"},"directories":{},"maintainers":[{"name":"atlaschain","email":"jq@atlaschain.org"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/codecs-data-structures_3.0.0_1756885185336_0.9784334276082556"},"_hasShrinkwrap":false}},"time":{"created":"2025-09-03T07:39:45.222Z","3.0.0":"2025-09-03T07:39:45.528Z","modified":"2025-09-03T07:39:45.801Z"},"maintainers":[{"name":"atlaschain","email":"jq@atlaschain.org"}],"description":"Codecs for various data structures","homepage":"https://github.com/anza-xyz/kit#readme","keywords":["blockchain","atlas","web3"],"repository":{"type":"git","url":"git+https://github.com/anza-xyz/kit.git"},"author":{"name":"Atlas Chain Foundation"},"bugs":{"url":"https://github.com/anza-xyz/kit/issues"},"license":"MIT","readme":"[![npm][npm-image]][npm-url]\n[![npm-downloads][npm-downloads-image]][npm-url]\n<br />\n[![code-style-prettier][code-style-prettier-image]][code-style-prettier-url]\n\n[code-style-prettier-image]: https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square\n[code-style-prettier-url]: https://github.com/prettier/prettier\n[npm-downloads-image]: https://img.shields.io/npm/dm/@atlas/codecs-data-structures?style=flat\n[npm-image]: https://img.shields.io/npm/v/@atlas/codecs-data-structures?style=flat\n[npm-url]: https://www.npmjs.com/package/@atlas/codecs-data-structures\n\n# @atlas/codecs-data-structures\n\nThis package contains codecs for various data structures such as arrays, maps, structs, tuples, enums, etc. It can be used standalone, but it is also exported as part of Kit [`@atlas/kit`](https://github.com/anza-xyz/kit/tree/main/packages/kit).\n\nThis package is also part of the [`@atlas/codecs` package](https://github.com/anza-xyz/kit/tree/main/packages/codecs) which acts as an entry point for all codec packages as well as for their documentation.\n\n## Array codec\n\nThe `getArrayCodec` function accepts any codec of type `T` and returns a codec of type `Array<T>`. For instance, here’s how we can create a codec for arrays of numbers that each fit in a single byte.\n\n```ts\nconst bytes = getArrayCodec(getU8Codec()).encode([1, 2, 3]);\nconst array = getArrayCodec(getU8Codec()).decode(bytes);\n```\n\nBy default, the size of the array is stored as a `u32` prefix before encoding the items.\n\n```ts\ngetArrayCodec(getU8Codec()).encode([1, 2, 3]);\n// 0x03000000010203\n//   |       └-- 3 items of 1 byte each.\n//   └-- 4-byte prefix telling us to read 3 items.\n```\n\nHowever, you may use the `size` option to configure this behaviour. It can be one of the following three strategies:\n\n- `Codec<number>`: When a number codec is provided, that codec will be used to encode and decode the size prefix.\n- `number`: When a number is provided, the codec will expect a fixed number of items in the array. An error will be thrown when trying to encode an array of a different length.\n- `\"remainder\"`: When the string `\"remainder\"` is passed as a size, the codec will use the remainder of the bytes to encode/decode its items. This means the size is not stored or known in advance but simply inferred from the rest of the buffer. For instance, if we have an array of `u16` numbers and 10 bytes remaining, we know there are 5 items in this array.\n\n```ts\ngetArrayCodec(getU8Codec(), { size: getU16Codec() }).encode([1, 2, 3]);\n// 0x0300010203\n//   |   └-- 3 items of 1 byte each.\n//   └-- 2-byte prefix telling us to read 3 items.\n\ngetArrayCodec(getU8Codec(), { size: 3 }).encode([1, 2, 3]);\n// 0x010203\n//   └-- 3 items of 1 byte each. There must always be 3 items in the array.\n\ngetArrayCodec(getU8Codec(), { size: 'remainder' }).encode([1, 2, 3]);\n// 0x010203\n//   └-- 3 items of 1 byte each. The size is inferred from the remainder of the bytes.\n```\n\nSeparate `getArrayEncoder` and `getArrayDecoder` functions are also available.\n\n```ts\nconst bytes = getArrayEncoder(getU8Encoder()).encode([1, 2, 3]);\nconst array = getArrayDecoder(getU8Decoder()).decode(bytes);\n```\n\n## Set codec\n\nThe `getSetCodec` function accepts any codec of type `T` and returns a codec of type `Set<T>`. For instance, here’s how we can create a codec for sets of numbers that each fit in a single byte.\n\n```ts\nconst bytes = getSetCodec(getU8Codec()).encode(new Set([1, 2, 3]));\nconst set = getSetCodec(getU8Codec()).decode(bytes);\n```\n\nJust like the array codec, it uses a `u32` size prefix by default but can be configured using the `size` option. [See the array codec](#array-codec) for more details.\n\n```ts\ngetSetCodec(getU8Codec(), { size: getU16Codec() }).encode(new Set([1, 2, 3]));\ngetSetCodec(getU8Codec(), { size: 3 }).encode(new Set([1, 2, 3]));\ngetSetCodec(getU8Codec(), { size: 'remainder' }).encode(new Set([1, 2, 3]));\n```\n\nSeparate `getSetEncoder` and `getSetDecoder` functions are also available.\n\n```ts\nconst bytes = getSetEncoder(getU8Encoder()).encode(new Set([1, 2, 3]));\nconst set = getSetDecoder(getU8Decoder()).decode(bytes);\n```\n\n## Map codec\n\nThe `getMapCodec` function accepts two codecs of type `K` and `V` and returns a codec of type `Map<K, V>`. For instance, here’s how we can create a codec for maps such that the keys are fixed strings of 8 bytes and the values are `u8` numbers.\n\n```ts\nconst keyCodec = fixCodecSize(getUtf8Codec(), 8);\nconst valueCodec = getU8Codec();\nconst bytes = getMapCodec(keyCodec, valueCodec).encode(new Map([['alice', 42]]));\nconst map = getMapCodec(keyCodec, valueCodec).decode(bytes);\n```\n\nJust like the array codec, it uses a `u32` size prefix by default.\n\n```ts\nconst keyCodec = fixCodecSize(getUtf8Codec(), 8);\nconst valueCodec = getU8Codec();\nconst myMap = new Map<string, number>();\nmyMap.set('alice', 42);\nmyMap.set('bob', 5);\n\ngetMapCodec(keyCodec, valueCodec).encode(myMap);\n// 0x02000000616c6963650000002a626f62000000000005\n//   |       |               | |               └-- 2nd entry value (5).\n//   |       |               | └-- 2nd entry key (\"bob\").\n//   |       |               └-- 1st entry value (42).\n//   |       └-- 1st entry key (\"alice\").\n//   └-- 4-byte prefix telling us to read 2 map entries.\n```\n\nHowever, it can be configured using the `size` option. [See the `size` option of the array codec](#array-codec) for more details.\n\n```ts\ngetMapCodec(keyCodec, valueCodec, { size: getU16Codec() }).encode(myMap);\ngetMapCodec(keyCodec, valueCodec, { size: 3 }).encode(myMap);\ngetMapCodec(keyCodec, valueCodec, { size: 'remainder' }).encode(myMap);\n```\n\nSeparate `getMapEncoder` and `getMapDecoder` functions are also available.\n\n```ts\nconst bytes = getMapEncoder(keyEncoder, valueEncoder).encode(myMap);\nconst map = getMapDecoder(keyDecoder, valueDecoder).decode(bytes);\n```\n\n## Tuple codec\n\nThe `getTupleCodec` function accepts any number of codecs — `T`, `U`, `V`, etc. — and returns a tuple codec of type `[T, U, V, …]` such that each item is in the order of the provided codecs.\n\n```ts\nconst codec = getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec()), getU8Codec(), getU64Codec()]);\nconst bytes = codec.encode(['alice', 42, 123]);\nconst tuple = codec.decode(bytes);\n```\n\nSeparate `getTupleEncoder` and `getTupleDecoder` functions are also available.\n\n```ts\nconst bytes = getTupleEncoder([getU8Encoder(), getU64Encoder()]).encode([42, 123]);\nconst tuple = getTupleDecoder([getU8Decoder(), getU64Decoder()]).decode(bytes);\n```\n\n## Struct codec\n\nThe `getStructCodec` function accepts any number of field codecs and returns a codec for an object containing all these fields. Each provided field is an array such that the first item is the name of the field and the second item is the codec used to encode and decode that field type.\n\n```ts\ntype Person = { name: string; age: number };\nconst personCodec: Codec<Person> = getStructCodec([\n    ['name', addCodecSizePrefix(getUtf8Codec(), getU32Codec())],\n    ['age', getU8Codec()],\n]);\n\nconst bytes = personCodec.encode({ name: 'alice', age: 42 });\nconst person = personCodec.decode(bytes);\n```\n\nSeparate `getStructEncoder` and `getStructDecoder` functions are also available.\n\n```ts\nconst personEncoder: Encoder<Person> = getStructEncoder([\n    ['name', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n    ['age', getU8Encoder()],\n]);\nconst personDecoder: Decoder<Person> = getStructDecoder([\n    ['name', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n    ['age', getU8Decoder()],\n]);\nconst bytes = personEncoder.encode({ name: 'alice', age: 42 });\nconst person = personDecoder.decode(bytes);\n```\n\n## Enum codec\n\nThe `getEnumCodec` function accepts a JavaScript enum constructor and returns a codec for encoding and decoding values of that enum.\n\n```ts\nenum Direction {\n    Left,\n    Right,\n}\n\nconst bytes = getEnumCodec(Direction).encode(Direction.Left);\nconst direction = getEnumCodec(Direction).decode(bytes);\n```\n\nWhen encoding an enum, you may either provide the value of the enum variant — e.g. `Direction.Left` — or its key — e.g. `'Left'`.\n\n```ts\nenum Direction {\n    Left,\n    Right,\n}\n\ngetEnumCodec(Direction).encode(Direction.Left); // 0x00\ngetEnumCodec(Direction).encode(Direction.Right); // 0x01\ngetEnumCodec(Direction).encode('Left'); // 0x00\ngetEnumCodec(Direction).encode('Right'); // 0x01\n```\n\nAs you can see, by default, a `u8` number is being used to store the enum value. However, a number codec may be passed as the `size` option to configure that behaviour.\n\n```ts\nconst u32DirectionCodec = getEnumCodec(Direction, { size: getU32Codec() });\nu32DirectionCodec.encode(Direction.Left); // 0x00000000\nu32DirectionCodec.encode(Direction.Right); // 0x01000000\n```\n\nThis function also works with lexical enums — e.g. `enum Direction { Left = '←' }` — explicit numerical enums — e.g. `enum Speed { Left = 50 }` — and hybrid enums with a mix of both.\n\n```ts\nenum Numbers {\n    One,\n    Five = 5,\n    Six,\n    Nine = 'nine',\n}\n\ngetEnumCodec(Numbers).encode(Direction.One); // 0x00\ngetEnumCodec(Numbers).encode(Direction.Five); // 0x01\ngetEnumCodec(Numbers).encode(Direction.Six); // 0x02\ngetEnumCodec(Numbers).encode(Direction.Nine); // 0x03\ngetEnumCodec(Numbers).encode('One'); // 0x00\ngetEnumCodec(Numbers).encode('Five'); // 0x01\ngetEnumCodec(Numbers).encode('Six'); // 0x02\ngetEnumCodec(Numbers).encode('Nine'); // 0x03\n```\n\nNotice how, by default, the index of the enum variant is used to encode the value of the enum. For instance, in the example above, `Numbers.Five` is encoded as `0x01` even though its value is `5`. This is also true for lexical enums.\n\nHowever, when dealing with numerical enums that have explicit values, you may use the `useValuesAsDiscriminators` option to encode the value of the enum variant instead of its index.\n\n```ts\nenum Numbers {\n    One,\n    Five = 5,\n    Six,\n    Nine = 9,\n}\n\nconst codec = getEnumCodec(Numbers, { useValuesAsDiscriminators: true });\ncodec.encode(Direction.One); // 0x00\ncodec.encode(Direction.Five); // 0x05\ncodec.encode(Direction.Six); // 0x06\ncodec.encode(Direction.Nine); // 0x09\ncodec.encode('One'); // 0x00\ncodec.encode('Five'); // 0x05\ncodec.encode('Six'); // 0x06\ncodec.encode('Nine'); // 0x09\n```\n\nNote that when using the `useValuesAsDiscriminators` option on an enum that contains a lexical value, an error will be thrown.\n\n```ts\nenum Lexical {\n    One,\n    Two = 'two',\n}\ngetEnumCodec(Lexical, { useValuesAsDiscriminators: true }); // Throws an error.\n```\n\nSeparate `getEnumEncoder` and `getEnumDecoder` functions are also available.\n\n```ts\nconst bytes = getEnumEncoder(Direction).encode(Direction.Left);\nconst direction = getEnumDecoder(Direction).decode(bytes);\n```\n\n## Literal union codec\n\nThe `getLiteralUnionCodec` function works similarly to the `getUnionCodec` function but does not require a JavaScript `enum` to exist.\n\nIt accepts an array of literal values — such as `string`, `number`, `boolean`, etc. — and returns a codec that encodes and decodes such values using by using their index in the array. It uses TypeScript unions to represent all the possible values.\n\n```ts\nconst codec = getLiteralUnionCodec(['left', 'right', 'up', 'down']);\n// ^? FixedSizeCodec<\"left\" | \"right\" | \"up\" | \"down\">\n\nconst bytes = codec.encode('left'); // 0x00\nconst value = codec.decode(bytes); // 'left'\n```\n\nAs you can see, it uses a `u8` number by default to store the index of the value. However, you may provide a number codec as the `size` option of the `getLiteralUnionCodec` function to customise that behaviour.\n\n```ts\nconst codec = getLiteralUnionCodec(['left', 'right', 'up', 'down'], {\n    size: getU32Codec(),\n});\n\ncodec.encode('left'); // 0x00000000\ncodec.encode('right'); // 0x01000000\ncodec.encode('up'); // 0x02000000\ncodec.encode('down'); // 0x03000000\n```\n\nSeparate `getLiteralUnionEncoder` and `getLiteralUnionDecoder` functions are also available.\n\n```ts\nconst bytes = getLiteralUnionEncoder(['left', 'right']).encode('left'); // 0x00\nconst value = getLiteralUnionDecoder(['left', 'right']).decode(bytes); // 'left'\n```\n\n## Discriminated union codec\n\nIn Rust, enums are powerful data types whose variants can be one of the following:\n\n- An empty variant — e.g. `enum Message { Quit }`.\n- A tuple variant — e.g. `enum Message { Write(String) }`.\n- A struct variant — e.g. `enum Message { Move { x: i32, y: i32 } }`.\n\nWhilst we do not have such powerful enums in JavaScript, we can emulate them in TypeScript using a union of objects such that each object is differentiated by a specific field. **We call this a discriminated union**.\n\nWe use a special field named `__kind` to distinguish between the different variants of a discriminated union. Additionally, since all variants are objects, we can use a `fields` property to wrap the array of tuple variants. Here is an example.\n\n```ts\ntype Message =\n    | { __kind: 'Quit' } // Empty variant.\n    | { __kind: 'Write'; fields: [string] } // Tuple variant.\n    | { __kind: 'Move'; x: number; y: number }; // Struct variant.\n```\n\nThe `getDiscriminatedUnionCodec` function helps us encode and decode these discriminated unions.\n\nIt requires the discriminator and codec of each variant as a first argument. Similarly to the struct codec, these are defined as an array of variant tuples where the first item is the discriminator of the variant and the second item is its codec. Since empty variants do not have data to encode, they simply use the unit codec — documented below — which does nothing.\n\nHere is how we can create a discriminated union codec for our previous example.\n\n```ts\nconst messageCodec = getDiscriminatedUnionCodec([\n    // Empty variant.\n    ['Quit', getUnitCodec()],\n\n    // Tuple variant.\n    ['Write', getStructCodec([['fields', getTupleCodec([addCodecSizePrefix(getUtf8Codec(), getU32Codec())])]])],\n\n    // Struct variant.\n    [\n        'Move',\n        getStructCodec([\n            ['x', getI32Codec()],\n            ['y', getI32Codec()],\n        ]),\n    ],\n]);\n```\n\nAnd here’s how we can use such a codec to encode discriminated unions. Notice that by default, they use a `u8` number prefix to distinguish between the different types of variants.\n\n```ts\nmessageCodec.encode({ __kind: 'Quit' });\n// 0x00\n//   └-- 1-byte discriminator (Index 0 — the \"Quit\" variant).\n\nmessageCodec.encode({ __kind: 'Write', fields: ['Hi'] });\n// 0x01020000004869\n//   | |       └-- utf8 string content (\"Hi\").\n//   | └-- u32 string prefix (2 characters).\n//   └-- 1-byte discriminator (Index 1 — the \"Write\" variant).\n\nmessageCodec.encode({ __kind: 'Move', x: 5, y: 6 });\n// 0x020500000006000000\n//   | |       └-- Field y (6).\n//   | └-- Field x (5).\n//   └-- 1-byte discriminator (Index 2 — the \"Move\" variant).\n```\n\nHowever, you may provide a number codec as the `size` option of the `getDiscriminatedUnionCodec` function to customise that behaviour.\n\n```ts\nconst u32MessageCodec = getDiscriminatedUnionCodec([...], {\n    size: getU32Codec(),\n});\n\nu32MessageCodec.encode({ __kind: 'Quit' });\n// 0x00000000\n//   └------┘ 4-byte discriminator (Index 0).\n\nu32MessageCodec.encode({ __kind: 'Write', fields: ['Hi'] });\n// 0x01000000020000004869\n//   └------┘ 4-byte discriminator (Index 1).\n\nu32MessageCodec.encode({ __kind: 'Move', x: 5, y: 6 });\n// 0x020000000500000006000000\n//   └------┘ 4-byte discriminator (Index 2).\n```\n\nYou may also customize the discriminator property — which defaults to `__kind` — by providing the desired property name as the `discriminator` option like so:\n\n```ts\nconst messageCodec = getDiscriminatedUnionCodec([...], {\n    discriminator: 'message',\n});\n\nmessageCodec.encode({ message: 'Quit' });\nmessageCodec.encode({ message: 'Write', fields: ['Hi'] });\nmessageCodec.encode({ message: 'Move', x: 5, y: 6 });\n```\n\nNote that, the discriminator value of a variant may be any scalar value — such as `number`, `bigint`, `boolean`, a JavaScript `enum`, etc. For instance, the following is also valid:\n\n```ts\nenum Message {\n    Quit,\n    Write,\n    Move,\n}\nconst messageCodec = getDiscriminatedUnionCodec([\n    [Message.Quit, getUnitCodec()],\n    [Message.Write, getStructCodec([...])],\n    [Message.Move, getStructCodec([...])],\n]);\n\ncodec.encode({ __kind: Message.Quit });\ncodec.encode({ __kind: Message.Write, fields: ['Hi'] });\ncodec.encode({ __kind: Message.Move, x: 5, y: 6 });\n```\n\nFinally, note that separate `getDiscriminatedUnionEncoder` and `getDiscriminatedUnionDecoder` functions are available.\n\n```ts\nconst bytes = getDiscriminatedUnionEncoder(variantEncoders).encode({ __kind: 'Quit' });\nconst message = getDiscriminatedUnionDecoder(variantDecoders).decode(bytes);\n```\n\n## Union codec\n\nThe `getUnionCodec` is a lower-lever codec helper that can be used to encode/decode any TypeScript union.\n\nIt accepts the following arguments:\n\n- An array of codecs, each defining a variant of the union.\n- A `getIndexFromValue` function which, given a value of the union, returns the index of the codec that should be used to encode that value.\n- A `getIndexFromBytes` function which, given the byte array to decode at a given offset, returns the index of the codec that should be used to decode the next bytes.\n\n```ts\nconst codec: Codec<number | boolean> = getUnionCodec(\n    [getU16Codec(), getBooleanCodec()],\n    value => (typeof value === 'number' ? 0 : 1),\n    (bytes, offset) => (bytes.slice(offset).length > 1 ? 0 : 1),\n);\n\ncodec.encode(42); // 0x2a00\ncodec.encode(true); // 0x01\n```\n\nAs usual, separate `getUnionEncoder` and `getUnionDecoder` functions are also available.\n\n```ts\nconst bytes = getUnionEncoder(encoders, getIndexFromValue).encode(42);\nconst value = getUnionDecoder(decoders, getIndexFromBytes).decode(bytes);\n```\n\n## Boolean codec\n\nThe `getBooleanCodec` function returns a `Codec<boolean>` that stores the boolean as `0` or `1` using a `u8` number by default.\n\n```ts\nconst bytes = getBooleanCodec().encode(true); // 0x01\nconst value = getBooleanCodec().decode(bytes); // true\n```\n\nYou may configure that behaviour by providing an explicit number codec as the `size` option of the `getBooleanCodec` function. That number codec will then be used to encode and decode the values `0` and `1` accordingly.\n\n```ts\ngetBooleanCodec({ size: getU16Codec() }).encode(false); // 0x0000\ngetBooleanCodec({ size: getU16Codec() }).encode(true); // 0x0100\n\ngetBooleanCodec({ size: getU32Codec() }).encode(false); // 0x00000000\ngetBooleanCodec({ size: getU32Codec() }).encode(true); // 0x01000000\n```\n\nSeparate `getBooleanEncoder` and `getBooleanDecoder` functions are also available.\n\n```ts\nconst bytes = getBooleanEncoder().encode(true); // 0x01\nconst value = getBooleanDecoder().decode(bytes); // true\n```\n\n## Nullable codec\n\nThe `getNullableCodec` function accepts a codec of type `T` and returns a codec of type `T | null`. It stores whether or not the item exists as a boolean prefix using a `u8` by default.\n\n```ts\nconst stringCodec = addCodecSizePrefix(getUtf8Codec(), getU32Codec());\n\ngetNullableCodec(stringCodec).encode('Hi');\n// 0x01020000004869\n//   | |       └-- utf8 string content (\"Hi\").\n//   | └-- u32 string prefix (2 characters).\n//   └-- 1-byte prefix (true — The item exists).\n\ngetNullableCodec(stringCodec).encode(null);\n// 0x00\n//   └-- 1-byte prefix (false — The item is null).\n```\n\nYou may provide a number codec as the `prefix` option of the `getNullableCodec` function to configure how to store the boolean prefix.\n\n```ts\nconst u32NullableStringCodec = getNullableCodec(stringCodec, {\n    prefix: getU32Codec(),\n});\n\nu32NullableStringCodec.encode('Hi');\n// 0x01000000020000004869\n//   └------┘ 4-byte prefix (true).\n\nu32NullableStringCodec.encode(null);\n// 0x00000000\n//   └------┘ 4-byte prefix (false).\n```\n\nAdditionally, if the item is a `FixedSizeCodec`, you may set the `noneValue` option to `\"zeroes\"` to also make the returned nullable codec a `FixedSizeCodec`. To do so, it will pad `null` values with zeroes to match the length of existing values.\n\n```ts\nconst fixedNullableStringCodec = getNullableCodec(\n    fixCodecSize(getUtf8Codec(), 8), // Only works with fixed-size items.\n    { noneValue: 'zeroes' },\n);\n\nfixedNullableStringCodec.encode('Hi');\n// 0x014869000000000000\n//   | └-- 8-byte utf8 string content (\"Hi\").\n//   └-- 1-byte prefix (true — The item exists).\n\nfixedNullableStringCodec.encode(null);\n// 0x000000000000000000\n//   | └-- 8-byte of padding to make a fixed-size codec.\n//   └-- 1-byte prefix (false — The item is null).\n```\n\nThe `noneValue` option can also be set to an explicit byte array to use as the padding for `null` values. Note that, in this case, the returned codec will not be a `FixedSizeCodec` as the byte array representing `null` values may be of any length.\n\n```ts\nconst codec = getNullableCodec(getUtf8Codec(), {\n    noneValue: new Uint8Array([255]), // 0xff means null.\n});\n\ncodec.encode('Hi');\n// 0x014869\n//   | └-- 2-byte utf8 string content (\"Hi\").\n//   └-- 1-byte prefix (true — The item exists).\n\ncodec.encode(null);\n// 0x00ff\n//   | └-- 1-byte representing null (0xff).\n//   └-- 1-byte prefix (false — The item is null).\n```\n\nLast but not least, the `prefix` option of the `getNullableCodec` function can also be set to `null`, meaning no prefix will be used to determine whether the item exists. In this case, the codec will rely on the `noneValue` option to determine whether the item is `null`.\n\n```ts\nconst codecWithZeroNoneValue = getNullableCodec(getU16Codec(), {\n    noneValue: 'zeroes', // 0x0000 means null.\n    prefix: null,\n});\ncodecWithZeroNoneValue.encode(42); // 0x2a00\ncodecWithZeroNoneValue.encode(null); // 0x0000\n\nconst codecWithCustomNoneValue = getNullableCodec(getU16Codec(), {\n    noneValue: new Uint8Array([255]), // 0xff means null.\n    prefix: null,\n});\ncodecWithCustomNoneValue.encode(42); // 0x2a00\ncodecWithCustomNoneValue.encode(null); // 0xff\n```\n\nFinally, note that if `prefix` is set to `null` and no `noneValue` is provided, the codec assumes that the item exists if and only if some remaining bytes are available to decode. This could be useful to describe data structures that may or may not have additional data to the end of the buffer.\n\n```ts\nconst codec = getNullableCodec(getU16Codec(), { prefix: null });\ncodec.encode(42); // 0x2a00\ncodec.encode(null); // Encodes nothing.\ncodec.decode(new Uint8Array([42, 0])); // 42\ncodec.decode(new Uint8Array([])); // null\n```\n\nTo recap, here are all the possible configurations of the `getNullableCodec` function, using a `u16` codec as an example.\n\n| `encode(42)` / `encode(null)` | No `noneValue` (default) | `noneValue: \"zeroes\"`       | Custom `noneValue` (`0xff`) |\n| ----------------------------- | ------------------------ | --------------------------- | --------------------------- |\n| `u8` prefix (default)         | `0x012a00` / `0x00`      | `0x012a00` / `0x000000`     | `0x012a00` / `0x00ff`       |\n| Custom `prefix` (`u16`)       | `0x01002a00` / `0x0000`  | `0x01002a00` / `0x00000000` | `0x01002a00` / `0x0000ff`   |\n| No `prefix`                   | `0x2a00` / `0x`          | `0x2a00` / `0x0000`         | `0x2a00` / `0xff`           |\n\nNote that you might be interested in the Rust-like alternative version of nullable codecs, available in [the `@atlas/options` package](https://github.com/anza-xyz/kit/tree/main/packages/options).\n\nSeparate `getNullableEncoder` and `getNullableDecoder` functions are also available.\n\n```ts\nconst bytes = getNullableEncoder(getU32Encoder()).encode(42);\nconst value = getNullableDecoder(getU32Decoder()).decode(bytes);\n```\n\n## Bytes codec\n\nThe `getBytesCodec` function returns a `Codec<Uint8Array>` meaning it converts `Uint8Arrays` to and from… `Uint8Arrays`! Whilst this might seem a bit useless, it can be useful when composed into other codecs. For example, you could use it in a struct codec to say that a particular field should be left unserialised.\n\n```ts\nconst bytes = getBytesCodec().encode(new Uint8Array([42])); // 0x2a\nconst value = getBytesCodec().decode(bytes); // 0x2a\n```\n\nThe `getBytesCodec` function will encode and decode `Uint8Arrays` using as much bytes as necessary. If you'd like to restrict the number of bytes used by this codec, you may combine it with the [`fixCodecSize`](https://github.com/anza-xyz/kit/tree/main/packages/codecs-core#fixing-the-size-of-codecs) or [`addCodecSizePrefix`](https://github.com/anza-xyz/kit/tree/main/packages/codecs-core#prefixing-the-size-of-codecs) primitives.\n\nHere are some examples of how you might use the `getBytesCodec` function.\n\n```ts\n// Variable size.\ngetBytesCodec().encode(new Uint8Array([42]));\n// 0x2a\n//   └-- Uint8Array content using any bytes available.\n\n// Prefixing the size with a 2-byte u16.\naddCodecSizePrefix(getBytesCodec(), getU16Codec()).encode(new Uint8Array([42]));\n// 0x01002a\n//   |   └-- Uint8Array content.\n//   └-- 2-byte prefix telling us to read 1 bytes\n\n// Fixing the size to 5 bytes.\nfixCodecSize(getBytesCodec(), 5).encode(new Uint8Array([42]));\n// 0x2a00000000\n//   └-- Uint8Array content padded to use exactly 5 bytes.\n```\n\nSeparate `getBytesEncoder` and `getBytesDecoder` functions are also available.\n\n```ts\nconst bytes = getBytesEncoder().encode(new Uint8Array([42]));\nconst value = getBytesDecoder().decode(bytes);\n```\n\n## Bit array codec\n\nThe `getBitArrayCodec` function returns a codec that encodes and decodes an array of booleans such that each boolean is represented by a single bit. It requires the size of the codec in bytes and an optional `backward` flag that can be used to reverse the order of the bits.\n\n```ts\nconst booleans = [true, false, true, false, true, false, true, false];\n\ngetBitArrayCodec(1).encode(booleans);\n// 0xaa or 0b10101010\n\ngetBitArrayCodec(1, { backward: true }).encode(booleans);\n// 0x55 or 0b01010101\n```\n\nSeparate `getBitArrayEncoder` and `getBitArrayDecoder` functions are also available.\n\n```ts\nconst bytes = getBitArrayEncoder(1).encode(booleans);\nconst decodedBooleans = getBitArrayDecoder(1).decode(bytes);\n```\n\n## Constant codec\n\nThe `getConstantCodec` function accepts any `Uint8Array` and returns a `Codec<void>`. When encoding, it will set the provided `Uint8Array` as-is. When decoding, it will assert that the next bytes contain the provided `Uint8Array` and move the offset forward.\n\n```ts\nconst codec = getConstantCodec(new Uint8Array([1, 2, 3]));\n\ncodec.encode(undefined); // 0x010203\ncodec.decode(new Uint8Array([1, 2, 3])); // undefined\ncodec.decode(new Uint8Array([1, 2, 4])); // Throws an error.\n```\n\nSeparate `getConstantEncoder` and `getConstantDecoder` functions are also available.\n\n```ts\ngetConstantEncoder(new Uint8Array([1, 2, 3])).encode(undefined);\ngetConstantDecoder(new Uint8Array([1, 2, 3])).decode(new Uint8Array([1, 2, 3]));\n```\n\n## Unit codec\n\nThe `getUnitCodec` function returns a `Codec<void>` that encodes `undefined` into an empty `Uint8Array` and returns `undefined` without consuming any bytes when decoding. This is more of a low-level codec that can be used internally by other codecs. For instance, this is how discriminated union codecs describe the codecs of empty variants.\n\n```ts\ngetUnitCodec().encode(undefined); // Empty Uint8Array\ngetUnitCodec().decode(anyBytes); // undefined\n```\n\nSeparate `getUnitEncoder` and `getUnitDecoder` functions are also available.\n\n```ts\ngetUnitEncoder().encode(undefined);\ngetUnitDecoder().decode(anyBytes);\n```\n\n---\n\nTo read more about the available codecs and how to use them, check out the documentation of the main [`@atlas/codecs` package](https://github.com/anza-xyz/kit/tree/main/packages/codecs).\n\n## Hidden prefix and suffix codec\n\nThe `getHiddenPrefixCodec` and `getHiddenSuffixCodec` functions allow us to respectively prepend or append a list of hidden `Codec<void>` to a given codec. When encoding, the hidden codecs will be encoded before or after the main codec and the offset will be moved accordingly. When decoding, the hidden codecs will be decoded but only the result of the main codec will be returned. This is particularly helpful when creating data structures that include constant values that should not be included in the final type.\n\n```ts\nconst codec: Codec<number> = getHiddenPrefixCodec(getU16Codec(), [\n    getConstantCodec(new Uint8Array([1, 2, 3])),\n    getConstantCodec(new Uint8Array([4, 5, 6])),\n]);\n\ncodec.encode(42);\n// 0x0102030405062a00\n//   |     |     └-- Our main u16 codec (value = 42).\n//   |     └-- Our second hidden prefix codec.\n//   └-- Our first hidden prefix codec.\n\ncodec.decode(new Uint8Array([1, 2, 3, 4, 5, 6, 42, 0])); // 42\n```\n\nAs usual, separate encoder and decoder functions are also available.\n\n```ts\ngetHiddenPrefixEncoder(encoder, prefixedEncoders);\ngetHiddenPrefixEncoder(decoder, prefixedDecoders);\ngetHiddenSuffixEncoder(encoder, suffixedEncoders);\ngetHiddenSuffixEncoder(decoder, suffixedDecoders);\n```\n","readmeFilename":"README.md","_rev":"1-57f5e7c0b2b544b9eece07d51b746236"}