Struct LruCache

Source
pub struct LruCache<K, V, S> { /* private fields */ }
Expand description

LRU 全称是Least Recently Used,即最近最久未使用的意思 一个 LRU 缓存普通级的实现, 接口参照Hashmap保持一致 设置容量之后将最大保持该容量大小的数据 后进的数据将会淘汰最久没有被访问的数据

§Examples

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("now", "ok");
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    lru.insert("auth", "tickbh");
    assert!(lru.len() == 3);
    assert_eq!(lru.get("hello"), Some(&"algorithm"));
    assert_eq!(lru.get("this"), Some(&"lru"));
    assert_eq!(lru.get("now"), None);
}

Implementations§

Source§

impl<K: Hash + Eq, V> LruCache<K, V, DefaultHasher>

Source

pub fn new(cap: usize) -> Self

Source§

impl<K, V, S> LruCache<K, V, S>

Source

pub fn with_hasher(cap: usize, hash_builder: S) -> LruCache<K, V, S>

提供hash函数

Source

pub fn get_check_step(&self) -> u64

获取当前检查lru的间隔

Source

pub fn set_check_step(&mut self, check_step: u64)

设置当前检查lru的间隔 单位为秒,意思就是每隔多少秒会清理一次数据 如果数据太大的话遍历一次可能会比较久的时长 一次清理时间复杂度O(n) 仅仅在插入时触发检查,获取时仅检查当前元素

Source

pub fn capacity(&self) -> usize

获取当前容量

Source

pub fn clear(&mut self)

清理当前数据

§Examples
use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("now", "ok");
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    assert!(lru.len() == 3);
    lru.clear();
    assert!(lru.len() == 0);
}
Source

pub fn len(&self) -> usize

获取当前长度

Source

pub fn is_full(&self) -> bool

Source

pub fn is_empty(&self) -> bool

Source

pub fn reserve(&mut self, additional: usize) -> &mut Self

扩展当前容量

Source

pub fn iter(&self) -> Iter<'_, K, V>

遍历当前的所有值

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    for (k, v) in lru.iter() {
        assert!(k == &"hello" || k == &"this");
        assert!(v == &"algorithm" || v == &"lru");
    }
    assert!(lru.len() == 2);
}
Source

pub fn iter_mut(&mut self) -> IterMut<'_, K, V>

遍历当前的所有值, 可变

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm".to_string());
    lru.insert("this", "lru".to_string());
    for (k, v) in lru.iter_mut() {
        v.push_str(" ok");
    }
    assert!(lru.len() == 2);
    assert!(lru.get(&"this") == Some(&"lru ok".to_string()));
    assert!(lru.get(&"hello") == Some(&"algorithm ok".to_string()));
}
Source

pub fn keys(&self) -> Keys<'_, K, V>

遍历当前的key值

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    let mut keys = lru.keys();
    assert!(keys.next()==Some(&"this"));
    assert!(keys.next()==Some(&"hello"));
    assert!(keys.next() == None);
}
Source

pub fn values(&self) -> Values<'_, K, V>

遍历当前的valus值

use algorithm::LruCache;
fn main() {
    let vec = vec![(1, 1), (2, 2), (3, 3)];
    let mut map: LruCache<_, _, _> = vec.into_iter().collect();
    for value in map.values_mut() {
    *value = (*value) * 2
    }
    let values: Vec<_> = map.values().cloned().collect();
    assert_eq!(values.len(), 3);
    assert!(values.contains(&2));
    assert!(values.contains(&4));
    assert!(values.contains(&6));
}
Source

pub fn values_mut(&mut self) -> ValuesMut<'_, K, V>

遍历当前的valus值

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm".to_string());
    lru.insert("this", "lru".to_string());
    {
        let mut values = lru.values_mut();
        values.next().unwrap().push_str(" ok");
        values.next().unwrap().push_str(" ok");
        assert!(values.next() == None);
    }
    assert_eq!(lru.get(&"this"), Some(&"lru ok".to_string()))
}
Source

