Skip to content

Commit

Permalink
fix(cbor): incorrect decoding with subarrays (#6344)
Browse files Browse the repository at this point in the history
  • Loading branch information
BlackAsLight authored Jan 15, 2025
1 parent 55b1c7e commit c73f668
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
4 changes: 2 additions & 2 deletions cbor/_common_decode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ function calcLength(
offset: number,
): [number | bigint, number] {
if (aI < 24) return [aI, offset];
const view = new DataView(input.buffer);
const view = new DataView(input.buffer, input.byteOffset, input.byteLength);
switch (aI) {
case 24:
return [view.getUint8(offset), offset + 1];
Expand Down Expand Up @@ -312,7 +312,7 @@ function decodeSeven(
case 23:
return [undefined, offset];
}
const view = new DataView(input.buffer);
const view = new DataView(input.buffer, input.byteOffset, input.byteLength);
switch (aI) {
case 25:
return [view.getFloat16(offset), offset + 2];
Expand Down
32 changes: 32 additions & 0 deletions cbor/decode_cbor_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -814,3 +814,35 @@ Deno.test("decodeCbor() rejecting tagNumber 259 due to invalid indefinite length
"More bytes were expected",
);
});

Deno.test("decodeCbor() correctly decoding with subarrays", () => {
let encodedData = encodeCbor(0);
let buffer = new Uint8Array(encodedData.length + 7);
buffer.set(encodedData, 7);
assertEquals(decodeCbor(buffer.subarray(7)), 0);

encodedData = encodeCbor(24);
buffer = new Uint8Array(encodedData.length + 7);
buffer.set(encodedData, 7);
assertEquals(decodeCbor(buffer.subarray(7)), 24);

encodedData = encodeCbor(2 ** 8);
buffer = new Uint8Array(encodedData.length + 7);
buffer.set(encodedData, 7);
assertEquals(decodeCbor(buffer.subarray(7)), 2 ** 8);

encodedData = encodeCbor(2 ** 16);
buffer = new Uint8Array(encodedData.length + 7);
buffer.set(encodedData, 7);
assertEquals(decodeCbor(buffer.subarray(7)), 2 ** 16);

encodedData = encodeCbor(2 ** 32);
buffer = new Uint8Array(encodedData.length + 7);
buffer.set(encodedData, 7);
assertEquals(decodeCbor(buffer.subarray(7)), 2n ** 32n);

encodedData = encodeCbor(3.14);
buffer = new Uint8Array(encodedData.length + 7);
buffer.set(encodedData, 7);
assertEquals(decodeCbor(buffer.subarray(7)), 3.14);
});

0 comments on commit c73f668

Please sign in to comment.