|
| 1 | +import Foundation |
| 2 | + |
| 3 | +public class ThreadSafeList<V> { |
| 4 | + |
| 5 | + private var items = [V]() |
| 6 | + private var itemQueue: DispatchQueue |
| 7 | + public init(identifier: String = UUID().uuidString) { |
| 8 | + itemQueue = DispatchQueue( |
| 9 | + label: "ThreadSafeList.\(String(describing: V.self)).queue.\(identifier)", |
| 10 | + qos: .userInitiated, |
| 11 | + attributes: .concurrent, |
| 12 | + target: DispatchQueue.global(qos: .userInitiated) |
| 13 | + ) |
| 14 | + } |
| 15 | + |
| 16 | + public func get(_ index: Int) -> V? { |
| 17 | + var value: V? |
| 18 | + itemQueue.sync { // safely read |
| 19 | + if self.items.indices.contains(index) { |
| 20 | + value = self.items[index] |
| 21 | + } else { |
| 22 | + value = nil |
| 23 | + } |
| 24 | + } |
| 25 | + return value |
| 26 | + } |
| 27 | + |
| 28 | + public func insert(_ value: V, at index: Int) { |
| 29 | + itemQueue.async(flags: .barrier) { // safely write |
| 30 | + self.items.insert(value, at: index) |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + @discardableResult public func remove(at index: Int) -> V? { |
| 35 | + guard let value = get(index) else { |
| 36 | + // make sure the index exists |
| 37 | + return nil |
| 38 | + } |
| 39 | + itemQueue.async(flags: .barrier) { // safely write |
| 40 | + self.items.remove(at: index) |
| 41 | + } |
| 42 | + return value |
| 43 | + } |
| 44 | + |
| 45 | + public func append(_ value: V) { |
| 46 | + itemQueue.async(flags: .barrier) { // safely write |
| 47 | + self.items.append(value) |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public func append(contentsOf values: [V]) { |
| 52 | + itemQueue.async(flags: .barrier) { // safely write |
| 53 | + self.items.append(contentsOf: values) |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + public func removeAll() { |
| 58 | + itemQueue.async(flags: .barrier) { // safely write |
| 59 | + self.items.removeAll() |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + public func getAll() -> [V] { |
| 64 | + var allItems = [V]() |
| 65 | + itemQueue.sync { // safely read |
| 66 | + allItems = self.items |
| 67 | + } |
| 68 | + return allItems |
| 69 | + } |
| 70 | + |
| 71 | + public func count() -> Int { |
| 72 | + var count = 0 |
| 73 | + itemQueue.sync { // safely read |
| 74 | + count = self.items.count |
| 75 | + } |
| 76 | + return count |
| 77 | + } |
| 78 | + |
| 79 | + public subscript(index: Int) -> V? { |
| 80 | + get { |
| 81 | + return self.get(index) |
| 82 | + } |
| 83 | + set(newValue) { |
| 84 | + if let value = newValue { |
| 85 | + self.insert(value, at: index) |
| 86 | + } else { |
| 87 | + self.remove(at: index) |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | +} |
0 commit comments