Skip to content

Commit

Permalink
Implement transferTo method in RealBufferedSource.inputStream
Browse files Browse the repository at this point in the history
Avoid unnecessary memory copying
  • Loading branch information
iseki0 committed Aug 4, 2024
1 parent 1d4d803 commit 16c3962
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions okio/src/jvmMain/kotlin/okio/RealBufferedSource.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
}
}

Expand Down

0 comments on commit 16c3962

Please sign in to comment.