refactor: packing

This commit is contained in:
cha0s 2021-01-10 03:38:09 -06:00
parent 76bf73fe02
commit 300d7e85bd
2 changed files with 29 additions and 23 deletions

View File

@ -1,10 +1,18 @@
import Packet from './packet';
import packets from './packets';
export default (latus) => class BundlePacket extends Packet {
static pack(packet) {
const packets = packet.data[1];
static bundle(packets) {
return this.pack({
data: [this.id, packets],
});
}
static get data() {
return 'buffer';
}
static packData(packets) {
// Pack up all the packets.
const packedPackets = new Array(packets.length);
for (let i = 0; i < packets.length; i++) {
@ -32,19 +40,15 @@ export default (latus) => class BundlePacket extends Packet {
packedPacket.copy(buffer, caret, 0);
caret += packedPacket.length;
}
// eslint-disable-next-line no-param-reassign
packet.data[1] = buffer;
return super.pack(packet);
return buffer;
}
static get data() {
return 'buffer';
static unbundle(buffer) {
return this.unpack(buffer).data;
}
static unpack(packet) {
const unpacked = super.unpack(packet);
const {data} = unpacked;
const bundled = [];
static unpackData(data) {
const packets = [];
let caret = 0;
while (caret < data.length) {
// Read packed length.
@ -61,10 +65,9 @@ export default (latus) => class BundlePacket extends Packet {
const {default: Packet} = packets(latus).fromId[packetId];
// Unpack and instantiate the packet.
const unpacked = Packet.unpack(packedPacket);
bundled.push(new Packet(unpacked.data));
packets.push(new Packet(unpacked.data));
}
unpacked.data = bundled;
return unpacked;
return packets;
}
};

View File

@ -30,23 +30,26 @@ export default class Packet {
nsp: packet.nsp || '/',
type: packet.type || BINARY_EVENT,
_id: packet.data[0],
data: packet.data[1],
data: this.packData(packet.data[1]),
});
}
static packPacket(packet) {
const {id} = packet.constructor;
return packet.constructor.pack({
data: [id, packet.data],
});
static packData(data) {
return data;
}
static respond(packet, socket) {
return packet.respond ? packet.respond(socket) : undefined;
}
static unpack(packet) {
return this.builder.decode(packet);
static unpack(buffer) {
const unpacked = this.builder.decode(buffer);
unpacked.data = Packet.unpackData(unpacked.data);
return unpacked;
}
static unpackData(data) {
return data;
}
static validate(packet, socket) {