All files / cbor / _common_decode.ts

94.47% Branches 188/199
100.00% Functions 11/11
93.60% Lines 322/344
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
 
 
x37
x37
 
 
x447852
x447852
x447852
x447852
 
x447852
x447500
x447500
x447850
x1826
x447852
x270596
x447852
x175073
x447852
x5
x447852
x447852
 
x37
x596633
x596633
 
x596627
x596633
x447773
x596633
x18
x596633
x19
x596633
x148726
x596633
x16
x596633
x18
x596633
x32
x596633
x25
x596633
x596633
 
x447804
x447804
x447804
x447804
 
x447804
x4
x4
 
x4
x447800
x447804
 
x18
x18
x18
x18
 
x18
x4
x4
 
x4
x14
x18
x18
x18
 
x21
x21
x21
x21
 
x21
x17
x3
x3
x3
x3
x3
x17
x4
x4
 
x3
x3
x3
x1
x1
x1
x1
 
x1
x2
x3
x1
x1
 
x1
x1
x1
x1
x1
x1
x3
 
 
x3
x3
 
x21
 
x148726
x148726
x148726
x148726
 
x148726
x148716
x148716
x148716
x148716
x148716
x148710
x3
x3
x3
x3
x3
x148710
x4
x4
x3
x3
x3
x1
x1
x1
x1
 
x1
x2
x3
x1
x1
 
x1
 
 
 
 
 
x1
x1
x1
x1
x1
x3
 
 
x3
x3
 
x148726
 
x16
x16
x16
x16
 
x16
x11
 
x11
x11
x11
x11
x101743
x101743
x101743
x101743
x11
x11
x10
x2
x2
x3
x3
x3
x3
 
 
x3
x3
 
x16
 
x18
x18
x18
x18
 
x18
x11
 
x11
x11
x11
x11
x148693
x148693
x1
x1
x1
x1
 
x1
x148693
x1
x1
 
x1
x148691
x148691
x148691
x148691
x9
x9
x14
x4
x4
x6
x6
x1
x1
x1
x1
 
x1
x6
x1
x1
 
x1
x2
x2
x2
x2
 
 
x3
x3
 
x18
 
x32
x32
x32
x32
 
x32
x1
x1
 
x1
x31
x31
x32
x1
x1
x1
x1
 
 
x32
x6
x6
x1
x1
x5
x5
x32
x2
x2
x1
x1
x1
x2
x1
x1
x32
x2
x2
x1
x1
x1
x2
x1
x1
x32
x16
x32
x4
x4
x4
x32
x32
 
x25
x25
x25
x25
 
x25
x25
x5
x25
x1
x25
x5
x25
x1
x25
x13
x13
 
 
 
 
x25
x10
x25
x3
x3
 
x25
x25
 
x16
x16
x16
 
x16
 
 
x16
x16
x10
 
x10
x10
x10
x10
x98671
x98671
x1
x1
 
x1
x98670
x98670
x98670
x98670
x9
x9
x12
x3
x3
x5
x5
x1
x1
 
x1
x2
x2
x2
x2
 
 
x3
x3
 
x16
















































































































I










































I









I































I

























































I























I





















































I

I















I
I
































I





// Copyright 2018-2026 the Deno authors. MIT license.

import { concat } from "@std/bytes";
import { CborTag } from "./tag.ts";
import type { CborType } from "./types.ts";

function calcLength(
  input: Uint8Array,
  aI: number,
  offset: number,
): [number | bigint, number] {
  if (aI < 24) return [aI, offset];
  const view = new DataView(input.buffer, input.byteOffset, input.byteLength);
  switch (aI) {
    case 24:
      return [view.getUint8(offset), offset + 1];
    case 25:
      return [view.getUint16(offset), offset + 2];
    case 26:
      return [view.getUint32(offset), offset + 4];
    default: // Only possible for it to be 27
      return [view.getBigUint64(offset), offset + 8];
  }
}

