tools::lru_cache: Make key generic.

Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
This commit is contained in:
Christian Ebner 2020-02-25 18:45:26 +01:00 committed by Dietmar Maurer
parent 03f779c6f5
commit 75c2ee7bab
2 changed files with 29 additions and 29 deletions

View File

@ -81,8 +81,8 @@ struct Context {
/// DirectoryEntry via the Decoder as well as the parent, in order /// DirectoryEntry via the Decoder as well as the parent, in order
/// to be able to include the parent directory on readdirplus calls. /// to be able to include the parent directory on readdirplus calls.
start_end_parent: HashMap<u64, (u64, u64)>, start_end_parent: HashMap<u64, (u64, u64)>,
gbt_cache: LruCache<Vec<(PxarGoodbyeItem, u64, u64)>>, gbt_cache: LruCache<u64, Vec<(PxarGoodbyeItem, u64, u64)>>,
entry_cache: LruCache<DirectoryEntry>, entry_cache: LruCache<u64, DirectoryEntry>,
} }
/// Cacher for the goodbye table. /// Cacher for the goodbye table.
@ -93,7 +93,7 @@ struct GbtCacher<'a> {
map: &'a HashMap<u64, (u64, u64)>, map: &'a HashMap<u64, (u64, u64)>,
} }
impl<'a> Cacher<Vec<(PxarGoodbyeItem, u64, u64)>> for GbtCacher<'a> { impl<'a> Cacher<u64, Vec<(PxarGoodbyeItem, u64, u64)>> for GbtCacher<'a> {
fn fetch(&mut self, key: u64) -> Result<Option<Vec<(PxarGoodbyeItem, u64, u64)>>, Error> { fn fetch(&mut self, key: u64) -> Result<Option<Vec<(PxarGoodbyeItem, u64, u64)>>, Error> {
let (end, _) = *self.map.get(&key).unwrap(); let (end, _) = *self.map.get(&key).unwrap();
let gbt = self.decoder.goodbye_table(None, end)?; let gbt = self.decoder.goodbye_table(None, end)?;
@ -109,7 +109,7 @@ struct EntryCacher<'a> {
map: &'a HashMap<u64, (u64, u64)>, map: &'a HashMap<u64, (u64, u64)>,
} }
impl<'a> Cacher<DirectoryEntry> for EntryCacher<'a> { impl<'a> Cacher<u64, DirectoryEntry> for EntryCacher<'a> {
fn fetch(&mut self, key: u64) -> Result<Option<DirectoryEntry>, Error> { fn fetch(&mut self, key: u64) -> Result<Option<DirectoryEntry>, Error> {
let entry = match key { let entry = match key {
0 => self.decoder.root()?, 0 => self.decoder.root()?,
@ -128,8 +128,8 @@ impl Context {
fn as_mut_refs(&mut self) -> ( fn as_mut_refs(&mut self) -> (
&mut Decoder, &mut Decoder,
&mut HashMap<u64, (u64, u64)>, &mut HashMap<u64, (u64, u64)>,
&mut LruCache<Vec<(PxarGoodbyeItem, u64, u64)>>, &mut LruCache<u64, Vec<(PxarGoodbyeItem, u64, u64)>>,
&mut LruCache<DirectoryEntry> &mut LruCache<u64, DirectoryEntry>
) { ) {
( &mut self.decoder, &mut self.start_end_parent, &mut self.gbt_cache, &mut self.entry_cache ) ( &mut self.decoder, &mut self.start_end_parent, &mut self.gbt_cache, &mut self.entry_cache )
} }
@ -347,8 +347,8 @@ impl Session {
F: FnOnce( F: FnOnce(
&mut Decoder, &mut Decoder,
&mut HashMap<u64, (u64, u64)>, &mut HashMap<u64, (u64, u64)>,
&mut LruCache<Vec<(PxarGoodbyeItem, u64, u64)>>, &mut LruCache<u64, Vec<(PxarGoodbyeItem, u64, u64)>>,
&mut LruCache<DirectoryEntry>, &mut LruCache<u64, DirectoryEntry>,
u64, u64,
) -> Result<(), i32>, ) -> Result<(), i32>,
{ {

View File

@ -8,29 +8,29 @@ use std::collections::HashMap;
use std::marker::PhantomData; use std::marker::PhantomData;
/// Interface for getting values on cache misses. /// Interface for getting values on cache misses.
pub trait Cacher<V> { pub trait Cacher<K, V> {
/// Fetch a value for key on cache miss. /// Fetch a value for key on cache miss.
/// ///
/// Whenever a cache miss occurs, the fetch method provides a corresponding value. /// Whenever a cache miss occurs, the fetch method provides a corresponding value.
/// If no value can be obtained for the given key, None is returned, the cache is /// If no value can be obtained for the given key, None is returned, the cache is
/// not updated in that case. /// not updated in that case.
fn fetch(&mut self, key: u64) -> Result<Option<V>, failure::Error>; fn fetch(&mut self, key: K) -> Result<Option<V>, failure::Error>;
} }
/// Node of the doubly linked list storing key and value /// Node of the doubly linked list storing key and value
struct CacheNode<V> { struct CacheNode<K, V> {
// We need to additionally store the key to be able to remove it // We need to additionally store the key to be able to remove it
// from the HashMap when removing the tail. // from the HashMap when removing the tail.
key: u64, key: K,
value: V, value: V,
prev: *mut CacheNode<V>, prev: *mut CacheNode<K, V>,
next: *mut CacheNode<V>, next: *mut CacheNode<K, V>,
// Dropcheck marker. See the phantom-data section in the rustonomicon. // Dropcheck marker. See the phantom-data section in the rustonomicon.
_marker: PhantomData<Box<CacheNode<V>>>, _marker: PhantomData<Box<CacheNode<K, V>>>,
} }
impl<V> CacheNode<V> { impl<K, V> CacheNode<K, V> {
fn new(key: u64, value: V) -> Self { fn new(key: K, value: V) -> Self {
Self { Self {
key, key,
value, value,
@ -49,7 +49,7 @@ impl<V> CacheNode<V> {
/// # fn main() -> Result<(), failure::Error> { /// # fn main() -> Result<(), failure::Error> {
/// struct LruCacher {}; /// struct LruCacher {};
/// ///
/// impl Cacher<u64> for LruCacher { /// impl Cacher<u64, u64> for LruCacher {
/// fn fetch(&mut self, key: u64) -> Result<Option<u64>, failure::Error> { /// fn fetch(&mut self, key: u64) -> Result<Option<u64>, failure::Error> {
/// Ok(Some(key)) /// Ok(Some(key))
/// } /// }
@ -88,16 +88,16 @@ impl<V> CacheNode<V> {
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
pub struct LruCache<V> { pub struct LruCache<K, V> {
map: HashMap<u64, *mut CacheNode<V>>, map: HashMap<K, *mut CacheNode<K, V>>,
head: *mut CacheNode<V>, head: *mut CacheNode<K, V>,
tail: *mut CacheNode<V>, tail: *mut CacheNode<K, V>,
capacity: usize, capacity: usize,
// Dropcheck marker. See the phantom-data section in the rustonomicon. // Dropcheck marker. See the phantom-data section in the rustonomicon.
_marker: PhantomData<Box<CacheNode<V>>>, _marker: PhantomData<Box<CacheNode<K, V>>>,
} }
impl<V> LruCache<V> { impl<K: std::cmp::Eq + std::hash::Hash + Copy, V> LruCache<K, V> {
/// Create LRU cache instance which holds up to `capacity` nodes at once. /// Create LRU cache instance which holds up to `capacity` nodes at once.
pub fn new(capacity: usize) -> Self { pub fn new(capacity: usize) -> Self {
Self { Self {
@ -123,7 +123,7 @@ impl<V> LruCache<V> {
/// Insert or update an entry identified by `key` with the given `value`. /// Insert or update an entry identified by `key` with the given `value`.
/// This entry is placed as the most recently used node at the head. /// This entry is placed as the most recently used node at the head.
pub fn insert(&mut self, key: u64, value: V) { pub fn insert(&mut self, key: K, value: V) {
match self.get_mut(key) { match self.get_mut(key) {
// Key already exists and get_mut brings node to the front, so only update its value. // Key already exists and get_mut brings node to the front, so only update its value.
Some(old_val) => *old_val = value, Some(old_val) => *old_val = value,
@ -140,7 +140,7 @@ impl<V> LruCache<V> {
/// Insert a key, value pair at the front of the linked list and it's pointer /// Insert a key, value pair at the front of the linked list and it's pointer
/// into the HashMap. /// into the HashMap.
fn insert_front(&mut self, key: u64, value: V) { fn insert_front(&mut self, key: K, value: V) {
// First create heap allocated `CacheNode` containing value. // First create heap allocated `CacheNode` containing value.
let mut node = Box::new(CacheNode::new(key, value)); let mut node = Box::new(CacheNode::new(key, value));
// Old head gets new heads next // Old head gets new heads next
@ -165,7 +165,7 @@ impl<V> LruCache<V> {
} }
/// Remove the given `key` and its `value` from the cache. /// Remove the given `key` and its `value` from the cache.
pub fn remove(&mut self, key: u64) -> Option<V> { pub fn remove(&mut self, key: K) -> Option<V> {
// Remove node pointer from the HashMap and get ownership of the node // Remove node pointer from the HashMap and get ownership of the node
let node_ptr = self.map.remove(&key)?; let node_ptr = self.map.remove(&key)?;
let node = unsafe { Box::from_raw(node_ptr) }; let node = unsafe { Box::from_raw(node_ptr) };
@ -209,7 +209,7 @@ impl<V> LruCache<V> {
/// Get a mutable reference to the value identified by `key`. /// Get a mutable reference to the value identified by `key`.
/// This will update the cache entry to be the most recently used entry. /// This will update the cache entry to be the most recently used entry.
/// On cache misses, None is returned. /// On cache misses, None is returned.
pub fn get_mut<'a>(&'a mut self, key: u64) -> Option<&'a mut V> { pub fn get_mut<'a>(&'a mut self, key: K) -> Option<&'a mut V> {
let node_ptr = self.map.get(&key)?; let node_ptr = self.map.get(&key)?;
if *node_ptr == self.head { if *node_ptr == self.head {
// node is already head, just return // node is already head, just return
@ -251,7 +251,7 @@ impl<V> LruCache<V> {
/// value. /// value.
/// If fetch returns a value, it is inserted as the most recently used entry /// If fetch returns a value, it is inserted as the most recently used entry
/// in the cache. /// in the cache.
pub fn access<'a>(&'a mut self, key: u64, cacher: &mut dyn Cacher<V>) -> Result<Option<&'a mut V>, failure::Error> { pub fn access<'a>(&'a mut self, key: K, cacher: &mut dyn Cacher<K, V>) -> Result<Option<&'a mut V>, failure::Error> {
if self.get_mut(key).is_some() { if self.get_mut(key).is_some() {
// get_mut brings the node to the front if present, so just return // get_mut brings the node to the front if present, so just return
return Ok(Some(unsafe { &mut (*self.head).value })); return Ok(Some(unsafe { &mut (*self.head).value }));