ThreadSafeDictionary.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // ThreadSafeDictionary.swift
  3. //
  4. // Created by Shashank on 29/10/20.
  5. //
  6. import Foundation
  7. class ThreadSafeDictionary<V: Hashable, T>: Collection {
  8. private var dictionary: [V: T]
  9. private let concurrentQueue = DispatchQueue(label: "com.nextcloud.ThreadSafeDictionary", attributes: .concurrent)
  10. var startIndex: Dictionary<V, T>.Index {
  11. self.concurrentQueue.sync {
  12. return self.dictionary.startIndex
  13. }
  14. }
  15. var endIndex: Dictionary<V, T>.Index {
  16. self.concurrentQueue.sync {
  17. return self.dictionary.endIndex
  18. }
  19. }
  20. init(dict: [V: T] = [V: T]()) {
  21. self.dictionary = dict
  22. }
  23. func index(after i: Dictionary<V, T>.Index) -> Dictionary<V, T>.Index {
  24. self.concurrentQueue.sync {
  25. return self.dictionary.index(after: i)
  26. }
  27. }
  28. subscript(key: V) -> T? {
  29. get {
  30. self.concurrentQueue.sync {
  31. return self.dictionary[key]
  32. }
  33. }
  34. set(newValue) {
  35. self.concurrentQueue.async(flags: .barrier) {[weak self] in
  36. self?.dictionary[key] = newValue
  37. }
  38. }
  39. }
  40. subscript(index: Dictionary<V, T>.Index) -> Dictionary<V, T>.Element {
  41. self.concurrentQueue.sync {
  42. return self.dictionary[index]
  43. }
  44. }
  45. func removeValue(forKey key: V) {
  46. self.concurrentQueue.async(flags: .barrier) {[weak self] in
  47. self?.dictionary.removeValue(forKey: key)
  48. }
  49. }
  50. func removeAll() {
  51. self.concurrentQueue.async(flags: .barrier) {[weak self] in
  52. self?.dictionary.removeAll()
  53. }
  54. }
  55. }