package theorycrafter.utils

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


actual fun InputStream.skipBytes(count: Long) {
    var remaining = count
    while (remaining > 0) {
        when (val skipped = skip(remaining)) {
            0L -> { // no bytes skipped
                // read one byte to check for EOS
                if (read() == -1) {
                    throw EOFException()
                }
                // one byte read so decrement number to skip
                remaining--
            }
            in 1..remaining -> {
                // adjust number to skip
                remaining -= skipped
            }
            else ->  // skipped negative or too many bytes
                throw IOException("Unable to skip exactly")
        }
    }
}


actual fun InputStream.readToEnd(): ByteArray {
    var buf = ByteArray(2048)

    var totalRead = 0
    while (true) {
        val amountRead = read(buf, totalRead, buf.size - totalRead)
        if (amountRead <= 0) break
        totalRead += amountRead
        if (totalRead == buf.size) {
            buf = buf.copyOf(buf.size * 2)
        }
    }

    val arr = ByteArray(totalRead)
    System.arraycopy(buf, 0, arr, 0, totalRead)
    return arr
}
