RadrootsIdentityMetadataTesting.swift (2003B)
1 import Foundation 2 import RadrootsKit 3 4 public final class RadrootsInMemoryIdentityMetadataStore: RadrootsIdentityMetadataStore, 5 @unchecked Sendable 6 { 7 public enum Operation: Equatable, Sendable { 8 case read 9 case write 10 case delete 11 } 12 13 public enum Failure: Error, Sendable { 14 case forced 15 } 16 17 private let lock = NSLock() 18 private var values: [RadrootsIdentityMetadataSlot: Data] = [:] 19 private var nextFailure: (Operation, RadrootsIdentityMetadataSlot)? 20 21 public init() {} 22 23 public func data(for slot: RadrootsIdentityMetadataSlot) throws -> Data? { 24 lock.lock() 25 defer { lock.unlock() } 26 try failIfRequested(.read, slot: slot) 27 return values[slot] 28 } 29 30 public func put(_ data: Data, for slot: RadrootsIdentityMetadataSlot) throws { 31 lock.lock() 32 defer { lock.unlock() } 33 try failIfRequested(.write, slot: slot) 34 values[slot] = data 35 } 36 37 public func delete(_ slot: RadrootsIdentityMetadataSlot) throws { 38 lock.lock() 39 defer { lock.unlock() } 40 try failIfRequested(.delete, slot: slot) 41 values.removeValue(forKey: slot) 42 } 43 44 public func failNext(_ operation: Operation, slot: RadrootsIdentityMetadataSlot) { 45 lock.lock() 46 nextFailure = (operation, slot) 47 lock.unlock() 48 } 49 50 public func rawData(for slot: RadrootsIdentityMetadataSlot) -> Data? { 51 lock.lock() 52 defer { lock.unlock() } 53 return values[slot] 54 } 55 56 public func replaceRawData(_ data: Data?, for slot: RadrootsIdentityMetadataSlot) { 57 lock.lock() 58 values[slot] = data 59 lock.unlock() 60 } 61 62 private func failIfRequested(_ operation: Operation, slot: RadrootsIdentityMetadataSlot) throws { 63 guard let failure = nextFailure, 64 failure.0 == operation, 65 failure.1 == slot 66 else { 67 return 68 } 69 nextFailure = nil 70 throw Failure.forced 71 } 72 }