From 98983a9dabacf8e6ea44e44c3b02f4d4e0e2c935 Mon Sep 17 00:00:00 2001 From: Dominik Csapak Date: Thu, 20 Jan 2022 11:16:08 +0100 Subject: [PATCH] pbs-tools: LruCache: implement Drop this fixes the leaked memory for the cache, as we had only pointers in the map/list which were freed, not the underlying chunks moves the 'clear' implementation out of the trait bounds so that Drop can reuse it this is used e.g. for file download from a pxar Signed-off-by: Dominik Csapak Signed-off-by: Wolfgang Bumiller --- pbs-tools/src/lru_cache.rs | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/pbs-tools/src/lru_cache.rs b/pbs-tools/src/lru_cache.rs index b1c0c6ac..fbd7673a 100644 --- a/pbs-tools/src/lru_cache.rs +++ b/pbs-tools/src/lru_cache.rs @@ -100,9 +100,25 @@ pub struct LruCache { _marker: PhantomData>>, } +impl Drop for LruCache { + fn drop (&mut self) { + self.clear(); + } +} + // trivial: if our contents are Send, the whole cache is Send unsafe impl Send for LruCache {} +impl LruCache { + /// Clear all the entries from the cache. + pub fn clear(&mut self) { + // This frees only the HashMap with the node pointers. + self.map.clear(); + // This frees the actual nodes and resets the list head and tail. + self.list.clear(); + } +} + impl LruCache { /// Create LRU cache instance which holds up to `capacity` nodes at once. pub fn new(capacity: usize) -> Self { @@ -115,14 +131,6 @@ impl LruCache { } } - /// Clear all the entries from the cache. - pub fn clear(&mut self) { - // This frees only the HashMap with the node pointers. - self.map.clear(); - // This frees the actual nodes and resets the list head and tail. - self.list.clear(); - } - /// 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. pub fn insert(&mut self, key: K, value: V) {