-
Notifications
You must be signed in to change notification settings - Fork 433
/
Copy pathLRUCache.swift
116 lines (99 loc) · 2.57 KB
/
LRUCache.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Simple LRU cache.
@_spi(Testing)
public class LRUCache<Key: Hashable, Value> {
private class _Node {
unowned var prev: _Node? = nil
unowned var next: _Node? = nil
let key: Key
var value: Value
init(key: Key, value: Value) {
self.key = key
self.value = value
}
}
private var table: [Key: _Node]
// Double linked list
private unowned var head: _Node?
private unowned var tail: _Node?
public let capacity: Int
public init(capacity: Int) {
self.table = [:]
self.head = nil
self.tail = nil
self.capacity = capacity
}
public var count: Int {
return table.count
}
public subscript(key: Key) -> Value? {
get {
guard let node = table[key] else {
return nil
}
moveToHead(node: node)
return node.value
}
set {
switch (table[key], newValue) {
case (nil, let newValue?): // create.
self.ensureCapacityForNewValue()
let node = _Node(key: key, value: newValue)
addToHead(node: node)
table[key] = node
case (let node?, let newValue?): // update.
moveToHead(node: node)
node.value = newValue
case (let node?, nil): // delete.
remove(node: node)
table[key] = nil
case (nil, nil): // no-op.
break
}
}
}
private func ensureCapacityForNewValue() {
while self.table.count >= self.capacity, let tail = self.tail {
remove(node: tail)
table[tail.key] = nil
}
}
private func moveToHead(node: _Node) {
if node === self.head {
return
}
remove(node: node)
addToHead(node: node)
}
private func addToHead(node: _Node) {
node.next = self.head
node.next?.prev = node
node.prev = nil
self.head = node
if self.tail == nil {
self.tail = node
}
}
private func remove(node: _Node) {
node.next?.prev = node.prev
node.prev?.next = node.next
if node === self.head {
self.head = node.next
}
if node === self.tail {
self.tail = node.prev
}
node.prev = nil
node.next = nil
}
}