@solana/codecs-core 2.0.0-experimental.fbd3974 → 2.0.0-experimental.fcff844

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.
@@ -12,11 +12,6 @@ function assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes
12
12
  throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);
13
13
  }
14
14
  }
15
- function assertFixedSizeCodec(data, message) {
16
- if (data.fixedSize === null) {
17
- throw new Error(message ?? "Expected a fixed-size codec, got a variable-size one.");
18
- }
19
- }
20
15
 
21
16
  // src/bytes.ts
22
17
  var mergeBytes = (byteArrays) => {
@@ -45,121 +40,161 @@ var padBytes = (bytes, length) => {
45
40
  };
46
41
  var fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);
47
42
 
43
+ // src/codec.ts
44
+ function getEncodedSize(value, encoder) {
45
+ return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);
46
+ }
47
+ function createEncoder(encoder) {
48
+ return Object.freeze({
49
+ ...encoder,
50
+ encode: (value) => {
51
+ const bytes = new Uint8Array(getEncodedSize(value, encoder));
52
+ encoder.write(value, bytes, 0);
53
+ return bytes;
54
+ }
55
+ });
56
+ }
57
+ function createDecoder(decoder) {
58
+ return Object.freeze({
59
+ ...decoder,
60
+ decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0]
61
+ });
62
+ }
63
+ function createCodec(codec) {
64
+ return Object.freeze({
65
+ ...codec,
66
+ decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],
67
+ encode: (value) => {
68
+ const bytes = new Uint8Array(getEncodedSize(value, codec));
69
+ codec.write(value, bytes, 0);
70
+ return bytes;
71
+ }
72
+ });
73
+ }
74
+ function isFixedSize(codec) {
75
+ return "fixedSize" in codec && typeof codec.fixedSize === "number";
76
+ }
77
+ function assertIsFixedSize(codec, message) {
78
+ if (!isFixedSize(codec)) {
79
+ throw new Error(message ?? "Expected a fixed-size codec, got a variable-size one.");
80
+ }
81
+ }
82
+ function isVariableSize(codec) {
83
+ return !isFixedSize(codec);
84
+ }
85
+ function assertIsVariableSize(codec, message) {
86
+ if (!isVariableSize(codec)) {
87
+ throw new Error(message ?? "Expected a variable-size codec, got a fixed-size one.");
88
+ }
89
+ }
90
+
48
91
  // src/combine-codec.ts
