12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- //
- // ThreadSafeDictionary.swift
- //
- // Created by Shashank on 29/10/20.
- //
- import Foundation
- class ThreadSafeDictionary<V: Hashable, T>: Collection {
- private var dictionary: [V: T]
- private let concurrentQueue = DispatchQueue(label: "com.nextcloud.ThreadSafeDictionary", attributes: .concurrent)
- var startIndex: Dictionary<V, T>.Index {
- self.concurrentQueue.sync {
- return self.dictionary.startIndex
- }
- }
- var endIndex: Dictionary<V, T>.Index {
- self.concurrentQueue.sync {
- return self.dictionary.endIndex
- }
- }
- init(dict: [V: T] = [V: T]()) {
- self.dictionary = dict
- }
- func index(after i: Dictionary<V, T>.Index) -> Dictionary<V, T>.Index {
- self.concurrentQueue.sync {
- return self.dictionary.index(after: i)
- }
- }
- subscript(key: V) -> T? {
- get {
- self.concurrentQueue.sync {
- return self.dictionary[key]
- }
- }
- set(newValue) {
- self.concurrentQueue.async(flags: .barrier) {[weak self] in
- self?.dictionary[key] = newValue
- }
- }
- }
- subscript(index: Dictionary<V, T>.Index) -> Dictionary<V, T>.Element {
- self.concurrentQueue.sync {
- return self.dictionary[index]
- }
- }
- func removeValue(forKey key: V) {
- self.concurrentQueue.async(flags: .barrier) {[weak self] in
- self?.dictionary.removeValue(forKey: key)
- }
- }
- func removeAll() {
- self.concurrentQueue.async(flags: .barrier) {[weak self] in
- self?.dictionary.removeAll()
- }
- }
- }
|