json-joy
Version:
Collection of libraries for building collaborative editing apps.
52 lines (51 loc) • 1.83 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.msgpackSizeFast = void 0;
const msgpack_1 = require("@jsonjoy.com/json-pack/lib/msgpack");
const isUint8Array_1 = require("@jsonjoy.com/util/lib/buffers/isUint8Array");
const arraySize = (arr) => {
let size = 2;
for (let i = arr.length - 1; i >= 0; i--)
size += (0, exports.msgpackSizeFast)(arr[i]);
return size;
};
const objectSize = (obj) => {
let size = 2;
// biome-ignore lint: object hasOwnProperty check is intentional, Object.hasOwn is too recent
for (const key in obj)
if (obj.hasOwnProperty(key))
size += 2 + key.length + (0, exports.msgpackSizeFast)(obj[key]);
return size;
};
/**
* Same as `jsonSizeFast`, but for MessagePack.
*
* - Allows Buffers or Uint8Arrays a MessagePack `bin` values. Adds 5 bytes overhead for them.
* - Allows embedded `JsonPackValue` values.
* - Allows MessagePack `JsonPackExtension` extensions. Adds 6 bytes overhead for them.
*
* @param value MessagePack value, which can contain binary data, extensions and embedded MessagePack.
* @returns Approximate size of the value in bytes.
*/
const msgpackSizeFast = (value) => {
if (value === null)
return 1;
switch (typeof value) {
case 'number':
return 9;
case 'string':
return 4 + value.length;
case 'boolean':
return 1;
}
if (value instanceof Array)
return arraySize(value);
if ((0, isUint8Array_1.isUint8Array)(value))
return 5 + value.length;
if (value instanceof msgpack_1.JsonPackValue)
return value.val.length;
if (value instanceof msgpack_1.JsonPackExtension)
return 6 + value.val.length;
return objectSize(value);
};
exports.msgpackSizeFast = msgpackSizeFast;
;