export function decode(input: Uint8Array, offset: number): [CborType, number] {
  const byte = input[offset++];
  if (byte == undefined) throw new RangeError("More bytes were expected");

  switch (byte >> 5) {
    case 0:
      return decodeZero(input, byte & 0b000_11111, offset);
    case 1:
      return decodeOne(input, byte & 0b000_11111, offset);
    case 2:
      return decodeTwo(input, byte & 0b000_11111, offset);
    case 3:
      return decodeThree(input, byte & 0b000_11111, offset);
    case 4:
      return decodeFour(input, byte & 0b000_11111, offset);
    case 5:
      return decodeFive(input, byte & 0b000_11111, offset);
    case 6:
      return decodeSix(input, byte & 0b000_11111, offset);
    default: // Only possible for it to be 7
      return decodeSeven(input, byte & 0b000_11111, offset);
  }
}

function decodeZero(
  input: Uint8Array,
  aI: number,
  offset: number,
): [number | bigint, number] {
  if (aI > 27) {
    throw new RangeError(
      `Cannot decode value (0b000_${aI.toString(2).padStart(5, "0")})`,
    );
  }
  return calcLength(input, aI, offset);
}

function decodeOne(
  input: Uint8Array,
  aI: number,
  offset: number,
): [number | bigint, number] {
  if (aI > 27) {
    throw new RangeError(
      `Cannot decode value (0b001_${aI.toString(2).padStart(5, "0")})`,
    );
  }
  const output = calcLength(input, aI, offset);
  output[0] = typeof output[0] === "bigint" ? -output[0] - 1n : -output[0] - 1;
  return output;
}

function decodeTwo(
  input: Uint8Array,
  aI: number,
  offset: number,
): [Uint8Array, number] {
  if (aI < 24) return [input.subarray(offset, offset + aI), offset + aI];
  if (aI <= 27) {
    const x = calcLength(input, aI, offset);
    const start = x[1];
    const end = Number(x[0]) + x[1];
    return [input.subarray(start, end), end];
  }
  if (aI === 31) {
    let byte = input[offset++];
    if (byte == undefined) throw new RangeError("More bytes were expected");

    const output: Uint8Array[] = [];
    while (byte !== 0b111_11111) {
      if (byte >> 5 !== 2) {
        throw new TypeError(
          `Cannot decode value (0b${(byte >> 5).toString(2).padStart(3, "0")}_${
            (byte & 0b11111).toString(2).padStart(5, "0")
          }) inside an indefinite length byte string`,
        );
      }
      const aI = byte & 0b000_11111;
      if (aI === 31) {
        throw new TypeError(
          "Indefinite length byte strings cannot contain indefinite length byte strings",
        );
      }
      const x = decodeTwo(input, aI, offset);
      output.push(x[0]);
      offset = x[1];
      byte = input[offset++];
      if (byte == undefined) throw new RangeError("More bytes were expected");
    }
    return [concat(output), offset + 1];
  }
  throw new RangeError(
    `Cannot decode value (0b010_${aI.toString(2).padStart(5, "0")})`,
  );
}

function decodeThree(
  input: Uint8Array,
  aI: number,
  offset: number,
): [string, number] {
  if (aI < 24) {
    return [
      new TextDecoder().decode(input.subarray(offset, offset + aI)),
      offset + aI,
    ];
  }
  if (aI <= 27) {
    const x = calcLength(input, aI, offset);
    const start = x[1];
    const end = Number(x[0]) + x[1];
    return [new TextDecoder().decode(input.subarray(start, end)), end];
  }
  if (aI === 31) {
    let byte = input[offset++];
    if (byte == undefined) throw new RangeError("More bytes were expected");
    const output: Uint8Array[] = [];
    while (byte !== 0b111_11111) {
      if (byte >> 5 !== 3) {
        throw new TypeError(
          `Cannot decode value (0b${(byte >> 5).toString(2).padStart(3, "0")}_${
            (byte & 0b11111).toString(2).padStart(5, "0")
          }) inside an indefinite length text string`,
        );
      }
      const aI = byte & 0b000_11111;
      if (aI === 31) {
        throw new TypeError(
          "Indefinite length text strings cannot contain indefinite length text strings",
        );
      }
      if (aI > 27) {
        throw new RangeError(
          `Cannot decode value (0b011_${aI.toString(2).padStart(5, "0")})`,
        );
      }
      const x = decodeTwo(input, aI, offset);
      output.push(x[0]);
      offset = x[1];
      byte = input[offset++];
      if (byte == undefined) throw new RangeError("More bytes were expected");
    }
    return [new TextDecoder().decode(concat(output)), offset + 1];
  }
  throw new RangeError(
    `Cannot decode value (0b011_${aI.toString(2).padStart(5, "0")})`,
  );
}

