Throw exception when trying to read after end of stream

This commit is contained in:
DBotThePony 2022-10-21 23:03:07 +07:00
parent f64ea09a1b
commit af916f39e9
Signed by: DBot
GPG Key ID: DCC23B5715498507

View File

@ -7,6 +7,7 @@ import java.io.InputStream
import java.io.OutputStream
import java.util.*
import java.util.function.Predicate
import kotlin.NoSuchElementException
import kotlin.math.absoluteValue
interface IStreamCodec<V> {
@ -137,6 +138,10 @@ fun InputStream.readDouble() = Double.fromBits(readLong())
fun InputStream.readVarIntLE(): Int {
val readFirst = read()
if (readFirst < 0) {
throw NoSuchElementException("Reached end of stream")
}
if (readFirst and 64 == 0) {
return if (readFirst and 128 != 0) -(readFirst and 63) else readFirst and 63
}
@ -149,6 +154,11 @@ fun InputStream.readVarIntLE(): Int {
while (nextBit != 0) {
result = result or (read shl i)
read = read()
if (read < 0) {
throw NoSuchElementException("Reached end of stream")
}
nextBit = read and 128
read = read and 127
@ -175,6 +185,10 @@ fun OutputStream.writeVarIntLE(value: Int) {
fun InputStream.readVarLongLE(): Long {
val readFirst = read()
if (readFirst < 0) {
throw NoSuchElementException("Reached end of stream")
}
if (readFirst and 64 == 0) {
return if (readFirst and 128 != 0) -(readFirst and 63).toLong() else (readFirst and 63).toLong()
}
@ -187,6 +201,11 @@ fun InputStream.readVarLongLE(): Long {
while (nextBit != 0) {
result = result or (read shl i).toLong()
read = read()
if (read < 0) {
throw NoSuchElementException("Reached end of stream")
}
nextBit = read and 128
read = read and 127