Protector.swift 5.3 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 _lock = UnsafeMutablePointer<os_unfair_lock>.allocate(capacity: 1)
  29. deinit {
  30. _lock.deallocate()
  31. }
  32. fileprivate func lock() {
  33. os_unfair_lock_lock(_lock)
  34. }
  35. fileprivate func unlock() {
  36. os_unfair_lock_unlock(_lock)
  37. }
  38. /// Executes a closure returning a value while acquiring the lock.
  39. ///
  40. /// - Parameter closure: The closure to run.
  41. /// - Returns: The value the closure generated.
  42. func around<T>(_ closure: () -> T) -> T {
  43. lock(); defer { unlock() }
  44. return closure()
  45. }
  46. /// Execute a closure while aquiring the lock.
  47. ///
  48. /// - Parameter closure: The closure to run.
  49. func around(_ closure: () -> Void) {
  50. lock(); defer { unlock() }
  51. return closure()
  52. }
  53. }
  54. /// A thread-safe wrapper around a value.
  55. @propertyDelegate @dynamicMemberLookup
  56. final class Protector<T> {
  57. private let lock = UnfairLock()
  58. var value: T
  59. init(_ value: T) {
  60. self.value = value
  61. }
  62. /// The contained value. Unsafe for anything more than direct read or write.
  63. var directValue: T {
  64. get { return lock.around { value } }
  65. set { lock.around { value = newValue } }
  66. }
  67. /// Synchronously read or transform the contained value.
  68. ///
  69. /// - Parameter closure: The closure to execute.
  70. /// - Returns: The return value of the closure passed.
  71. func read<U>(_ closure: (T) -> U) -> U {
  72. return lock.around { closure(self.value) }
  73. }
  74. /// Synchronously modify the protected value.
  75. ///
  76. /// - Parameter closure: The closure to execute.
  77. /// - Returns: The modified value.
  78. @discardableResult
  79. func write<U>(_ closure: (inout T) -> U) -> U {
  80. return lock.around { closure(&self.value) }
  81. }
  82. init(initialValue: T) {
  83. value = initialValue
  84. }
  85. subscript<Property>(dynamicMember keyPath: WritableKeyPath<T, Property>) -> Property {
  86. get { return lock.around { value[keyPath: keyPath] } }
  87. set { lock.around { value[keyPath: keyPath] = newValue } }
  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. /// - Returns: Whether the transtion occured.
  131. func attemptToTransitionTo(_ state: Request.State) -> Bool {
  132. return lock.around {
  133. guard value.state.canTransitionTo(state) else { return false }
  134. value.state = state
  135. return true
  136. }
  137. }
  138. /// Perform a closure while locked with the provided `Request.State`.
  139. ///
  140. /// - Parameter perform: The closure to perform while locked.
  141. func withState(perform: (Request.State) -> Void) {
  142. lock.around { perform(value.state) }
  143. }
  144. }