|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2025 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +/// A cache that stores key-value pairs up to a given capacity. |
| 14 | +/// |
| 15 | +/// The least recently used key-value pair is removed when the cache exceeds its capacity. |
| 16 | +package struct LRUCache<Key: Hashable, Value> { |
| 17 | + private struct Priority { |
| 18 | + var next: Key? |
| 19 | + var previous: Key? |
| 20 | + |
| 21 | + init(next: Key? = nil, previous: Key? = nil) { |
| 22 | + self.next = next |
| 23 | + self.previous = previous |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + // The hash map for accessing cached key-value pairs. |
| 28 | + private var cache: [Key: Value] |
| 29 | + |
| 30 | + // Doubly linked list of priorities keeping track of the first and last entries. |
| 31 | + private var priorities: [Key: Priority] |
| 32 | + private var firstPriority: Key? = nil |
| 33 | + private var lastPriority: Key? = nil |
| 34 | + |
| 35 | + /// The maximum number of key-value pairs that can be stored in the cache. |
| 36 | + package let capacity: Int |
| 37 | + |
| 38 | + /// The number of key-value pairs within the cache. |
| 39 | + package var count: Int { cache.count } |
| 40 | + |
| 41 | + /// A collection containing just the keys of the cache. |
| 42 | + /// |
| 43 | + /// Keys will **not** be in the same order that they were added to the cache. |
| 44 | + package var keys: any Collection<Key> { cache.keys } |
| 45 | + |
| 46 | + /// A collection containing just the values of the cache. |
| 47 | + /// |
| 48 | + /// Values will **not** be in the same order that they were added to the cache. |
| 49 | + package var values: any Collection<Value> { cache.values } |
| 50 | + |
| 51 | + package init(capacity: Int) { |
| 52 | + assert(capacity > 0, "LRUCache capacity must be greater than 0") |
| 53 | + self.capacity = capacity |
| 54 | + self.cache = Dictionary(minimumCapacity: capacity) |
| 55 | + self.priorities = Dictionary(minimumCapacity: capacity) |
| 56 | + } |
| 57 | + |
| 58 | + /// Assigns the given key as the first priority in the doubly linked list of priorities. |
| 59 | + private mutating func addPriority(forKey key: Key) { |
| 60 | + guard let currentFirstPriority = firstPriority else { |
| 61 | + firstPriority = key |
| 62 | + lastPriority = key |
| 63 | + priorities[key] = Priority() |
| 64 | + return |
| 65 | + } |
| 66 | + priorities[key] = Priority(next: currentFirstPriority) |
| 67 | + priorities[currentFirstPriority]?.previous = key |
| 68 | + firstPriority = key |
| 69 | + } |
| 70 | + |
| 71 | + /// Removes the given key from the doubly linked list of priorities. |
| 72 | + private mutating func removePriority(forKey key: Key) { |
| 73 | + guard let priority = priorities.removeValue(forKey: key) else { |
| 74 | + return |
| 75 | + } |
| 76 | + // Update the first and last priorities |
| 77 | + if firstPriority == key { |
| 78 | + firstPriority = priority.next |
| 79 | + } |
| 80 | + if lastPriority == key { |
| 81 | + lastPriority = priority.previous |
| 82 | + } |
| 83 | + // Update the previous and next keys in the priority list |
| 84 | + if let previousPriority = priority.previous { |
| 85 | + priorities[previousPriority]?.next = priority.next |
| 86 | + } |
| 87 | + if let nextPriority = priority.next { |
| 88 | + priorities[nextPriority]?.previous = priority.previous |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + /// Removes all key-value pairs from the cache. |
| 93 | + package mutating func removeAll() { |
| 94 | + cache.removeAll() |
| 95 | + priorities.removeAll() |
| 96 | + firstPriority = nil |
| 97 | + lastPriority = nil |
| 98 | + } |
| 99 | + |
| 100 | + /// Removes all the elements that satisfy the given predicate. |
| 101 | + package mutating func removeAll(where shouldBeRemoved: (_: ((key: Key, value: Value)) throws -> Bool)) rethrows { |
| 102 | + cache = try cache.filter { entry in |
| 103 | + guard try shouldBeRemoved(entry) else { |
| 104 | + return true |
| 105 | + } |
| 106 | + removePriority(forKey: entry.key) |
| 107 | + return false |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + /// Removes the given key and its associated value from the cache. |
| 112 | + /// |
| 113 | + /// Returns the value that was associated with the key. |
| 114 | + @discardableResult |
| 115 | + package mutating func removeValue(forKey key: Key) -> Value? { |
| 116 | + removePriority(forKey: key) |
| 117 | + return cache.removeValue(forKey: key) |
| 118 | + } |
| 119 | + |
| 120 | + package subscript(key: Key) -> Value? { |
| 121 | + mutating _read { |
| 122 | + removePriority(forKey: key) |
| 123 | + addPriority(forKey: key) |
| 124 | + yield cache[key] |
| 125 | + } |
| 126 | + set { |
| 127 | + guard let newValue else { |
| 128 | + removeValue(forKey: key) |
| 129 | + return |
| 130 | + } |
| 131 | + cache[key] = newValue |
| 132 | + // Move the key up the priority list by removing and then adding it |
| 133 | + removePriority(forKey: key) |
| 134 | + addPriority(forKey: key) |
| 135 | + if cache.count > capacity, let lastPriority { |
| 136 | + removeValue(forKey: lastPriority) |
| 137 | + } |
| 138 | + } |
| 139 | + } |
| 140 | +} |
0 commit comments