From 300d7e85bd0fc9563cd7842876e76264b83a7362 Mon Sep 17 00:00:00 2001 From: cha0s Date: Sun, 10 Jan 2021 03:38:09 -0600 Subject: [PATCH] refactor: packing --- packages/socket/src/packet/bundle.js | 33 +++++++++++++++------------- packages/socket/src/packet/packet.js | 19 +++++++++------- 2 files changed, 29 insertions(+), 23 deletions(-) diff --git a/packages/socket/src/packet/bundle.js b/packages/socket/src/packet/bundle.js index afbc124..7747ce6 100644 --- a/packages/socket/src/packet/bundle.js +++ b/packages/socket/src/packet/bundle.js @@ -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; } }; diff --git a/packages/socket/src/packet/packet.js b/packages/socket/src/packet/packet.js index 22e6a95..e9f8d1d 100644 --- a/packages/socket/src/packet/packet.js +++ b/packages/socket/src/packet/packet.js @@ -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) {