sos_client/source/
cache_yes.rs

1use std::fs::File;
2use std::path::Path;
3
4use super::base::SourceTrait;
5#[cfg(feature = "look-ahead")]
6use super::look_ahead_yes::PrebuiltData;
7use super::root::SourceRoot;
8use crate::error::*;
9
10use serde::{de::DeserializeOwned, Serialize};
11
12const PATH_CACHE: &str = "./.cache";
13#[cfg(feature = "look-ahead")]
14const PATH_CACHE_PREBUILT: &str = "./.prebuilt.cache";
15
16impl<V, Imp> SourceRoot<V, Imp>
17where
18    Imp: SourceTrait,
19{
20    pub fn load<P>(root: P, imp: Imp) -> Result<Self>
21    where
22        P: AsRef<Path>,
23        V: DeserializeOwned,
24    {
25        let root = root.as_ref();
26
27        let path = root.join(PATH_CACHE);
28        if path.exists() {
29            let file = File::open(path)?;
30            Ok(Self {
31                #[cfg(feature = "look-ahead")]
32                prebuilt: load_prebuilt_data(root, &imp)?,
33                data: bincode::deserialize_from(file)?,
34                root: root.to_owned(),
35                imp,
36            })
37        } else {
38            Self::new(root, imp)
39        }
40    }
41
42    pub fn save(&self) -> Result<()>
43    where
44        V: Serialize,
45    {
46        #[cfg(feature = "look-ahead")]
47        {
48            let file = File::create(self.root.join(PATH_CACHE_PREBUILT))?;
49            bincode::serialize_into(file, &self.prebuilt)?;
50        }
51
52        {
53            let file = File::create(self.root.join(PATH_CACHE))?;
54            bincode::serialize_into(file, &self.data)?;
55        }
56        Ok(())
57    }
58}
59
60#[cfg(feature = "look-ahead")]
61fn load_prebuilt_data<Imp>(root: &Path, imp: &Imp) -> Result<PrebuiltData<Imp::PrebuiltCode>>
62where
63    Imp: SourceTrait,
64{
65    let path = root.join(PATH_CACHE_PREBUILT);
66    if path.exists() {
67        let file = File::open(path)?;
68        Ok(PrebuiltData {
69            inner: bincode::deserialize_from(file)?,
70        })
71    } else {
72        Ok(PrebuiltData::load(root, imp))
73    }
74}