From 0802079578d33a3cccc51620915042812dda0514 Mon Sep 17 00:00:00 2001 From: Yuri Schimke Date: Sat, 15 Feb 2025 17:43:15 +0000 Subject: [PATCH] Fix for repeated reads --- .../kotlin/okhttp3/MultipartReader.kt | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartReader.kt b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartReader.kt index ef0db693625c..d4d2fece2a23 100644 --- a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartReader.kt +++ b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/MultipartReader.kt @@ -186,15 +186,16 @@ class MultipartReader * one byte left to read. */ private fun currentPartBytesRemaining(maxResult: Long): Long { + // Avoid indexOf scanning repeatedly over the entire source by using limit + // Since maxResult could be midway through the boundary, read further to be safe. val limitSource = source.peek().limit(maxResult + crlfDashDashBoundary.size).buffer() limitSource.require(crlfDashDashBoundary.size.toLong()) + val delimiterIndex = limitSource.buffer.indexOf(crlfDashDashBoundary) - val toRead = - when (delimiterIndex) { - -1L -> minOf(maxResult, limitSource.buffer.size - crlfDashDashBoundary.size + 1) - else -> minOf(maxResult, delimiterIndex) - } - return toRead + return when (delimiterIndex) { + -1L -> minOf(maxResult, limitSource.buffer.size - crlfDashDashBoundary.size + 1) + else -> minOf(maxResult, delimiterIndex) + } } @Throws(IOException::class)