Skip to content

Commit

Permalink
Remove usage to toDuration()
Browse files Browse the repository at this point in the history
The toDuration() function was only introduced in Kotlin 1.6. If using
okhttp3 as part of a gradle 7.4.2 plugin it will run with Kotlin 1.5.31
in the runtime classpath, which results in a NoSuchMethodError.
  • Loading branch information
staktrace committed Jun 13, 2022
1 parent da6c06d commit fd547c5
Showing 1 changed file with 14 additions and 7 deletions.
Expand Up @@ -18,9 +18,9 @@

package okhttp3.internal

import kotlin.time.Duration
import kotlin.time.DurationUnit
import kotlin.time.ExperimentalTime
import kotlin.time.toDuration
import okhttp3.CacheControl
import okhttp3.Headers

Expand Down Expand Up @@ -50,20 +50,20 @@ internal fun CacheControl.commonToString(): String {

internal fun CacheControl.Builder.commonMaxAge(maxAge: Int, timeUnit: DurationUnit) = apply {
require(maxAge >= 0) { "maxAge < 0: $maxAge" }
val maxAgeSecondsLong = maxAge.toDuration(timeUnit).inWholeSeconds
this.maxAgeSeconds = maxAgeSecondsLong.commonClampToInt()
val maxAgeSecondsDouble = Duration.convert(maxAge.toDouble(), timeUnit, DurationUnit.SECONDS)
this.maxAgeSeconds = maxAgeSecondsDouble.commonClampToInt()
}

internal fun CacheControl.Builder.commonMaxStale(maxStale: Int, timeUnit: DurationUnit) = apply {
require(maxStale >= 0) { "maxStale < 0: $maxStale" }
val maxStaleSecondsLong = maxStale.toDuration(timeUnit).inWholeSeconds
this.maxStaleSeconds = maxStaleSecondsLong.commonClampToInt()
val maxStaleSecondsDouble = Duration.convert(maxStale.toDouble(), timeUnit, DurationUnit.SECONDS)
this.maxStaleSeconds = maxStaleSecondsDouble.commonClampToInt()
}

internal fun CacheControl.Builder.commonMinFresh(minFresh: Int, timeUnit: DurationUnit) = apply {
require(minFresh >= 0) { "minFresh < 0: $minFresh" }
val minFreshSecondsLong = minFresh.toDuration(timeUnit).inWholeSeconds
this.minFreshSeconds = minFreshSecondsLong.commonClampToInt()
val minFreshSecondsDouble = Duration.convert(minFresh.toDouble(), timeUnit, DurationUnit.SECONDS)
this.minFreshSeconds = minFreshSecondsDouble.commonClampToInt()
}

internal fun Long.commonClampToInt(): Int {
Expand All @@ -73,6 +73,13 @@ internal fun Long.commonClampToInt(): Int {
}
}

internal fun Double.commonClampToInt(): Int {
return when {
this > Int.MAX_VALUE -> Int.MAX_VALUE
else -> toInt()
}
}

internal fun CacheControl.Companion.commonForceNetwork() = CacheControl.Builder()
.noCache()
.build()
Expand Down

0 comments on commit fd547c5

Please sign in to comment.