Codec
An object that can encode and decode a value to and from a byte array.
A Codec can be either:
- A FixedSizeCodec, where all encoded values have the same fixed size.
- A VariableSizeCodec, where encoded values can vary in size.
Type Parameters
| Type Parameter | Default type |
|---|---|
TFrom | - |
TTo extends TFrom | TFrom |
Example
Remarks
For convenience, codecs can encode looser types than they decode.
That is, type TFrom can be a superset of type TTo.
For instance, a Codec<bigint | number, bigint> can encode both
bigint and number values, but will always decode to a bigint.
It is worth noting that codecs are the union of encoders and decoders.
This means that a Codec<TFrom, TTo> can be combined from an Encoder<TFrom>
and a Decoder<TTo> using the combineCodec function. This is particularly
useful for library authors who want to expose all three types of objects to their users.
Aside from combining encoders and decoders, codecs can also be created from scratch using
the createCodec function but it is more common to compose multiple codecs together
using the various helpers of the @solana/codecs package.
For instance, here's how you might create a Codec for a Person object type that contains
a name string and an age number:
Note that composed Codec types are clever enough to understand whether
they are fixed-size or variable-size. In the example above, getU32Codec() is
a fixed-size codec, while addCodecSizePrefix(getUtf8Codec(), getU32Codec())
is a variable-size codec. This makes the final Person codec a variable-size codec.