| 346 | } |
| 347 | |
| 348 | function decodeMap( |
| 349 | input: Uint8Array, |
| 350 | offset: number, |
| 351 | ): [Map<CborType, CborType>, number] { |
| 352 | const byte = input[offset++]; |
| 353 | if (byte == undefined) throw new RangeError("More bytes were expected"); |
| 354 | if (byte >> 5 !== 5) throw new TypeError('Invalid TagItem: Expected a "map"'); |
| 355 | const aI = byte & 0b000_11111; |
| 356 | if (aI <= 27) { |
| 357 | const x = calcLength(input, aI, offset); |
| 358 | // Can safely assume `x[0] < 2 ** 53` as JavaScript doesn't support an `Map` being that large. |
| 359 | const length = Number(x[0]); |
| 360 | offset = x[1]; |
| 361 | const output = new Map<CborType, CborType>(); |
| 362 | for (let i = 0; i < length; ++i) { |
| 363 | const y = decode(input, offset); |
| 364 | if (output.has(y[0])) { |
| 365 | throw new TypeError( |
| 366 | `A Map cannot have duplicate keys: Key (${y[0]}) already exists`, |
| 367 | ); // https://datatracker.ietf.org/doc/html/rfc8949#name-specifying-keys-for-maps |
| 368 | } |
| 369 | const z = decode(input, y[1]); |
| 370 | output.set(y[0], z[0]); |
| 371 | offset = z[1]; |
| 372 | } |
| 373 | return [output, offset]; |
| 374 | } |
| 375 | if (aI === 31) { |
| 376 | const output = new Map<CborType, CborType>(); |
| 377 | while (input[offset] !== 0b111_11111) { |
| 378 | const x = decode(input, offset); |
| 379 | if (output.has(x[0])) { |
| 380 | throw new TypeError( |
| 381 | `A Map cannot have duplicate keys: Key (${x[0]}) already exists`, |
| 382 | ); // https://datatracker.ietf.org/doc/html/rfc8949#name-specifying-keys-for-maps |
| 383 | } |
| 384 | const y = decode(input, x[1]); |
| 385 | output.set(x[0], y[0]); |
| 386 | offset = y[1]; |
| 387 | } |
| 388 | return [output, offset + 1]; |
| 389 | } |
| 390 | throw new RangeError( |
| 391 | `Cannot decode value (0b101_${aI.toString(2).padStart(5, "0")})`, |
| 392 | ); |
| 393 | } |