rg3d_core/
io.rs

1use std::io::Error;
2use std::path::Path;
3
4#[derive(Debug)]
5pub enum FileLoadError {
6    Io(std::io::Error),
7    Custom(String),
8}
9
10impl From<std::io::Error> for FileLoadError {
11    fn from(e: Error) -> Self {
12        Self::Io(e)
13    }
14}
15
16#[cfg(target_arch = "wasm32")]
17impl From<wasm_bindgen::JsValue> for FileLoadError {
18    fn from(value: wasm_bindgen::JsValue) -> Self {
19        let string = match js_sys::JSON::stringify(&value) {
20            Ok(string) => String::from(string),
21            Err(_) => format!("{:?}", value),
22        };
23        Self::Custom(string)
24    }
25}
26
27pub async fn load_file<P: AsRef<Path>>(path: P) -> Result<Vec<u8>, FileLoadError> {
28    #[cfg(not(target_arch = "wasm32"))]
29    {
30        use std::fs::File;
31        use std::io::Read;
32
33        let mut file = File::open(path)?;
34        let mut buffer = Vec::new();
35        file.read_to_end(&mut buffer)?;
36        Ok(buffer)
37    }
38
39    #[cfg(target_arch = "wasm32")]
40    {
41        use js_sys::Uint8Array;
42        use wasm_bindgen::JsCast;
43        use wasm_bindgen_futures::JsFuture;
44
45        match web_sys::window() {
46            Some(window) => {
47                let resp_value =
48                    JsFuture::from(window.fetch_with_str(path.as_ref().to_str().unwrap())).await?;
49
50                let resp: web_sys::Response = resp_value.dyn_into().unwrap();
51                let data = JsFuture::from(resp.array_buffer().unwrap()).await?;
52                let bytes = Uint8Array::new(&data).to_vec();
53                Ok(bytes)
54            }
55            None => Err(FileLoadError::Custom("Window not found!".to_owned())),
56        }
57    }
58}
59
60pub async fn exists<P: AsRef<Path>>(path: P) -> bool {
61    #[cfg(not(target_arch = "wasm32"))]
62    {
63        path.as_ref().exists()
64    }
65
66    #[cfg(target_arch = "wasm32")]
67    {
68        use wasm_bindgen::JsCast;
69        use wasm_bindgen_futures::JsFuture;
70
71        match web_sys::window() {
72            Some(window) => {
73                if let Ok(resp_value) =
74                    JsFuture::from(window.fetch_with_str(path.as_ref().to_str().unwrap())).await
75                {
76                    let resp: web_sys::Response = resp_value.dyn_into().unwrap();
77
78                    resp.status() == 200
79                } else {
80                    false
81                }
82            }
83            None => false,
84        }
85    }
86}