oxygengine_core/fetch/engines/
fs.rs

1#![cfg(not(feature = "web"))]
2
3use crate::fetch::{FetchCancelReason, FetchEngine, FetchProcess, FetchStatus};
4use std::{
5    env::var,
6    path::{Path, PathBuf},
7};
8
9#[derive(Clone)]
10pub struct FsFetchEngine {
11    root_path: PathBuf,
12}
13
14impl Default for FsFetchEngine {
15    fn default() -> Self {
16        Self {
17            root_path: match var("OXY_FETCH_ENGINE_PATH") {
18                Ok(value) => value.into(),
19                Err(_) => Default::default(),
20            },
21        }
22    }
23}
24
25impl FsFetchEngine {
26    pub fn new<S: AsRef<Path>>(root_path: &S) -> Self {
27        Self {
28            root_path: match var("OXY_FETCH_ENGINE_PATH") {
29                Ok(value) => value.into(),
30                Err(_) => root_path.as_ref().into(),
31            },
32        }
33    }
34}
35
36impl FetchEngine for FsFetchEngine {
37    fn fetch(&mut self, path: &str) -> Result<Box<FetchProcess>, FetchStatus> {
38        #[cfg(feature = "parallel")]
39        {
40            let path = self.root_path.join(path);
41            let process = FetchProcess::new_start();
42            let mut p = process.clone();
43            rayon::spawn(move || {
44                if let Ok(bytes) = std::fs::read(path) {
45                    p.done(bytes);
46                } else {
47                    p.cancel(FetchCancelReason::Error);
48                }
49            });
50            Ok(Box::new(process))
51        }
52        #[cfg(not(feature = "parallel"))]
53        {
54            if let Ok(bytes) = std::fs::read(self.root_path.join(path)) {
55                Ok(Box::new(FetchProcess::new_done(bytes)))
56            } else {
57                Err(FetchStatus::Canceled(FetchCancelReason::Error))
58            }
59        }
60    }
61}