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