In addition to @Joop Eggen’s answer, I would suggest also checking for extra bytes after decompression has completed, and handling DataFormatException, because as far as I can see you wanted to decompress a single "data" byte array.
val toParse: ByteByffer = TODO()
inflater.setInput(toParse)
var messageBytes = ByteArray(toParse.remaining())
var messageSize = 0
while (!inflater.finished()) {
if (messageSize == messageBytes.size) {
messageBytes = messageBytes.copyOf(messageSize * 2)
}
try {
val decompressedSize = inflater.inflate(messageBytes, messageSize, messageBytes.size - messageSize)
messageSize += decompressedSize
// A return value of 0 indicates that needsInput() or needsDictionary() should be called in order
// to determine if more input data or a preset dictionary is required.
if (decompressedSize == 0) {
if (inflater.needsInput()) {
throw IllegalArgumentException("Malformed message: insufficient bytes to complete decompression.")
}
if (inflater.needsDictionary()) {
throw IllegalArgumentException("Malformed message: deflate with custom dictionary is not supported.")
}
}
} catch (error: DataFormatException) {
throw IllegalArgumentException("Malformed message: invalid deflate data: ${error.message}", error)
}
}
// Returns the total number of bytes remaining in the input buffer.
// This can be used to find out what bytes still remain in the input buffer after decompression has finished.
if (inflater.remaining > 0) {
throw IllegalArgumentException("Malformed message: extra ${inflater.remaining} bytes detected after decompression was complete.")
}
inflater.end() // or .reset() if you want to reuse