UNPKG

@mrhiden/cstruct

Version:

For packing and unpacking bytes (C like structures) in/from Buffer based on Object/Array type for parsing.

68 lines (67 loc) 2.55 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CStructMetadata = void 0; const cstruct_be_1 = require("./cstruct-be"); const cstruct_le_1 = require("./cstruct-le"); class CStructMetadata { constructor() { this.model = {}; this.types = {}; this.cStruct = null; } static getMetadata(target) { const constructorMetadata = target.constructor?.[this.CStructSymbol]; const prototypeMetadata = target.prototype?.[this.CStructSymbol]; const targetMetadata = target[this.CStructSymbol]; let metadata = constructorMetadata ?? prototypeMetadata ?? targetMetadata; if (!metadata) { metadata = target[this.CStructSymbol] = new CStructMetadata(); if ('model' in target) { metadata.model = target.model; metadata.types = target.types; } } return metadata; } static addProperty(target, propertyName, options) { const metadata = CStructMetadata.getMetadata(target); metadata.model[propertyName] = options.type; } static addClass(target, options) { const metadata = CStructMetadata.getMetadata(target); metadata.types = options.types; metadata.model = options.model ?? metadata.model; metadata.class = target; metadata.className = target.name; } static getCStructBE(struct) { const metadata = CStructMetadata.getMetadata(struct); if (!metadata.cStruct) { if (!metadata.model) { throw Error(`Provided struct is not decorated.`); } metadata.cStruct = cstruct_be_1.CStructBE.fromModelTypes(metadata.model, metadata.types); } return metadata.cStruct; } static getCStructLE(struct) { const metadata = CStructMetadata.getMetadata(struct); if (!metadata.cStruct) { if (!metadata.model) { throw Error(`Provided struct is not decorated.`); } metadata.cStruct = cstruct_le_1.CStructLE.fromModelTypes(metadata.model, metadata.types); } return metadata.cStruct; } static getModel(struct) { const metadata = CStructMetadata.getMetadata(struct); return metadata.model; } static getTypes(struct) { const metadata = CStructMetadata.getMetadata(struct); return metadata.types; } } exports.CStructMetadata = CStructMetadata; CStructMetadata.CStructSymbol = Symbol('CStruct');