Protected.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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 os(Linux) || os(Windows)
  48. extension NSLock: Lock {}
  49. #endif
  50. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
  51. /// An `os_unfair_lock` wrapper.
  52. final class UnfairLock: Lock {
  53. private let unfairLock: os_unfair_lock_t
  54. init() {
  55. unfairLock = .allocate(capacity: 1)
  56. unfairLock.initialize(to: os_unfair_lock())
  57. }
  58. deinit {
  59. unfairLock.deinitialize(count: 1)
  60. unfairLock.deallocate()
  61. }
  62. fileprivate func lock() {
  63. os_unfair_lock_lock(unfairLock)
  64. }
  65. fileprivate func unlock() {
  66. os_unfair_lock_unlock(unfairLock)
  67. }
  68. }
  69. #endif
  70. /// A thread-safe wrapper around a value.
  71. @propertyWrapper
  72. @dynamicMemberLookup
  73. final class Protected<T> {
  74. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
  75. private let lock = UnfairLock()
  76. #elseif os(Linux) || os(Windows)
  77. private let lock = NSLock()
  78. #endif
  79. private var value: T
  80. init(_ value: T) {
  81. self.value = value
  82. }
  83. /// The contained value. Unsafe for anything more than direct read or write.
  84. var wrappedValue: T {
  85. get { lock.around { value } }
  86. set { lock.around { value = newValue } }
  87. }
  88. var projectedValue: Protected<T> { self }
  89. init(wrappedValue: T) {
  90. value = wrappedValue
  91. }
  92. /// Synchronously read or transform the contained value.
  93. ///
  94. /// - Parameter closure: The closure to execute.
  95. ///
  96. /// - Returns: The return value of the closure passed.
  97. func read<U>(_ closure: (T) throws -> U) rethrows -> U {
  98. try lock.around { try closure(self.value) }
  99. }
  100. /// Synchronously modify the protected value.
  101. ///
  102. /// - Parameter closure: The closure to execute.
  103. ///
  104. /// - Returns: The modified value.
  105. @discardableResult
  106. func write<U>(_ closure: (inout T) throws -> U) rethrows -> U {
  107. try lock.around { try closure(&self.value) }
  108. }
  109. subscript<Property>(dynamicMember keyPath: WritableKeyPath<T, Property>) -> Property {
  110. get { lock.around { value[keyPath: keyPath] } }
  111. set { lock.around { value[keyPath: keyPath] = newValue } }
  112. }
  113. subscript<Property>(dynamicMember keyPath: KeyPath<T, Property>) -> Property {
  114. lock.around { value[keyPath: keyPath] }
  115. }
  116. }
  117. extension Protected where T == Request.MutableState {
  118. /// Attempts to transition to the passed `State`.
  119. ///
  120. /// - Parameter state: The `State` to attempt transition to.
  121. ///
  122. /// - Returns: Whether the transition occurred.
  123. func attemptToTransitionTo(_ state: Request.State) -> Bool {
  124. lock.around {
  125. guard value.state.canTransitionTo(state) else { return false }
  126. value.state = state
  127. return true
  128. }
  129. }
  130. /// Perform a closure while locked with the provided `Request.State`.
  131. ///
  132. /// - Parameter perform: The closure to perform while locked.
  133. func withState(perform: (Request.State) -> Void) {
  134. lock.around { perform(value.state) }
  135. }
  136. }