Skip to content

Commit

Permalink
Fix Closeable.use NullPointerException (#1453)
Browse files Browse the repository at this point in the history
* Fix Cloneable.use NullPointerException

* Add assertNull
  • Loading branch information
05nelsonm committed Mar 5, 2024
1 parent 940496a commit fe6ac99
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
9 changes: 5 additions & 4 deletions okio/src/commonMain/kotlin/okio/Okio.kt
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@ private class BlackholeSink : Sink {

/** Execute [block] then close this. This will be closed even if [block] throws. */
inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
var result: R? = null
var thrown: Throwable? = null

try {
result = block(this)
val result = try {
block(this)
} catch (t: Throwable) {
thrown = t
null
} finally {
try {
this?.close()
Expand All @@ -69,5 +69,6 @@ inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
}

if (thrown != null) throw thrown
return result!!
@Suppress("UNCHECKED_CAST")
return result as R
}
10 changes: 10 additions & 0 deletions okio/src/nonWasmTest/kotlin/okio/UseTest.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package okio

import kotlin.test.Test
import kotlin.test.assertNull
import okio.Path.Companion.toPath
import okio.fakefilesystem.FakeFileSystem

Expand All @@ -25,4 +26,13 @@ class UseTest {

fakeFileSystem.checkNoOpenFiles()
}

@Test
fun acceptsNullReturn() {
val result = object : Closeable {
override fun close() {}
}.use { null }

assertNull(result)
}
}

0 comments on commit fe6ac99

Please sign in to comment.