Skip to content

Commit

Permalink
KTOR-5252 Fix peekTo EOFException
Browse files Browse the repository at this point in the history
  • Loading branch information
e5l committed Dec 6, 2022
1 parent ee367bc commit 269af75
Showing 1 changed file with 16 additions and 12 deletions.
28 changes: 16 additions & 12 deletions ktor-io/jvm/src/io/ktor/utils/io/ByteBufferChannel.kt
Expand Up @@ -2328,19 +2328,23 @@ internal open class ByteBufferChannel(
var bytesCopied = 0
val desiredSize = (min + offset).coerceAtMost(4088L).toInt()

read(desiredSize) { nioBuffer ->
if (nioBuffer.remaining() > offset) {
val view = nioBuffer.duplicate()!!
view.position(view.position() + offset.toInt())

val oldLimit = view.limit()
val canCopyToDestination = minOf(max, destination.size - destinationOffset)
val newLimit = minOf(view.limit().toLong(), canCopyToDestination + offset)
view.limit(newLimit.toInt())
bytesCopied = view.remaining()
view.copyTo(destination, destinationOffset.toInt())
view.limit(oldLimit)
try {
read(desiredSize) { nioBuffer ->
if (nioBuffer.remaining() > offset) {
val view = nioBuffer.duplicate()!!
view.position(view.position() + offset.toInt())

val oldLimit = view.limit()
val canCopyToDestination = minOf(max, destination.size - destinationOffset)
val newLimit = minOf(view.limit().toLong(), canCopyToDestination + offset)
view.limit(newLimit.toInt())
bytesCopied = view.remaining()
view.copyTo(destination, destinationOffset.toInt())
view.limit(oldLimit)
}
}
} catch (_: EOFException) {
// ignore
}

return bytesCopied.toLong()
Expand Down

0 comments on commit 269af75

Please sign in to comment.