From 08eaac940ba39c82cc2b338be0421877951446ae Mon Sep 17 00:00:00 2001 From: Leonid Stashevsky Date: Tue, 6 Dec 2022 09:15:51 +0100 Subject: [PATCH] KTOR-5252 Fix peekTo EOFException --- .../src/io/ktor/utils/io/ByteBufferChannel.kt | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/ktor-io/jvm/src/io/ktor/utils/io/ByteBufferChannel.kt b/ktor-io/jvm/src/io/ktor/utils/io/ByteBufferChannel.kt index b34e387f310..d2254d3868b 100644 --- a/ktor-io/jvm/src/io/ktor/utils/io/ByteBufferChannel.kt +++ b/ktor-io/jvm/src/io/ktor/utils/io/ByteBufferChannel.kt @@ -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 @@ -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()