Protected.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 {
  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: () -> T) -> T {
  36. lock(); defer { unlock() }
  37. return closure()
  38. }
  39. /// Execute a closure while acquiring the lock.
  40. ///
  41. /// - Parameter closure: The closure to run.
  42. func around(_ closure: () -> Void) {
  43. lock(); defer { unlock() }
  44. closure()
  45. }
  46. }
  47. #if os(Linux)
  48. /// A `pthread_mutex_t` wrapper.
  49. final class MutexLock: Lock {
  50. private var mutex: UnsafeMutablePointer<pthread_mutex_t>
  51. init() {
  52. mutex = .allocate(capacity: 1)
  53. var attr = pthread_mutexattr_t()
  54. pthread_mutexattr_init(&attr)
  55. pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK))
  56. let error = pthread_mutex_init(mutex, &attr)
  57. precondition(error == 0, "Failed to create pthread_mutex")
  58. }
  59. deinit {
  60. let error = pthread_mutex_destroy(mutex)
  61. precondition(error == 0, "Failed to destroy pthread_mutex")
  62. }
  63. fileprivate func lock() {
  64. let error = pthread_mutex_lock(mutex)
  65. precondition(error == 0, "Failed to lock pthread_mutex")
  66. }
  67. fileprivate func unlock() {
  68. let error = pthread_mutex_unlock(mutex)
  69. precondition(error == 0, "Failed to unlock pthread_mutex")
  70. }
  71. }
  72. #endif
  73. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
  74. /// An `os_unfair_lock` wrapper.
  75. final class UnfairLock: Lock {
  76. private let unfairLock: os_unfair_lock_t
  77. init() {
  78. unfairLock = .allocate(capacity: 1)
  79. unfairLock.initialize(to: os_unfair_lock())
  80. }
  81. deinit {
  82. unfairLock.deinitialize(count: 1)
  83. unfairLock.deallocate()
  84. }
  85. fileprivate func lock() {
  86. os_unfair_lock_lock(unfairLock)
  87. }
  88. fileprivate func unlock() {
  89. os_unfair_lock_unlock(unfairLock)
  90. }
  91. }
  92. #endif
  93. /// A thread-safe wrapper around a value.
  94. @propertyWrapper
  95. @dynamicMemberLookup
  96. final class Protected<T> {
  97. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
  98. private let lock = UnfairLock()
  99. #elseif os(Linux)
  100. private let lock = MutexLock()
  101. #endif
  102. private var value: T
  103. init(_ value: T) {
  104. self.value = value
  105. }
  106. /// The contained value. Unsafe for anything more than direct read or write.
  107. var wrappedValue: T {
  108. get { lock.around { value } }
  109. set { lock.around { value = newValue } }
  110. }
  111. var projectedValue: Protected<T> { self }
  112. init(wrappedValue: T) {
  113. value = wrappedValue
  114. }
  115. /// Synchronously read or transform the contained value.
  116. ///
  117. /// - Parameter closure: The closure to execute.
  118. ///
  119. /// - Returns: The return value of the closure passed.
  120. func read<U>(_ closure: (T) -> U) -> U {
  121. lock.around { closure(self.value) }
  122. }
  123. /// Synchronously modify the protected value.
  124. ///
  125. /// - Parameter closure: The closure to execute.
  126. ///
  127. /// - Returns: The modified value.
  128. @discardableResult
  129. func write<U>(_ closure: (inout T) -> U) -> U {
  130. lock.around { closure(&self.value) }
  131. }
  132. subscript<Property>(dynamicMember keyPath: WritableKeyPath<T, Property>) -> Property {
  133. get { lock.around { value[keyPath: keyPath] } }
  134. set { lock.around { value[keyPath: keyPath] = newValue } }
  135. }
  136. }
  137. extension Protected where T: RangeReplaceableCollection {
  138. /// Adds a new element to the end of this protected collection.
  139. ///
  140. /// - Parameter newElement: The `Element` to append.
  141. func append(_ newElement: T.Element) {
  142. write { (ward: inout T) in
  143. ward.append(newElement)
  144. }
  145. }
  146. /// Adds the elements of a sequence to the end of this protected collection.
  147. ///
  148. /// - Parameter newElements: The `Sequence` to append.
  149. func append<S: Sequence>(contentsOf newElements: S) where S.Element == T.Element {
  150. write { (ward: inout T) in
  151. ward.append(contentsOf: newElements)
  152. }
  153. }
  154. /// Add the elements of a collection to the end of the protected collection.
  155. ///
  156. /// - Parameter newElements: The `Collection` to append.
  157. func append<C: Collection>(contentsOf newElements: C) where C.Element == T.Element {
  158. write { (ward: inout T) in
  159. ward.append(contentsOf: newElements)
  160. }
  161. }
  162. }
  163. extension Protected where T == Data? {
  164. /// Adds the contents of a `Data` value to the end of the protected `Data`.
  165. ///
  166. /// - Parameter data: The `Data` to be appended.
  167. func append(_ data: Data) {
  168. write { (ward: inout T) in
  169. ward?.append(data)
  170. }
  171. }
  172. }
  173. extension Protected where T == Request.MutableState {
  174. /// Attempts to transition to the passed `State`.
  175. ///
  176. /// - Parameter state: The `State` to attempt transition to.
  177. ///
  178. /// - Returns: Whether the transition occurred.
  179. func attemptToTransitionTo(_ state: Request.State) -> Bool {
  180. lock.around {
  181. guard value.state.canTransitionTo(state) else { return false }
  182. value.state = state
  183. return true
  184. }
  185. }
  186. /// Perform a closure while locked with the provided `Request.State`.
  187. ///
  188. /// - Parameter perform: The closure to perform while locked.
  189. func withState(perform: (Request.State) -> Void) {
  190. lock.around { perform(value.state) }
  191. }
  192. }