diff --git a/cbor/_common_encode.ts b/cbor/_common_encode.ts index b038bd86eb4a..08123023a817 100644 --- a/cbor/_common_encode.ts +++ b/cbor/_common_encode.ts @@ -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( @@ -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); } diff --git a/cbor/encode_cbor_test.ts b/cbor/encode_cbor_test.ts index 0e71085be55d..06c1f05cf612 100644 --- a/cbor/encode_cbor_test.ts +++ b/cbor/encode_cbor_test.ts @@ -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(