From 95dc61cce88426f56662cec5c4702072d7b3f86c Mon Sep 17 00:00:00 2001 From: George Fu Date: Thu, 20 Jun 2024 17:59:55 +0000 Subject: [PATCH] encode string bytelength instead of strlength --- .../core/src/submodules/cbor/cbor-encode.ts | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/packages/core/src/submodules/cbor/cbor-encode.ts b/packages/core/src/submodules/cbor/cbor-encode.ts index 624ddefed18..253e345c386 100644 --- a/packages/core/src/submodules/cbor/cbor-encode.ts +++ b/packages/core/src/submodules/cbor/cbor-encode.ts @@ -177,9 +177,10 @@ export function encode(input: any): void { } else if (typeof input === "object") { const keys = Object.keys(input); encodeHeader(majorMap, keys.length); - for (let i = 0; i < keys.length; i++) { - encodeString(keys[i]); - encode(input[keys[i]]); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + encodeString(key); + encode(input[key]); } return; } @@ -188,10 +189,14 @@ export function encode(input: any): void { } function encodeString(input: string) { - ensureSpace(input.length * 8); - encodeHeader(majorUtf8String, input.length); - if (USE_BUFFER && (data as BufferWithUtf8Write).utf8Write) { - cursor += (data as BufferWithUtf8Write).utf8Write(input, cursor); + ensureSpace(input.length * 4); + encodeHeader(majorUtf8String, Buffer.byteLength(input)); + if (USE_BUFFER) { + if ((data as BufferWithUtf8Write).utf8Write) { + cursor += (data as BufferWithUtf8Write).write(input, cursor); + } else { + cursor += (data as Buffer).write(input, cursor); + } } else if (input.length < 200) { for (let i = 0; i < input.length; ++i) { const c = input.charCodeAt(i);