ronantakizawa/codereview-bench huggingface dataset:
Repository: square/okhttp
File: okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt (Kotlin)

Code before:
   * curl -X POST -H "Authorization: Bearer token" --data "{\"key\":\"value\"}" "https://example.com/api"
   * ```
   *
   * @return a cURL command string representing this request.
   */
  fun curl(): String {
    val curl = StringBuilder("curl")
    // Add method if not GET
    if (method != "GET") {
      curl.append(" -X ").append(method)
    }

    for ((name, value) in headers) {
      curl
        .append(" -H ")
        .append("\"")
        .append(name)
        .append(": ")
        .append(value)
        .append("\"")
    }

    body?.let { requestBody ->
      val buffer = okio.Buffer()
      requestBody.writeTo(buffer)

      val contentType = requestBody.contentType()?.toString() ?: ""

      if (contentType.startsWith("text/") ||
        contentType.contains("json") ||
        contentType.contains("xml") ||
        contentType.contains("form-urlencoded")
      ) {
        val bodyString = buffer.readUtf8()
        curl
          .append(" --data ")
          .append("\"")
          .append(bodyString.replace("\"", "\\\""))
          .append("\"")
      } else {
        curl.append(" --data-binary \"[binary body omitted]\"")
      }
    }

    curl.append(" \"").append(url).append("\"")
    return curl.toString()
  }
}


Review comment (suggestion):
It might be better to use `Buffer` here, because we would append request body

Code after:
  }

  /**
   * Returns a cURL command equivalent to this request, useful for debugging and reproducing requests.
   *
   * This includes the HTTP method, headers, request body (if present), and URL.
   *
   * Example:
   * ```
   * curl -X POST -H "Authorization: Bearer token" --data "{\"key\":\"value\"}" "https://example.com/api"
   * ```
   *
   * **Note:** This method will write the body
   * to a temporary [okio.Buffer] in memory. This may have side effects if the [RequestBody] is streaming
   * or can be consumed only once. Calling this method might prevent re-sending the request body later.
   *
   * @param binaryFileName default file name to use when dumping binary body data to a file (default: `"request_body.bin"`)
   * @param binaryMode default mode to use when writing binary body data (default: `"BinaryMode.STDIN"`)
   * @return a cURL command string representing this request.
   */
  @JvmOverloads
  fun toCurl(
    binaryMode: BinaryMode = BinaryMode.STDIN,
    binaryFileName: String? = "request_body.bin",
  ): String {
    val curl = StringBuilder("curl")

    // Add method if not GET
    if (method != "GET") {
      curl.append(" -X ").append(method)
    }

    // Append headers
    for ((name, value) in headers) {
      curl
        .append(" -H \"")
        .append(name)
        .append(": ")
        .append(value)
        .append("\"")
    }

    // Append body if present
    body?.let { requestBody ->
      val buffer = Buffer()
      requestBody.writeTo(buffer)

      // Clone so we can read multiple times without consuming
      val peekBuffer = buffer.clone()
      val isBinary = isBinaryData(peekBuffer)
Repository: square/okhttp
File: okhttp/src/commonJvmAndroid/kotlin/okhttp3/Request.kt (Kotlin)

Code before:
          }
        }
      } else {
        val bodyString = buffer.readString(StandardCharsets.UTF_8)
        curl
          .append(" --data \"")
          .append(bodyString.replace("\"", "\\\""))
          .append("\"")
      }
    }

    curl.append(" \"").append(url).append("\"")
    return curl.toString()
  }

  /**
   * Detects binary data by checking for non-printable characters in a buffer.
   */
  private fun isBinaryData(buffer: Buffer): Boolean {
    val peekBuffer = buffer.clone()
    var totalBytes = 0
    var binaryCount = 0

    while (!peekBuffer.exhausted() && totalBytes < 4096) { // limit to first 4KB for performance
      val b = peekBuffer.readByte().toInt() and 0xFF
      if ((b < 0x20 && b !in listOf(0x09, 0x0A, 0x0D)) || b > 0x7E) {
        binaryCount++
      }
      totalBytes++
    }

    return totalBytes > 0 && binaryCount > totalBytes * 0.1
  }
}


Review comment (suggestion):
`List<Integer>` is not good...
`intArrayOf` or `byteArrayOf` should be here, or directly `b != 0x09 || b != 0x0A || b != 0x0D`

Code after:
          }
          BinaryMode.STDIN -> {
            curl.append(" --data-binary @-")
          }
          BinaryMode.OMIT -> {
            curl.append(" --data-binary \"[binary body omitted]\"")
          }
        }
      } else {
        val bodyString = buffer.readString(StandardCharsets.UTF_8)
        curl
          .append(" --data \"")
          .append(bodyString.replace("\"", "\\\""))
          .append("\"")
      }
    }

    curl.append(" \"").append(url).append("\"")
    return curl.toString()
  }

  /**
   * Detects binary data by checking for non-printable characters in a buffer.
   */
  private fun isBinaryData(peekBuffer: Buffer): Boolean {
    var totalBytes = 0
    var binaryCount = 0
    val textSafeBytes = intArrayOf(0x09, 0x0A, 0x0D) // tab, LF, CR

    while (!peekBuffer.exhausted() && totalBytes < 4096) { // limit to first 4KB for performance
      val b = peekBuffer.readByte().toInt() and 0xFF
      if ((b < 0x20 && b !in textSafeBytes) || b > 0x7E) {
        binaryCount++
      }
      totalBytes++
    }

    return totalBytes > 0 && binaryCount > totalBytes * 0.1
  }
}
Repository: square/okhttp
File: okcurl/src/test/kotlin/okhttp3/curl/OkcurlTest.kt (Kotlin)

Code before:
/*
 * Copyright (C) 2014 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.curl

import com.github.ajalt.clikt.core.main
import kotlin.test.Test

class OkcurlTest {
  @Test
  fun simple() {
    Main().main(listOf("--help"))
  }
}


Review comment (suggestion):
This whole test seems redundant with `MainTest` which already parses, binds, and runs the `Main` command many times.

Code after:
/*
 * Copyright (C) 2014 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.curl

import com.github.ajalt.clikt.core.main
import kotlin.test.BeforeTest
import kotlin.test.Test
import okhttp3.TestUtil.assumeNotWindows

class OkcurlTest {
  @BeforeTest
  fun skipWindows() {
    // Failing with
    // org.gradle.internal.remote.internal.MessageIOException: Could not write '/127.0.0.1:16225'.
    assumeNotWindows()
  }

  @Test
  fun simple() {
    Main().main(listOf("--help"))
  }
}
Repository: square/okhttp
File: okhttp/src/androidMain/kotlin/okhttp3/OkHttp.android.kt (Kotlin)

Code before:
package okhttp3

import android.content.Context
import okhttp3.internal.CONST_VERSION
import okhttp3.internal.platform.Platform
import okhttp3.internal.platform.PlatformRegistry

actual object OkHttp {
  @JvmStatic
  actual val Version: String = CONST_VERSION

  @Suppress("MayBeConstant") // Non-const so external callers get the runtime version.
  @JvmField
  @Deprecated(level = DeprecationLevel.WARNING, message = "Replaced with Version", replaceWith = ReplaceWith("Version"))
  val VERSION: String = CONST_VERSION

  /**
   * Configure the ApplicationContext. Not needed unless the AndroidX Startup [Initializer] is disabled, or running
   * a robolectric test.
   *
   * The functionality that will fail without a valid Context is primarily Cookies and URL Domain handling, but
   * may expand in the future.
   */
  fun initialize(applicationContext: Context) {
    if (PlatformRegistry.applicationContext != null) {
      Platform.get().log("Ignoring OkHttp.initialize as applicationContext already initialised")
    } else {
      // Make sure we aren't using an Activity or Service Context
      PlatformRegistry.applicationContext = applicationContext.applicationContext
    }
  }
}


Review comment (bug):
Why log? It seems like the kind of log message that isn’t actionable enough. I’d rather we either fail with an exception (so the developer can fix it) or silently fail (because who cares?)

Code after:
/*
 * Copyright (C) 2025 Block, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3

import android.content.Context
import okhttp3.internal.CONST_VERSION
import okhttp3.internal.platform.PlatformRegistry

actual object OkHttp {
  @JvmField
  actual val VERSION: String = CONST_VERSION

  /**
   * Configure the ApplicationContext. Not needed unless the AndroidX Startup [Initializer] is disabled, or running
   * a robolectric test.
   *
   * The functionality that will fail without a valid Context is primarily Cookies and URL Domain handling, but
   * may expand in the future.
   */
  fun initialize(applicationContext: Context) {
    if (PlatformRegistry.applicationContext == null) {
      // Make sure we aren't using an Activity or Service Context
      PlatformRegistry.applicationContext = applicationContext.applicationContext
    }
  }
}
Repository: square/okhttp
File: okhttp-zstd/src/main/kotlin/okhttp3/zstd/ZstdInterceptor.kt (Kotlin)

Code before:
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.zstd

import com.squareup.zstd.okio.zstdDecompress
import okhttp3.CompressionInterceptor
import okio.BufferedSource
import okio.Source

/**
 * Transparent Zstandard response support.
 *
 * This must be installed as an application interceptor.
 *
 * Adds `Accept-Encoding: zstd,gzip` to request and checks (and strips) for `Content-Encoding: zstd`
 * in responses.
 *
 * This replaces the transparent gzip compression in OkHttp.
 */
object ZstdInterceptor : CompressionInterceptor(Zstd, Gzip)

val Zstd =
  object : CompressionInterceptor.DecompressionAlgorithm {
    override val encoding: String = "zstd"

    override fun BufferedSource.decompress(): Source = this.zstdDecompress()
  }


Review comment (refactor):
We can remove this object from the public API. We haven’t published a release with it yet, and with your new API the caller can do something almost as good:

```kotlin
val client = OkHttpClient.Builder()
  .addInterceptor(CompressionInterceptor(Zstd, Gzip))
  .build()
