writers.clj

Bowmap · bowmap.git · Tickets

Branches > main > 4f918a3 > files / src / net / bowmap / network / frame / writers.clj

(ns net.bowmap.network.frame.writers
  "Functions for writing values into frames.
   Functions look like type->, where 'type' is a Minecraft protocol type.
   See https://minecraft.wiki/w/Java_Edition_protocol/Packets#Data_types"
  (:require
   [clojure.data.json :as json])
  (:import
   [io.netty.buffer ByteBuf]
   [java.nio.charset Charset]))

(def byte-> ByteBuf/.writeByte)
(def ubyte-> ByteBuf/.writeByte)
(def short-> ByteBuf/.writeShort)
(def ushort-> ByteBuf/.writeShort)
(def int-> ByteBuf/.writeInt)
(def long-> ByteBuf/.writeLong)
(def float-> ByteBuf/.writeFloat)
(def double-> ByteBuf/.writeDouble)

(defn varint-> [buf n]
  (loop [buf buf
         n n]
    (let [b (bit-and n 0x7F)
          nxt (unsigned-bit-shift-right n 7)]
      (if (zero? nxt)
        (ByteBuf/.writeByte buf b)
        (recur (ByteBuf/.writeByte buf (bit-or b 0x80))
               nxt)))))

(defn string-> [buf s]
  {:pre [(string? s)]}
  (doto buf
    (varint-> (count s))
    (ByteBuf/.writeCharSequence s (Charset/forName "UTF-8"))))

(defn json-> [buf s]
  (string-> buf (json/write-str s)))