pub fn hasher(&self) -> &S

Source§

impl<K: Hash + Eq, V, S: BuildHasher> LruCache<K, V, S>

Source

pub fn full_increase(&mut self)

Source

pub fn full_decrease(&mut self) -> Option<(K, V)>

Source

pub fn drain(&mut self) -> Drain<'_, K, V, S>

排出当前数据

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    {
        let mut drain = lru.drain();
        assert!(drain.next()==Some(("hello", "algorithm")));
    }
    assert!(lru.len() == 0);
}
Source

pub fn pop_usual(&mut self) -> Option<(K, V)>

弹出栈顶上的数据, 最常使用的数据

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    assert!(lru.pop_usual()==Some(("this", "lru")));
    assert!(lru.len() == 1);
}
Source

pub fn pop_unusual(&mut self) -> Option<(K, V)>

弹出栈尾上的数据, 最久未使用的数据

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    assert!(lru.pop_unusual()==Some(("hello", "algorithm")));
    assert!(lru.len() == 1);
}
Source

pub fn peek_usual(&mut self) -> Option<(&K, &V)>

取出栈顶上的数据, 最近使用的数据

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    assert!(lru.peek_usual()==Some((&"this", &"lru")));
    assert!(lru.len() == 2);
}
Source

pub fn peek_unusual(&mut self) -> Option<(&K, &V)>

取出栈尾上的数据, 最久未使用的数据

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    assert!(lru.peek_unusual()==Some((&"hello", &"algorithm")));
    assert!(lru.len() == 2);
}
Source

pub fn contains_key<Q>(&mut self, k: &Q) -> bool
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Source

pub fn raw_get<Q>(&self, k: &Q) -> Option<&V>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

获取key值相对应的value值, 根据hash判定

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    assert!(lru.raw_get(&"this") == Some(&"lru"));
}
Source

pub fn get<Q>(&mut self, k: &Q) -> Option<&V>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

获取key值相对应的value值, 根据hash判定

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    assert!(lru.get(&"this") == Some(&"lru"));
}
Source

pub fn get_key_value<Q>(&mut self, k: &Q) -> Option<(&K, &V)>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

获取key值相对应的key和value值, 根据hash判定

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    assert!(lru.get_key_value(&"this") == Some((&"this", &"lru")));
}
Source

pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

获取key值相对应的value值, 根据hash判定, 可编辑被改变

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm".to_string());
    lru.insert("this", "lru".to_string());
    lru.get_mut(&"this").unwrap().insert_str(3, " good");
    assert!(lru.get_key_value(&"this") == Some((&"this", &"lru good".to_string())));
}
Source

pub fn get_mut_key_value<Q>(&mut self, k: &Q) -> Option<(&K, &mut V)>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Source

pub fn insert(&mut self, k: K, v: V) -> Option<V>

插入值, 如果值重复将返回原来的数据

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    assert!(lru.insert("this", "lru good") == Some(&"lru"));
}
Source

pub fn insert_with_ttl(&mut self, k: K, v: V, ttl: u64) -> Option<V>

插入带有生存时间的元素 每次获取像redis一样,并不会更新生存时间 如果需要更新则需要手动的进行重新设置

Source

pub fn capture_insert(&mut self, k: K, v: V) -> Option<(K, V, bool)>

Source

pub fn capture_insert_with_ttl( &mut self, k: K, v: V, ttl: u64, ) -> Option<(K, V, bool)>

Source

pub fn get_or_insert<F>(&mut self, k: K, f: F) -> &V
where F: FnOnce() -> V,

Source

pub fn get_or_insert_mut<'a, F>(&'a mut self, k: K, f: F) -> &mut V
where F: FnOnce() -> V,

Source

pub fn clear_expire(&mut self)

Source

