Protected.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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: () 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. /// An `os_unfair_lock` wrapper.
  49. final class UnfairLock: Lock {
  50. private let unfairLock: os_unfair_lock_t
  51. init() {
  52. unfairLock = .allocate(capacity: 1)
  53. unfairLock.initialize(to: os_unfair_lock())
  54. }
  55. deinit {
  56. unfairLock.deinitialize(count: 1)
  57. unfairLock.deallocate()
  58. }
  59. fileprivate func lock() {
  60. os_unfair_lock_lock(unfairLock)
  61. }
  62. fileprivate func unlock() {
  63. os_unfair_lock_unlock(unfairLock)
  64. }
  65. }
  66. #elseif canImport(Foundation)
  67. extension NSLock: Lock {}
  68. #else
  69. #error("This platform needs a Lock-conforming type without Foundation.")
  70. #endif
  71. /// A thread-safe wrapper around a value.
  72. @dynamicMemberLookup
  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 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. subscript<Property>(dynamicMember keyPath: WritableKeyPath<Value, Property>) -> Property {
  109. get { lock.around { value[keyPath: keyPath] } }
  110. set { lock.around { value[keyPath: keyPath] = newValue } }
  111. }
  112. subscript<Property>(dynamicMember keyPath: KeyPath<Value, Property>) -> Property {
  113. lock.around { value[keyPath: keyPath] }
  114. }
  115. }
  116. extension Protected where Value == Request.MutableState {
  117. /// Attempts to transition to the passed `State`.
  118. ///
  119. /// - Parameter state: The `State` to attempt transition to.
  120. ///
  121. /// - Returns: Whether the transition occurred.
  122. func attemptToTransitionTo(_ state: Request.State) -> Bool {
  123. lock.around {
  124. guard value.state.canTransitionTo(state) else { return false }
  125. value.state = state
  126. return true
  127. }
  128. }
  129. /// Perform a closure while locked with the provided `Request.State`.
  130. ///
  131. /// - Parameter perform: The closure to perform while locked.
  132. func withState(perform: (Request.State) -> Void) {
  133. lock.around { perform(value.state) }
  134. }
  135. }
  136. extension Protected: Equatable where Value: Equatable {
  137. static func ==(lhs: Protected<Value>, rhs: Protected<Value>) -> Bool {
  138. lhs.read { left in rhs.read { right in left == right }}
  139. }
  140. }
  141. extension Protected: Hashable where Value: Hashable {
  142. func hash(into hasher: inout Hasher) {
  143. read { hasher.combine($0) }
  144. }
  145. }