Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions cbor/_common_encode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ export function calcEncodingSize(x: CborType): number {
for (const y of x) size += calcEncodingSize(y[0]) + calcEncodingSize(y[1]);
return size;
}
let pairs = 0;
// Must iterate the same keys as encodeObject().
const keys = Object.keys(x);
let size = 0;
for (const y in x) {
++pairs;
for (const y of keys) {
size += calcHeaderSize(y.length) + y.length + calcEncodingSize(x[y]);
}
return size + calcHeaderSize(pairs);
return size + calcHeaderSize(keys.length);
}

export function encode(
Expand Down Expand Up @@ -217,8 +217,10 @@ function encodeObject(
offset: number,
): number {
output[offset] = 0b101_00000;
offset = encodeHeader(0b101_00000, Object.keys(input).length, output, offset);
for (const key in input) {
// Must iterate the same keys as calcEncodingSize().
const keys = Object.keys(input);
offset = encodeHeader(0b101_00000, keys.length, output, offset);
for (const key of keys) {
offset = encodeString(key, output, offset);
offset = encode(input[key], output, offset);
}
Expand Down
15 changes: 15 additions & 0 deletions cbor/encode_cbor_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,21 @@ Deno.test("encodeCbor() encoding objects", () => {
// Can't test the next two bracket up due to JavaScript limitations.
});

Deno.test("encodeCbor() ignores inherited enumerable properties", () => {
const input: { [k: string]: CborType } = Object.assign(
Object.create({ inherited: 1 }),
{ own: 2 },
);
assertEquals(
encodeCbor(input),
new Uint8Array([
0b101_00001,
...encodeCbor("own"),
...encodeCbor(2),
]),
);
});

Deno.test("encodeCbor() encoding CborTag()", () => {
const bytes = new Uint8Array(random(0, 24)).map((_) => random(0, 256));
assertEquals(
Expand Down
Loading