Skip to content

Commit

Permalink
Implement transferTo method in RealBufferedSource.inputStream (#1501)
Browse files Browse the repository at this point in the history
* Implement transferTo method in RealBufferedSource.inputStream

Avoid unnecessary memory copying

* Update okio/src/jvmMain/kotlin/okio/RealBufferedSource.kt

Co-authored-by: Jake Wharton <[email protected]>

---------

Co-authored-by: Jake Wharton <[email protected]>
  • Loading branch information
iseki0 and JakeWharton authored Sep 19, 2024
1 parent 4e6123f commit b284bc0
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 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,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
}
}
}

Expand Down

0 comments on commit b284bc0

Please sign in to comment.