async.swift (2257B)
1 // radroots-swift-cancellation-v1. Only the observing Rust future is cancelled; 2 // admitted work and obtained material remain owned by the shared runtime. 3 // NSLock serializes cancel against release. The unchecked Sendable owner has 4 // no unsynchronized mutable state; its immutable C callback is Sendable. 5 fileprivate final class UniffiRustCancellation: @unchecked Sendable { 6 private let lock = NSLock() 7 private var handle: UInt64? 8 private let cancelFunction: @Sendable (UInt64) -> Void 9 init(_ handle: UInt64, _ cancelFunction: @escaping @Sendable (UInt64) -> Void) { 10 self.handle = handle 11 self.cancelFunction = cancelFunction 12 } 13 func cancel() { 14 lock.lock() 15 defer { lock.unlock() } 16 if let handle { cancelFunction(handle) } 17 } 18 func finish() { 19 lock.lock() 20 defer { lock.unlock() } 21 handle = nil 22 } 23 } 24 25 fileprivate func uniffiRustCallAsync<F, T>( 26 rustFutureFunc: () -> UInt64, 27 pollFunc: (UInt64, @escaping UniffiRustFutureContinuationCallback, UInt64) -> (), 28 completeFunc: (UInt64, UnsafeMutablePointer<RustCallStatus>) -> F, 29 cancelFunc: @escaping @Sendable (UInt64) -> Void, 30 freeFunc: (UInt64) -> (), 31 liftFunc: (F) throws -> T, 32 errorHandler: ((RustBuffer) throws -> Swift.Error)? 33 ) async throws -> T { 34 try Task.checkCancellation() 35 __RADROOTS_ENSURE_INIT__ 36 let handle = rustFutureFunc() 37 let cancellation = UniffiRustCancellation(handle, cancelFunc) 38 defer { 39 cancellation.finish() 40 freeFunc(handle) 41 } 42 return try await withTaskCancellationHandler { 43 var ready: Int8 44 repeat { 45 ready = await withUnsafeContinuation { continuation in 46 let callbackHandle = uniffiContinuationHandleMap.insert(obj: continuation) 47 pollFunc(handle, { callbackHandle, status in 48 uniffiFutureContinuationCallback(handle: callbackHandle, pollResult: status) 49 }, callbackHandle) 50 } 51 } while ready != UNIFFI_RUST_FUTURE_POLL_READY 52 let result = try makeRustCall({ completeFunc(handle, $0) }, errorHandler: errorHandler) 53 return try liftFunc(result) 54 } onCancel: { 55 cancellation.cancel() 56 } 57 }