silphius/app/packets/index.js
2024-06-22 22:33:54 -05:00

23 lines
729 B
JavaScript

import gather from '@/util/gather.js';
const Gathered = gather(import.meta.glob('./*.js', {eager: true, import: 'default'}));
const typeToId = new Map(Object.entries(Gathered).map(([type], id) => [type, id]));
const idToType = new Map(Object.entries(Gathered).map(([type], id) => [id, type]));
export function decode(packed) {
const view = ArrayBuffer.isView(packed) ? packed : new DataView(packed);
const type = idToType.get(view.getUint16(0, true));
const Packet = Gathered[type];
return {
type,
payload: Packet.decode(view),
};
}
export function encode(packet) {
const encoded = Gathered[packet.type].encode(packet.payload);
encoded.setUint16(0, typeToId.get(packet.type), true);
return encoded;
}