如何在Rust中实现fetch-cached-or-load操作?

问题描述 投票:0回答:1

我正在尝试创建一个具有以下操作的简单缓存:“从缓存,必要时加载”。这是一个working example(为了简单起见,使用文件加载):

use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};

#[derive(Debug, Default)]
pub struct FileCache {
    /// Map storing contents of loaded files.
    files: HashMap<PathBuf, Vec<u8>>,
}

impl FileCache {
    /// Get a file's contents, loading it if it hasn't yet been loaded.
    pub fn get(&mut self, path: &Path) -> io::Result<&[u8]> {
        if let Some(_) = self.files.get(path) {
            println!("Cached");
            return Ok(self.files.get(path).expect("just checked"));
        }
        let buf = self.load(path)?;
        Ok(self.files.entry(path.to_owned()).or_insert(buf))
    }
    /// Load a file, returning its contents.
    fn load(&self, path: &Path) -> io::Result<Vec<u8>> {
        println!("Loading");
        let mut buf = Vec::new();
        use std::io::Read;
        File::open(path)?.read_to_end(&mut buf)?;
        Ok(buf)
    }
}

pub fn main() -> io::Result<()> {
    let mut store = FileCache::default();
    let path = Path::new("src/main.rs");
    println!("Length: {}", store.get(path)?.len());
    println!("Length: {}", store.get(path)?.len());
    Ok(())
}

if let的成功分支对self.files.get进行了额外的调用和一个额外的expect。我们只是称呼它,并对其进行模式匹配结果,所以我们只想返回匹配项:

    pub fn get(&mut self, path: &Path) -> io::Result<&[u8]> {
        if let Some(x) = self.files.get(path) {
            println!("Cached");
            return Ok(x);
        }
        let buf = self.load(path)?;
        Ok(self.files.entry(path.to_owned()).or_insert(buf))
    }

但是此fails the borrow checker

error[E0502]: cannot borrow `self.files` as mutable because it is also borrowed as immutable
  --> src/main.rs:20:12
   |
14 |     pub fn get(&mut self, path: &Path) -> io::Result<&[u8]> {
   |                - let's call the lifetime of this reference `'1`
15 |         if let Some(x) = self.files.get(path) {
   |                          ---------- immutable borrow occurs here
16 |             println!("Cached");
17 |             return Ok(x);
   |                    ----- returning this value requires that `self.files` is borrowed for `'1`
...
20 |         Ok(self.files.entry(path.to_owned()).or_insert(buf))
   |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here

我不明白为什么这两个版本的行为会有所不同。是不是在这两种情况下,都在self.files生存期内借入了&self?在第一表格,我们放下借款并获得新的借款,但我不知道为什么应该有所作为。第二种形式如何使我违反内存安全性,以及如何在无需额外查询的情况下编写此代码和expect检查?

我已经阅读了How do I write a rust function that can both read and write to a cache?,与之相关,但是那里的答案要么重复查找(如我的工作示例)或克隆价值(价格昂贵),所以还不够。

rust borrow-checker
1个回答
1
投票

两个实现都应该是合法的Rust代码。 rustc拒绝第二个错误的事实实际上是issue 58910跟踪的错误。

详细说明:

pub fn get(&mut self, path: &Path) -> io::Result<&[u8]> {
    if let Some(x) = self.files.get(path) { // ---+ x
        println!("Cached");                    // |
        return Ok(x);                          // |
    }                                          // |
    let buf = self.load(path)?;                // |
    Ok(self.files.entry(path.to_owned())       // |
        .or_insert(buf))                       // |
}                                              // v

通过在某些表达式中绑定到变量xself.files被作为不可变借用。相同的x之后会返回给调用者,这意味着self.files会一直借用直到调用者中的某个点。因此,在当前的Rust借阅检查器实现中,self.files始终是整个get函数的借用。以后不能再将其视为可变借用。没有考虑到x在提前返回后就不再使用的事实。您的第一个实现可以解决此问题。由于let some(_) = ...不会创建任何绑定,因此不会有相同的问题。尽管由于多次查找,它的确增加了运行时成本。

这是Niko的NLL RFC中描述的problem case #3。好消息是:

TL; DR:Polonius应该可以解决此问题。

([Polonius是还在开发中的Rust借位检查器的第3化身。

© www.soinside.com 2019 - 2024. All rights reserved.