@mrhiden/cstruct
Version:
For packing and unpacking bytes (C like structures) in/from Buffer based on Object/Array type for parsing.
48 lines (47 loc) • 1.69 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReadWriteBase = void 0;
const types_1 = require("./types");
class ReadWriteBase {
constructor() {
this.dynamicTypeLengthRegex = /^(?<dynamicType>\w+)\.(?<dynamicLength>\w+)$/;
this.staticTypeLengthRegex = /^(?<staticType>\w+)(?<staticLength>\d+)$/;
this.stringTypes = ['s', 'string'];
this.wstringTypes = ['ws', 'wstring'];
this.bufferTypes = ['buf', 'buffer'];
this.jsonTypes = ['j', 'json', 'any'];
}
getDynamicTypeLengthGroupsMatch(key) {
return key.match(this.dynamicTypeLengthRegex)?.groups;
}
getStaticTypeLengthGroupsMatch(key) {
return key.match(this.staticTypeLengthRegex)?.groups;
}
getSpecialType(modelType) {
if (this.stringTypes.includes(modelType)) {
return types_1.SpecialType.String;
}
if (this.wstringTypes.includes(modelType)) {
return types_1.SpecialType.WString;
}
if (this.bufferTypes.includes(modelType)) {
return types_1.SpecialType.Buffer;
}
if (this.jsonTypes.includes(modelType)) {
return types_1.SpecialType.Json;
}
}
getStaticSize(size) {
const value = +size;
return {
isStatic: !Number.isNaN(value),
staticSize: value
};
}
extractTypeAndSize(modelType, dynamicLength) {
const specialType = this.getSpecialType(modelType);
const { isStatic, staticSize } = this.getStaticSize(dynamicLength);
return { specialType, isStatic, staticSize };
}
}
exports.ReadWriteBase = ReadWriteBase;