pub fn del_ttl<Q>(&mut self, k: &Q)
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Source

pub fn set_ttl<Q>(&mut self, k: &Q, expire: u64) -> bool
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Source

pub fn get_ttl<Q>(&mut self, k: &Q) -> Option<u64>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Source

pub fn remove<Q>(&mut self, k: &Q) -> Option<(K, V)>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

移除元素

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    assert!(lru.remove("this") == Some(("this", "lru")));
    assert!(lru.len() == 1);
}
Source

pub fn remove_with_ttl<Q>(&mut self, k: &Q) -> Option<(K, V, u64)>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Source

pub fn retain<F>(&mut self, f: F)
where F: FnMut(&K, &mut V) -> bool,

根据保留当前的元素, 返回false则表示抛弃元素

use algorithm::LruCache;
fn main() {
    let mut lru = LruCache::new(3);
    lru.insert("hello", "algorithm");
    lru.insert("this", "lru");
    lru.insert("year", "2024");
    lru.retain(|_, v| *v == "2024" || *v == "lru");
    assert!(lru.len() == 2);
    assert!(lru.get("this") == Some(&"lru"));
}
Source§

impl<K: Hash + Eq, V: Default, S: BuildHasher> LruCache<K, V, S>

Source

pub fn get_or_insert_default(&mut self, k: K) -> &V

Source

pub fn get_or_insert_default_mut(&mut self, k: K) -> &mut V

Trait Implementations§

Source§

impl<K: Clone + Hash + Eq, V: Clone, S: Clone + BuildHasher> Clone for LruCache<K, V, S>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<K, V, S> Debug for LruCache<K, V, S>
where K: Ord + Debug, V: Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<K: Hash + Eq, V> Default for LruCache<K, V, DefaultHasher>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<K, V, S> Drop for LruCache<K, V, S>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<K: Hash + Eq, V> Extend<(K, V)> for LruCache<K, V, DefaultHasher>

Source§

fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<K: Hash + Eq, V> FromIterator<(K, V)> for LruCache<K, V, DefaultHasher>

Source§

fn from_iter<T: IntoIterator<Item = (K, V)>>( iter: T, ) -> LruCache<K, V, DefaultHasher>

Creates a value from an iterator. Read more
Source§

impl<'a, K, V, S> Index<&'a K> for LruCache<K, V, S>
where K: Hash + Eq, S: BuildHasher,

Source§

type Output = V

The returned type after indexing.
Source§

fn index(&self, index: &K) -> &V

Performs the indexing (container[index]) operation. Read more
Source§

impl<'a, K, V, S> IndexMut<&'a K> for LruCache<K, V, S>
where K: Hash + Eq, S: BuildHasher,

Source§

fn index_mut(&mut self, index: &K) -> &mut V

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl<K: Hash + Eq, V, S: BuildHasher> IntoIterator for LruCache<K, V, S>

Source§

type Item = (K, V)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<K, V, S>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> IntoIter<K, V, S>

Creates an iterator from a value. Read more
Source§

impl<K, V, S> PartialEq for LruCache<K, V, S>
where K: Eq + Hash, V: PartialEq, S: BuildHasher,

Source§

fn eq(&self, other: &LruCache<K, V, S>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<K, V, S> Eq for LruCache<K, V, S>
where K: Eq + Hash, V: PartialEq, S: BuildHasher,

Source§

impl<K: Send, V: Send, S: Send> Send for LruCache<K, V, S>

Source§

impl<K: Sync, V: Sync, S: Sync> Sync for LruCache<K, V, S>

Auto Trait Implementations§

§

impl<K, V, S> Freeze for LruCache<K, V, S>
where S: Freeze,

§

impl<K, V, S> RefUnwindSafe for LruCache<K, V, S>

§

impl<K, V, S> Unpin for LruCache<K, V, S>
where S: Unpin,

§

impl<K, V, S> UnwindSafe for LruCache<K, V, S>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.