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 08eaac9
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions ktor-io/jvm/src/io/ktor/utils/io/ByteBufferChannel.kt
Expand Up @@ -1631,6 +1631,7 @@ internal open class ByteBufferChannel(

override suspend fun read(min: Int, consumer: (ByteBuffer) -> Unit) {
require(min >= 0) { "min should be positive or zero" }
if (min == 0) return

val read = reading {
val av = it.availableForRead
Expand Down Expand Up @@ -2328,19 +2329,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 08eaac9

Please sign in to comment.