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 Sep 18, 2024
1 parent f74b84c commit e6064c7
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 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,24 @@ 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 = try {
Math.addExact(count, buffer.size)
} catch (ignored: ArithmeticException) {
Long.MAX_VALUE
}
buffer.writeTo(out)
}
return count
}
}
}

Expand Down

0 comments on commit e6064c7

Please sign in to comment.