Read/write byte array
This commit is contained in:
parent
e150738f37
commit
ac9a882f12
@ -4,7 +4,7 @@ kotlin.code.style=official
|
|||||||
specifyKotlinAsDependency=false
|
specifyKotlinAsDependency=false
|
||||||
|
|
||||||
projectGroup=ru.dbotthepony.kommons
|
projectGroup=ru.dbotthepony.kommons
|
||||||
projectVersion=2.1.2
|
projectVersion=2.1.3
|
||||||
|
|
||||||
guavaDepVersion=33.0.0
|
guavaDepVersion=33.0.0
|
||||||
gsonDepVersion=2.8.9
|
gsonDepVersion=2.8.9
|
||||||
|
@ -46,6 +46,12 @@ private fun InputStream.readOrError(): Int {
|
|||||||
return read
|
return read
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun InputStream.readOrError(bytes: ByteArray): ByteArray {
|
||||||
|
val read = read(bytes)
|
||||||
|
check(read == bytes.size) { "Expected to read ${bytes.size} bytes, but only $read were read" }
|
||||||
|
return bytes
|
||||||
|
}
|
||||||
|
|
||||||
fun InputStream.readInt(): Int {
|
fun InputStream.readInt(): Int {
|
||||||
if (this is DataInput) {
|
if (this is DataInput) {
|
||||||
return readInt()
|
return readInt()
|
||||||
@ -253,3 +259,10 @@ fun <S : InputStream, V : Any> S.readOptional(reader: S.() -> V): Optional<V> {
|
|||||||
return Optional.of(reader(this))
|
return Optional.of(reader(this))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun InputStream.readByteArray(maxRead: Int = Int.MAX_VALUE): ByteArray {
|
||||||
|
val size = readVarInt()
|
||||||
|
if (size > maxRead)
|
||||||
|
throw IllegalArgumentException("Trying to read $size bytes when $maxRead is the max allowed")
|
||||||
|
return readOrError(ByteArray(size))
|
||||||
|
}
|
||||||
|
@ -283,3 +283,8 @@ fun <S : OutputStream, V : Any> S.writeOptional(value: Optional<V>, writer: S.(V
|
|||||||
writer(this, value.get())
|
writer(this, value.get())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun OutputStream.writeByteArray(value: ByteArray) {
|
||||||
|
writeVarInt(value.size)
|
||||||
|
write(value)
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user