```

Code after:
/*
 * Copyright (C) 2025 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.zstd

import com.squareup.zstd.okio.zstdDecompress
import okhttp3.CompressionInterceptor
import okio.BufferedSource
import okio.Source

/**
 * Support for Zstandard encoding. Use via the [CompressionInterceptor].
 */
val Zstd =
  object : CompressionInterceptor.DecompressionAlgorithm {
    override val encoding: String = "zstd"

    override fun decompress(compressedSource: BufferedSource): Source = compressedSource.zstdDecompress()
  }
Repository: square/okhttp
File: okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/BufferedSocket.kt (Kotlin)

Code before:
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.internal.connection

import java.net.Socket as JavaNetSocket
import okio.BufferedSink
import okio.BufferedSource
import okio.Socket
import okio.Socket as OkioSocket
import okio.asOkioSocket
import okio.buffer

interface BufferedSocket : OkioSocket {
  override val source: BufferedSource
  override val sink: BufferedSink
}

fun JavaNetSocket.asBufferedSocket(): BufferedSocket = asOkioSocket().asBufferedSocket()

fun Socket.asBufferedSocket(): BufferedSocket =
  object : BufferedSocket {
    private val delegate = this@asBufferedSocket
    override val source = delegate.source.buffer()
    override val sink = delegate.sink.buffer()

    override fun cancel() {
      delegate.cancel()
    }
  }


Review comment (suggestion):
```suggestion
fun OkioSocket.asBufferedSocket(): BufferedSocket =
```
You have this imported twice as two different names

Code after:
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.internal.connection

import java.net.Socket as JavaNetSocket
import okio.BufferedSink
import okio.BufferedSource
import okio.Socket as OkioSocket
import okio.asOkioSocket
import okio.buffer

interface BufferedSocket : OkioSocket {
  override val source: BufferedSource
  override val sink: BufferedSink
}

fun JavaNetSocket.asBufferedSocket(): BufferedSocket = asOkioSocket().asBufferedSocket()

fun OkioSocket.asBufferedSocket(): BufferedSocket =
  object : BufferedSocket {
    private val delegate = this@asBufferedSocket
    override val source = delegate.source.buffer()
    override val sink = delegate.sink.buffer()

    override fun cancel() {
      delegate.cancel()
    }
  }
Repository: square/okhttp
File: okhttp/src/commonJvmAndroid/kotlin/okhttp3/CompressionInterceptor.kt (Kotlin)

Code before:
      .removeHeader("Content-Encoding")
      .removeHeader("Content-Length")
      .body(decompressedSource.asResponseBody(body.contentType(), -1))
      .build()
  }

  internal fun lookupDecompressor(encoding: String): DecompressionAlgorithm? =
    algorithms.find {
      it.encoding.equals(encoding, ignoreCase = true)
    }

  /**
   * A decompression algorithm such as Gzip. Must provide the Accept-Encoding value and decompress a Source.
   */
  interface DecompressionAlgorithm {
    val encoding: String

    fun decompress(compressedSource: BufferedSource): Source
  }

  companion object {
    /**
     * Request "gzip" compression.
     */
    @JvmField
    public val Gzip =
      object : DecompressionAlgorithm {
        override val encoding: String = "gzip"

        override fun decompress(compressedSource: BufferedSource): Source = GzipSource(compressedSource)
      }
  }
}


Review comment (suggestion):
Make this a top-level object so Java people can do this?

```java
CompressionInterceptor interceptor = new CompressionInterceptor(
      Zstd.INSTANCE,
      Gzip.INSTANCE,
      Brotli.INSTANCE
)
```

Code after:
      .removeHeader("Content-Encoding")
      .removeHeader("Content-Length")
      .body(decompressedSource.asResponseBody(body.contentType(), -1))
      .build()
  }

  internal fun lookupDecompressor(encoding: String): DecompressionAlgorithm? =
    algorithms.find {
      it.encoding.equals(encoding, ignoreCase = true)
    }

  /**
   * A decompression algorithm such as Gzip. Must provide the Accept-Encoding value and decompress a Source.
   */
  interface DecompressionAlgorithm {
    val encoding: String

    fun decompress(compressedSource: BufferedSource): Source
  }

  companion object {
    /**
     * Request "gzip" compression.
     */
    @JvmField
    public val Gzip =
      object : DecompressionAlgorithm {
        override val encoding: String get() = "gzip"

        override fun decompress(compressedSource: BufferedSource): Source = GzipSource(compressedSource)
      }
  }
}
Repository: square/okhttp
File: okhttp-brotli/src/main/kotlin/okhttp3/brotli/BrotliInterceptor.kt (Kotlin)

Code before:
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.brotli

import okhttp3.CompressionInterceptor
import okio.BufferedSource
import okio.Source
import okio.source
import org.brotli.dec.BrotliInputStream

/**
 * Transparent Brotli response support.
 *
 * Adds Accept-Encoding: br to request and checks (and strips) for Content-Encoding: br in
 * responses.  n.b. this replaces the transparent gzip compression in BridgeInterceptor.
 */
object BrotliInterceptor : CompressionInterceptor(Brotli, Gzip)

object Brotli : CompressionInterceptor.DecompressionAlgorithm {
  override val encoding: String = "br"

  override fun decompress(compressedSource: BufferedSource): Source = BrotliInputStream(compressedSource.inputStream()).source()
}


Review comment (suggestion):
no backing field needed
```suggestion
  override val encoding: String get() = "br"
