stream.clj

Branches > main > 4115884 > files / src / net / bowmap / network / stream.clj

(ns net.bowmap.network.stream
  (:require
   [dev.grahp.error :refer [raise]]
   [net.bowmap.network.protocol.types :as t])
  (:import
   [io.netty.buffer ByteBuf Unpooled]
   [java.io InputStream OutputStream]))

; Reading and writing frames to and from InputStreams and OutputStreams

(defn read-byte!!
  "Either returns an unsigned byte from 'in', or throws"
  [input-stream]
  (let [x (InputStream/.read input-stream)]
    (if (= -1 x)
      (raise "EOF while reading from InputStream")
      x)))

(defn read-varint!!
  "Either returns a varint from 'in', or throws"
  [input-stream]
  (loop [num-read 0
         result 0]
    (if (>= num-read t/max-varint-size)
      (raise "VarInt too long")
      (let [b (read-byte!! input-stream)
            result' (bit-or result (bit-shift-left (bit-and b 0x7F) (* 7 num-read)))]
        (if (zero? (bit-and b 0x80))
          result'
          (recur (inc num-read) result'))))))

(defn read-frame!! [input-stream]
  (let [len (read-varint!! input-stream)
        arr (byte-array len)]
    (loop [offset 0]
      (when (< offset len)
        (let [r (InputStream/.read input-stream arr offset (- len offset))]
          (if (= r -1)
            (throw (Exception. "EOF while reading frame"))
            (recur (+ offset r))))))
    (Unpooled/wrappedBuffer arr)))

(defn write-frame!! [frame output-stream]
  (let [len (ByteBuf/.readableBytes frame)
        arr (byte-array len)]
    (ByteBuf/.readBytes frame arr)
    (OutputStream/.write output-stream arr)
    (OutputStream/.flush output-stream)))