Yokan / rebuild
Course 1 8624561

TarStreams.kt

composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/TarStreams.kt

implementation36 lines
1package eu.friedcutlet.yokan.services.files23import java.io.EOFException4import java.io.InputStream5import java.io.OutputStream67/** Transfers a TAR payload with bounded memory, or skips it without materializing it. */8internal fun InputStream.transferTarEntry(size: Long, output: OutputStream? = null) {9    require(size >= 0) { "Negative TAR entry size" }10    var remaining = size11    val buffer = if (output != null) ByteArray(minOf(size, 64 * 1024L).toInt()) else null12    while (remaining > 0) {13        if (output == null) {14            val skipped = skip(remaining)15            if (skipped > 0) {16                remaining -= skipped17            } else {18                if (read() < 0) throw EOFException("Truncated TAR entry")19                remaining--20            }21        } else {22            val bytes = checkNotNull(buffer)23            val count = read(bytes, 0, minOf(remaining, bytes.size.toLong()).toInt())24            if (count < 0) throw EOFException("Truncated TAR entry")25            if (count == 0) {26                val byte = read()27                if (byte < 0) throw EOFException("Truncated TAR entry")28                output.write(byte)29                remaining--30            } else {31                output.write(bytes, 0, count)32                remaining -= count33            }34        }35    }36}37

Search chapters, reference and source filenames.