pub struct Store<K, V>where
K: Serialize + DeserializeOwned + Eq,
V: Serialize + DeserializeOwned,{ /* private fields */ }Expand description
LRU store, backed by by sled.
The typical use case is: you want a persistent cache, with an interface that has similarities with a basic HashMap. And, you do not want it to grow too much, and prefer to drop on the floor data which has not been accessed for a long time.
LRU is normally used for in-memory caches, but here it’s implemented on something which is persistent. Implementation is inspired from work on the in-memory cache HashLRU.
In most cases this implementation tries to be as close as possible to the standard collections HashMap however there are a few differences:
- keys and values must be (de)serialiable
- keys must implement Eq
- no iterator on mutables
- as it relies on external data, any operation can fail
- inserts take references, gets return owned values
This latest aspect is really the fundamental difference: as here all the data is serialized and stored within the store, returning a reference does not really make any sense. Conversely, when putting values in the store, you don’t need to transfer ownership: the store is going to make a serializable copy anyway.
Examples
use disklru::Store;
let mut store = Store::open_temporary(4).unwrap();
store.insert(&1, &10).unwrap();
store.insert(&2, &20).unwrap();
store.insert(&3, &30).unwrap();
store.insert(&4, &40).unwrap();
store.insert(&5, &50).unwrap();
// key1 has been dropped, size is limited to 4
assert_eq!(Some(2), store.lru().unwrap());
assert_eq!(Some(20), store.get(&2).unwrap());
// getting key2 has made key3 the least recently used item
assert_eq!(Some(3), store.lru().unwrap());
assert_eq!(Some(40), store.get(&4).unwrap());
// getting key4 makes it the most recently used item
assert_eq!("[3: 30, 5: 50, 2: 20, 4: 40]", format!("{}", store));
store.flush().unwrap(); // commit