Created
April 9, 2025 02:46
-
-
Save ObuchiYuki/327817c3dc9b00ba29beb72e6106a7a4 to your computer and use it in GitHub Desktop.
It’s a Continuation that doesn’t leak if not resumed, and if resumed multiple times, it finishes with the first value/error.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
final public class OptionalContinuation<T, E: Error>: Sendable { | |
@usableFromInline let hasResumed = OSAllocatedUnfairLock(initialState: false) | |
@usableFromInline let continuation: CheckedContinuation<T?, E> | |
@inlinable public init(_ continuation: CheckedContinuation<T?, E>) { | |
self.continuation = continuation | |
} | |
@inlinable public func resume(returning value: T) { | |
self.hasResumed.withLock { | |
guard !$0 else { return }; $0 = true | |
self.continuation.resume(returning: value) | |
} | |
} | |
@inlinable public func resume(throwing error: E) { | |
self.hasResumed.withLock { | |
guard !$0 else { return }; $0 = true | |
self.continuation.resume(throwing: error) | |
} | |
} | |
@inlinable deinit { | |
self.hasResumed.withLock { | |
guard !$0 else { return }; $0 = true | |
self.continuation.resume(returning: nil) | |
} | |
} | |
} | |
@inlinable public func withOptionalContinuation<T>( | |
isolation: isolated (any Actor)? = #isolation, | |
function: String = #function, _ body: (OptionalContinuation<T, Never>) -> Void | |
) async -> T? { | |
return await withCheckedContinuation(isolation: isolation, function: function) { continuation in | |
let autoCompleter = OptionalContinuation(continuation) | |
body(autoCompleter) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment