silphius/app/packets/index.js

21 lines
566 B
JavaScript
Raw Normal View History

2024-06-10 22:42:30 -05:00
import gather from '@/engine/gather.js';
const Gathered = gather(import.meta.glob('./*.js', {eager: true, import: 'default'}));
export function decode(packed) {
const view = ArrayBuffer.isView(packed) ? packed : new DataView(packed);
const id = view.getUint16(0, true);
const Packet = Gathered[id];
return {
type: Packet.type,
payload: Packet.decode(view),
};
}
export function encode(packet) {
const Packet = Gathered[packet.type];
const encoded = Packet.encode(packet.payload);
encoded.setUint16(0, Packet.id, true);
return encoded;
}