2
0

Protector.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. fileprivate func lock() {
  38. os_unfair_lock_lock(unfairLock)
  39. }
  40. fileprivate 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. /// - Returns: The value the closure generated.
  47. func around<T>(_ closure: () -> T) -> T {
  48. lock(); defer { unlock() }
  49. return closure()
  50. }
  51. /// Execute a closure while aquiring the lock.
  52. ///
  53. /// - Parameter closure: The closure to run.
  54. func around(_ closure: () -> Void) {
  55. lock(); defer { unlock() }
  56. return closure()
  57. }
  58. }
  59. /// A thread-safe wrapper around a value.
  60. final class Protector<T> {
  61. private let lock = UnfairLock()
  62. private var value: T
  63. init(_ value: T) {
  64. self.value = value
  65. }
  66. /// The contained value. Unsafe for anything more than direct read or write.
  67. var directValue: T {
  68. get { return lock.around { value } }
  69. set { lock.around { value = newValue } }
  70. }
  71. /// Synchronously read or transform the contained value.
  72. ///
  73. /// - Parameter closure: The closure to execute.
  74. /// - Returns: The return value of the closure passed.
  75. func read<U>(_ closure: (T) -> U) -> U {
  76. return lock.around { closure(self.value) }
  77. }
  78. /// Synchronously modify the protected value.
  79. ///
  80. /// - Parameter closure: The closure to execute.
  81. /// - Returns: The modified value.
  82. @discardableResult
  83. func write<U>(_ closure: (inout T) -> U) -> U {
  84. return lock.around { closure(&self.value) }
  85. }
  86. }
  87. extension Protector where T: RangeReplaceableCollection {
  88. /// Adds a new element to the end of this protected collection.
  89. ///
  90. /// - Parameter newElement: The `Element` to append.
  91. func append(_ newElement: T.Element) {
  92. write { (ward: inout T) in
  93. ward.append(newElement)
  94. }
  95. }
  96. /// Adds the elements of a sequence to the end of this protected collection.
  97. ///
  98. /// - Parameter newElements: The `Sequence` to append.
  99. func append<S: Sequence>(contentsOf newElements: S) where S.Element == T.Element {
  100. write { (ward: inout T) in
  101. ward.append(contentsOf: newElements)
  102. }
  103. }
  104. /// Add the elements of a collection to the end of the protected collection.
  105. ///
  106. /// - Parameter newElements: The `Collection` to append.
  107. func append<C: Collection>(contentsOf newElements: C) where C.Element == T.Element {
  108. write { (ward: inout T) in
  109. ward.append(contentsOf: newElements)
  110. }
  111. }
  112. }
  113. extension Protector where T == Data? {
  114. /// Adds the contents of a `Data` value to the end of the protected `Data`.
  115. ///
  116. /// - Parameter data: The `Data` to be appended.
  117. func append(_ data: Data) {
  118. write { (ward: inout T) in
  119. ward?.append(data)
  120. }
  121. }
  122. }
  123. extension Protector where T == Request.MutableState {
  124. /// Attempts to transition to the passed `State`.
  125. ///
  126. /// - Parameter state: The `State` to attempt transition to.
  127. /// - Returns: Whether the transtion occured.
  128. func attemptToTransitionTo(_ state: Request.State) -> Bool {
  129. return lock.around {
  130. guard value.state.canTransitionTo(state) else { return false }
  131. value.state = state
  132. return true
  133. }
  134. }
  135. /// Perform a closure while locked with the provided `Request.State`.
  136. ///
  137. /// - Parameter perform: The closure to perform while locked.
  138. func withState(perform: (Request.State) -> Void) {
  139. lock.around { perform(value.state) }
  140. }
  141. }