Scoop API

scoop:scoop.core:0.1.0

src/resources.scoop

Selected production source · src/resources.scoop

1/**
2 * A resource with explicit cleanup. Whether repeated disposal is accepted is specified by each
3 * implementation.
4 */
5public interface Disposable {
6 /**
7 * Releases the resource according to the implementation's ownership contract.
8 */
9 public fun dispose()
12/**
13 * A disposable resource whose cleanup operation is named close.
14 */
15public interface Closeable : Disposable {
16 /**
17 * Closes the resource according to its ownership contract.
18 */
19 public fun close()
20 /**
21 * Delegates disposal to close.
22 */
23 public override fun dispose() { close() }
26/**
27 * Preserves both failures when a resource body and its cleanup throw.
28 */
29public class ResourceUseException public constructor(
30 /**
31 * The exception thrown by the resource body.
32 */
33 public val primaryFailure: Throwable,
34 /**
35 * The exception thrown while disposing the resource after the body failed.
36 */
37 public val cleanupFailure: Throwable
38) : Exception(Some("resource body and cleanup both failed"))
40/**
41 * Runs the block and always disposes the receiver on exit, including exceptional exit. If both
42 * body and cleanup fail, throws ResourceUseException containing both failures.
43 */
44public fun <T : Disposable, R> T.use(block: (T) -> R): R {
45 val result = try {
46 block(this)
47 } catch (primary: Throwable) {
48 try {
49 dispose()
50 } catch (cleanup: Throwable) {
51 throw ResourceUseException(primary, cleanup)
52 }
53 throw primary
54 }
55 dispose()
56 return result
59/**
60 * Runs the block and always disposes the receiver on exit, including exceptional exit. If both
61 * body and cleanup fail, throws ResourceUseException containing both failures.
62 */
63public suspend fun <T : Disposable, R> T.use(block: suspend (T) -> R): R {
64 val result = try {
65 block(this)
66 } catch (primary: Throwable) {
67 try {
68 dispose()
69 } catch (cleanup: Throwable) {
70 throw ResourceUseException(primary, cleanup)
71 }
72 throw primary
73 }
74 dispose()
75 return result