import Foundation /// A Mutex protects a value with an NSLock. /// /// We'll replace it with the SE-0433 Mutex when it is available. /// final class Mutex { private var _value: T private var lock = NSLock() init(_ value: T) { _value = value } /// Runs the provided closure while holding a lock on the value. /// /// - parameter body: A closure that can modify the value. func withLock(_ body: (inout T) throws -> U) rethrows -> U { lock.lock() defer { lock.unlock() } return try body(&_value) } } // Inspired by extension Mutex { func load() -> T { withLock { $0 } } func store(_ value: T) { withLock { $0 = value } } } extension Mutex where T: Numeric { @discardableResult func increment() -> T { withLock { n in n += 1 return n } } @discardableResult func decrement() -> T { withLock { n in n -= 1 return n } } } extension Mutex: @unchecked Sendable where T: Sendable { } // MARK: - UnsafeSendableMutex /// `UnsafeSendableMutex` is a Mutex that is always Sendable. It is unsafe, /// because it does not guarantee that its value won't escape from the /// critical section. /// /// We'll replace it with the SE-0433 Mutex when it is available. /// /// /// For a longer discussion about Sendable and mutexes, see /// final class UnsafeSendableMutex: @unchecked Sendable { private var _value: T private var lock = NSLock() init(_ value: sending T) { _value = value } /// Runs the provided closure while holding a lock on the value. /// /// - parameter body: A closure that can modify the value. func withLock(_ body: (inout T) throws -> U) rethrows -> U { lock.lock() defer { lock.unlock() } return try body(&_value) } }