From 16c3962cd34cfe31f4780922193364d3ce67ba3f Mon Sep 17 00:00:00 2001 From: iseki Date: Fri, 2 Aug 2024 14:09:25 +0800 Subject: [PATCH] Implement transferTo method in RealBufferedSource.inputStream Avoid unnecessary memory copying --- .../src/jvmMain/kotlin/okio/RealBufferedSource.kt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/okio/src/jvmMain/kotlin/okio/RealBufferedSource.kt b/okio/src/jvmMain/kotlin/okio/RealBufferedSource.kt index 029b93d297..a313fcd1e9 100644 --- a/okio/src/jvmMain/kotlin/okio/RealBufferedSource.kt +++ b/okio/src/jvmMain/kotlin/okio/RealBufferedSource.kt @@ -17,6 +17,7 @@ package okio import java.io.IOException import java.io.InputStream +import java.io.OutputStream import java.nio.ByteBuffer import java.nio.charset.Charset import okio.internal.commonClose @@ -174,6 +175,20 @@ internal actual class RealBufferedSource actual constructor( override fun close() = this@RealBufferedSource.close() override fun toString() = "${this@RealBufferedSource}.inputStream()" + + override fun transferTo(out: OutputStream): Long { + if (closed) throw IOException("closed") + var count = 0L + while (true) { + if (buffer.size == 0L) { + val read = source.read(buffer, Segment.SIZE.toLong()) + if (read == -1L) break + } + count += buffer.size + buffer.writeTo(out) + } + return count + } } }