1 /*
2  * Copyright 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.datastore.core
18 
19 /** Datastore common version of java.io.Closeable */
20 @Suppress("NotCloseable") // No closable in KMP common.
21 interface Closeable {
22 
23     /** Closes the specified resource. */
closenull24     fun close()
25 }
26 
27 /**
28  * Ensures a Closeable object has its close() method called at the end of the supplied block.
29  *
30  * @throws Throwable any exceptions thrown in the block will propagate through this method.
31  */
32 @Suppress("NotCloseable", "DocumentExceptions") // No closable in KMP common.
33 inline fun <T : Closeable, R> T.use(block: (T) -> R): R {
34     var thrown: Throwable? = null
35 
36     try {
37         return block(this)
38     } catch (t: Throwable) {
39         thrown = t
40     } finally {
41         try {
42             this.close()
43         } catch (t: Throwable) {
44             if (thrown == null) {
45                 thrown = t
46             } else {
47                 thrown.addSuppressed(t)
48             }
49         }
50 
51         if (thrown != null) {
52             throw thrown
53         }
54     }
55     // We either returned in the try block, or thrown must be not null, so this code is unreachable.
56     error(
57         """Unreachable code. If this occurs, please file a bug here:
58         https://b.corp.google.com/issues/new?component=907884&template=1466542"""
59     )
60 }
61