ThreadSafeArray.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. //
  2. // ThreadSafeArray.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 31/01/24.
  6. // Copyright © 2024 Marino Faggiana. All rights reserved.
  7. //
  8. // http://basememara.com/creating-thread-safe-arrays-in-swift/
  9. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  10. //
  11. // This program is free software: you can redistribute it and/or modify
  12. // it under the terms of the GNU General Public License as published by
  13. // the Free Software Foundation, either version 3 of the License, or
  14. // (at your option) any later version.
  15. //
  16. // This program is distributed in the hope that it will be useful,
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. // GNU General Public License for more details.
  20. //
  21. // You should have received a copy of the GNU General Public License
  22. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. //
  24. import Foundation
  25. /// A thread-safe array.
  26. public class ThreadSafeArray<Element> {
  27. private var array = [Element]()
  28. private let queue = DispatchQueue(label: "com.nextcloud.ThreadSafeArray", attributes: .concurrent)
  29. public init() { }
  30. public convenience init(_ array: [Element]) {
  31. self.init()
  32. self.array = array
  33. }
  34. }
  35. // MARK: - Properties
  36. public extension ThreadSafeArray {
  37. /// The first element of the collection.
  38. var first: Element? {
  39. var result: Element?
  40. queue.sync { result = self.array.first }
  41. return result
  42. }
  43. /// The last element of the collection.
  44. var last: Element? {
  45. var result: Element?
  46. queue.sync { result = self.array.last }
  47. return result
  48. }
  49. /// The number of elements in the array.
  50. var count: Int {
  51. var result = 0
  52. queue.sync { result = self.array.count }
  53. return result
  54. }
  55. /// A Boolean value indicating whether the collection is empty.
  56. var isEmpty: Bool {
  57. var result = false
  58. queue.sync { result = self.array.isEmpty }
  59. return result
  60. }
  61. /// A textual representation of the array and its elements.
  62. var description: String {
  63. var result = ""
  64. queue.sync { result = self.array.description }
  65. return result
  66. }
  67. }
  68. // MARK: - Immutable
  69. public extension ThreadSafeArray {
  70. /// Returns the first element of the sequence that satisfies the given predicate.
  71. ///
  72. /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.
  73. /// - Returns: The first element of the sequence that satisfies predicate, or nil if there is no element that satisfies predicate.
  74. func first(where predicate: (Element) -> Bool) -> Element? {
  75. var result: Element?
  76. queue.sync { result = self.array.first(where: predicate) }
  77. return result
  78. }
  79. /// Returns the last element of the sequence that satisfies the given predicate.
  80. ///
  81. /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.
  82. /// - Returns: The last element of the sequence that satisfies predicate, or nil if there is no element that satisfies predicate.
  83. func last(where predicate: (Element) -> Bool) -> Element? {
  84. var result: Element?
  85. queue.sync { result = self.array.last(where: predicate) }
  86. return result
  87. }
  88. /// Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.
  89. ///
  90. /// - Parameter isIncluded: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array.
  91. /// - Returns: An array of the elements that includeElement allowed.
  92. func filter(_ isIncluded: @escaping (Element) -> Bool) -> ThreadSafeArray {
  93. var result: ThreadSafeArray?
  94. queue.sync { result = ThreadSafeArray(self.array.filter(isIncluded)) }
  95. return result!
  96. }
  97. /// Returns the first index in which an element of the collection satisfies the given predicate.
  98. ///
  99. /// - Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.
  100. /// - Returns: The index of the first element for which predicate returns true. If no elements in the collection satisfy the given predicate, returns nil.
  101. func index(where predicate: (Element) -> Bool) -> Int? {
  102. var result: Int?
  103. queue.sync { result = self.array.firstIndex(where: predicate) }
  104. return result
  105. }
  106. /// Returns the elements of the collection, sorted using the given predicate as the comparison between elements.
  107. ///
  108. /// - Parameter areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.
  109. /// - Returns: A sorted array of the collection’s elements.
  110. func sorted(by areInIncreasingOrder: (Element, Element) -> Bool) -> ThreadSafeArray {
  111. var result: ThreadSafeArray?
  112. queue.sync { result = ThreadSafeArray(self.array.sorted(by: areInIncreasingOrder)) }
  113. return result!
  114. }
  115. /// Returns an array containing the results of mapping the given closure over the sequence’s elements.
  116. ///
  117. /// - Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value.
  118. /// - Returns: An array of the non-nil results of calling transform with each element of the sequence.
  119. func map<ElementOfResult>(_ transform: @escaping (Element) -> ElementOfResult) -> [ElementOfResult] {
  120. var result = [ElementOfResult]()
  121. queue.sync { result = self.array.map(transform) }
  122. return result
  123. }
  124. /// Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.
  125. ///
  126. /// - Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value.
  127. /// - Returns: An array of the non-nil results of calling transform with each element of the sequence.
  128. func compactMap<ElementOfResult>(_ transform: (Element) -> ElementOfResult?) -> [ElementOfResult] {
  129. var result = [ElementOfResult]()
  130. queue.sync { result = self.array.compactMap(transform) }
  131. return result
  132. }
  133. /// Returns the result of combining the elements of the sequence using the given closure.
  134. ///
  135. /// - Parameters:
  136. /// - initialResult: The value to use as the initial accumulating value. initialResult is passed to nextPartialResult the first time the closure is executed.
  137. /// - nextPartialResult: A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the nextPartialResult closure or returned to the caller.
  138. /// - Returns: The final accumulated value. If the sequence has no elements, the result is initialResult.
  139. func reduce<ElementOfResult>(_ initialResult: ElementOfResult, _ nextPartialResult: @escaping (ElementOfResult, Element) -> ElementOfResult) -> ElementOfResult {
  140. var result: ElementOfResult?
  141. queue.sync { result = self.array.reduce(initialResult, nextPartialResult) }
  142. return result ?? initialResult
  143. }
  144. /// Returns the result of combining the elements of the sequence using the given closure.
  145. ///
  146. /// - Parameters:
  147. /// - initialResult: The value to use as the initial accumulating value.
  148. /// - updateAccumulatingResult: A closure that updates the accumulating value with an element of the sequence.
  149. /// - Returns: The final accumulated value. If the sequence has no elements, the result is initialResult.
  150. func reduce<ElementOfResult>(into initialResult: ElementOfResult, _ updateAccumulatingResult: @escaping (inout ElementOfResult, Element) -> Void) -> ElementOfResult {
  151. var result: ElementOfResult?
  152. queue.sync { result = self.array.reduce(into: initialResult, updateAccumulatingResult) }
  153. return result ?? initialResult
  154. }
  155. /// Calls the given closure on each element in the sequence in the same order as a for-in loop.
  156. ///
  157. /// - Parameter body: A closure that takes an element of the sequence as a parameter.
  158. func forEach(_ body: (Element) -> Void) {
  159. queue.sync { self.array.forEach(body) }
  160. }
  161. /// Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.
  162. ///
  163. /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match.
  164. /// - Returns: true if the sequence contains an element that satisfies predicate; otherwise, false.
  165. func contains(where predicate: (Element) -> Bool) -> Bool {
  166. var result = false
  167. queue.sync { result = self.array.contains(where: predicate) }
  168. return result
  169. }
  170. /// Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.
  171. ///
  172. /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element satisfies a condition.
  173. /// - Returns: true if the sequence contains only elements that satisfy predicate; otherwise, false.
  174. func allSatisfy(_ predicate: (Element) -> Bool) -> Bool {
  175. var result = false
  176. queue.sync { result = self.array.allSatisfy(predicate) }
  177. return result
  178. }
  179. /// Returns the array
  180. ///
  181. /// - Returns: the array part.
  182. func getArray() -> [Element]? {
  183. var results: [Element]?
  184. queue.sync { results = self.array }
  185. return results
  186. }
  187. }
  188. // MARK: - Mutable
  189. public extension ThreadSafeArray {
  190. /// Adds a new element at the end of the array.
  191. ///
  192. /// - Parameter element: The element to append to the array.
  193. func append(_ element: Element) {
  194. queue.async(flags: .barrier) {
  195. self.array.append(element)
  196. }
  197. }
  198. /// Adds new elements at the end of the array.
  199. ///
  200. /// - Parameter element: The elements to append to the array.
  201. func append(_ elements: [Element]) {
  202. queue.async(flags: .barrier) {
  203. self.array += elements
  204. }
  205. }
  206. /// Inserts a new element at the specified position.
  207. ///
  208. /// - Parameters:
  209. /// - element: The new element to insert into the array.
  210. /// - index: The position at which to insert the new element.
  211. func insert(_ element: Element, at index: Int) {
  212. queue.async(flags: .barrier) {
  213. self.array.insert(element, at: index)
  214. }
  215. }
  216. /// Removes and returns the element at the specified position.
  217. ///
  218. /// - Parameters:
  219. /// - index: The position of the element to remove.
  220. /// - completion: The handler with the removed element.
  221. func remove(at index: Int, completion: ((Element) -> Void)? = nil) {
  222. queue.async(flags: .barrier) {
  223. let element = self.array.remove(at: index)
  224. DispatchQueue.main.async { completion?(element) }
  225. }
  226. }
  227. /// Removes and returns the elements that meet the criteria.
  228. ///
  229. /// - Parameters:
  230. /// - predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.
  231. /// - completion: The handler with the removed elements.
  232. func remove(where predicate: @escaping (Element) -> Bool, completion: (([Element]) -> Void)? = nil) {
  233. queue.async(flags: .barrier) {
  234. var elements = [Element]()
  235. while let index = self.array.firstIndex(where: predicate) {
  236. elements.append(self.array.remove(at: index))
  237. }
  238. DispatchQueue.main.async { completion?(elements) }
  239. }
  240. }
  241. /// Removes all elements from the array.
  242. ///
  243. /// - Parameter completion: The handler with the removed elements.
  244. func removeAll(completion: (([Element]) -> Void)? = nil) {
  245. queue.async(flags: .barrier) {
  246. let elements = self.array
  247. self.array.removeAll()
  248. DispatchQueue.main.async { completion?(elements) }
  249. }
  250. }
  251. }
  252. public extension ThreadSafeArray {
  253. /// Accesses the element at the specified position if it exists.
  254. ///
  255. /// - Parameter index: The position of the element to access.
  256. /// - Returns: optional element if it exists.
  257. subscript(index: Int) -> Element? {
  258. get {
  259. var result: Element?
  260. queue.sync {
  261. guard self.array.startIndex..<self.array.endIndex ~= index else { return }
  262. result = self.array[index]
  263. }
  264. return result
  265. }
  266. set {
  267. guard let newValue = newValue else { return }
  268. queue.async(flags: .barrier) {
  269. self.array[index] = newValue
  270. }
  271. }
  272. }
  273. }
  274. // MARK: - Equatable
  275. public extension ThreadSafeArray where Element: Equatable {
  276. /// Returns a Boolean value indicating whether the sequence contains the given element.
  277. ///
  278. /// - Parameter element: The element to find in the sequence.
  279. /// - Returns: true if the element was found in the sequence; otherwise, false.
  280. func contains(_ element: Element) -> Bool {
  281. var result = false
  282. queue.sync { result = self.array.contains(element) }
  283. return result
  284. }
  285. }
  286. // MARK: - Infix operators
  287. public extension ThreadSafeArray {
  288. /// Adds a new element at the end of the array.
  289. ///
  290. /// - Parameters:
  291. /// - left: The collection to append to.
  292. /// - right: The element to append to the array.
  293. static func += (left: inout ThreadSafeArray, right: Element) {
  294. left.append(right)
  295. }
  296. /// Adds new elements at the end of the array.
  297. ///
  298. /// - Parameters:
  299. /// - left: The collection to append to.
  300. /// - right: The elements to append to the array.
  301. static func += (left: inout ThreadSafeArray, right: [Element]) {
  302. left.append(right)
  303. }
  304. }