|
| 1 | +// |
| 2 | +// Locked.swift |
| 3 | +// YUKLock |
| 4 | +// |
| 5 | +// Created by Ruslan Lutfullin on 2/7/21. |
| 6 | +// |
| 7 | + |
| 8 | +// MARK: - |
| 9 | +@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *) |
| 10 | +@propertyWrapper |
| 11 | +@dynamicMemberLookup |
| 12 | +public final class Locked<Value, LockType: Lock> { |
| 13 | + // MARK: Internal Props |
| 14 | + @usableFromInline internal let lock = LockType() |
| 15 | + @usableFromInline internal var value: Value |
| 16 | + |
| 17 | + // MARK: Public Props |
| 18 | + public var wrappedValue: Value { |
| 19 | + _read { |
| 20 | + lock.lock() |
| 21 | + defer { |
| 22 | + lock.unlock() |
| 23 | + } |
| 24 | + yield value |
| 25 | + } |
| 26 | + _modify { |
| 27 | + lock.lock() |
| 28 | + defer { |
| 29 | + lock.unlock() |
| 30 | + } |
| 31 | + yield &value |
| 32 | + } |
| 33 | + } |
| 34 | + public var projectedValue: Locked { self } |
| 35 | + |
| 36 | + // MARK: Public Methods |
| 37 | + @inlinable public func read<T>(_ body: (Value) throws -> T) rethrows -> T? { |
| 38 | + try lock.trySync { try body(value) } |
| 39 | + } |
| 40 | + @inlinable @discardableResult public func write<T>(_ body: (inout Value) throws -> T) rethrows -> T? { |
| 41 | + try lock.trySync { try body(&value) } |
| 42 | + } |
| 43 | + |
| 44 | + // MARK: Public Subscripts |
| 45 | + @inlinable public subscript<Property>(dynamicMember keyPath: KeyPath<Value, Property>) -> Property { |
| 46 | + lock.sync { value[keyPath: keyPath] } |
| 47 | + } |
| 48 | + @inlinable public subscript<Property>(dynamicMember keyPath: WritableKeyPath<Value, Property>) -> Property { |
| 49 | + get { |
| 50 | + lock.sync { value[keyPath: keyPath] } |
| 51 | + } |
| 52 | + set { |
| 53 | + lock.sync { value[keyPath: keyPath] = newValue } |
| 54 | + } |
| 55 | + } |
| 56 | + @inlinable public subscript<Property>(dynamicMember keyPath: ReferenceWritableKeyPath<Value, Property>) -> Property { |
| 57 | + get { |
| 58 | + lock.sync { value[keyPath: keyPath] } |
| 59 | + } |
| 60 | + set { |
| 61 | + lock.sync { value[keyPath: keyPath] = newValue } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + // MARK: Public Inits |
| 66 | + @inlinable public init(wrappedValue: Value) { |
| 67 | + value = wrappedValue |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +// MARK: - |
| 72 | +@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *) |
| 73 | +public typealias UnfairLocked<Value> = Locked<Value, UnfairLock> |
| 74 | + |
| 75 | +// MARK: - |
| 76 | +@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *) |
| 77 | +public typealias RecursiveLocked<Value> = Locked<Value, RecursiveLock> |
0 commit comments