serialize.clj
Branches > main > 6a591c6 > files / src / net / bowmap / server / packet / serialize.clj
(ns net.bowmap.server.packet.serialize
(:require
[net.bowmap.server.packet.clientbound :as clientbound]
[net.bowmap.server.packet.frame :as frame]
[net.bowmap.server.packet.phase :as phase]
[net.bowmap.server.packet.readers :as readers]
[net.bowmap.server.packet.schema :as p]
[net.bowmap.server.packet.serverbound :as serverbound]
[net.bowmap.server.packet.writers :as writers])
(:import
[io.netty.buffer Unpooled]))
(defn encode-packet
"Encodes a packet into a frame.
Throws when the packet cannot be encoded."
[{::phase/keys! [phase]} {::p/keys! [id] :as packet}]
(let [numeric-id (req! (clientbound/phase->id->numeric-id phase) id)
writer (req! (clientbound/phase->id->writer phase) id)]
(frame/ByteBuf->frame
(-> (Unpooled/buffer)
(writers/varint> numeric-id)
(writer packet)))))
(defn decode-frame
"Decodes a packet from a frame.
Can throw if the frame does not contain a valid packet."
[{:keys! [::phase/phase]} frame]
(let [buf (frame/->ByteBuf frame)
numeric-id (readers/varint< buf)
id (req! (serverbound/phase->numeric-id->id phase) numeric-id)
reader (id (serverbound/phase->id->reader phase))]
(assoc (when reader
(reader buf))
::p/id id)))