@ac-kit/format-cbor 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,61 @@
1
1
  # @ac-kit/format-cbor
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5152230: The binary decoder and encoder no longer recurse: a hostile input of nested
8
+ arrays, maps or tags (a million levels of `0x81`) used to overflow the call
9
+ stack, and the resulting `RangeError` was reported by `decodeCborItem` as an
10
+ `incomplete` item. Nesting of any depth now decodes, encodes and walks
11
+ (`walkDataValue`, same pre-order and control markers) with
12
+ the native stack at constant depth; the decoded output is unchanged.
13
+
14
+ New optional `budget` in `decodeCbor(bytes, options)`,
15
+ `decodeCborItem(buffer, offset, options)` and `new CborItemDecoder(options)`:
16
+ one unit is charged per data item. A `WorkBudget` is used as given and its
17
+ errors propagate unchanged; a number is a private limit whose exhaustion throws
18
+ the new `CborLimitExceededError` (with `limit` and the core error as `cause`),
19
+ never reported as a decode `error` result. Without `budget`, nothing changes.
20
+
21
+ Also fixed: invalid UTF-8 in a text string now throws (or reports, from
22
+ `decodeCborItem` and `CborItemDecoder`) a `CborDecodeError` instead of leaking
23
+ a `TypeError` that ended decoder streams. `parseCborNotation`, `diagToValue`,
24
+ `printDataValue`, `printDiagNode`, `dataValueToJson` and `jsonToDataValue` are
25
+ iterative too, so a deep value that decodes can also be printed and converted.
26
+ `CborItemDecoder` charges a shared `WorkBudget` once per item however the bytes
27
+ are chunked, and a retry rechecks only the bytes the previous attempt read, so a
28
+ large definite-length string fed in small chunks stays linear. Indefinite-length
29
+ strings and containers are still decoded again from their start on every chunk,
30
+ quadratic in the number of chunks with or without a budget. `encodeCbor` and `walkDataValue` require an acyclic value; a
31
+ cyclic one is not detected.
32
+
33
+ ### Patch Changes
34
+
35
+ - Updated dependencies [2a0fe74]
36
+ - Updated dependencies [5152230]
37
+ - Updated dependencies [5152230]
38
+ - Updated dependencies [2a0fe74]
39
+ - Updated dependencies [5152230]
40
+ - Updated dependencies [2a0fe74]
41
+ - Updated dependencies [5152230]
42
+ - Updated dependencies [5152230]
43
+ - Updated dependencies [2a0fe74]
44
+ - Updated dependencies [2a0fe74]
45
+ - Updated dependencies [5152230]
46
+ - Updated dependencies [5152230]
47
+ - Updated dependencies [5152230]
48
+ - Updated dependencies [5152230]
49
+ - Updated dependencies [5152230]
50
+ - Updated dependencies [5152230]
51
+ - Updated dependencies [5152230]
52
+ - Updated dependencies [5152230]
53
+ - Updated dependencies [5152230]
54
+ - @ac-kit/algo@0.4.0
55
+ - @ac-kit/core@0.10.0
56
+ - @ac-kit/format-core@0.4.0
57
+ - @ac-kit/math-numbers@0.2.7
58
+
3
59
  ## 0.1.9
4
60
 
5
61
  ### Patch Changes
package/README.md CHANGED
@@ -47,6 +47,34 @@ exactly the case that needs this shape. `CborItemDecoder` adapts it to
47
47
  complete buffer (a CBOR sequence already fully in memory) or `DecodeStream` for
48
48
  one arriving in chunks over time.
49
49
 
