MCPcopy Create free account
hub / github.com/denoland/std / calcEncodingSize

Function calcEncodingSize

cbor/_common_encode.ts:23–61  ·  view source on GitHub ↗
(x: CborType)

Source from the content-addressed store, hash-verified

21}
22
23export function calcEncodingSize(x: CborType): number {
24 if (x == undefined || typeof x === "boolean") return 1;
25 if (typeof x === "number") {
26 return x % 1 === 0 ? calcHeaderSize(x < 0 ? -x - 1 : x) : 9;
27 }
28 if (typeof x === "bigint") {
29 if (x < 0n) x = -x - 1n;
30 if (x < 2n ** 64n) return calcHeaderSize(x);
31 const bytes = calcBytes(x);
32 return 1 + calcHeaderSize(bytes) + bytes;
33 }
34 if (typeof x === "string") {
35 return calcHeaderSize(x.length * 3) + x.length * 3;
36 }
37 if (x instanceof Uint8Array) {
38 return calcHeaderSize(x.length) + x.length;
39 }
40 if (x instanceof Date) return 1 + calcEncodingSize(x.getTime() / 1000);
41 if (x instanceof CborTag) {
42 return calcHeaderSize(x.tagNumber) + calcEncodingSize(x.tagContent);
43 }
44 if (x instanceof Array) {
45 let size = calcHeaderSize(x.length);
46 for (const y of x) size += calcEncodingSize(y);
47 return size;
48 }
49 if (x instanceof Map) {
50 let size = 3 + calcHeaderSize(x.size);
51 for (const y of x) size += calcEncodingSize(y[0]) + calcEncodingSize(y[1]);
52 return size;
53 }
54 let pairs = 0;
55 let size = 0;
56 for (const y in x) {
57 ++pairs;
58 size += calcHeaderSize(y.length) + y.length + calcEncodingSize(x[y]);
59 }
60 return size + calcHeaderSize(pairs);
61}
62
63export function encode(
64 input: CborType,

Callers 2

encodeCborFunction · 0.90
encodeCborSequenceFunction · 0.90

Calls 2

calcHeaderSizeFunction · 0.85
calcBytesFunction · 0.85

Tested by

no test coverage detected