-
Notifications
You must be signed in to change notification settings - Fork 661
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Restore optimized JVM I/O functions in coil-network-ktor3. (#2478)
- Loading branch information
1 parent
62eb144
commit fcc16e5
Showing
3 changed files
with
13 additions
and
24 deletions.
There are no files selected for viewing
File renamed without changes.
37 changes: 13 additions & 24 deletions
37
coil-network-ktor3/src/jvmCommonMain/kotlin/coil3/network/ktor3/internal/utils.jvmCommon.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
File renamed without changes.