7个版本

0.10.1 2020年7月6日
0.10.0 2018年7月22日
0.9.0 2018年6月19日
0.8.4 2017年7月31日

#113 in 缓存

Download history 132/week @ 2024-03-13 119/week @ 2024-03-20 78/week @ 2024-03-27 144/week @ 2024-04-03 139/week @ 2024-04-10 133/week @ 2024-04-17 80/week @ 2024-04-24 98/week @ 2024-05-01 101/week @ 2024-05-08 77/week @ 2024-05-15 71/week @ 2024-05-22 92/week @ 2024-05-29 85/week @ 2024-06-05 151/week @ 2024-06-12 89/week @ 2024-06-19 87/week @ 2024-06-26

每月429次下载
3 crates 中使用

MIT/Apache

38KB
450

双队列(2Q)缓存

将键映射到值的2Q缓存

2Q是对LRU缓存的改进,通过分别跟踪最近访问和频繁访问的条目,从而避免了缓存被大量新条目扫描而损坏:只有最近列表会被清理。

缓存分为三个部分,最近条目、频繁条目和幽灵条目。最近包含最新添加的条目。频繁是一个LRU缓存,包含频繁访问的条目。幽灵包含最近从最近缓存中移除的键。

缓存中的新条目最初放置在最近部分。当最近部分填满后,最近部分最老的条目将被移除,其键将被放置在幽灵部分。当一个条目被请求但未找到,但其键在幽灵列表中找到时,该条目将被推送到频繁部分的前面。

示例

use cache_2q::Cache;

// type inference lets us omit an explicit type signature (which
// would be `Cache<&str, &str>` in this example).
let mut book_reviews = Cache::new(1024);

// review some books.
book_reviews.insert("Adventures of Huckleberry Finn",    "My favorite book.");
book_reviews.insert("Grimms' Fairy Tales",               "Masterpiece.");
book_reviews.insert("Pride and Prejudice",               "Very enjoyable.");
book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");

// check for a specific one.
if !book_reviews.contains_key("Les Misérables") {
    println!("We've got {} reviews, but Les Misérables ain't one.",
             book_reviews.len());
}

// oops, this review has a lot of spelling mistakes, let's delete it.
book_reviews.remove("The Adventures of Sherlock Holmes");

// look up the values associated with some keys.
let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
for book in &to_find {
    match book_reviews.get(book) {
        Some(review) => println!("{}: {}", book, review),
        None => println!("{} is unreviewed.", book)
    }
}

// iterate over everything.
for (book, review) in &book_reviews {
    println!("{}: \"{}\"", book, review);
}

缓存还实现了条目API,允许进行更复杂的方法来获取、设置、更新和删除键及其值

use cache_2q::Cache;

// type inference lets us omit an explicit type signature (which
// would be `Cache<&str, u8>` in this example).
let mut player_stats = Cache::new(32);

fn random_stat_buff() -> u8 {
    // could actually return some random value here - let's just return
    // some fixed value for now
    42
}

// insert a key only if it doesn't already exist
player_stats.entry("health").or_insert(100);

// insert a key using a function that provides a new value only if it
// doesn't already exist
player_stats.entry("defence").or_insert_with(random_stat_buff);

// update a key, guarding against the key possibly not being set
let stat = player_stats.entry("attack").or_insert(100);
*stat += random_stat_buff();

依赖项

~49KB