Protector.swift 4.7 KB

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