package chat.vojo.proxy.core.net

import java.io.EOFException
import java.io.InputStream

/** Reads exactly [len] bytes into [buf] starting at [off] or throws [EOFException]. */
fun InputStream.readFully(buf: ByteArray, off: Int = 0, len: Int = buf.size) {
    var read = 0
    while (read < len) {
        val n = read(buf, off + read, len - read)
        if (n < 0) throw EOFException("stream closed after $read/$len bytes")
        read += n
    }
}

/** Reads exactly [len] bytes into a fresh array. */
fun InputStream.readExact(len: Int): ByteArray {
    val b = ByteArray(len)
    readFully(b, 0, len)
    return b
}

fun u16be(hi: Int, lo: Int): Int = ((hi and 0xff) shl 8) or (lo and 0xff)
