codec.clj

Bowmap · bowmap.git · Tickets

Branches > main > 23ec393 > files / src / net / bowmap / server / protocol / codec.clj

(ns net.bowmap.server.protocol.codec
  (:require
   [net.bowmap.server.protocol.clientbound-packets :as clientbound]
   [net.bowmap.server.protocol.frame :refer [frame]]
   [net.bowmap.server.protocol.packet :as packet]
   [net.bowmap.server.protocol.phase :as phase]
   [net.bowmap.server.protocol.readers :as readers]
   [net.bowmap.server.protocol.serverbound-packets :as serverbound]
   [net.bowmap.server.protocol.writers :as writers]))

(defn encode-packet
  "Encodes a packet into a frame.
   Throws when the packet cannot be encoded."
  [{::phase/keys! [phase]} {::packet/keys! [id] :as packet}]
  (let [numeric-id (req! (clientbound/phase->id->numeric-id phase) id)
        schema (req! (clientbound/phase->id->schema phase) id)
        payload-writer (if (and numeric-id schema)
                         (writers/to-writer schema)
                         (throw (ex-info "No such packet with that id!" {:phase phase :numeric-id numeric-id})))]
    (-> (frame)
        (writers/varint> numeric-id)
        (payload-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 [numeric-id (readers/varint< frame)
        id (req! (serverbound/phase->numeric-id->id phase) numeric-id)
        schema (req! (serverbound/phase->id->schemas phase) id)
        payload-reader (readers/to-reader schema)]
    (assoc (payload-reader frame)
           ::packet/id id)))