Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restore optimized JVM I/O functions in coil-network-ktor3. #2478

Merged
merged 1 commit into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,37 +1,26 @@
package coil3.network.ktor3.internal

import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.core.readFully
import io.ktor.utils.io.core.remaining
import io.ktor.utils.io.readRemaining
import io.ktor.utils.io.copyTo
import java.io.RandomAccessFile
import okio.BufferedSink
import okio.FileSystem
import okio.Path

// TODO: Use JVM-optimized implementations from Ktor 2 once
// https://youtrack.jetbrains.com/issue/KTOR-7220 is fixed.

internal actual suspend fun ByteReadChannel.writeTo(sink: BufferedSink) {
val buffer = ByteArray(OKIO_BUFFER_SIZE)

while (!isClosedForRead) {
val packet = readRemaining(buffer.size.toLong())
if (packet.exhausted()) break

// TODO: Figure out how to remove 'buffer' and read directly into 'sink'.
val bytesRead = packet.remaining.toInt()
packet.readFully(buffer, 0, bytesRead)
sink.write(buffer, 0, bytesRead)
}

closedCause?.let { throw it }
copyTo(sink)
}

internal actual suspend fun ByteReadChannel.writeTo(fileSystem: FileSystem, path: Path) {
fileSystem.write(path) {
writeTo(this)
if (fileSystem === FileSystem.SYSTEM) {
// Fast path: normal jvm File, write to FileChannel directly.
RandomAccessFile(path.toFile(), "rw").use {
copyTo(it.channel)
}
} else {
// Slow path: cannot guarantee a "real" file.
fileSystem.write(path) {
copyTo(this)
}
}
}

// Okio uses 8 KB internally.
private const val OKIO_BUFFER_SIZE = 8 * 1024