frame.clj

Bowmap · bowmap.git · Tickets

Branches > main > 76c8f42 > files / src / net / bowmap / server / protocol / frame.clj

(ns net.bowmap.server.protocol.frame
  "A framed byte buffer containing one serialized Minecraft protocol packet.
   See https://minecraft.wiki/w/Java_Edition_protocol/Packets for the format."
  (:require
   [clojure.spec.alpha :as s]
   [net.bowmap.server.protocol.types :refer [max-varint-size]]
   [net.bowmap.server.protocol.writers :refer [varint->]])
  (:import
   [io.netty.buffer ByteBuf CompositeByteBuf Unpooled]))

(s/def ::frame #(instance? ByteBuf %))

(defn frame
  "Returns an empty frame, or a frame containing the bytes of an array."
  ([] (Unpooled/buffer))
  ([arr] (Unpooled/wrappedBuffer arr)))

(defn- composite-byte-buf
  "Returns a CompositeByteBuf containing 'bufs'."
  [& bufs]
  (-> (Unpooled/compositeBuffer (count bufs))
      (CompositeByteBuf/.addComponents true bufs)))

(defn length-prefixed
  "Returns a frame prefixed by the the varint length of the given frame."
  [frame]
  (composite-byte-buf
    (varint-> (Unpooled/buffer max-varint-size) (ByteBuf/.writerIndex frame))
    frame))