From b284bc07803e4f9658a1e65c55d57abe28c85c1e Mon Sep 17 00:00:00 2001 From: iseki Date: Thu, 19 Sep 2024 21:26:48 +0800 Subject: [PATCH] Implement transferTo method in RealBufferedSource.inputStream (#1501) * Implement transferTo method in RealBufferedSource.inputStream Avoid unnecessary memory copying * Update okio/src/jvmMain/kotlin/okio/RealBufferedSource.kt Co-authored-by: Jake Wharton --------- Co-authored-by: Jake Wharton --- .../jvmMain/kotlin/okio/RealBufferedSource.kt | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/okio/src/jvmMain/kotlin/okio/RealBufferedSource.kt b/okio/src/jvmMain/kotlin/okio/RealBufferedSource.kt index 029b93d297..65134edea2 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,23 @@ 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 + if (count < 0) { + count = Long.MAX_VALUE + } + buffer.writeTo(out) + } + return count + } } }