package eu.friedcutlet.yokan.services.files import java.io.EOFException import java.io.InputStream import java.io.OutputStream /** Transfers a TAR payload with bounded memory, or skips it without materializing it. */ internal fun InputStream.transferTarEntry(size: Long, output: OutputStream? = null) { require(size >= 0) { "Negative TAR entry size" } var remaining = size val buffer = if (output != null) ByteArray(minOf(size, 64 * 1024L).toInt()) else null while (remaining > 0) { if (output == null) { val skipped = skip(remaining) if (skipped > 0) { remaining -= skipped } else { if (read() < 0) throw EOFException("Truncated TAR entry") remaining-- } } else { val bytes = checkNotNull(buffer) val count = read(bytes, 0, minOf(remaining, bytes.size.toLong()).toInt()) if (count < 0) throw EOFException("Truncated TAR entry") if (count == 0) { val byte = read() if (byte < 0) throw EOFException("Truncated TAR entry") output.write(byte) remaining-- } else { output.write(bytes, 0, count) remaining -= count } } } }