diff --git a/gradle.properties b/gradle.properties index 0870c91..4f78a11 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,7 +4,7 @@ kotlin.code.style=official specifyKotlinAsDependency=false projectGroup=ru.dbotthepony.kommons -projectVersion=2.1.2 +projectVersion=2.1.3 guavaDepVersion=33.0.0 gsonDepVersion=2.8.9 diff --git a/src/main/kotlin/ru/dbotthepony/kommons/io/InputStreamUtils.kt b/src/main/kotlin/ru/dbotthepony/kommons/io/InputStreamUtils.kt index 54ebae7..7ec55a7 100644 --- a/src/main/kotlin/ru/dbotthepony/kommons/io/InputStreamUtils.kt +++ b/src/main/kotlin/ru/dbotthepony/kommons/io/InputStreamUtils.kt @@ -46,6 +46,12 @@ private fun InputStream.readOrError(): Int { 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 { if (this is DataInput) { return readInt() @@ -253,3 +259,10 @@ fun S.readOptional(reader: S.() -> V): Optional { 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)) +} diff --git a/src/main/kotlin/ru/dbotthepony/kommons/io/OutputStreamUtils.kt b/src/main/kotlin/ru/dbotthepony/kommons/io/OutputStreamUtils.kt index 1b7eb66..b6cea04 100644 --- a/src/main/kotlin/ru/dbotthepony/kommons/io/OutputStreamUtils.kt +++ b/src/main/kotlin/ru/dbotthepony/kommons/io/OutputStreamUtils.kt @@ -283,3 +283,8 @@ fun S.writeOptional(value: Optional, writer: S.(V writer(this, value.get()) } } + +fun OutputStream.writeByteArray(value: ByteArray) { + writeVarInt(value.size) + write(value) +}