Protected.swift 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. //
  2. // Protected.swift
  3. //
  4. // Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. private protocol Lock: Sendable {
  26. func lock()
  27. func unlock()
  28. }
  29. extension Lock {
  30. /// Executes a closure returning a value while acquiring the lock.
  31. ///
  32. /// - Parameter closure: The closure to run.
  33. ///
  34. /// - Returns: The value the closure generated.
  35. func around<T>(_ closure: () throws -> T) rethrows -> T {
  36. lock(); defer { unlock() }
  37. return try closure()
  38. }
  39. /// Execute a closure while acquiring the lock.
  40. ///
  41. /// - Parameter closure: The closure to run.
  42. func around(_ closure: () throws -> Void) rethrows {
  43. lock(); defer { unlock() }
  44. try closure()
  45. }
  46. }
  47. #if canImport(Darwin)
  48. // Number of Apple engineers who insisted on inspecting this: 5
  49. /// An `os_unfair_lock` wrapper.
  50. final class UnfairLock: Lock, @unchecked Sendable {
  51. private let unfairLock: os_unfair_lock_t
  52. init() {
  53. unfairLock = .allocate(capacity: 1)
  54. unfairLock.initialize(to: os_unfair_lock())
  55. }
  56. deinit {
  57. unfairLock.deinitialize(count: 1)
  58. unfairLock.deallocate()
  59. }
  60. fileprivate func lock() {
  61. os_unfair_lock_lock(unfairLock)
  62. }
  63. fileprivate func unlock() {
  64. os_unfair_lock_unlock(unfairLock)
  65. }
  66. }
  67. #elseif canImport(Foundation)
  68. extension NSLock: Lock {}
  69. #else
  70. #error("This platform needs a Lock-conforming type without Foundation.")
  71. #endif
  72. /// A thread-safe wrapper around a value.
  73. @dynamicMemberLookup
  74. final class Protected<Value> {
  75. #if canImport(Darwin)
  76. private let lock = UnfairLock()
  77. #elseif canImport(Foundation)
  78. private let lock = NSLock()
  79. #else
  80. #error("This platform needs a Lock-conforming type without Foundation.")
  81. #endif
  82. #if compiler(>=6)
  83. private nonisolated(unsafe) var value: Value
  84. #else
  85. private var value: Value
  86. #endif
  87. init(_ value: Value) {
  88. self.value = value
  89. }
  90. /// Synchronously read or transform the contained value.
  91. ///
  92. /// - Parameter closure: The closure to execute.
  93. ///
  94. /// - Returns: The return value of the closure passed.
  95. func read<U>(_ closure: (Value) throws -> U) rethrows -> U {
  96. try lock.around { try closure(self.value) }
  97. }
  98. /// Synchronously modify the protected value.
  99. ///
  100. /// - Parameter closure: The closure to execute.
  101. ///
  102. /// - Returns: The modified value.
  103. @discardableResult
  104. func write<U>(_ closure: (inout Value) throws -> U) rethrows -> U {
  105. try lock.around { try closure(&self.value) }
  106. }
  107. /// Synchronously update the protected value.
  108. ///
  109. /// - Parameter value: The `Value`.
  110. func write(_ value: Value) {
  111. write { $0 = value }
  112. }
  113. subscript<Property>(dynamicMember keyPath: WritableKeyPath<Value, Property>) -> Property {
  114. get { lock.around { value[keyPath: keyPath] } }
  115. set { lock.around { value[keyPath: keyPath] = newValue } }
  116. }
  117. subscript<Property>(dynamicMember keyPath: KeyPath<Value, Property>) -> Property {
  118. lock.around { value[keyPath: keyPath] }
  119. }
  120. }
  121. #if compiler(>=6)
  122. extension Protected: Sendable {}
  123. #else
  124. extension Protected: @unchecked Sendable {}
  125. #endif
  126. extension Protected where Value == Request.MutableState {
  127. /// Attempts to transition to the passed `State`.
  128. ///
  129. /// - Parameter state: The `State` to attempt transition to.
  130. ///
  131. /// - Returns: Whether the transition occurred.
  132. func attemptToTransitionTo(_ state: Request.State) -> Bool {
  133. lock.around {
  134. guard value.state.canTransitionTo(state) else { return false }
  135. value.state = state
  136. return true
  137. }
  138. }
  139. /// Perform a closure while locked with the provided `Request.State`.
  140. ///
  141. /// - Parameter perform: The closure to perform while locked.
  142. func withState(perform: (Request.State) -> Void) {
  143. lock.around { perform(value.state) }
  144. }
  145. }
  146. extension Protected: Equatable where Value: Equatable {
  147. static func ==(lhs: Protected<Value>, rhs: Protected<Value>) -> Bool {
  148. lhs.read { left in rhs.read { right in left == right }}
  149. }
  150. }
  151. extension Protected: Hashable where Value: Hashable {
  152. func hash(into hasher: inout Hasher) {
  153. read { hasher.combine($0) }
  154. }
  155. }