diff --git a/Sources/RefdsShared/Foundation/RefdsDictionary.swift b/Sources/RefdsShared/Foundation/RefdsDictionary.swift index aff176b..d3a702b 100644 --- a/Sources/RefdsShared/Foundation/RefdsDictionary.swift +++ b/Sources/RefdsShared/Foundation/RefdsDictionary.swift @@ -7,26 +7,42 @@ public actor RefdsDictionary< > { private var elements: [Key: Value] = [:] private let keyPath: KeyPath + private let maxCapacity: Int? public init( for type: Value.Type, - by keyPath: KeyPath + by keyPath: KeyPath, + maxCapacity: Int? = nil ) { self.keyPath = keyPath + self.maxCapacity = maxCapacity } public subscript(key: Key) -> Value? { get { elements[key] } set { guard let newValue else { return remove(for: key) } + guard canInsert else { return } if elements[key] == nil { insert(for: key) } elements[key] = newValue } } + @discardableResult + public func removeFirst() -> Value? { + guard let firstKey = keys.first else { return nil } + let element = elements[firstKey] + remove(for: firstKey) + return element + } + + public var count: Int { keys.count } public var keys: [Key] = [] - public var values: [Value] { - keys.compactMap { elements[$0] } + public var values: [Value] { keys.compactMap { elements[$0] } } + + private var canInsert: Bool { + guard let maxCapacity else { return true } + return count < maxCapacity } private func insert(for key: Key) {