de.bixilon.mbf.LimitedInputStream.kt Maven / Gradle / Ivy
package de.bixilon.mbf
import java.io.InputStream
@Deprecated("kutil")
class LimitedInputStream(val stream: InputStream, limit: Long) : InputStream() {
private var left = limit
init {
if (limit < 0) throw IllegalArgumentException("Limit can not be < 0: $limit")
}
constructor(stream: InputStream, limit: Int) : this(stream, limit.toLong())
override fun available(): Int {
return minOf(left, stream.available().toLong()).toInt()
}
override fun read(): Int {
if (left == 0L) return -1
val read = stream.read()
if (read == -1) return -1
left--
return read
}
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (left == 0L) return -1
val length = minOf(len.toLong(), left).toInt()
val read = stream.read(b, off, length)
if (read == -1) return -1
left -= read
return read
}
override fun skip(n: Long): Long {
val n = minOf(left, n)
val skipped = stream.skip(n)
left -= skipped
return skipped
}
}