struffer
Version:
Struct + Buffer = Struffer
83 lines • 2.85 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const common_1 = require("./common");
const base_1 = require("./base");
/**
* Struct + Buffer
*
* Also works with Uint8Arrays
* @param strufferName The name of your struffer
* @param structure The definition of your struffer. An array of `[type, name]` for each member.
* @returns Your custom struffer class
*/
function default_1(strufferName, structure) {
const structInfo = new Map();
const memberOrder = structure.map(i => i[1]);
let nextByte = 0;
for (const [type, name] of structure) {
const typeInfo = common_1.parseType(type);
const info = {
startByteOffset: nextByte,
startBitOffset: 0,
endByteOffset: nextByte,
endBitOffset: 7,
endianness: typeInfo.endianness,
signature: typeInfo.signature,
bitSize: typeInfo.bitSize,
};
if (info.bitSize % 8 !== 0) {
// tslint:disable-next-line:max-line-length
throw new Error('Struffers only support bit sizes that are multiples of eight. For arbitrary bit sizes, use AdvancedStruffers instead.');
}
const byteSize = info.bitSize / 8;
info.endByteOffset = nextByte + (byteSize - 1);
nextByte = info.endByteOffset + 1;
structInfo.set(name, info);
}
const byteLength = nextByte;
const bitLength = byteLength * 8;
return class Struffer extends base_1.default {
get kind() {
return strufferName;
}
get info() {
return structInfo;
}
get order() {
return memberOrder;
}
static get byteLength() {
return byteLength;
}
static get bitLength() {
return bitLength;
}
getBits(name) {
const info = structInfo.get(name);
if (!info) {
throw new Error('Structure member not found!');
}
let bits = [];
const byteLength = info.bitSize / 8;
for (let i = 0; i < byteLength; i++) {
bits = bits.concat(common_1.unsignedSplit(this.buffer[info.startByteOffset + this.offset + i], 8));
}
return bits;
}
setBits(name, _bits) {
const info = structInfo.get(name);
if (!info) {
throw new Error('Structure member not found!');
}
const bits = _bits.slice();
let i = 0;
while (bits.length > 0) {
const chunk = bits.splice(0, 8);
this.buffer[info.startByteOffset + this.offset + i] = common_1.joinBits(chunk);
i++;
}
}
};
}
exports.default = default_1;
//# sourceMappingURL=struffer.js.map