Files
node-screenlogic/messages/SLMessage.js
Parnic ed99d411b2 Minor optimization to set buffer size appropriately
This avoids unnecessary allocations/reallocations while decoding a message by pre-sizing the buffer to the amount we know it will require. I feel like there's probably a better way to handle this, but this works for now.
2020-02-10 21:36:13 -06:00

102 lines
2.1 KiB
JavaScript

'use strict';
const SmartBuffer = require('smart-buffer').SmartBuffer;
exports.SLMessage = class SLMessage extends SmartBuffer {
constructor(senderId, messageId, size) {
var options;
if (size) {
options = {
size: size,
};
}
super(options);
if (typeof senderId === 'number' || typeof senderId === 'undefined') {
this.writeUInt16LE(senderId || 0);
this.writeUInt16LE(messageId || 0);
this._wroteSize = false;
} else if (senderId) {
this._wroteSize = true;
var buffer = senderId;
this.writeBuffer(buffer, 0);
this.decode();
}
}
toBuffer() {
this.encode();
if (this._wroteSize === false) {
this.insertInt32LE(this.length - 4, 4);
this._wroteSize = true;
} else {
this.writeInt32LE(this.length - 8, 4);
}
return super.toBuffer();
}
writeSLString(str) {
this.writeInt32LE(str.length);
this.writeString(str);
this.skipWrite(SLMessage.slackForAlignment(str.length));
}
readSLString() {
var len = this.readInt32LE();
var str = this.readString(len);
this.readOffset += SLMessage.slackForAlignment(len);
return str;
}
writeSLBuffer(buf) {
this.writeInt32LE(buf.length);
this.writeBuffer(buf);
}
writeSLArray(arr) {
this.writeInt32LE(arr.length);
for (var i = 0; i < arr.length; i++) {
this.writeUInt8(arr[i]);
}
this.skipWrite(SLMessage.slackForAlignment(arr.length));
}
readSLArray() {
var len = this.readInt32LE();
var retval = new Array(len);
for (var i = 0; i < len; i++) {
retval[i] = this.readUInt8();
}
this.readOffset += SLMessage.slackForAlignment(len);
return retval;
}
skipWrite(num) {
if (num > 0) {
this.writeBuffer(Buffer.alloc(num));
}
}
decode() {
this.readOffset = 0;
this.senderId = this.readUInt16LE();
this.messageId = this.readUInt16LE();
this.dataLength = this.readInt32LE();
}
static slackForAlignment(val) {
return (4 - val % 4) % 4;
}
encode() {}
};