```

Code after:
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.brotli

import okhttp3.CompressionInterceptor
import okio.BufferedSource
import okio.Source
import okio.source
import org.brotli.dec.BrotliInputStream

/**
 * Transparent Brotli response support.
 *
 * Adds Accept-Encoding: br to request and checks (and strips) for Content-Encoding: br in
 * responses.  n.b. this replaces the transparent gzip compression in BridgeInterceptor.
 */
object BrotliInterceptor : CompressionInterceptor(Brotli, Gzip)

object Brotli : CompressionInterceptor.DecompressionAlgorithm {
  override val encoding: String get() = "br"

  override fun decompress(compressedSource: BufferedSource): Source = BrotliInputStream(compressedSource.inputStream()).source()
}
Repository: square/okhttp
File: okhttp-zstd/src/main/kotlin/okhttp3/zstd/Zstd.kt (Kotlin)

Code before:
 * Copyright (C) 2025 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.zstd

import com.squareup.zstd.okio.zstdDecompress
import okhttp3.CompressionInterceptor
import okio.BufferedSource
import okio.Source

/**
 * Support for Zstandard encoding. Use via the [CompressionInterceptor].
 */
object Zstd : CompressionInterceptor.DecompressionAlgorithm {
  override val encoding: String = "zstd"

  override fun decompress(compressedSource: BufferedSource): Source = compressedSource.zstdDecompress()
}


Review comment (suggestion):
```suggestion
  override val encoding: String get() = "zstd"
