package net.sergeych.toread.fb2

import java.util.zip.DataFormatException
import java.util.zip.Inflater

internal actual fun inflateRaw(input: ByteArray, expectedSize: Int): ByteArray {
    val inflater = Inflater(true)
    return try {
        inflater.setInput(input)
        val output = ByteArray(expectedSize)
        val inflated = inflater.inflate(output)
        if (!inflater.finished() || inflated != expectedSize) {
            throw Fb2ParseException("Could not inflate ZIP entry: expected $expectedSize bytes, got $inflated")
        }
        output
    } catch (cause: DataFormatException) {
        throw Fb2ParseException("Could not inflate ZIP entry: ${cause.message ?: "invalid deflate stream"}")
    } finally {
        inflater.end()
    }
}
