smpl_utils/
io.rs

1pub struct FileLoader {}
2#[cfg(not(target_arch = "wasm32"))]
3use std::fs::File;
4#[cfg(not(target_arch = "wasm32"))]
5impl FileLoader {
6    /// # Panics
7    /// Will panic if the path cannot be opened
8    #[allow(clippy::unused_async)]
9    pub async fn open(file_path: &str) -> File {
10        File::open(file_path).unwrap()
11    }
12}
13#[cfg(target_arch = "wasm32")]
14use {
15    std::io::Cursor,
16    wasm_bindgen::JsCast,
17    wasm_bindgen_futures::JsFuture,
18    web_sys::{Request, RequestInit, RequestMode, Response},
19};
20#[cfg(target_arch = "wasm32")]
21impl FileLoader {
22    pub async fn open(file_path: &str) -> Cursor<Vec<u8>> {
23        let result = fetch_as_binary(file_path).await.unwrap();
24        Cursor::new(result)
25    }
26}
27#[cfg(target_arch = "wasm32")]
28pub async fn fetch_as_binary(url: &str) -> Result<Vec<u8>, String> {
29    let opts = RequestInit::new();
30    opts.set_method("GET");
31    opts.set_mode(RequestMode::Cors);
32    let request = match Request::new_with_str_and_init(&url, &opts) {
33        Ok(request) => request,
34        Err(_e) => return Err("Failed to create request".to_string()),
35    };
36    let window = web_sys::window().unwrap();
37    let response = match JsFuture::from(window.fetch_with_request(&request)).await {
38        Ok(response) => response,
39        Err(_e) => return Err("Failed to fetch".to_string()),
40    };
41    let response: Response = match response.dyn_into() {
42        Ok(response) => response,
43        Err(_e) => return Err("Failed to dyn_into Response".to_string()),
44    };
45    let buffer = match response.array_buffer() {
46        Ok(buffer) => buffer,
47        Err(_e) => return Err("Failed to get as array buffer".to_string()),
48    };
49    let buffer = match JsFuture::from(buffer).await {
50        Ok(buffer) => buffer,
51        Err(_e) => return Err("Failed to ...?".to_string()),
52    };
53    Ok(js_sys::Uint8Array::new(&buffer).to_vec())
54}
55/// associating a extension with a enum
56use strum::IntoEnumIterator;
57use strum_macros::EnumIter;
58#[derive(Debug, EnumIter)]
59pub enum FileType {
60    Smpl,
61    Gltf,
62    Mcs,
63    Unknown,
64}
65impl FileType {
66    pub fn value(&self) -> &'static [&'static str] {
67        match self {
68            Self::Smpl => &["smpl"],
69            Self::Gltf => &["gltf"],
70            Self::Mcs => &["mcs"],
71            Self::Unknown => &[""],
72        }
73    }
74    pub fn find_match(ext: &str) -> Self {
75        Self::iter()
76            .find(|filetype| filetype.value().contains(&(ext.to_lowercase()).as_str()))
77            .unwrap_or(FileType::Unknown)
78    }
79}