如何在Rust中实现静态缓存?

时间:2019-06-24 01:21:39

标签: rust lifetime

我想在rust中实现静态缓存。

我尝试了chashmap

extern crate chashmap;
extern crate lazy_static;
use chashmap::{CHashMap, ReadGuard};
use lazy_static::lazy_static;
use std::collections::HashMap;

struct Data {}

#[derive(Default)]
struct Merged {
    types: HashMap<String, Data>,
}

fn merge(ls: &[String]) -> ReadGuard<'static, Vec<String>, Merged> {
    lazy_static! {
        static ref CACHE: CHashMap<Vec<String>, Merged> = Default::default();
    }

    let libs = ls.to_vec();

    let merged = Merged::default();

    CACHE.insert(libs, merged);

    return CACHE.get(ls).unwrap();
}

fn get<'a>(ls: &[String], name: &str) -> Option<&'a Data> {
    let lib = merge(ls);

    if let Some(ty) = lib.types.get(name) {
        return Some(&*ty);
    }

    None
}

fn main() {}
[package]
name = "stackoverflow-56728860"
version = "0.1.0"
authors = ["강동윤 <kdy1@outlook.kr>"]
edition = "2018"

[dependencies]
lazy_static = "1"
chashmap = "2"

github repo

但是我想从该函数返回对数据的静态引用。返回的数据仅取决于ls。也就是说,如果输入(ls)相同,则结果将相同。

此外,如果释放读取锁,则可以泄漏数据。

1 个答案:

答案 0 :(得分:0)

我以某种方式解决了泄漏问题。

fn merge(ls: &[Lib]) -> &'static Merged {
    lazy_static! {
        static ref CACHE: CHashMap<Vec<Lib>, &'static Merged> = Default::default();
    }

    // ...

    CACHE.insert(libs, Box::leak(merged));

    return &*CACHE.get(ls).unwrap();
}