Protected.swift 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. final class Protected<Value> {
  74. #if canImport(Darwin)
  75. private let lock = UnfairLock()
  76. #elseif canImport(Foundation)
  77. private let lock = NSLock()
  78. #else
  79. #error("This platform needs a Lock-conforming type without Foundation.")
  80. #endif
  81. private nonisolated(unsafe) var value: Value
  82. init(_ value: Value) {
  83. self.value = value
  84. }
  85. /// Synchronously read or transform the contained value.
  86. ///
  87. /// - Parameter closure: The closure to execute.
  88. ///
  89. /// - Returns: The return value of the closure passed.
  90. func read<U>(_ closure: (Value) throws -> U) rethrows -> U {
  91. try lock.around { try closure(self.value) }
  92. }
  93. /// Synchronously modify the protected value.
  94. ///
  95. /// - Parameter closure: The closure to execute.
  96. ///
  97. /// - Returns: The modified value.
  98. @discardableResult
  99. func write<U>(_ closure: (inout Value) throws -> U) rethrows -> U {
  100. try lock.around { try closure(&self.value) }
  101. }
  102. /// Synchronously update the protected value.
  103. ///
  104. /// - Parameter value: The `Value`.
  105. func write(_ value: Value) {
  106. write { $0 = value }
  107. }
  108. }
  109. #if compiler(>=6)
  110. extension Protected: Sendable {}
  111. #endif
  112. extension Protected where Value == Request.MutableState {
  113. /// Attempts to transition to the passed `State`.
  114. ///
  115. /// - Parameter state: The `State` to attempt transition to.
  116. ///
  117. /// - Returns: Whether the transition occurred.
  118. func attemptToTransitionTo(_ state: Request.State) -> Bool {
  119. lock.around {
  120. guard value.state.canTransitionTo(state) else { return false }
  121. value.state = state
  122. return true
  123. }
  124. }
  125. /// Perform a closure while locked with the provided `Request.State`.
  126. ///
  127. /// - Parameter perform: The closure to perform while locked.
  128. func withState(perform: (Request.State) -> Void) {
  129. lock.around { perform(value.state) }
  130. }
  131. }
  132. extension Protected: Equatable where Value: Equatable {
  133. static func ==(lhs: Protected<Value>, rhs: Protected<Value>) -> Bool {
  134. lhs.read { left in rhs.read { right in left == right }}
  135. }
  136. }
  137. extension Protected: Hashable where Value: Hashable {
  138. func hash(into hasher: inout Hasher) {
  139. read { hasher.combine($0) }
  140. }
  141. }