function decodeFour(
  input: Uint8Array,
  aI: number,
  offset: number,
): [CborType[], number] {
  if (aI <= 27) {
    const x = calcLength(input, aI, offset);
    // Can safely assume `x[0] < 2 ** 53` as JavaScript doesn't support an `Array` being that large.
    const length = Number(x[0]);
    offset = x[1];
    const output: CborType[] = new Array(length);
    for (let i = 0; i < length; ++i) {
      const y = decode(input, offset);
      output[i] = y[0];
      offset = y[1];
    }
    return [output, offset];
  }
  if (aI === 31) {
    const output: CborType[] = [];
    while (input[offset] !== 0b111_11111) {
      const x = decode(input, offset);
      output.push(x[0]);
      offset = x[1];
    }
    return [output, offset + 1];
  }
  throw new RangeError(
    `Cannot decode value (0b100_${aI.toString(2).padStart(5, "0")})`,
  );
}

function decodeFive(
  input: Uint8Array,
  aI: number,
  offset: number,
): [{ [k: string]: CborType }, number] {
  if (aI <= 27) {
    const x = calcLength(input, aI, offset);
    // Can safely assume `x[0] < 2 ** 53` as JavaScript doesn't support an `Object` being that large.
    const length = Number(x[0]);
    offset = x[1];
    const output: { [k: string]: CborType } = {};
    for (let i = 0; i < length; ++i) {
      const y = decode(input, offset);
      if (typeof y[0] !== "string") {
        throw new TypeError(
          `Cannot decode key of type (${typeof y[
            0
          ]}): This implementation only supports "text string" keys`,
        );
      }
      if (output[y[0]] !== undefined) {
        throw new TypeError(
          `A Map cannot have duplicate keys: Key (${y[0]}) already exists`,
        ); // https://datatracker.ietf.org/doc/html/rfc8949#name-specifying-keys-for-maps
      }
      const z = decode(input, y[1]);
      output[y[0]] = z[0];
      offset = z[1];
    }
    return [output, offset];
  }
  if (aI === 31) {
    const output: { [k: string]: CborType } = {};
    while (input[offset] !== 0b111_11111) {
      const x = decode(input, offset);
      if (typeof x[0] !== "string") {
        throw new TypeError(
          `Cannot decode key of type (${typeof x[
            0
          ]}): This implementation only supports "text string" keys`,
        );
      }
      if (output[x[0]] !== undefined) {
        throw new TypeError(
          `A Map cannot have duplicate keys: Key (${x[0]}) already exists`,
        ); // https://datatracker.ietf.org/doc/html/rfc8949#name-specifying-keys-for-maps
      }
      const y = decode(input, x[1]);
      output[x[0]] = y[0];
      offset = y[1];
    }
    return [output, offset + 1];
  }
  throw new RangeError(
    `Cannot decode value (0b101_${aI.toString(2).padStart(5, "0")})`,
  );
}