```

Code after:
 * Copyright (C) 2025 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.zstd

import com.squareup.zstd.okio.zstdDecompress
import okhttp3.CompressionInterceptor
import okio.BufferedSource
import okio.Source

/**
 * Support for Zstandard encoding. Use via the [CompressionInterceptor].
 */
object Zstd : CompressionInterceptor.DecompressionAlgorithm {
  override val encoding: String get() = "zstd"

  override fun decompress(compressedSource: BufferedSource): Source = compressedSource.zstdDecompress()
}
Repository: square/okhttp
File: okhttp/src/commonJvmAndroid/kotlin/okhttp3/CompressionInterceptor.kt (Kotlin)

Code before:
      .body(decompressedSource.asResponseBody(body.contentType(), -1))
      .build()
  }

  internal fun lookupDecompressor(encoding: String): DecompressionAlgorithm? =
    algorithms.find {
      it.encoding.equals(encoding, ignoreCase = true)
    }

  /**
   * A decompression algorithm such as Gzip. Must provide the Accept-Encoding value and decompress a Source.
   */
  interface DecompressionAlgorithm {
    val encoding: String

    fun decompress(compressedSource: BufferedSource): Source
  }

  companion object {
    /**
     * Request "gzip" compression.
     */
    @JvmField
    public val Gzip =
      object : DecompressionAlgorithm {
        override val encoding: String = "gzip"

        override fun decompress(compressedSource: BufferedSource): Source = GzipSource(compressedSource)
      }
  }
}


Review comment (suggestion):
```suggestion
        override val encoding: String get() = "gzip"
```

Code after:
      .body(decompressedSource.asResponseBody(body.contentType(), -1))
      .build()
  }

  internal fun lookupDecompressor(encoding: String): DecompressionAlgorithm? =
    algorithms.find {
      it.encoding.equals(encoding, ignoreCase = true)
    }

  /**
   * A decompression algorithm such as Gzip. Must provide the Accept-Encoding value and decompress a Source.
   */
  interface DecompressionAlgorithm {
    val encoding: String

    fun decompress(compressedSource: BufferedSource): Source
  }

  companion object {
    /**
     * Request "gzip" compression.
     */
    @JvmField
    public val Gzip =
      object : DecompressionAlgorithm {
        override val encoding: String get() = "gzip"

        override fun decompress(compressedSource: BufferedSource): Source = GzipSource(compressedSource)
      }
  }
}