50
+ ## Untrusted input
51
+
52
+ The binary decoder and encoder, `walkDataValue`, the notation parser and
53
+ printers (`parseCborNotation`, `printDataValue`, `printDiagNode`,
54
+ `diagToValue`) and the JSON bridge (`dataValueToJson`, `jsonToDataValue`) keep
55
+ nesting on the heap, so a million nested arrays decode (or fail with this
56
+ package's own error) instead of throwing `RangeError`. Values handed to the
57
+ encoder and walker must be acyclic. Cap the work of a binary decode with a
58
+ budget, charged one unit per data item:
59
+
60
+ ```ts
61
+ import { CborLimitExceededError, decodeCbor } from "@ac-kit/format-cbor";
62
+
63
+ try {
64
+ decodeCbor(new Uint8Array(1000).fill(0x81), { budget: 100 });
65
+ } catch (error) {
66
+ console.log(error instanceof CborLimitExceededError); // true
67
+ }
68
+ ```
69
+
70
+ Pass a `WorkBudget` from `@ac-kit/core` instead of a number to share one
71
+ allowance across calls. `CborItemDecoder` fed chunk by chunk charges a shared
72
+ budget once per item, not once per retry. Each new chunk decodes the pending item
73
+ again from its start: a definite-length string costs only its head per retry, so
74
+ it stays linear, but an indefinite-length string or a container is replayed in
75
+ full, so its cost grows with the square of the number of chunks, with or without
76
+ a budget.
77
+
50
78
  ## Scope
51
79
 
52
80
  Implemented: all 8 major types, definite- and indefinite-length decoding,
@@ -1,6 +1,22 @@
1
+ import { type WorkBudget } from "@ac-kit/core";
1
2
  import type { Decoder, DecodeResult } from "@ac-kit/format-core";
2
3
  import type { DataValue } from "../ast.js";
3
4
  import { CborDecodeError } from "../errors.js";
5
+ /** Options of the binary decoders. */
6
+ export type CborDecodeOptions = {
7
+ /**
8
+ * Caps the work of one decode: one unit is charged per data item, before it
9
+ * is read. A `WorkBudget` (`@ac-kit/core`) is used as given, so one allowance
10
+ * can span several calls, and what it throws propagates unchanged. A number
11
+ * is a private limit, a positive safe integer or `Infinity`, whose exhaustion
12
+ * throws {@link CborLimitExceededError}. Unset, the decode is bounded only by
13
+ * the input, since every item takes at least one byte.
14
+ *
15
+ * Nesting never uses the native call stack, so depth costs heap, not a
16
+ * `RangeError`; use the budget to bound it.
17
+ */
18
+ readonly budget?: WorkBudget | number;
19
+ };
4
20
  /** Outcome of {@link decodeCborItem}. */
5
21
  export type CborItemDecodeResult = {
6
22
  readonly status: "incomplete";
@@ -22,17 +38,38 @@ export type CborItemDecodeResult = {
22
38
  * tokenize-to-array function — CBOR is self-delimiting but an item's total
23
39
  * length isn't known until it is fully parsed, which is exactly the shape that
24
40
  * needs an incremental result instead of an eager array). Unlike
25
- * `DecodeResult`, `incomplete` carries no `needAtLeast` — the recursive descent
26
- * has no cheap way to compute one; a caller retries once more bytes arrive.
27
- * {@link CborItemDecoder} adapts this to the `Decoder` contract directly, for
28
- * driving via `decodeAll`/`DecodeStream`.
41
+ * `DecodeResult`, `incomplete` carries no `needAtLeast` — the decoder has no
42
+ * cheap way to compute one; a caller retries once more bytes arrive, and each
43
+ * retry decodes from `offset` again, charging its budget again (see
44
+ * {@link CborItemDecoder} for a retry that does not). {@link CborItemDecoder}
45
+ * adapts this to the `Decoder` contract directly, for driving via
46
+ * `decodeAll`/`DecodeStream`.
47
+ *
48
+ * Complexity: O(item size) time; memory O(nesting depth) beyond the decoded
49
+ * value, on the heap — the native call stack does not grow with nesting.
50
+ *
51
+ * @throws {CborLimitExceededError} When `options.budget` is a number that runs
52
+ * out.
53
+ * @throws {RangeError} When `options.budget` is a number that is not a positive
54
+ * safe integer or `Infinity`.
55
+ * @throws Whatever a caller's `WorkBudget` throws, unchanged.
29
56
  */
30
- export declare function decodeCborItem(buffer: Uint8Array, offset?: number): CborItemDecodeResult;
57
+ export declare function decodeCborItem(buffer: Uint8Array, offset?: number, options?: CborDecodeOptions): CborItemDecodeResult;
31
58
  /**
32
59
  * Decodes exactly one CBOR data item from `bytes`; no trailing bytes are
33
60
  * allowed.
61
+ *
62
+ * Complexity: as {@link decodeCborItem}.
63
+ *
64
+ * @throws {CborDecodeError} When the input is malformed (including invalid
65
+ * UTF-8 in a text string), truncated or has trailing bytes.
66
+ * @throws {CborLimitExceededError} When `options.budget` is a number that runs
67
+ * out.
68
+ * @throws {RangeError} When `options.budget` is a number that is not a positive
69
+ * safe integer or `Infinity`.
70
+ * @throws Whatever a caller's `WorkBudget` throws, unchanged.
34
71
  */
35
- export declare function decodeCbor(bytes: Uint8Array): DataValue;
72
+ export declare function decodeCbor(bytes: Uint8Array, options?: CborDecodeOptions): DataValue;
36
73
  /**
37
74
  * Adapts {@link decodeCborItem} to `@ac-kit/format-core`'s `Decoder` contract,
38
75
  * for decoding a CBOR sequence (RFC 8742) via `decodeAll` (a complete buffer)
@@ -45,8 +82,40 @@ export declare function decodeCbor(bytes: Uint8Array): DataValue;
45
82
  * which is what lets one bad item in a sequence not end the whole stream. An
46
83
  * error at offset zero is reported as `fatal`, since retrying from an unmoved
47
84
  * position could not terminate.
85
+ *
86
+ * Fed chunk by chunk, `DecodeStream` retries an incomplete item from its start
87
+ * each time. With a shared `WorkBudget`, a retry charges only the items beyond
88
+ * those already charged for the pending item, so an item costs the same however
89
+ * its bytes are split. A retry counts as the same item when its view starts
90
+ * with the bytes the previous unfinished attempt read (for a definite-length
91
+ * string still arriving, only its 1–9 byte head), since those alone decided the
92
+ * charges; any other view, and `reset()` (which `DecodeDriver.clear()` calls),
93
+ * forgets the charged units. The check and the copy it keeps cost O(bytes read
94
+ * by the previous attempt). A definite-length string fed in small chunks
95
+ * therefore decodes in linear time. Indefinite-length strings and containers
96
+ * are re-decoded from their start on every chunk, so their cost is quadratic in
97
+ * the number of chunks, with or without a budget (the budget adds a compare and
98
+ * copy of the same order). A numeric budget is private to each `decode` call,
99
+ * so it caps one attempt.
100
+ *
101
+ * @throws {CborLimitExceededError} From `decode`, when a numeric budget runs
102
+ * out.
103
+ * @throws {RangeError} From `decode`, for an invalid numeric budget.
104
+ * @throws Whatever a shared `WorkBudget` throws, unchanged, from `decode`.
48
105
  */
49
106
  export declare class CborItemDecoder implements Decoder<DataValue, Uint8Array, CborDecodeError> {
107
+ private readonly options?;
108
+ /** @param options Applied to every item; a shared `WorkBudget` spans them. */
109
+ constructor(options?: CborDecodeOptions | undefined);
110
+ /** Units already charged to a shared budget for the pending item. */
111
+ private charged;
112
+ /**
113
+ * Copy of the bytes the last unfinished attempt read, which alone decided
114
+ * `charged`; undefined when nothing is pending.
115
+ */
116
+ private chargedPrefix;
117
+ /** Forgets the pending item, so a shared budget is charged afresh. */
118
+ reset(): void;
50
119
  decode(view: Uint8Array): DecodeResult<DataValue, CborDecodeError>;
51
120
  }
52
121
  //# sourceMappingURL=decoder.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"decoder.d.ts","sourceRoot":"","sources":["../../src/binary/decoder.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGjE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AA8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
+ import { ByteReader, bytesIsEqual, concatBytes, decodeText, getBigUint64Be, getFloat32Be, getFloat64Be, getUint32Be, FixedWorkBudget, withWorkBudget, } from "@ac-kit/core";
2
2
  import { Float16 } from "@ac-kit/math-numbers";
3
- import { CborDecodeError } from "../errors.js";
3
+ import { CborDecodeError, CborLimitExceededError } from "../errors.js";
4
4
  const BREAK_BYTE = 0xff;
5
5
  function readArgument(reader, additionalInfo) {
6
6
  if (additionalInfo < 24)
@@ -33,6 +33,19 @@ function decodeByteString(reader, additionalInfo) {
33
33
  }
34
34
  return new Uint8Array(reader.read(Number(readArgument(reader, additionalInfo))));
35
35
  }
36
+ function decodeUtf8(bytes) {
37
+ try {
38
+ return decodeText(bytes, "utf-8", { fatal: true });
39
+ }
40
+ catch (error) {
41
+ if (error instanceof TypeError) {
42
+ throw new CborDecodeError("Invalid UTF-8 in text string", {
43
+ cause: error,
44
+ });
45
+ }
46
+ throw error;
47
+ }
48
+ }
36
49
  function decodeTextString(reader, additionalInfo) {
37
50
  if (additionalInfo === 31) {
38
51
  const chunks = [];
@@ -45,39 +58,9 @@ function decodeTextString(reader, additionalInfo) {
45
58
  chunks.push(new Uint8Array(reader.read(Number(readArgument(reader, chunkAdditionalInfo)))));
46
59
  }
47
60
  reader.readByte();
48
- return decodeText(concatBytes(chunks), "utf-8", { fatal: true });
49
- }
50
- return decodeText(reader.read(Number(readArgument(reader, additionalInfo))), "utf-8", { fatal: true });
51
- }
52
- function decodeArray(reader, additionalInfo) {
53
- const items = [];
54
- if (additionalInfo === 31) {
55
- while (reader.peekByte() !== BREAK_BYTE)
56
- items.push(decodeItem(reader));
57
- reader.readByte();
58
- }
59
- else {
60
- const length = Number(readArgument(reader, additionalInfo));
61
- for (let index = 0; index < length; index++)
62
- items.push(decodeItem(reader));
63
- }
64
- return { kind: "array", items };
65
- }
66
- function decodeMap(reader, additionalInfo) {
67
- const entries = [];
68
- if (additionalInfo === 31) {
69
- while (reader.peekByte() !== BREAK_BYTE) {
70
- entries.push([decodeItem(reader), decodeItem(reader)]);
71
- }
72
- reader.readByte();
73
- }
74
- else {
75
- const count = Number(readArgument(reader, additionalInfo));
76
- for (let index = 0; index < count; index++) {
77
- entries.push([decodeItem(reader), decodeItem(reader)]);
78
- }
61
+ return decodeUtf8(concatBytes(chunks));
79
62
  }
80
- return { kind: "map", entries };
63
+ return decodeUtf8(reader.read(Number(readArgument(reader, additionalInfo))));
81
64
  }
82
65
  function decodeSimpleOrFloat(reader, additionalInfo) {
83
66
  if (additionalInfo < 20)
@@ -113,51 +96,164 @@ function decodeSimpleOrFloat(reader, additionalInfo) {
113
96
  throw new CborDecodeError(`Reserved additional information value ${additionalInfo} for major type 7`);
114
97
  }
115
98
  }
116
- function decodeItem(reader) {
117
- const initialByte = reader.readByte();
118
- const majorType = initialByte >>> 5;
119
- const additionalInfo = initialByte & 0x1f;
120
- switch (majorType) {
121
- case 0:
122
- return { kind: "int", value: readArgument(reader, additionalInfo) };
123
- case 1:
124
- return { kind: "int", value: -1n - readArgument(reader, additionalInfo) };
125
- case 2:
126
- return { kind: "bytes", value: decodeByteString(reader, additionalInfo) };
127
- case 3:
128
- return { kind: "text", value: decodeTextString(reader, additionalInfo) };
129
- case 4:
130
- return decodeArray(reader, additionalInfo);
131
- case 5:
132
- return decodeMap(reader, additionalInfo);
133
- case 6: {
134
- const tag = readArgument(reader, additionalInfo);
135
- return { kind: "tag", tag, value: decodeItem(reader) };
99
+ function finishFrame(frame) {
100
+ const { values } = frame;
101
+ if (frame.majorType === 4) {
102
+ return { kind: "array", items: values };
103
+ }
104
+ if (frame.majorType === 5) {
105
+ const entries = [];
106
+ for (let index = 0; index < values.length; index += 2) {
107
+ entries.push([values[index], values[index + 1]]);
136
108
  }
137
- default:
138
- return decodeSimpleOrFloat(reader, additionalInfo);
109
+ return { kind: "map", entries };
139
110
  }
111
+ return { kind: "tag", tag: frame.tag, value: values[0] };
140
112
  }
141
113
  /**
142
- * Attempts to decode one top-level CBOR data item starting at `offset`.
143
- *
144
- * Modeled on `@ac-kit/format-core`'s incremental `DecodeResult` (this package's
145
- * answer to whether a "Lexer" should be a streaming class or an eager
146
- * tokenize-to-array function — CBOR is self-delimiting but an item's total
147
- * length isn't known until it is fully parsed, which is exactly the shape that
148
- * needs an incremental result instead of an eager array). Unlike
149
- * `DecodeResult`, `incomplete` carries no `needAtLeast` — the recursive descent
150
- * has no cheap way to compute one; a caller retries once more bytes arrive.
151
- * {@link CborItemDecoder} adapts this to the `Decoder` contract directly, for
152
- * driving via `decodeAll`/`DecodeStream`.
114
+ * Whether the next byte may be the break that closes `frame`. A map awaiting a
115
+ * value or a tag awaiting its content takes it as an item head instead, which
116
+ * rejects it as a reserved encoding.
117
+ */
118
+ function isAwaitingBreak(frame) {
119
+ return (frame.remaining === Infinity &&
120
+ (frame.majorType === 4 ||
121
+ (frame.majorType === 5 && !(frame.values.length & 1))));
122
+ }
123
+ /**
124
+ * Decodes one item with the nesting held on an explicit stack: native recursion
125
+ * would let a few kilobytes of `0x81` overflow the engine's call stack. A
126
+ * hand-written stack rather than `runTrampoline`: scalars (the bulk of any
127
+ * payload) need no generator, and a frame is one small object.
128
+ */
129
+ function decodeItem(reader, budget) {
130
+ const stack = [];
131
+ let completed;
132
+ for (;;) {
133
+ if (completed !== undefined) {
134
+ const frame = stack[stack.length - 1];
135
+ if (frame === undefined)
136
+ return completed;
137
+ frame.values.push(completed);
138
+ completed = undefined;
139
+ frame.remaining--;
140
+ if (frame.remaining === 0) {
141
+ stack.pop();
142
+ completed = finishFrame(frame);
143
+ }
144
+ continue;
145
+ }
146
+ const open = stack[stack.length - 1];
147
+ if (open !== undefined &&
148
+ isAwaitingBreak(open) &&
149
+ reader.peekByte() === BREAK_BYTE) {
150
+ reader.readByte();
151
+ stack.pop();
152
+ completed = finishFrame(open);
153
+ continue;
154
+ }
155
+ budget?.spend(1);
156
+ const initialByte = reader.readByte();
157
+ const majorType = initialByte >>> 5;
158
+ const additionalInfo = initialByte & 0x1f;
159
+ switch (majorType) {
160
+ case 0:
161
+ completed = {
162
+ kind: "int",
163
+ value: readArgument(reader, additionalInfo),
164
+ };
165
+ break;
166
+ case 1:
167
+ completed = {
168
+ kind: "int",
169
+ value: -1n - readArgument(reader, additionalInfo),
170
+ };
171
+ break;
172
+ case 2:
173
+ completed = {
174
+ kind: "bytes",
175
+ value: decodeByteString(reader, additionalInfo),
176
+ };
177
+ break;
178
+ case 3:
179
+ completed = {
180
+ kind: "text",
181
+ value: decodeTextString(reader, additionalInfo),
182
+ };
183
+ break;
184
+ case 4:
185
+ case 5: {
186
+ const remaining = additionalInfo === 31
187
+ ? Infinity
188
+ : Number(readArgument(reader, additionalInfo)) *
189
+ (majorType === 5 ? 2 : 1);
190
+ const frame = {
191
+ majorType,
192
+ tag: 0n,
193
+ values: [],
194
+ remaining,
195
+ };
196
+ if (remaining === 0) {
197
+ completed = finishFrame(frame);
198
+ }
199
+ else {
200
+ stack.push(frame);
201
+ }
202
+ break;
203
+ }
204
+ case 6:
205
+ stack.push({
206
+ majorType,
207
+ tag: readArgument(reader, additionalInfo),
208
+ values: [],
209
+ remaining: 1,
210
+ });
211
+ break;
212
+ default:
213
+ completed = decodeSimpleOrFloat(reader, additionalInfo);
214
+ }
215
+ }
216
+ }
217
+ /**
218
+ * Runs the decode under `options.budget`. Whatever the budget throws is
219
+ * recorded in `failure.error`, so the caller can tell it from the reader's
220
+ * `RangeError` that means "incomplete".
153
221
  */
154
- export function decodeCborItem(buffer, offset = 0) {
155
- const reader = new ByteReader(buffer, offset);
222
+ function decodeWithBudget(reader, budget, failure) {
223
+ if (budget === undefined)
224
+ return decodeItem(reader, undefined);
225
+ return withWorkBudget(budget, (work) => decodeItem(reader, {
226
+ spend(cost) {
227
+ try {
228
+ work.spend(cost);
229
+ }
230
+ catch (error) {
231
+ failure.error = error;
232
+ throw error;
233
+ }
234
+ },
235
+ }), (cause) => new CborLimitExceededError(cause.limit, { cause }));
236
+ }
237
+ /**
238
+ * Decodes one item from `reader`'s position, mapping the reader's `RangeError`
239
+ * to `incomplete`. On return or throw, `reader.position` is how far the decoder
240
+ * read: everything that influenced the outcome and the budget charges lies
241
+ * before it, since a read that runs out consumes nothing.
242
+ */
243
+ function decodeFromReader(reader, options) {
244
+ if (typeof options?.budget === "number") {
245
+ // Validates the limit here, where a RangeError cannot be read as "incomplete".
246
+ new FixedWorkBudget(options.budget);
247
+ }
248
+ const offset = reader.position;
249
+ const failure = {};
156
250
  try {
157
- const value = decodeItem(reader);
251
+ const value = decodeWithBudget(reader, options?.budget, failure);
158
252
  return { status: "item", value, consumed: reader.position - offset };
159
253
  }
160
254
  catch (error) {
255
+ if (error === failure.error)
256
+ throw error;
161
257
  if (error instanceof RangeError)
162
258
  return { status: "incomplete" };
163
259
  if (error instanceof CborDecodeError) {
@@ -170,12 +266,49 @@ export function decodeCborItem(buffer, offset = 0) {
170
266
  throw error;
171
267
  }
172
268
  }
269
+ /**
270
+ * Attempts to decode one top-level CBOR data item starting at `offset`.
271
+ *
272
+ * Modeled on `@ac-kit/format-core`'s incremental `DecodeResult` (this package's
273
+ * answer to whether a "Lexer" should be a streaming class or an eager
274
+ * tokenize-to-array function — CBOR is self-delimiting but an item's total
275
+ * length isn't known until it is fully parsed, which is exactly the shape that
276
+ * needs an incremental result instead of an eager array). Unlike
277
+ * `DecodeResult`, `incomplete` carries no `needAtLeast` — the decoder has no
278
+ * cheap way to compute one; a caller retries once more bytes arrive, and each
279
+ * retry decodes from `offset` again, charging its budget again (see
280
+ * {@link CborItemDecoder} for a retry that does not). {@link CborItemDecoder}
281
+ * adapts this to the `Decoder` contract directly, for driving via
282
+ * `decodeAll`/`DecodeStream`.
283
+ *
284
+ * Complexity: O(item size) time; memory O(nesting depth) beyond the decoded
285
+ * value, on the heap — the native call stack does not grow with nesting.
286
+ *
287
+ * @throws {CborLimitExceededError} When `options.budget` is a number that runs
288
+ * out.
289
+ * @throws {RangeError} When `options.budget` is a number that is not a positive
290
+ * safe integer or `Infinity`.
291
+ * @throws Whatever a caller's `WorkBudget` throws, unchanged.
292
+ */
293
+ export function decodeCborItem(buffer, offset = 0, options) {
294
+ return decodeFromReader(new ByteReader(buffer, offset), options);
295
+ }
173
296
  /**
174
297
  * Decodes exactly one CBOR data item from `bytes`; no trailing bytes are
175
298
  * allowed.
299
+ *
300
+ * Complexity: as {@link decodeCborItem}.
301
+ *
302
+ * @throws {CborDecodeError} When the input is malformed (including invalid
303
+ * UTF-8 in a text string), truncated or has trailing bytes.
304
+ * @throws {CborLimitExceededError} When `options.budget` is a number that runs
305
+ * out.
306
+ * @throws {RangeError} When `options.budget` is a number that is not a positive
307
+ * safe integer or `Infinity`.
308
+ * @throws Whatever a caller's `WorkBudget` throws, unchanged.
176
309
  */
177
- export function decodeCbor(bytes) {
178
- const result = decodeCborItem(bytes);
310
+ export function decodeCbor(bytes, options) {
311
+ const result = decodeCborItem(bytes, 0, options);
179
312
  if (result.status === "incomplete") {
180
313
  throw new CborDecodeError("Unexpected end of input while decoding a CBOR data item");
181
314
  }
@@ -198,28 +331,101 @@ export function decodeCbor(bytes) {
198
331
  * which is what lets one bad item in a sequence not end the whole stream. An
199
332
  * error at offset zero is reported as `fatal`, since retrying from an unmoved
200
333
  * position could not terminate.
334
+ *
335
+ * Fed chunk by chunk, `DecodeStream` retries an incomplete item from its start
336
+ * each time. With a shared `WorkBudget`, a retry charges only the items beyond
337
+ * those already charged for the pending item, so an item costs the same however
338
+ * its bytes are split. A retry counts as the same item when its view starts
339
+ * with the bytes the previous unfinished attempt read (for a definite-length
340
+ * string still arriving, only its 1–9 byte head), since those alone decided the
341
+ * charges; any other view, and `reset()` (which `DecodeDriver.clear()` calls),
342
+ * forgets the charged units. The check and the copy it keeps cost O(bytes read
343
+ * by the previous attempt). A definite-length string fed in small chunks
344
+ * therefore decodes in linear time. Indefinite-length strings and containers
345
+ * are re-decoded from their start on every chunk, so their cost is quadratic in
346
+ * the number of chunks, with or without a budget (the budget adds a compare and
347
+ * copy of the same order). A numeric budget is private to each `decode` call,
348
+ * so it caps one attempt.
349
+ *
350
+ * @throws {CborLimitExceededError} From `decode`, when a numeric budget runs
351
+ * out.
352
+ * @throws {RangeError} From `decode`, for an invalid numeric budget.
353
+ * @throws Whatever a shared `WorkBudget` throws, unchanged, from `decode`.
201
354
  */
202
355
  export class CborItemDecoder {
356
+ options;
357
+ /** @param options Applied to every item; a shared `WorkBudget` spans them. */
358
+ constructor(options) {
359
+ this.options = options;
360
+ }
361
+ /** Units already charged to a shared budget for the pending item. */
362
+ charged = 0;
363
+ /**
364
+ * Copy of the bytes the last unfinished attempt read, which alone decided
365
+ * `charged`; undefined when nothing is pending.
366
+ */
367
+ chargedPrefix;
368
+ /** Forgets the pending item, so a shared budget is charged afresh. */
369
+ reset() {
370
+ this.charged = 0;
371
+ this.chargedPrefix = undefined;
372
+ }
203
373
  decode(view) {
204
- const result = decodeCborItem(view, 0);
205
- switch (result.status) {
206
- case "item":
207
- return {
208
- status: "decoded",
209
- value: result.value,
210
- consumed: result.consumed,
211
- };
212
- case "error":
213
- return result.consumed > 0
214
- ? {
215
- status: "error",
216
- error: result.error,
217
- consumed: result.consumed,
218
- }
219
- : { status: "fatal", error: result.error };
220
- default:
221
- return { status: "incomplete" };
374
+ const shared = this.options?.budget;
375
+ if (shared === undefined || typeof shared === "number") {
376
+ return toDecodeResult(decodeCborItem(view, 0, this.options));
377
+ }
378
+ const prefix = this.chargedPrefix;
379
+ if (prefix !== undefined &&
380
+ !(view.length >= prefix.length &&
381
+ bytesIsEqual(view.subarray(0, prefix.length), prefix))) {
382
+ this.reset();
383
+ }
384
+ let attempted = 0;
385
+ const budget = {
386
+ spend: (cost) => {
387
+ attempted += cost;
388
+ if (attempted > this.charged) {
389
+ shared.spend(attempted - this.charged);
390
+ this.charged = attempted;
391
+ }
392
+ },
393
+ };
394
+ const reader = new ByteReader(view);
395
+ let result;
396
+ try {
397
+ result = decodeFromReader(reader, { budget });
222
398
  }
399
+ finally {
400
+ if (result === undefined || result.status === "incomplete") {
401
+ // Not `view.slice`: on a Node `Buffer` it is a view the caller may overwrite.
402
+ this.chargedPrefix = new Uint8Array(view.subarray(0, reader.position));
403
+ }
404
+ else {
405
+ this.reset();
406
+ }
407
+ }
408
+ return toDecodeResult(result);
409
+ }
410
+ }
411
+ function toDecodeResult(result) {
412
+ switch (result.status) {
413
+ case "item":
414
+ return {
415
+ status: "decoded",
416
+ value: result.value,
417
+ consumed: result.consumed,
418
+ };
419
+ case "error":
420
+ return result.consumed > 0
421
+ ? {
422
+ status: "error",
423
+ error: result.error,
424
+ consumed: result.consumed,
425
+ }
426
+ : { status: "fatal", error: result.error };
427
+ default:
428
+ return { status: "incomplete" };
223
429
  }
224
430
  }
225
431
  //# sourceMappingURL=decoder.js.map