Protector.swift 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. //
  2. // Protector.swift
  3. //
  4. // Copyright (c) 2014-2018 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. // MARK: -
  26. /// An `os_unfair_lock` wrapper.
  27. final class UnfairLock {
  28. private let unfairLock: os_unfair_lock_t
  29. init() {
  30. unfairLock = .allocate(capacity: 1)
  31. unfairLock.initialize(to: os_unfair_lock())
  32. }
  33. deinit {
  34. unfairLock.deinitialize(count: 1)
  35. unfairLock.deallocate()
  36. }
  37. private func lock() {
  38. os_unfair_lock_lock(unfairLock)
  39. }
  40. private func unlock() {
  41. os_unfair_lock_unlock(unfairLock)
  42. }
  43. /// Executes a closure returning a value while acquiring the lock.
  44. ///
  45. /// - Parameter closure: The closure to run.
  46. ///
  47. /// - Returns: The value the closure generated.
  48. func around<T>(_ closure: () -> T) -> T {
  49. lock(); defer { unlock() }
  50. return closure()
  51. }
  52. /// Execute a closure while acquiring the lock.
  53. ///
  54. /// - Parameter closure: The closure to run.
  55. func around(_ closure: () -> Void) {
  56. lock(); defer { unlock() }
  57. return closure()
  58. }
  59. }
  60. /// A thread-safe wrapper around a value.
  61. final class Protector<T> {
  62. private let lock = UnfairLock()
  63. private var value: T
  64. init(_ value: T) {
  65. self.value = value
  66. }
  67. /// The contained value. Unsafe for anything more than direct read or write.
  68. var directValue: T {
  69. get { return lock.around { value } }
  70. set { lock.around { value = newValue } }
  71. }
  72. /// Synchronously read or transform the contained value.
  73. ///
  74. /// - Parameter closure: The closure to execute.
  75. ///
  76. /// - Returns: The return value of the closure passed.
  77. func read<U>(_ closure: (T) -> U) -> U {
  78. return lock.around { closure(self.value) }
  79. }
  80. /// Synchronously modify the protected value.
  81. ///
  82. /// - Parameter closure: The closure to execute.
  83. ///
  84. /// - Returns: The modified value.
  85. @discardableResult
  86. func write<U>(_ closure: (inout T) -> U) -> U {
  87. return lock.around { closure(&self.value) }
  88. }
  89. }
  90. extension Protector where T: RangeReplaceableCollection {
  91. /// Adds a new element to the end of this protected collection.
  92. ///
  93. /// - Parameter newElement: The `Element` to append.
  94. func append(_ newElement: T.Element) {
  95. write { (ward: inout T) in
  96. ward.append(newElement)
  97. }
  98. }
  99. /// Adds the elements of a sequence to the end of this protected collection.
  100. ///
  101. /// - Parameter newElements: The `Sequence` to append.
  102. func append<S: Sequence>(contentsOf newElements: S) where S.Element == T.Element {
  103. write { (ward: inout T) in
  104. ward.append(contentsOf: newElements)
  105. }
  106. }
  107. /// Add the elements of a collection to the end of the protected collection.
  108. ///
  109. /// - Parameter newElements: The `Collection` to append.
  110. func append<C: Collection>(contentsOf newElements: C) where C.Element == T.Element {
  111. write { (ward: inout T) in
  112. ward.append(contentsOf: newElements)
  113. }
  114. }
  115. }
  116. extension Protector where T == Data? {
  117. /// Adds the contents of a `Data` value to the end of the protected `Data`.
  118. ///
  119. /// - Parameter data: The `Data` to be appended.
  120. func append(_ data: Data) {
  121. write { (ward: inout T) in
  122. ward?.append(data)
  123. }
  124. }
  125. }
  126. extension Protector where T == 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. return 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. }