Closed bblum closed 11 years ago
Servo's got an LRUCache: https://github.com/mozilla/servo/blob/master/src/components/util/cache.rs#L114
It has some O(n) operations, though.
This is also the same data structure as OrderedDict
in python and LinkedHashMap
, they provide both the LRU cache use case and also a hash map recording the insertion order.
Closing as a duplicate of #4988.
The standard way of representing an LRU is to have nodes be stored in a hashmap or binary search tree, with lookup-by-key, and in a linked-list which represents recency. This allows O(1) or O(logn) lookup/insert time, and constant time update/eviction with the recency list.
The representation is usually something like:
This is more difficult to represent in Rust. You could do it with
@mut
pointers, but we all know what would go wrong there, and also that would prevent you from sharing it between tasks. You could also do it with unsafe pointers. I suggest instead representing it as a vector, and replacing the pointers with indices into the vector.