ronantakizawa/codereview-bench huggingface dataset:
Repository: ktorio/ktor
File: ktor-client/ktor-client-core/common/src/io/ktor/client/engine/Utils.kt (Kotlin)

Code before:
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/

package io.ktor.client.engine

import io.ktor.client.utils.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.util.*
import io.ktor.utils.io.*
import kotlinx.coroutines.*
import kotlin.coroutines.*

/**
 * Default user agent to use in a ktor client.
 */
@InternalAPI
public val KTOR_DEFAULT_USER_AGENT: String = "ktor-client"

private val DATE_HEADERS = setOf(
    HttpHeaders.Date,
    HttpHeaders.Expires,
    HttpHeaders.LastModified,
    HttpHeaders.IfModifiedSince,
    HttpHeaders.IfUnmodifiedSince
)

/**
 * Merge headers from [content] and [requestHeaders] according to [OutgoingContent] properties
 */
@InternalAPI
public fun mergeHeaders(
    requestHeaders: Headers,
    content: OutgoingContent,
    block: (key: String, value: String) -> Unit
) {
    buildHeaders {
        appendAll(requestHeaders)
        appendAll(content.headers)
    }.forEach { key, values ->

Review comment (suggestion):
```suggestion
 * Default user agent to use in a Ktor client.
```

Code after:
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/

package io.ktor.client.engine

import io.ktor.client.utils.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.util.*
import io.ktor.utils.io.*
import kotlinx.coroutines.*
import kotlin.coroutines.*

/**
 * Default user agent to use in a Ktor client.
 */
@InternalAPI
public val KTOR_DEFAULT_USER_AGENT: String = "ktor-client"

private val DATE_HEADERS = setOf(
    HttpHeaders.Date,
    HttpHeaders.Expires,
    HttpHeaders.LastModified,
    HttpHeaders.IfModifiedSince,
    HttpHeaders.IfUnmodifiedSince
)

/**
 * Merge headers from [content] and [requestHeaders] according to [OutgoingContent] properties
 */
@InternalAPI
public fun mergeHeaders(
    requestHeaders: Headers,
    content: OutgoingContent,
    block: (key: String, value: String) -> Unit
) {
    buildHeaders {
        appendAll(requestHeaders)
        appendAll(content.headers)
    }.forEach { key, values ->
Repository: ktorio/ktor
File: build.gradle.kts (Kotlin)

Code before:
)

extra["nonDefaultProjectStructure"] = mutableListOf(
    "ktor-bom",
    "ktor-java-modules-test",
)

val disabledExplicitApiModeProjects = listOf(
    "ktor-client-tests",
    "ktor-server-test-base",
    "ktor-server-test-suites",
    "ktor-server-tests",
    "ktor-client-content-negotiation-tests",
    "ktor-junit"
)

apply(from = "gradle/compatibility.gradle")

plugins {
    id("org.jetbrains.dokka") version "1.9.20" apply false
    id("org.jetbrains.kotlinx.binary-compatibility-validator") version "0.16.3"
    //id("com.osacky.doctor") version "0.10.0"
}

//doctor {
//    enableTestCaching = false
//}

subprojects {
    group = "io.ktor"
    version = configuredVersion
    extra["hostManager"] = HostManager()

    setupTrainForSubproject()

    val nonDefaultProjectStructure: List<String> by rootProject.extra
    if (nonDefaultProjectStructure.contains(project.name)) return@subprojects

    apply(plugin = "kotlin-multiplatform")
    apply(plugin = "atomicfu-conventions")

    configureTargets()
    if (CI) configureTestTasksOnCi()

    configurations {
        maybeCreate("testOutput")
    }

    kotlin {
        if (!disabledExplicitApiModeProjects.contains(project.name)) explicitApi()


Review comment (suggestion):
I'm going to disable Gradle Doctor by default but provide a way to enable it.
To do so, I should port behavior of `enableTestCaching = false` first to benefit from it even with disabled Gradle Doctor. 

Code after:
)

extra["nonDefaultProjectStructure"] = mutableListOf(
    "ktor-bom",
    "ktor-java-modules-test",
)

val disabledExplicitApiModeProjects = listOf(
    "ktor-client-tests",
    "ktor-server-test-base",
    "ktor-server-test-suites",
    "ktor-server-tests",
    "ktor-client-content-negotiation-tests",
    "ktor-junit"
)

apply(from = "gradle/compatibility.gradle")

plugins {
    alias(libs.plugins.dokka) apply false
    alias(libs.plugins.binaryCompatibilityValidator)
    conventions.gradleDoctor
}

subprojects {
    group = "io.ktor"
    version = configuredVersion
    extra["hostManager"] = HostManager()

    setupTrainForSubproject()

    val nonDefaultProjectStructure: List<String> by rootProject.extra
    if (nonDefaultProjectStructure.contains(project.name)) return@subprojects

    apply(plugin = "kotlin-multiplatform")
    apply(plugin = "atomicfu-conventions")

    configureTargets()
    if (CI) configureTestTasksOnCi()

    configurations {
        maybeCreate("testOutput")
    }

    kotlin {
        if (!disabledExplicitApiModeProjects.contains(project.name)) explicitApi()

        configureSourceSets()
        setupJvmToolchain()

        compilerOptions {
Repository: ktorio/ktor
File: ktor-io/common/test/ByteReadChannelOperationsTest.kt (Kotlin)

Code before:
        assertFailsWith<IOException> {
            input.readUntil("abc".encodeToByteString(), ByteChannel(), limit = 10, ignoreMissing = true)
        }
    }

    @Test
    fun readUntilMissing() = testSuspend {
        val input = "It's not in here".toByteChannel()
        assertFailsWith<IOException> {
            input.readUntil("note".encodeToByteString(), ByteChannel())
        }
    }

    @Test
    fun skipIfFound() = testSuspend {
        val input = "This is a test of the skipIfFound".toByteChannel()
        assertFalse(input.skipIfFound("Won't find this".encodeToByteString()))
        assertTrue(input.skipIfFound("This is a test of the ".encodeToByteString()))
        assertEquals("skipIfFound", input.readUTF8Line())
    }

    // this test ensures we don't get stuck on awaitContent
    @OptIn(InternalAPI::class, InternalIoApi::class)
    @Test
    fun readIntWithPartialContents() = runTest {
        withTimeout(1000) {
            val channel = ByteChannel()
            channel.readBuffer.buffer.writeByte(1)
            channel.writeByte(1)
            channel.writeByte(1)
            channel.writeByte(1)
            channel.flush()
            assertEquals(16843009, channel.readInt())
        }
    }

    @OptIn(InternalAPI::class)
    private suspend fun String.toByteChannel() = ByteChannel().also {
        it.writeBuffer.writeString(this)
        it.flushAndClose()
    }
}


Review comment (suggestion):
Minor: You can pass the timeout as a parameter to `runTest` (only if it should be "real time" timeout)

Code after:
        val input = "This is a test of the readUntil limit".toByteChannel()
        assertFailsWith<IOException> {
            input.readUntil("abc".encodeToByteString(), ByteChannel(), limit = 10, ignoreMissing = true)
        }
    }

    @Test
    fun readUntilMissing() = testSuspend {
        val input = "It's not in here".toByteChannel()
        assertFailsWith<IOException> {
            input.readUntil("note".encodeToByteString(), ByteChannel())
        }
    }

    @Test
    fun skipIfFound() = testSuspend {
        val input = "This is a test of the skipIfFound".toByteChannel()
        assertFalse(input.skipIfFound("Won't find this".encodeToByteString()))
        assertTrue(input.skipIfFound("This is a test of the ".encodeToByteString()))
        assertEquals("skipIfFound", input.readUTF8Line())
    }

    // this test ensures we don't get stuck on awaitContent
    @OptIn(InternalAPI::class, InternalIoApi::class)
    @Test
    fun readIntWithPartialContents() = runTest(timeout = 1.seconds) {
        val channel = ByteChannel()
        channel.readBuffer.buffer.writeByte(1)
        channel.writeByte(1)
        channel.writeByte(1)
        channel.writeByte(1)
        channel.flush()
        assertEquals(16843009, channel.readInt())
    }

    @OptIn(InternalAPI::class)
    private suspend fun String.toByteChannel() = ByteChannel().also {
        it.writeBuffer.writeString(this)
        it.flushAndClose()
    }
}
Repository: ktorio/ktor
File: ktor-io/common/src/io/ktor/utils/io/ByteWriteChannelOperations.kt (Kotlin)

Code before:
import kotlinx.io.Buffer
import kotlinx.io.unsafe.*
import kotlin.coroutines.*

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeByte(value: Byte) {
    writeBuffer.writeByte(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeShort(value: Short) {
    writeBuffer.writeShort(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeInt(value: Int) {
    writeBuffer.writeInt(value)
    flushIfNeeded()
}

/**
 * Writes a 32-bit floating-point value to the current [ByteWriteChannel].
 *
 * @param value The floating-point value to be written to the channel.
 */
@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeFloat(value: Float) {
    writeBuffer.writeFloat(value)
    flushIfNeeded()
}

/**
 * Writes a 64-bit floating-point value to the current [ByteWriteChannel].
 *
 * @param value The floating-point value to be written to the channel.
 */
@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeDouble(value: Double) {
    writeBuffer.writeDouble(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeLong(value: Long) {
    writeBuffer.writeLong(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)

Review comment (suggestion):
Probably, could be shortened
```suggestion
 * Writes a 32-bit floating-point [value] to the current [ByteWriteChannel].
```

Code after:
import kotlinx.io.Buffer
import kotlinx.io.unsafe.*
import kotlin.coroutines.*

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeByte(value: Byte) {
    writeBuffer.writeByte(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeShort(value: Short) {
    writeBuffer.writeShort(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeInt(value: Int) {
    writeBuffer.writeInt(value)
    flushIfNeeded()
}

/**
 * Writes a 32-bit floating-point [value] to the current [ByteWriteChannel].
 */
@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeFloat(value: Float) {
    writeBuffer.writeFloat(value)
    flushIfNeeded()
}

/**
 * Writes a 64-bit floating-point value to the current [ByteWriteChannel].
 *
 * @param value The floating-point value to be written to the channel.
 */
@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeDouble(value: Double) {
    writeBuffer.writeDouble(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeLong(value: Long) {
    writeBuffer.writeLong(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeByteArray(array: ByteArray) {
    writeBuffer.write(array)
Repository: ktorio/ktor
File: ktor-io/common/src/io/ktor/utils/io/ByteWriteChannelOperations.kt (Kotlin)

Code before:

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeShort(value: Short) {
    writeBuffer.writeShort(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeInt(value: Int) {
    writeBuffer.writeInt(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeLong(value: Long) {
    writeBuffer.writeLong(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeByteArray(array: ByteArray) {
    writeBuffer.write(array)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeSource(source: Source) {
    writeBuffer.transferFrom(source)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeString(value: String) {
    writeBuffer.writeText(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeFully(value: ByteArray, startIndex: Int = 0, endIndex: Int = value.size) {
    writeBuffer.write(value, startIndex, endIndex)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeBuffer(value: RawSource) {
    writeBuffer.transferFrom(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeStringUtf8(value: String) {

Review comment (suggestion):
And one more place here
```suggestion
 * Writes a 64-bit floating-point [value] to the current [ByteWriteChannel].
```

Code after:

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeShort(value: Short) {
    writeBuffer.writeShort(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeInt(value: Int) {
    writeBuffer.writeInt(value)
    flushIfNeeded()
}

/**
 * Writes a 32-bit floating-point [value] to the current [ByteWriteChannel].
 */
@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeFloat(value: Float) {
    writeBuffer.writeFloat(value)
    flushIfNeeded()
}

/**
 * Writes a 64-bit floating-point value to the current [ByteWriteChannel].
 *
 * @param value The floating-point value to be written to the channel.
 */
@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeDouble(value: Double) {
    writeBuffer.writeDouble(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeLong(value: Long) {
    writeBuffer.writeLong(value)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeByteArray(array: ByteArray) {
    writeBuffer.write(array)
    flushIfNeeded()
}

@OptIn(InternalAPI::class)
public suspend fun ByteWriteChannel.writeSource(source: Source) {
    writeBuffer.transferFrom(source)
    flushIfNeeded()
}
Repository: ktorio/ktor
File: ktor-server/ktor-server-test-base/common/test/io/ktor/server/test/base/BaseTestTest.kt (Kotlin)

Code before:
    @Test
    fun `runTest - retry test by default on non-JVM platform`(): TestResult {
        var retryCount = 0
        return runTest {
            if (!PlatformUtils.IS_JVM && retryCount++ < 1) fail("This test should be retried")
        }
    }

    @Test
    fun `runTest - don't retry test by default on JVM platform`(): TestResult {
        var retryCount = 0
        return runTest {
            if (PlatformUtils.IS_JVM && retryCount++ > 0) fail("This test should not be retried")
        }
    }

    @Test
    fun `runTest - more than one retry`(): TestResult {
        var retryCount = 0
        return runTest(retries = 3) {
            if (retryCount++ < 3) fail("This test should be retried")
        }
    }

    @Test
    fun `runTest - retry should work collected exceptions`(): TestResult {
        var retryCount = 0
        return runTest(retries = 1) {
            if (retryCount++ < 1) collectUnhandledException(Exception("This test should be retried"))
        }
    }
}


Review comment (suggestion):
```suggestion
    fun `runTest - retry should work with collected exceptions`(): TestResult {
```

Code after:
    @Test
    fun `runTest - retry test by default on non-JVM platform`(): TestResult {
        var retryCount = 0
        return runTest {
            if (!PlatformUtils.IS_JVM && retryCount++ < 1) fail("This test should be retried")
        }
    }

    @Test
    fun `runTest - don't retry test by default on JVM platform`(): TestResult {
        var retryCount = 0
        return runTest {
            if (PlatformUtils.IS_JVM && retryCount++ > 0) fail("This test should not be retried")
        }
    }

    @Test
    fun `runTest - more than one retry`(): TestResult {
        var retryCount = 0
        return runTest(retries = 3) {
            if (retryCount++ < 3) fail("This test should be retried")
        }
    }

    @Test
    fun `runTest - retry should work with collected exceptions`(): TestResult {
        var retryCount = 0
        return runTest(retries = 1) {
            if (retryCount++ < 1) collectUnhandledException(Exception("This test should be retried"))
        }
    }
}
Repository: ktorio/ktor
File: ktor-server/ktor-server-plugins/ktor-server-swagger/jvm/src/io/ktor/server/plugins/swagger/SwaggerConfig.kt (Kotlin)

Code before:
 * A configuration for the Swagger UI endpoint.
 */
public class SwaggerConfig {
    internal var customStyle: String? = null

    /**
     * Specifies a Swagger UI version to use.
     */
    public var version: String = "5.17.12"

    /**
     * Specifies a URL for a custom CSS applied to a Swagger UI.
     *
     * Example: https://unpkg.com/swagger-ui-themes@3.0.1/themes/3.x/theme-monokai.css
     */
    public fun customStyle(path: String?) {
        customStyle = path
    }

    /**
     * Swagger package location
     */
    public var packageLocation: String = "https://unpkg.com/swagger-ui-dist"

    /**
     * Whether to allow deep linking in Swagger UI, as described here: https://swagger.io/docs/open-source-tools/swagger-ui/usage/deep-linking/
     *
     * Defaults to `false`.
     */
    public var deepLinking: Boolean = false

    /*
     * Swagger favicon location
     */
    public var faviconLocation: String = "https://unpkg.com/swagger-ui-dist@$version/favicon-32x32.png"
}


Review comment (suggestion):
Minor. Let's use a hyperlink here:
 ```suggestion
      * Whether to allow [deep linking in Swagger UI](https://swagger.io/docs/open-source-tools/swagger-ui/usage/deep-linking/).
```

Code after:
 * A configuration for the Swagger UI endpoint.
 */
public class SwaggerConfig {
    internal var customStyle: String? = null

    /**
     * Specifies a Swagger UI version to use.
     */
    public var version: String = "5.17.12"

    /**
     * Specifies a URL for a custom CSS applied to a Swagger UI.
     *
     * Example: https://unpkg.com/swagger-ui-themes@3.0.1/themes/3.x/theme-monokai.css
     */
    public fun customStyle(path: String?) {
        customStyle = path
    }

    /**
     * Swagger package location
     */
    public var packageLocation: String = "https://unpkg.com/swagger-ui-dist"

    /**
     * Whether to allow [deep linking in Swagger UI](https://swagger.io/docs/open-source-tools/swagger-ui/usage/deep-linking/).
     *
     * Defaults to `false`.
     */
    public var deepLinking: Boolean = false

    /*
     * Swagger favicon location
     */
    public var faviconLocation: String = "https://unpkg.com/swagger-ui-dist@$version/favicon-32x32.png"
}
Repository: ktorio/ktor
File: ktor-network/common/test/io/ktor/network/sockets/tests/TCPSocketTest.kt (Kotlin)

Code before:

        assertFailsWith<EOFException> {
            serverInput.readByte()
        }

        serverConnection.close()
        server.close()
    }

    @Test
    fun testAcceptErrorOnSocketClose() = testSockets { selector ->
        val socket = aSocket(selector)
            .tcp()
            .bind(InetSocketAddress("127.0.0.1", 0))

        launch {
            assertFailsWith<IOException> {
                socket.accept()
            }
        }
        delay(100) // Make sure socket is awaiting connection using ACCEPT

        socket.close()
    }
}


Review comment (bug):
```suggestion
        val acceptJob = launch {
            assertFailsWith<NullPointerException> {
                socket.accept()
            }
        }
        yield()

        socket.close()
        acceptJob.join()
```

Code after:
            delay(100)
            clientConnection.close()
        }

        assertFailsWith<EOFException> {
            serverInput.readByte()
        }

        serverConnection.close()
        server.close()
    }

    @Test
    fun testAcceptErrorOnSocketClose() = testSockets { selector ->
        val socket = aSocket(selector)
            .tcp()
            .bind(InetSocketAddress("127.0.0.1", 0))

        launch {
            assertFailsWith<IOException> {
                socket.accept()
            }
        }
        delay(100) // Make sure socket is awaiting connection using ACCEPT

        socket.close()
    }
}
Repository: ktorio/ktor
File: ktor-client/ktor-client-core/js/src/io/ktor/client/engine/js/browser/BrowserFetch.kt (Kotlin)

Code before:
    @Suppress("UNCHECKED_CAST_TO_EXTERNAL_INTERFACE")
    val stream: ReadableStream<Uint8Array> = response.body ?: return ByteReadChannel.Empty
    return channelFromStream(stream)
}

internal fun CoroutineScope.channelFromStream(
    stream: ReadableStream<Uint8Array>
): ByteReadChannel = writer {
    val reader: ReadableStreamDefaultReader<Uint8Array> = stream.getReader()
    while (true) {
        try {
            val chunk = reader.readChunk() ?: break
            channel.writeFully(chunk.asByteArray())
            channel.flush()
        } catch (cause: Throwable) {
            reader.cancel(cause)
            throw cause
        }
    }
}.channel

internal suspend fun ReadableStreamDefaultReader<Uint8Array>.readChunk(): Uint8Array? =
    suspendCancellableCoroutine { continuation ->
        read().then {
            val chunk = it.value
            val result = if (it.done) null else chunk
            continuation.resumeWith(Result.success(result))
        }.catch { cause ->
            continuation.resumeWithException(cause)
        }
    }


Review comment (suggestion):
Made this coroutine non-cancellable to ensure the exception thrown on `controller.abort()` is propagated to the upper level.

Code after:
import kotlin.coroutines.suspendCoroutine

internal fun CoroutineScope.readBodyBrowser(response: Response): ByteReadChannel {
    @Suppress("UnsafeCastFromDynamic")
    val stream: ReadableStream<Uint8Array> = response.body ?: return ByteReadChannel.Empty
    return channelFromStream(stream)
}

internal fun CoroutineScope.channelFromStream(
    stream: ReadableStream<Uint8Array>
): ByteReadChannel = writer {
    val reader: ReadableStreamDefaultReader<Uint8Array> = stream.getReader()
    try {
        while (true) {
            val chunk = reader.readChunk() ?: break
            channel.writeFully(chunk.asByteArray())
            channel.flush()
        }
    } catch (cause: Throwable) {
        reader.cancel(cause).catch { /* ignore */ }.await()
        throw cause
    }
}.channel

internal suspend fun ReadableStreamDefaultReader<Uint8Array>.readChunk(): Uint8Array? =
    suspendCoroutine { continuation ->
        read().then {
            val chunk = it.value
            val result = if (it.done) null else chunk
            continuation.resume(result)
        }.catch { cause ->
            continuation.resumeWithException(cause)
        }
    }