function decodeSix(
  input: Uint8Array,
  aI: number,
  offset: number,
): [Date | bigint | Map<CborType, CborType> | CborTag<CborType>, number] {
  if (aI > 27) {
    throw new RangeError(
      `Cannot decode value (0b110_${aI.toString(2).padStart(5, "0")})`,
    );
  }
  const x = decodeZero(input, aI, offset);
  switch (BigInt(x[0])) {
    case 0n: {
      const y = decode(input, x[1]);
      if (typeof y[0] !== "string") {
        throw new TypeError('Invalid TagItem: Expected a "text string"');
      }
      return [new Date(y[0]), y[1]];
    }
    case 1n: {
      const y = decode(input, x[1]);
      if (typeof y[0] !== "number" && typeof y[0] !== "bigint") {
        throw new TypeError('Invalid TagItem: Expected a "integer" or "float"');
      }
      return [new Date(Number(y[0]) * 1000), y[1]];
    }
    case 2n: {
      const y = decode(input, x[1]);
      if (!(y[0] instanceof Uint8Array)) {
        throw new TypeError('Invalid TagItem: Expected a "byte string"');
      }
      let z = 0n;
      for (const byte of y[0]) z = (z << 8n) | BigInt(byte);
      return [z, y[1]];
    }
    case 3n: {
      const y = decode(input, x[1]);
      if (!(y[0] instanceof Uint8Array)) {
        throw new TypeError('Invalid TagItem: Expected a "byte string"');
      }
      let z = 0n;
      for (const byte of y[0]) z = (z << 8n) | BigInt(byte);
      return [-z - 1n, y[1]];
    }
    case 259n:
      return decodeMap(input, x[1]);
    default: {
      const y = decode(input, x[1]);
      return [new CborTag(x[0], y[0]), y[1]];
    }
  }
}

function decodeSeven(
  input: Uint8Array,
  aI: number,
  offset: number,
): [undefined | null | boolean | number, number] {
  switch (aI) {
    case 20:
      return [false, offset];
    case 21:
      return [true, offset];
    case 22:
      return [null, offset];
    case 23:
      return [undefined, offset];
  }
  const view = new DataView(input.buffer, input.byteOffset, input.byteLength);
  switch (aI) {
    case 25:
      return [view.getFloat16(offset), offset + 2];
    case 26:
      return [view.getFloat32(offset), offset + 4];
    case 27:
      return [view.getFloat64(offset), offset + 8];
    default:
      throw new RangeError(
        `Cannot decode value (0b111_${aI.toString(2).padStart(5, "0")})`,
      );
  }
}

function decodeMap(
  input: Uint8Array,
  offset: number,
): [Map<CborType, CborType>, number] {
  const byte = input[offset++];
  if (byte == undefined) throw new RangeError("More bytes were expected");
  if (byte >> 5 !== 5) throw new TypeError('Invalid TagItem: Expected a "map"');
  const aI = byte & 0b000_11111;
  if (aI <= 27) {
    const x = calcLength(input, aI, offset);
    // Can safely assume `x[0] < 2 ** 53` as JavaScript doesn't support an `Map` being that large.
    const length = Number(x[0]);
    offset = x[1];
    const output = new Map<CborType, CborType>();
    for (let i = 0; i < length; ++i) {
      const y = decode(input, offset);
      if (output.has(y[0])) {
        throw new TypeError(
          `A Map cannot have duplicate keys: Key (${y[0]}) already exists`,
        ); // https://datatracker.ietf.org/doc/html/rfc8949#name-specifying-keys-for-maps
      }
      const z = decode(input, y[1]);
      output.set(y[0], z[0]);
      offset = z[1];
    }
    return [output, offset];
  }
  if (aI === 31) {
    const output = new Map<CborType, CborType>();
    while (input[offset] !== 0b111_11111) {
      const x = decode(input, offset);
      if (output.has(x[0])) {
        throw new TypeError(
          `A Map cannot have duplicate keys: Key (${x[0]}) already exists`,
        ); // https://datatracker.ietf.org/doc/html/rfc8949#name-specifying-keys-for-maps
      }
      const y = decode(input, x[1]);
      output.set(x[0], y[0]);
      offset = y[1];
    }
    return [output, offset + 1];
  }
  throw new RangeError(
    `Cannot decode value (0b101_${aI.toString(2).padStart(5, "0")})`,
  );
}