| 1 |
# hashlink -- HashMap-like containers that hold their key-value pairs in a user controllable order |
| 2 |
|
| 3 |
[](https://circleci.com/gh/kyren/hashlink) |
| 4 |
[](https://crates.io/crates/hashlink) |
| 5 |
[](https://docs.rs/hashlink) |
| 6 |
|
| 7 |
This crate is a fork of |
| 8 |
[linked-hash-map](https://github.com/contain-rs/linked-hash-map) that builds on |
| 9 |
top of [hashbrown](https://github.com/rust-lang/hashbrown) to implement more up |
| 10 |
to date versions of `LinkedHashMap` `LinkedHashSet`, and `LruCache`. |
| 11 |
|
| 12 |
One important API change is that when a `LinkedHashMap` is used as a LRU cache, |
| 13 |
it allows you to easily retrieve an entry and move it to the back OR produce a |
| 14 |
new entry at the back without needlessly repeating key hashing and lookups: |
| 15 |
|
| 16 |
``` rust |
| 17 |
let mut lru_cache = LinkedHashMap::new(); |
| 18 |
let key = "key".to_owned(); |
| 19 |
// Try to find my expensive to construct and hash key |
| 20 |
let _cached_val = match lru_cache.raw_entry_mut().from_key(&key) { |
| 21 |
RawEntryMut::Occupied(mut occupied) => { |
| 22 |
// Cache hit, move entry to the back. |
| 23 |
occupied.to_back(); |
| 24 |
occupied.into_mut() |
| 25 |
} |
| 26 |
RawEntryMut::Vacant(vacant) => { |
| 27 |
// Insert expensive to construct key and expensive to compute value, |
| 28 |
// automatically inserted at the back. |
| 29 |
vacant.insert(key.clone(), 42).1 |
| 30 |
} |
| 31 |
}; |
| 32 |
``` |
| 33 |
|
| 34 |
Or, a simpler way to do the same thing: |
| 35 |
|
| 36 |
``` rust |
| 37 |
let mut lru_cache = LinkedHashMap::new(); |
| 38 |
let key = "key".to_owned(); |
| 39 |
let _cached_val = lru_cache |
| 40 |
.raw_entry_mut() |
| 41 |
.from_key(&key) |
| 42 |
.or_insert_with(|| (key.clone(), 42)); |
| 43 |
``` |
| 44 |
|
| 45 |
This crate contains a decent amount of unsafe code from handling its internal |
| 46 |
linked list, and the unsafe code has diverged quite a lot from the original |
| 47 |
`linked-hash-map` implementation. It currently passes tests under miri and |
| 48 |
sanitizers, but it should probably still receive more review and testing, and |
| 49 |
check for test code coverage. |
| 50 |
|
| 51 |
## Credit |
| 52 |
|
| 53 |
There is a huge amount of code in this crate that is copied verbatim from |
| 54 |
`linked-hash-map` and `hashbrown`, especially tests, associated types like |
| 55 |
iterators, and things like `Debug` impls. |
| 56 |
|
| 57 |
## License |
| 58 |
|
| 59 |
This library is licensed the same as |
| 60 |
[linked-hash-map](https://github.com/contain-rs/linked-hash-map) and |
| 61 |
[hashbrown](https://github.com/rust-lang/hashbrown), it is licensed under either |
| 62 |
of: |
| 63 |
|
| 64 |
* MIT license [LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT |
| 65 |
* Apache License 2.0 [LICENSE-APACHE](LICENSE-APACHE) or https://opensource.org/licenses/Apache-2.0 |
| 66 |
|
| 67 |
at your option. |