49
- function combineCodec(encoder, decoder, description) {
50
- if (encoder.fixedSize !== decoder.fixedSize) {
92
+ function combineCodec(encoder, decoder) {
93
+ if (isFixedSize(encoder) !== isFixedSize(decoder)) {
94
+ throw new Error(`Encoder and decoder must either both be fixed-size or variable-size.`);
95
+ }
96
+ if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {
51
97
  throw new Error(
52
98
  `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`
53
99
  );
54
100
  }
55
- if (encoder.maxSize !== decoder.maxSize) {
101
+ if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {
56
102
  throw new Error(
57
103
  `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`
58
104
  );
59
105
  }
60
- if (description === void 0 && encoder.description !== decoder.description) {
61
- throw new Error(
62
- `Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. Pass a custom description as a third argument if you want to override the description and bypass this error.`
63
- );
64
- }
65
106
  return {
107
+ ...decoder,
108
+ ...encoder,
66
109
  decode: decoder.decode,
67
- description: description ?? encoder.description,
68
110
  encode: encoder.encode,
69
- fixedSize: encoder.fixedSize,
70
- maxSize: encoder.maxSize
111
+ read: decoder.read,
112
+ write: encoder.write
71
113
  };
72
114
  }
73
115
 
74
116
  // src/fix-codec.ts
75
- function fixCodecHelper(data, fixedBytes, description) {
76
- return {
77
- description: description ?? `fixed(${fixedBytes}, ${data.description})`,
117
+ function fixEncoder(encoder, fixedBytes) {
118
+ return createEncoder({
78
119
  fixedSize: fixedBytes,
79
- maxSize: fixedBytes
80
- };
81
- }
82
- function fixEncoder(encoder, fixedBytes, description) {
83
- return {
84
- ...fixCodecHelper(encoder, fixedBytes, description),
85
- encode: (value) => fixBytes(encoder.encode(value), fixedBytes)
86
- };
120
+ write: (value, bytes, offset) => {
121
+ const variableByteArray = encoder.encode(value);
122
+ const fixedByteArray = variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;
123
+ bytes.set(fixedByteArray, offset);
124
+ return offset + fixedBytes;
125
+ }
126
+ });
87
127
  }
88
- function fixDecoder(decoder, fixedBytes, description) {
89
- return {
90
- ...fixCodecHelper(decoder, fixedBytes, description),
91
- decode: (bytes, offset = 0) => {
128
+ function fixDecoder(decoder, fixedBytes) {
129
+ return createDecoder({
130
+ fixedSize: fixedBytes,
131
+ read: (bytes, offset) => {
92
132
  assertByteArrayHasEnoughBytesForCodec("fixCodec", fixedBytes, bytes, offset);
93
133
  if (offset > 0 || bytes.length > fixedBytes) {
94
134
  bytes = bytes.slice(offset, offset + fixedBytes);
95
135
  }
96
- if (decoder.fixedSize !== null) {
136
+ if (isFixedSize(decoder)) {
97
137
  bytes = fixBytes(bytes, decoder.fixedSize);
98
138
  }
99
- const [value] = decoder.decode(bytes, 0);
139
+ const [value] = decoder.read(bytes, 0);
100
140
  return [value, offset + fixedBytes];
101
141
  }
102
- };
142
+ });
103
143
  }
104
- function fixCodec(codec, fixedBytes, description) {
105
- return combineCodec(fixEncoder(codec, fixedBytes, description), fixDecoder(codec, fixedBytes, description));
144
+ function fixCodec(codec, fixedBytes) {
145
+ return combineCodec(fixEncoder(codec, fixedBytes), fixDecoder(codec, fixedBytes));
106
146
  }
107
147
 
108
148
  // src/map-codec.ts
109
149
  function mapEncoder(encoder, unmap) {
110
- return {
111
- description: encoder.description,
112
- encode: (value) => encoder.encode(unmap(value)),
113
- fixedSize: encoder.fixedSize,
114
- maxSize: encoder.maxSize
115
- };
150
+ return createEncoder({
151
+ ...isVariableSize(encoder) ? { ...encoder, getSizeFromValue: (value) => encoder.getSizeFromValue(unmap(value)) } : encoder,
152
+ write: (value, bytes, offset) => encoder.write(unmap(value), bytes, offset)
153
+ });
116
154
  }
117
155
  function mapDecoder(decoder, map) {
118
- return {
119
- decode: (bytes, offset = 0) => {
120
- const [value, length] = decoder.decode(bytes, offset);
121
- return [map(value, bytes, offset), length];
122
- },
123
- description: decoder.description,
124
- fixedSize: decoder.fixedSize,
125
- maxSize: decoder.maxSize
126
- };
156
+ return createDecoder({
157
+ ...decoder,
158
+ read: (bytes, offset) => {
159
+ const [value, newOffset] = decoder.read(bytes, offset);
160
+ return [map(value, bytes, offset), newOffset];
161
+ }
162
+ });
127
163
  }
128
164
  function mapCodec(codec, unmap, map) {
129
- return {
130
- decode: map ? mapDecoder(codec, map).decode : codec.decode,
131
- description: codec.description,
132
- encode: mapEncoder(codec, unmap).encode,
133
- fixedSize: codec.fixedSize,
134
- maxSize: codec.maxSize
135
- };
165
+ return createCodec({
166
+ ...mapEncoder(codec, unmap),
167
+ read: map ? mapDecoder(codec, map).read : codec.read
168
+ });
136
169
  }
137
170
 
138
171
  // src/reverse-codec.ts
139
172
  function reverseEncoder(encoder) {
140
- assertFixedSizeCodec(encoder, "Cannot reverse a codec of variable size.");
141
- return {
173
+ assertIsFixedSize(encoder, "Cannot reverse a codec of variable size.");
174
+ return createEncoder({
142
175
  ...encoder,
143
- encode: (value) => encoder.encode(value).reverse()
144
- };
176
+ write: (value, bytes, offset) => {
177
+ const newOffset = encoder.write(value, bytes, offset);
178
+ const slice = bytes.slice(offset, offset + encoder.fixedSize).reverse();
179
+ bytes.set(slice, offset);
180
+ return newOffset;
181
+ }
182
+ });
145
183
  }
146
184
  function reverseDecoder(decoder) {
147
- assertFixedSizeCodec(decoder, "Cannot reverse a codec of variable size.");
148
- return {
185
+ assertIsFixedSize(decoder, "Cannot reverse a codec of variable size.");
186
+ return createDecoder({
149
187
  ...decoder,
150
- decode: (bytes, offset = 0) => {
188
+ read: (bytes, offset) => {
151
189
  const reverseEnd = offset + decoder.fixedSize;
152
190
  if (offset === 0 && bytes.length === reverseEnd) {
153
- return decoder.decode(bytes.reverse(), offset);
191
+ return decoder.read(bytes.reverse(), offset);
154
192
  }
155
- const newBytes = mergeBytes([
156
- ...offset === 0 ? [] : [bytes.slice(0, offset)],
157
- bytes.slice(offset, reverseEnd).reverse(),
158
- ...bytes.length === reverseEnd ? [] : [bytes.slice(reverseEnd)]
159
- ]);
160
- return decoder.decode(newBytes, offset);
193
+ const reversedBytes = bytes.slice();
194
+ reversedBytes.set(bytes.slice(offset, reverseEnd).reverse(), offset);
195
+ return decoder.read(reversedBytes, offset);
161
196
  }
162
- };
197
+ });
163
198
  }
164
199
  function reverseCodec(codec) {
165
200
  return combineCodec(reverseEncoder(codec), reverseDecoder(codec));
@@ -167,12 +202,19 @@ function reverseCodec(codec) {
167
202
 
168
203
  exports.assertByteArrayHasEnoughBytesForCodec = assertByteArrayHasEnoughBytesForCodec;
169
204
  exports.assertByteArrayIsNotEmptyForCodec = assertByteArrayIsNotEmptyForCodec;
170
- exports.assertFixedSizeCodec = assertFixedSizeCodec;
205
+ exports.assertIsFixedSize = assertIsFixedSize;
206
+ exports.assertIsVariableSize = assertIsVariableSize;
171
207
  exports.combineCodec = combineCodec;
208
+ exports.createCodec = createCodec;
209
+ exports.createDecoder = createDecoder;
210
+ exports.createEncoder = createEncoder;
172
211
  exports.fixBytes = fixBytes;
173
212
  exports.fixCodec = fixCodec;
174
213
  exports.fixDecoder = fixDecoder;
175
214
  exports.fixEncoder = fixEncoder;
215
+ exports.getEncodedSize = getEncodedSize;
216
+ exports.isFixedSize = isFixedSize;
217
+ exports.isVariableSize = isVariableSize;
176
218
  exports.mapCodec = mapCodec;
177
219
  exports.mapDecoder = mapDecoder;
178
220
  exports.mapEncoder = mapEncoder;
@@ -181,3 +223,5 @@ exports.padBytes = padBytes;
181
223
  exports.reverseCodec = reverseCodec;
182
224
  exports.reverseDecoder = reverseDecoder;
183
225
  exports.reverseEncoder = reverseEncoder;
226
+ //# sourceMappingURL=out.js.map
227
+ //# sourceMappingURL=index.browser.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/assertions.ts","../src/bytes.ts","../src/combine-codec.ts","../src/fix-codec.ts","../src/map-codec.ts","../src/reverse-codec.ts"],"names":[],"mappings":";AAKO,SAAS,kCAAkC,kBAA0B,OAAmB,SAAS,GAAG;AACvG,MAAI,MAAM,SAAS,UAAU,GAAG;AAE5B,UAAM,IAAI,MAAM,UAAU,gBAAgB,oCAAoC;AAAA,EAClF;AACJ;AAKO,SAAS,sCACZ,kBACA,UACA,OACA,SAAS,GACX;AACE,QAAM,cAAc,MAAM,SAAS;AACnC,MAAI,cAAc,UAAU;AAExB,UAAM,IAAI,MAAM,UAAU,gBAAgB,cAAc,QAAQ,eAAe,WAAW,GAAG;AAAA,EACjG;AACJ;AAKO,SAAS,qBACZ,MACA,SACqC;AACrC,MAAI,KAAK,cAAc,MAAM;AAEzB,UAAM,IAAI,MAAM,WAAW,uDAAuD;AAAA,EACtF;AACJ;;;ACnCO,IAAM,aAAa,CAAC,eAAyC;AAChE,QAAM,qBAAqB,WAAW,OAAO,SAAO,IAAI,MAAM;AAC9D,MAAI,mBAAmB,WAAW,GAAG;AACjC,WAAO,WAAW,SAAS,WAAW,CAAC,IAAI,IAAI,WAAW;AAAA,EAC9D;AAEA,MAAI,mBAAmB,WAAW,GAAG;AACjC,WAAO,mBAAmB,CAAC;AAAA,EAC/B;AAEA,QAAM,cAAc,mBAAmB,OAAO,CAAC,OAAO,QAAQ,QAAQ,IAAI,QAAQ,CAAC;AACnF,QAAM,SAAS,IAAI,WAAW,WAAW;AACzC,MAAI,SAAS;AACb,qBAAmB,QAAQ,SAAO;AAC9B,WAAO,IAAI,KAAK,MAAM;AACtB,cAAU,IAAI;AAAA,EAClB,CAAC;AACD,SAAO;AACX;AAMO,IAAM,WAAW,CAAC,OAAmB,WAA+B;AACvE,MAAI,MA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IACjC,WAAW,MAAM;AAAA,IACjB,SAAS,MAAM;AAAA,EACnB;AACJ;;;AChDO,SAAS,eAAkB,SAAiC;AAC/D,uBAAqB,SAAS,0CAA0C;AACxE,SAAO;AAAA,IACH,GAAG;AAAA,IACH,QAAQ,CAAC,UAAa,QAAQ,OAAO,KAAK,EAAE,QAAQ;AAAA,EACxD;AACJ;AAKO,SAAS,eAAkB,SAAiC;AAC/D,uBAAqB,SAAS,0CAA0C;AACxE,SAAO;AAAA,IACH,GAAG;AAAA,IACH,QAAQ,CAAC,OAAmB,SAAS,MAAM;AACvC,YAAM,aAAa,SAAS,QAAQ;AACpC,UAAI,WAAW,KAAK,MAAM,WAAW,YAAY;AAC7C,eAAO,QAAQ,OAAO,MAAM,QAAQ,GAAG,MAAM;AAAA,MACjD;AACA,YAAM,WAAW,WAAW;AAAA,QACxB,GAAI,WAAW,IAAI,CAAC,IAAI,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC;AAAA,QAC/C,MAAM,MAAM,QAAQ,UAAU,EAAE,QAAQ;AAAA,QACxC,GAAI,MAAM,WAAW,aAAa,CAAC,IAAI,CAAC,MAAM,MAAM,UAAU,CAAC;AAAA,MACnE,CAAC;AACD,aAAO,QAAQ,OAAO,UAAU,MAAM;AAAA,IAC1C;AAAA,EACJ;AACJ;AAKO,SAAS,aAAiC,OAAiC;AAC9E,SAAO,aAAa,eAAe,KAAK,GAAG,eAAe,KAAK,CAAC;AACpE","sourcesContent":["import { CodecData } from './codec';\n\n/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n\n/**\n * Asserts that a given codec is fixed-size codec.\n */\nexport function assertFixedSizeCodec(\n data: Pick<CodecData, 'fixedSize'>,\n message?: string\n): asserts data is { fixedSize: number } {\n if (data.fixedSize === null) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Combines an encoder and a decoder into a codec.\n * The encoder and decoder must have the same fixed size, max size and description.\n * If a description is provided, it will override the encoder and decoder descriptions.\n */\nexport function combineCodec<From, To extends From = From>(\n encoder: Encoder<From>,\n decoder: Decoder<To>,\n description?: string\n): Codec<From, To> {\n if (encoder.fixedSize !== decoder.fixedSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`\n );\n }\n\n if (encoder.maxSize !== decoder.maxSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`\n );\n }\n\n if (description === undefined && encoder.description !== decoder.description) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. ` +\n `Pass a custom description as a third argument if you want to override the description and bypass this error.`\n );\n }\n\n return {\n decode: decoder.decode,\n description: description ?? encoder.description,\n encode: encoder.encode,\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport { Codec, CodecData, Decoder, Encoder } from './codec';\nimport { combineCodec } from './combine-codec';\n\nfunction fixCodecHelper(data: CodecData, fixedBytes: number, description?: string): CodecData {\n return {\n description: description ?? `fixed(${fixedBytes}, ${data.description})`,\n fixedSize: fixedBytes,\n maxSize: fixedBytes,\n };\n}\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n * @param description - A custom description for the encoder.\n */\nexport function fixEncoder<T>(encoder: Encoder<T>, fixedBytes: number, description?: string): Encoder<T> {\n return {\n ...fixCodecHelper(encoder, fixedBytes, description),\n encode: (value: T) => fixBytes(encoder.encode(value), fixedBytes),\n };\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n * @param description - A custom description for the decoder.\n */\nexport function fixDecoder<T>(decoder: Decoder<T>, fixedBytes: number, description?: string): Decoder<T> {\n return {\n ...fixCodecHelper(decoder, fixedBytes, description),\n decode: (bytes: Uint8Array, offset = 0) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodec', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (decoder.fixedSize !== null) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.decode(bytes, 0);\n return [value, offset + fixedBytes];\n },\n };\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n * @param description - A custom description for the codec.\n */\nexport function fixCodec<T, U extends T = T>(\n codec: Codec<T, U>,\n fixedBytes: number,\n description?: string\n): Codec<T, U> {\n return combineCodec(fixEncoder(codec, fixedBytes, description), fixDecoder(codec, fixedBytes, description));\n}\n","import { Codec, Decoder, Encoder } from './codec';\n\n/**\n * Converts an encoder A to a encoder B by mapping their values.\n */\nexport function mapEncoder<T, U>(encoder: Encoder<T>, unmap: (value: U) => T): Encoder<U> {\n return {\n description: encoder.description,\n encode: (value: U) => encoder.encode(unmap(value)),\n fixedSize: encoder.fixedSize,\n maxSize: encoder.maxSize,\n };\n}\n\n/**\n * Converts an decoder A to a decoder B by mapping their values.\n */\nexport function mapDecoder<T, U>(\n decoder: Decoder<T>,\n map: (value: T, bytes: Uint8Array, offset: number) => U\n): Decoder<U> {\n return {\n decode: (bytes: Uint8Array, offset = 0) => {\n const [value, length] = decoder.decode(bytes, offset);\n return [map(value, bytes, offset), length];\n },\n description: decoder.description,\n fixedSize: decoder.fixedSize,\n maxSize: decoder.maxSize,\n };\n}\n\n/**\n * Converts a codec A to a codec B by mapping their values.\n */\nexport function mapCodec<NewFrom, OldFrom, To extends NewFrom & OldFrom>(\n codec: Codec<OldFrom, To>,\n unmap: (value: NewFrom) => OldFrom\n): Codec<NewFrom, To>;\nexport function mapCodec<NewFrom, OldFrom, NewTo extends NewFrom = NewFrom, OldTo extends OldFrom = OldFrom>(\n codec: Codec<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map: (value: OldTo, bytes: Uint8Array, offset: number) => NewTo\n): Codec<NewFrom, NewTo>;\nexport function mapCodec<NewFrom, OldFrom, NewTo extends NewFrom = NewFrom, OldTo extends OldFrom = OldFrom>(\n codec: Codec<OldFrom, OldTo>,\n unmap: (value: NewFrom) => OldFrom,\n map?: (value: OldTo, bytes: Uint8Array, offset: number) => NewTo\n): Codec<NewFrom, NewTo> {\n return {\n decode: map ? mapDecoder(codec, map).decode : (codec.decode as unknown as Decoder<NewTo>['decode']),\n description: codec.description,\n encode: mapEncoder(codec, unmap).encode,\n fixedSize: codec.fixedSize,\n maxSize: codec.maxSize,\n };\n}\n","import { assertFixedSizeCodec } from './assertions';\nimport { mergeBytes } from './bytes';\nimport { Codec, Decoder, Encoder } from './codec';\nimport { combineCodec } from './combine-codec';\n\n/**\n * Reverses the bytes of a fixed-size encoder.\n */\nexport function reverseEncoder<T>(encoder: Encoder<T>): Encoder<T> {\n assertFixedSizeCodec(encoder, 'Cannot reverse a codec of variable size.');\n return {\n ...encoder,\n encode: (value: T) => encoder.encode(value).reverse(),\n };\n}\n\n/**\n * Reverses the bytes of a fixed-size decoder.\n */\nexport function reverseDecoder<T>(decoder: Decoder<T>): Decoder<T> {\n assertFixedSizeCodec(decoder, 'Cannot reverse a codec of variable size.');\n return {\n ...decoder,\n decode: (bytes: Uint8Array, offset = 0) => {\n const reverseEnd = offset + decoder.fixedSize;\n if (offset === 0 && bytes.length === reverseEnd) {\n return decoder.decode(bytes.reverse(), offset);\n }\n const newBytes = mergeBytes([\n ...(offset === 0 ? [] : [bytes.slice(0, offset)]),\n bytes.slice(offset, reverseEnd).reverse(),\n ...(bytes.length === reverseEnd ? [] : [bytes.slice(reverseEnd)]),\n ]);\n return decoder.decode(newBytes, offset);\n },\n };\n}\n\n/**\n * Reverses the bytes of a fixed-size codec.\n */\nexport function reverseCodec<T, U extends T = T>(codec: Codec<T, U>): Codec<T, U> {\n return combineCodec(reverseEncoder(codec), reverseDecoder(codec));\n}\n"]}
1
+ {"version":3,"sources":["../src/assertions.ts","../src/bytes.ts","../src/codec.ts","../src/combine-codec.ts","../src/fix-codec.ts","../src/map-codec.ts","../src/reverse-codec.ts"],"names":[],"mappings":";AAGO,SAAS,kCAAkC,kBAA0B,OAAmB,SAAS,GAAG;AACvG,MAAI,MAAM,SAAS,UAAU,GAAG;AAE5B,UAAM,IAAI,MAAM,UAAU,gBAAgB,oCAAoC;AAAA,EAClF;AACJ;AAKO,SAAS,sCACZ,kBACA,UACA,OACA,SAAS,GACX;AACE,QAAM,cAAc,MAAM,SAAS;AACnC,MAAI,cAAc,UAAU;AAExB,UAAM,IAAI,MAAM,UAAU,gBAAgB,cAAc,QAAQ,eAAe,WAAW,GAAG;AAAA,EACjG;AACJ;;;ACpBO,IAAM,aAAa,CAAC,eAAyC;AAChE,QAAM,qBAAqB,WAAW,OAAO,SAAO,IAAI,MAAM;AAC9D,MAAI,mBAAmB,WAAW,GAAG;AACjC,WAAO,WAAW,SAAS,WAAW,CAAC,IAAI,IAAI,WAAW;AAAA,EAC9D;AAEA,MAAI,mBAAmB,WAAW,GAAG;AACjC,WAAO,mBAAmB,CAAC;AAAA,EAC/B;AAEA,QAAM,cAAc,mBAAmB,OAAO,CAAC,OAAO,QAAQ,QAAQ,IAAI,QAAQ,CAAC;AACnF,QAAM,SAAS,IAAI,WAAW,WAAW;AACzC,MAAI,SAAS;AACb,qBAAmB,QAAQ,SAAO;AAC9B,WAAO,IAAI,KAAK,MAAM;AACtB,cAAU,IAAI;AAAA,EAClB,CAAC;AACD,SAAO;AACX;AAMO,IAAM,WAAW,CAAC,OAAmB,WAA+B;AACvE,MAAI,MAAM,UAAU;AAAQ,WAAO;AACnC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AA,IACH,OAAO,CAAC,OAAc,OAAO,WAAW;AACpC,YAAM,YAAY,QAAQ,MAAM,OAAO,OAAO,MAAM;AACpD,YAAM,QAAQ,MAAM,MAAM,QAAQ,SAAS,QAAQ,SAAS,EAAE,QAAQ;AACtE,YAAM,IAAI,OAAO,MAAM;AACvB,aAAO;AAAA,IACX;AAAA,EACJ,CAAC;AACL;AAKO,SAAS,eACZ,SAC4B;AAC5B,oBAAkB,SAAS,0CAA0C;AACrE,SAAO,cAAc;AAAA,IACjB,GAAG;AAAA,IACH,MAAM,CAAC,OAAO,WAAW;AACrB,YAAM,aAAa,SAAS,QAAQ;AACpC,UAAI,WAAW,KAAK,MAAM,WAAW,YAAY;AAC7C,eAAO,QAAQ,KAAK,MAAM,QAAQ,GAAG,MAAM;AAAA,MAC/C;AACA,YAAM,gBAAgB,MAAM,MAAM;AAClC,oBAAc,IAAI,MAAM,MAAM,QAAQ,UAAU,EAAE,QAAQ,GAAG,MAAM;AACnE,aAAO,QAAQ,KAAK,eAAe,MAAM;AAAA,IAC7C;AAAA,EACJ,CAAC;AACL;AAKO,SAAS,aACZ,OACiC;AACjC,SAAO,aAAa,eAAe,KAAK,GAAG,eAAe,KAAK,CAAC;AACpE","sourcesContent":["/**\n * Asserts that a given byte array is not empty.\n */\nexport function assertByteArrayIsNotEmptyForCodec(codecDescription: string, bytes: Uint8Array, offset = 0) {\n if (bytes.length - offset <= 0) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] cannot decode empty byte arrays.`);\n }\n}\n\n/**\n * Asserts that a given byte array has enough bytes to decode.\n */\nexport function assertByteArrayHasEnoughBytesForCodec(\n codecDescription: string,\n expected: number,\n bytes: Uint8Array,\n offset = 0,\n) {\n const bytesLength = bytes.length - offset;\n if (bytesLength < expected) {\n // TODO: Coded error.\n throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);\n }\n}\n","/**\n * Concatenates an array of `Uint8Array`s into a single `Uint8Array`.\n * Reuses the original byte array when applicable.\n */\nexport const mergeBytes = (byteArrays: Uint8Array[]): Uint8Array => {\n const nonEmptyByteArrays = byteArrays.filter(arr => arr.length);\n if (nonEmptyByteArrays.length === 0) {\n return byteArrays.length ? byteArrays[0] : new Uint8Array();\n }\n\n if (nonEmptyByteArrays.length === 1) {\n return nonEmptyByteArrays[0];\n }\n\n const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n nonEmptyByteArrays.forEach(arr => {\n result.set(arr, offset);\n offset += arr.length;\n });\n return result;\n};\n\n/**\n * Pads a `Uint8Array` with zeroes to the specified length.\n * If the array is longer than the specified length, it is returned as-is.\n */\nexport const padBytes = (bytes: Uint8Array, length: number): Uint8Array => {\n if (bytes.length >= length) return bytes;\n const paddedBytes = new Uint8Array(length).fill(0);\n paddedBytes.set(bytes);\n return paddedBytes;\n};\n\n/**\n * Fixes a `Uint8Array` to the specified length.\n * If the array is longer than the specified length, it is truncated.\n * If the array is shorter than the specified length, it is padded with zeroes.\n */\nexport const fixBytes = (bytes: Uint8Array, length: number): Uint8Array =>\n padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);\n","/**\n * Defines an offset in bytes.\n */\nexport type Offset = number;\n\ntype BaseEncoder<TFrom> = {\n /** Encode the provided value and return the encoded bytes directly. */\n readonly encode: (value: TFrom) => Uint8Array;\n /**\n * Writes the encoded value into the provided byte array at the given offset.\n * Returns the offset of the next byte after the encoded value.\n */\n readonly write: (value: TFrom, bytes: Uint8Array, offset: Offset) => Offset;\n};\n\nexport type FixedSizeEncoder<TFrom, TSize extends number = number> = BaseEncoder<TFrom> & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\nexport type VariableSizeEncoder<TFrom> = BaseEncoder<TFrom> & {\n /** The total size of the encoded value in bytes. */\n readonly getSizeFromValue: (value: TFrom) => number;\n /** The maximum size an encoded value can be in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can encode a value to a `Uint8Array`.\n */\nexport type Encoder<TFrom> = FixedSizeEncoder<TFrom> | VariableSizeEncoder<TFrom>;\n\ntype BaseDecoder<TTo> = {\n /** Decodes the provided byte array at the given offset (or zero) and returns the value directly. */\n readonly decode: (bytes: Uint8Array, offset?: Offset) => TTo;\n /**\n * Reads the encoded value from the provided byte array at the given offset.\n * Returns the decoded value and the offset of the next byte after the encoded value.\n */\n readonly read: (bytes: Uint8Array, offset: Offset) => [TTo, Offset];\n};\n\nexport type FixedSizeDecoder<TTo, TSize extends number = number> = BaseDecoder<TTo> & {\n /** The fixed size of the encoded value in bytes. */\n readonly fixedSize: TSize;\n};\n\nexport type VariableSizeDecoder<TTo> = BaseDecoder<TTo> & {\n /** The maximum size an encoded value can be in bytes, if applicable. */\n readonly maxSize?: number;\n};\n\n/**\n * An object that can decode a value from a `Uint8Array`.\n */\nexport type Decoder<TTo> = FixedSizeDecoder<TTo> | VariableSizeDecoder<TTo>;\n\nexport type FixedSizeCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number> = FixedSizeEncoder<\n TFrom,\n TSize\n> &\n FixedSizeDecoder<TTo, TSize>;\n\nexport type VariableSizeCodec<TFrom, TTo extends TFrom = TFrom> = VariableSizeEncoder<TFrom> & VariableSizeDecoder<TTo>;\n\n/**\n * An object that can encode and decode a value to and from a `Uint8Array`.\n * It supports encoding looser types than it decodes for convenience.\n * For example, a `bigint` encoder will always decode to a `bigint`\n * but can be used to encode a `number`.\n *\n * @typeParam TFrom - The type of the value to encode.\n * @typeParam TTo - The type of the decoded value. Defaults to `TFrom`.\n */\nexport type Codec<TFrom, TTo extends TFrom = TFrom> = FixedSizeCodec<TFrom, TTo> | VariableSizeCodec<TFrom, TTo>;\n\n/**\n * Get the encoded size of a given value in bytes.\n */\nexport function getEncodedSize<TFrom>(\n value: TFrom,\n encoder: { fixedSize: number } | { getSizeFromValue: (value: TFrom) => number },\n): number {\n return 'fixedSize' in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);\n}\n\n/** Fills the missing `encode` function using the existing `write` function. */\nexport function createEncoder<TFrom, TSize extends number>(\n encoder: Omit<FixedSizeEncoder<TFrom, TSize>, 'encode'>,\n): FixedSizeEncoder<TFrom, TSize>;\nexport function createEncoder<TFrom>(encoder: Omit<VariableSizeEncoder<TFrom>, 'encode'>): VariableSizeEncoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>,\n): Encoder<TFrom>;\nexport function createEncoder<TFrom>(\n encoder: Omit<FixedSizeEncoder<TFrom>, 'encode'> | Omit<VariableSizeEncoder<TFrom>, 'encode'>,\n): Encoder<TFrom> {\n return Object.freeze({\n ...encoder,\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, encoder));\n encoder.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\n/** Fills the missing `decode` function using the existing `read` function. */\nexport function createDecoder<TTo, TSize extends number>(\n decoder: Omit<FixedSizeDecoder<TTo, TSize>, 'decode'>,\n): FixedSizeDecoder<TTo, TSize>;\nexport function createDecoder<TTo>(decoder: Omit<VariableSizeDecoder<TTo>, 'decode'>): VariableSizeDecoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>,\n): Decoder<TTo>;\nexport function createDecoder<TTo>(\n decoder: Omit<FixedSizeDecoder<TTo>, 'decode'> | Omit<VariableSizeDecoder<TTo>, 'decode'>,\n): Decoder<TTo> {\n return Object.freeze({\n ...decoder,\n decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0],\n });\n}\n\n/** Fills the missing `encode` and `decode` function using the existing `write` and `read` functions. */\nexport function createCodec<TFrom, TTo extends TFrom = TFrom, TSize extends number = number>(\n codec: Omit<FixedSizeCodec<TFrom, TTo, TSize>, 'encode' | 'decode'>,\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec: Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>,\n): VariableSizeCodec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>,\n): Codec<TFrom, TTo>;\nexport function createCodec<TFrom, TTo extends TFrom = TFrom>(\n codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, 'encode' | 'decode'>\n | Omit<VariableSizeCodec<TFrom, TTo>, 'encode' | 'decode'>,\n): Codec<TFrom, TTo> {\n return Object.freeze({\n ...codec,\n decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],\n encode: value => {\n const bytes = new Uint8Array(getEncodedSize(value, codec));\n codec.write(value, bytes, 0);\n return bytes;\n },\n });\n}\n\nexport function isFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n): encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function isFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n): decoder is FixedSizeDecoder<TTo, TSize>;\nexport function isFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n): codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function isFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number },\n): codec is { fixedSize: TSize };\nexport function isFixedSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { fixedSize: number } {\n return 'fixedSize' in codec && typeof codec.fixedSize === 'number';\n}\n\nexport function assertIsFixedSize<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize> | VariableSizeEncoder<TFrom>,\n message?: string,\n): asserts encoder is FixedSizeEncoder<TFrom, TSize>;\nexport function assertIsFixedSize<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize> | VariableSizeDecoder<TTo>,\n message?: string,\n): asserts decoder is FixedSizeDecoder<TTo, TSize>;\nexport function assertIsFixedSize<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize> | VariableSizeCodec<TFrom, TTo>,\n message?: string,\n): asserts codec is FixedSizeCodec<TFrom, TTo, TSize>;\nexport function assertIsFixedSize<TSize extends number>(\n codec: { fixedSize: TSize } | { maxSize?: number },\n message?: string,\n): asserts codec is { fixedSize: TSize };\nexport function assertIsFixedSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string,\n): asserts codec is { fixedSize: number } {\n if (!isFixedSize(codec)) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a fixed-size codec, got a variable-size one.');\n }\n}\n\nexport function isVariableSize<TFrom>(encoder: Encoder<TFrom>): encoder is VariableSizeEncoder<TFrom>;\nexport function isVariableSize<TTo>(decoder: Decoder<TTo>): decoder is VariableSizeDecoder<TTo>;\nexport function isVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n): codec is VariableSizeCodec<TFrom, TTo>;\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number };\nexport function isVariableSize(codec: { fixedSize: number } | { maxSize?: number }): codec is { maxSize?: number } {\n return !isFixedSize(codec);\n}\n\nexport function assertIsVariableSize<T>(\n encoder: Encoder<T>,\n message?: string,\n): asserts encoder is VariableSizeEncoder<T>;\nexport function assertIsVariableSize<T>(\n decoder: Decoder<T>,\n message?: string,\n): asserts decoder is VariableSizeDecoder<T>;\nexport function assertIsVariableSize<TFrom, TTo extends TFrom>(\n codec: Codec<TFrom, TTo>,\n message?: string,\n): asserts codec is VariableSizeCodec<TFrom, TTo>;\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string,\n): asserts codec is { maxSize?: number };\nexport function assertIsVariableSize(\n codec: { fixedSize: number } | { maxSize?: number },\n message?: string,\n): asserts codec is { maxSize?: number } {\n if (!isVariableSize(codec)) {\n // TODO: Coded error.\n throw new Error(message ?? 'Expected a variable-size codec, got a fixed-size one.');\n }\n}\n","import {\n Codec,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\n\n/**\n * Combines an encoder and a decoder into a codec.\n * The encoder and decoder must have the same fixed size, max size and description.\n * If a description is provided, it will override the encoder and decoder descriptions.\n */\nexport function combineCodec<TFrom, TTo extends TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize>,\n decoder: FixedSizeDecoder<TTo, TSize>,\n): FixedSizeCodec<TFrom, TTo, TSize>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: VariableSizeEncoder<TFrom>,\n decoder: VariableSizeDecoder<TTo>,\n): VariableSizeCodec<TFrom, TTo>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: Encoder<TFrom>,\n decoder: Decoder<TTo>,\n): Codec<TFrom, TTo>;\nexport function combineCodec<TFrom, TTo extends TFrom>(\n encoder: Encoder<TFrom>,\n decoder: Decoder<TTo>,\n): Codec<TFrom, TTo> {\n if (isFixedSize(encoder) !== isFixedSize(decoder)) {\n // TODO: Coded error.\n throw new Error(`Encoder and decoder must either both be fixed-size or variable-size.`);\n }\n\n if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`,\n );\n }\n\n if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {\n // TODO: Coded error.\n throw new Error(\n `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`,\n );\n }\n\n return {\n ...decoder,\n ...encoder,\n decode: decoder.decode,\n encode: encoder.encode,\n read: decoder.read,\n write: encoder.write,\n };\n}\n","import { assertByteArrayHasEnoughBytesForCodec } from './assertions';\nimport { fixBytes } from './bytes';\nimport {\n Codec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isFixedSize,\n Offset,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n/**\n * Creates a fixed-size encoder from a given encoder.\n *\n * @param encoder - The encoder to wrap into a fixed-size encoder.\n * @param fixedBytes - The fixed number of bytes to write.\n */\nexport function fixEncoder<TFrom, TSize extends number>(\n encoder: Encoder<TFrom>,\n fixedBytes: TSize,\n): FixedSizeEncoder<TFrom, TSize> {\n return createEncoder({\n fixedSize: fixedBytes,\n write: (value: TFrom, bytes: Uint8Array, offset: Offset) => {\n // Here we exceptionally use the `encode` function instead of the `write`\n // function as using the nested `write` function on a fixed-sized byte\n // array may result in a out-of-bounds error on the nested encoder.\n const variableByteArray = encoder.encode(value);\n const fixedByteArray =\n variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;\n bytes.set(fixedByteArray, offset);\n return offset + fixedBytes;\n },\n });\n}\n\n/**\n * Creates a fixed-size decoder from a given decoder.\n *\n * @param decoder - The decoder to wrap into a fixed-size decoder.\n * @param fixedBytes - The fixed number of bytes to read.\n */\nexport function fixDecoder<TTo, TSize extends number>(\n decoder: Decoder<TTo>,\n fixedBytes: TSize,\n): FixedSizeDecoder<TTo, TSize> {\n return createDecoder({\n fixedSize: fixedBytes,\n read: (bytes: Uint8Array, offset: Offset) => {\n assertByteArrayHasEnoughBytesForCodec('fixCodec', fixedBytes, bytes, offset);\n // Slice the byte array to the fixed size if necessary.\n if (offset > 0 || bytes.length > fixedBytes) {\n bytes = bytes.slice(offset, offset + fixedBytes);\n }\n // If the nested decoder is fixed-size, pad and truncate the byte array accordingly.\n if (isFixedSize(decoder)) {\n bytes = fixBytes(bytes, decoder.fixedSize);\n }\n // Decode the value using the nested decoder.\n const [value] = decoder.read(bytes, 0);\n return [value, offset + fixedBytes];\n },\n });\n}\n\n/**\n * Creates a fixed-size codec from a given codec.\n *\n * @param codec - The codec to wrap into a fixed-size codec.\n * @param fixedBytes - The fixed number of bytes to read/write.\n */\nexport function fixCodec<TFrom, TTo extends TFrom, TSize extends number>(\n codec: Codec<TFrom, TTo>,\n fixedBytes: TSize,\n): FixedSizeCodec<TFrom, TTo, TSize> {\n return combineCodec(fixEncoder(codec, fixedBytes), fixDecoder(codec, fixedBytes));\n}\n","import {\n Codec,\n createCodec,\n createDecoder,\n createEncoder,\n Decoder,\n Encoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n isVariableSize,\n VariableSizeCodec,\n VariableSizeDecoder,\n VariableSizeEncoder,\n} from './codec';\n\n/**\n * Converts an encoder A to a encoder B by mapping their values.\n */\nexport function mapEncoder<TOldFrom, TNewFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TOldFrom, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeEncoder<TNewFrom, TSize>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: VariableSizeEncoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeEncoder<TNewFrom>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder<TNewFrom>;\nexport function mapEncoder<TOldFrom, TNewFrom>(\n encoder: Encoder<TOldFrom>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Encoder<TNewFrom> {\n return createEncoder({\n ...(isVariableSize(encoder)\n ? { ...encoder, getSizeFromValue: (value: TNewFrom) => encoder.getSizeFromValue(unmap(value)) }\n : encoder),\n write: (value: TNewFrom, bytes, offset) => encoder.write(unmap(value), bytes, offset),\n });\n}\n\n/**\n * Converts an decoder A to a decoder B by mapping their values.\n */\nexport function mapDecoder<TOldTo, TNewTo, TSize extends number>(\n decoder: FixedSizeDecoder<TOldTo, TSize>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): FixedSizeDecoder<TNewTo, TSize>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: VariableSizeDecoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): VariableSizeDecoder<TNewTo>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): Decoder<TNewTo>;\nexport function mapDecoder<TOldTo, TNewTo>(\n decoder: Decoder<TOldTo>,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): Decoder<TNewTo> {\n return createDecoder({\n ...decoder,\n read: (bytes: Uint8Array, offset) => {\n const [value, newOffset] = decoder.read(bytes, offset);\n return [map(value, bytes, offset), newOffset];\n },\n });\n}\n\n/**\n * Converts a codec A to a codec B by mapping their values.\n */\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom, TSize extends number>(\n codec: FixedSizeCodec<TOldFrom, TTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n): FixedSizeCodec<TNewFrom, TTo, TSize>;\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: VariableSizeCodec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n): VariableSizeCodec<TNewFrom, TTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TTo extends TNewFrom & TOldFrom>(\n codec: Codec<TOldFrom, TTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n): Codec<TNewFrom, TTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom, TSize extends number>(\n codec: FixedSizeCodec<TOldFrom, TOldTo, TSize>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): FixedSizeCodec<TNewFrom, TNewTo, TSize>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: VariableSizeCodec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): VariableSizeCodec<TNewFrom, TNewTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): Codec<TNewFrom, TNewTo>;\nexport function mapCodec<TOldFrom, TNewFrom, TOldTo extends TOldFrom, TNewTo extends TNewFrom>(\n codec: Codec<TOldFrom, TOldTo>,\n unmap: (value: TNewFrom) => TOldFrom,\n map?: (value: TOldTo, bytes: Uint8Array, offset: number) => TNewTo,\n): Codec<TNewFrom, TNewTo> {\n return createCodec({\n ...mapEncoder(codec, unmap),\n read: map ? mapDecoder(codec, map).read : (codec.read as unknown as Decoder<TNewTo>['read']),\n });\n}\n","import {\n assertIsFixedSize,\n createDecoder,\n createEncoder,\n FixedSizeCodec,\n FixedSizeDecoder,\n FixedSizeEncoder,\n} from './codec';\nimport { combineCodec } from './combine-codec';\n\n/**\n * Reverses the bytes of a fixed-size encoder.\n */\nexport function reverseEncoder<TFrom, TSize extends number>(\n encoder: FixedSizeEncoder<TFrom, TSize>,\n): FixedSizeEncoder<TFrom, TSize> {\n assertIsFixedSize(encoder, 'Cannot reverse a codec of variable size.');\n return createEncoder({\n ...encoder,\n write: (value: TFrom, bytes, offset) => {\n const newOffset = encoder.write(value, bytes, offset);\n const slice = bytes.slice(offset, offset + encoder.fixedSize).reverse();\n bytes.set(slice, offset);\n return newOffset;\n },\n });\n}\n\n/**\n * Reverses the bytes of a fixed-size decoder.\n */\nexport function reverseDecoder<TTo, TSize extends number>(\n decoder: FixedSizeDecoder<TTo, TSize>,\n): FixedSizeDecoder<TTo, TSize> {\n assertIsFixedSize(decoder, 'Cannot reverse a codec of variable size.');\n return createDecoder({\n ...decoder,\n read: (bytes, offset) => {\n const reverseEnd = offset + decoder.fixedSize;\n if (offset === 0 && bytes.length === reverseEnd) {\n return decoder.read(bytes.reverse(), offset);\n }\n const reversedBytes = bytes.slice();\n reversedBytes.set(bytes.slice(offset, reverseEnd).reverse(), offset);\n return decoder.read(reversedBytes, offset);\n },\n });\n}\n\n/**\n * Reverses the bytes of a fixed-size codec.\n */\nexport function reverseCodec<TFrom, TTo extends TFrom, TSize extends number>(\n codec: FixedSizeCodec<TFrom, TTo, TSize>,\n): FixedSizeCodec<TFrom, TTo, TSize> {\n return combineCodec(reverseEncoder(codec), reverseDecoder(codec));\n}\n"]}
@@ -10,11 +10,6 @@ function assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes
10
10
  throw new Error(`Codec [${codecDescription}] expected ${expected} bytes, got ${bytesLength}.`);
11
11
  }
12
12
  }
13
- function assertFixedSizeCodec(data, message) {
14
- if (data.fixedSize === null) {
15
- throw new Error(message ?? "Expected a fixed-size codec, got a variable-size one.");
16
- }
17
- }
18
13
 
19
14
  // src/bytes.ts
20
15
  var mergeBytes = (byteArrays) => {
@@ -43,126 +38,166 @@ var padBytes = (bytes, length) => {
43
38
  };
44
39
  var fixBytes = (bytes, length) => padBytes(bytes.length <= length ? bytes : bytes.slice(0, length), length);
45
40
 
41
+ // src/codec.ts
42
+ function getEncodedSize(value, encoder) {
43
+ return "fixedSize" in encoder ? encoder.fixedSize : encoder.getSizeFromValue(value);
44
+ }
45
+ function createEncoder(encoder) {
46
+ return Object.freeze({
47
+ ...encoder,
48
+ encode: (value) => {
49
+ const bytes = new Uint8Array(getEncodedSize(value, encoder));
50
+ encoder.write(value, bytes, 0);
51
+ return bytes;
52
+ }
53
+ });
54
+ }
55
+ function createDecoder(decoder) {
56
+ return Object.freeze({
57
+ ...decoder,
58
+ decode: (bytes, offset = 0) => decoder.read(bytes, offset)[0]
59
+ });
60
+ }
61
+ function createCodec(codec) {
62
+ return Object.freeze({
63
+ ...codec,
64
+ decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],
65
+ encode: (value) => {
66
+ const bytes = new Uint8Array(getEncodedSize(value, codec));
67
+ codec.write(value, bytes, 0);
68
+ return bytes;
69
+ }
70
+ });
71
+ }
72
+ function isFixedSize(codec) {
73
+ return "fixedSize" in codec && typeof codec.fixedSize === "number";
74
+ }
75
+ function assertIsFixedSize(codec, message) {
76
+ if (!isFixedSize(codec)) {
77
+ throw new Error(message ?? "Expected a fixed-size codec, got a variable-size one.");
78
+ }
79
+ }
80
+ function isVariableSize(codec) {
81
+ return !isFixedSize(codec);
82
+ }
83
+ function assertIsVariableSize(codec, message) {
84
+ if (!isVariableSize(codec)) {
85
+ throw new Error(message ?? "Expected a variable-size codec, got a fixed-size one.");
86
+ }
87
+ }
88
+
46
89
  // src/combine-codec.ts
47
- function combineCodec(encoder, decoder, description) {
48
- if (encoder.fixedSize !== decoder.fixedSize) {
90
+ function combineCodec(encoder, decoder) {
91
+ if (isFixedSize(encoder) !== isFixedSize(decoder)) {
92
+ throw new Error(`Encoder and decoder must either both be fixed-size or variable-size.`);
93
+ }
94
+ if (isFixedSize(encoder) && isFixedSize(decoder) && encoder.fixedSize !== decoder.fixedSize) {
49
95
  throw new Error(
50
96
  `Encoder and decoder must have the same fixed size, got [${encoder.fixedSize}] and [${decoder.fixedSize}].`
51
97
  );
52
98
  }
53
- if (encoder.maxSize !== decoder.maxSize) {
99
+ if (!isFixedSize(encoder) && !isFixedSize(decoder) && encoder.maxSize !== decoder.maxSize) {
54
100
  throw new Error(
55
101
  `Encoder and decoder must have the same max size, got [${encoder.maxSize}] and [${decoder.maxSize}].`
56
102
  );
57
103
  }
58
- if (description === void 0 && encoder.description !== decoder.description) {
59
- throw new Error(
60
- `Encoder and decoder must have the same description, got [${encoder.description}] and [${decoder.description}]. Pass a custom description as a third argument if you want to override the description and bypass this error.`
61
- );
62
- }
63
104
  return {
105
+ ...decoder,
106
+ ...encoder,
64
107
  decode: decoder.decode,
65
- description: description ?? encoder.description,
66
108
  encode: encoder.encode,
67
- fixedSize: encoder.fixedSize,
68
- maxSize: encoder.maxSize
109
+ read: decoder.read,
110
+ write: encoder.write
69
111
  };
70
112
  }
71
113
 
72
114
  // src/fix-codec.ts
73
- function fixCodecHelper(data, fixedBytes, description) {
74
- return {
75
- description: description ?? `fixed(${fixedBytes}, ${data.description})`,
115
+ function fixEncoder(encoder, fixedBytes) {
116
+ return createEncoder({
76
117
  fixedSize: fixedBytes,
77
- maxSize: fixedBytes
78
- };
79
- }
80
- function fixEncoder(encoder, fixedBytes, description) {
81
- return {
82
- ...fixCodecHelper(encoder, fixedBytes, description),
83
- encode: (value) => fixBytes(encoder.encode(value), fixedBytes)
84
- };
118
+ write: (value, bytes, offset) => {
119
+ const variableByteArray = encoder.encode(value);
120
+ const fixedByteArray = variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;
121
+ bytes.set(fixedByteArray, offset);
122
+ return offset + fixedBytes;
123
+ }
124
+ });
85
125
  }
86
- function fixDecoder(decoder, fixedBytes, description) {
87
- return {
88
- ...fixCodecHelper(decoder, fixedBytes, description),
89
- decode: (bytes, offset = 0) => {
126
+ function fixDecoder(decoder, fixedBytes) {
127
+ return createDecoder({
128
+ fixedSize: fixedBytes,
129
+ read: (bytes, offset) => {
90
130
  assertByteArrayHasEnoughBytesForCodec("fixCodec", fixedBytes, bytes, offset);
91
131
  if (offset > 0 || bytes.length > fixedBytes) {
92
132
  bytes = bytes.slice(offset, offset + fixedBytes);
93
133
  }
94
- if (decoder.fixedSize !== null) {
134
+ if (isFixedSize(decoder)) {
95
135
  bytes = fixBytes(bytes, decoder.fixedSize);
96
136
  }
97
- const [value] = decoder.decode(bytes, 0);
137
+ const [value] = decoder.read(bytes, 0);
98
138
  return [value, offset + fixedBytes];
99
139
  }
100
- };
140
+ });
101
141
  }
102
- function fixCodec(codec, fixedBytes, description) {
103
- return combineCodec(fixEncoder(codec, fixedBytes, description), fixDecoder(codec, fixedBytes, description));
142
+ function fixCodec(codec, fixedBytes) {
143
+ return combineCodec(fixEncoder(codec, fixedBytes), fixDecoder(codec, fixedBytes));
104
144
  }
105
145
 
106
146
  // src/map-codec.ts
107
147
  function mapEncoder(encoder, unmap) {
108
- return {
109
- description: encoder.description,
110
- encode: (value) => encoder.encode(unmap(value)),
111
- fixedSize: encoder.fixedSize,
112
- maxSize: encoder.maxSize
113
- };
148
+ return createEncoder({
149
+ ...isVariableSize(encoder) ? { ...encoder, getSizeFromValue: (value) => encoder.getSizeFromValue(unmap(value)) } : encoder,
150
+ write: (value, bytes, offset) => encoder.write(unmap(value), bytes, offset)
151
+ });
114
152
  }
115
153
  function mapDecoder(decoder, map) {
116
- return {
117
- decode: (bytes, offset = 0) => {
118
- const [value, length] = decoder.decode(bytes, offset);
119
- return [map(value, bytes, offset), length];
120
- },
121
- description: decoder.description,
122
- fixedSize: decoder.fixedSize,
123
- maxSize: decoder.maxSize
124
- };
154
+ return createDecoder({
155
+ ...decoder,
156
+ read: (bytes, offset) => {
157
+ const [value, newOffset] = decoder.read(bytes, offset);
158
+ return [map(value, bytes, offset), newOffset];
159
+ }
160
+ });
125
161
  }
126
162
  function mapCodec(codec, unmap, map) {
127
- return {
128
- decode: map ? mapDecoder(codec, map).decode : codec.decode,
129
- description: codec.description,
130
- encode: mapEncoder(codec, unmap).encode,
131
- fixedSize: codec.fixedSize,
132
- maxSize: codec.maxSize
133
- };
163
+ return createCodec({
164
+ ...mapEncoder(codec, unmap),
165
+ read: map ? mapDecoder(codec, map).read : codec.read
166
+ });
134
167
  }
135
168
 
136
169
  // src/reverse-codec.ts
137
170
  function reverseEncoder(encoder) {
138
- assertFixedSizeCodec(encoder, "Cannot reverse a codec of variable size.");
139
- return {
171
+ assertIsFixedSize(encoder, "Cannot reverse a codec of variable size.");
172
+ return createEncoder({
140
173
  ...encoder,
141
- encode: (value) => encoder.encode(value).reverse()
142
- };
174
+ write: (value, bytes, offset) => {
175
+ const newOffset = encoder.write(value, bytes, offset);
176
+ const slice = bytes.slice(offset, offset + encoder.fixedSize).reverse();
177
+ bytes.set(slice, offset);
178
+ return newOffset;
179
+ }
180
+ });
143
181
  }
144
182
  function reverseDecoder(decoder) {
145
- assertFixedSizeCodec(decoder, "Cannot reverse a codec of variable size.");
146
- return {
183
+ assertIsFixedSize(decoder, "Cannot reverse a codec of variable size.");
184
+ return createDecoder({
147
185
  ...decoder,
148
- decode: (bytes, offset = 0) => {
186
+ read: (bytes, offset) => {
149
187
  const reverseEnd = offset + decoder.fixedSize;
150
188
  if (offset === 0 && bytes.length === reverseEnd) {
151
- return decoder.decode(bytes.reverse(), offset);
189
+ return decoder.read(bytes.reverse(), offset);
152
190
  }
153
- const newBytes = mergeBytes([
154
- ...offset === 0 ? [] : [bytes.slice(0, offset)],
155
- bytes.slice(offset, reverseEnd).reverse(),
156
- ...bytes.length === reverseEnd ? [] : [bytes.slice(reverseEnd)]
157
- ]);
158
- return decoder.decode(newBytes, offset);
191
+ const reversedBytes = bytes.slice();
192
+ reversedBytes.set(bytes.slice(offset, reverseEnd).reverse(), offset);
193
+ return decoder.read(reversedBytes, offset);
159
194
  }
160
- };
195
+ });
161
196
  }
162
197
  function reverseCodec(codec) {
163
198
  return combineCodec(reverseEncoder(codec), reverseDecoder(codec));
164
199
  }
165
200
 
166
- export { assertByteArrayHasEnoughBytesForCodec, assertByteArrayIsNotEmptyForCodec, assertFixedSizeCodec, combineCodec, fixBytes, fixCodec, fixDecoder, fixEncoder, mapCodec, mapDecoder, mapEncoder, mergeBytes, padBytes, reverseCodec, reverseDecoder, reverseEncoder };
201
+ export { assertByteArrayHasEnoughBytesForCodec, assertByteArrayIsNotEmptyForCodec, assertIsFixedSize, assertIsVariableSize, combineCodec, createCodec, createDecoder, createEncoder, fixBytes, fixCodec, fixDecoder, fixEncoder, getEncodedSize, isFixedSize, isVariableSize, mapCodec, mapDecoder, mapEncoder, mergeBytes, padBytes, reverseCodec, reverseDecoder, reverseEncoder };
167
202
  //# sourceMappingURL=out.js.map
168
203
  //# sourceMappingURL=index.browser.js.map