Skip to main content

wgame_fs/
lib.rs

1//! Cross-platform file reading utilities.
2//!
3//! Provides async file reading for both desktop (std) and web platforms.
4//! Native paths are relative to the process working directory; web paths are URLs
5//! relative to the page. Embed bytes when assets must work from any directory.
6//!
7//! # Examples
8//!
9//! ```rust
10//! use wgame_fs::{read_bytes, read_string};
11//!
12//! async fn example() -> anyhow::Result<()> {
13//!     // Read file as bytes
14//!     let bytes = read_bytes("assets/image.png").await?;
15//!     
16//!     // Read file as string
17//!     let text = read_string("assets/config.json").await?;
18//!     
19//!     Ok(())
20//! }
21//! ```
22
23#![forbid(unsafe_code)]
24
25pub type Path = str;
26pub type PathBuf = String;
27
28/// Reads a file and returns its contents as bytes.
29#[cfg(feature = "std")]
30pub async fn read_bytes(path: impl AsRef<Path>) -> anyhow::Result<Vec<u8>> {
31    Ok(async_fs::read(path.as_ref()).await?)
32}
33
34/// Reads a file and returns its contents as a string.
35#[cfg(feature = "std")]
36pub async fn read_string(path: impl AsRef<Path>) -> anyhow::Result<String> {
37    Ok(async_fs::read_to_string(path.as_ref()).await?)
38}
39
40#[cfg(feature = "web")]
41mod web {
42    use crate::Path;
43    use anyhow::{Context, Error, Result, anyhow, bail};
44    use js_sys::{ArrayBuffer, Uint8Array};
45    use wasm_bindgen::prelude::*;
46    use wasm_bindgen_futures::JsFuture;
47    use web_sys::{Request, RequestInit, RequestMode, Response};
48
49    fn value_to_error(value: JsValue) -> Error {
50        anyhow!("{value:?}")
51    }
52
53    async fn request(path: &str) -> Result<Response> {
54        let opts = RequestInit::new();
55        opts.set_method("GET");
56        opts.set_mode(RequestMode::Cors);
57
58        let request = Request::new_with_str_and_init(path, &opts).map_err(value_to_error)?;
59
60        /*
61        request
62            .headers()
63            .set("Accept", "application/json")?;
64        */
65
66        let window = web_sys::window().unwrap();
67        let resp_value = JsFuture::from(window.fetch_with_request(&request))
68            .await
69            .map_err(value_to_error)?;
70
71        // `resp_value` is a `Response` object.
72        assert!(resp_value.is_instance_of::<Response>());
73        let resp: Response = resp_value.dyn_into().unwrap();
74
75        let status = resp.status();
76        log::info!("Status: {status}");
77        if status != 200 {
78            bail!("Status {}: {}", status, resp.status_text())
79        }
80
81        Ok(resp)
82    }
83
84    async fn request_bytes(path: &str) -> Result<Vec<u8>> {
85        let resp = request(path).await?;
86
87        // Convert this other `Promise` into a rust `Future`.
88        let buffer_value = JsFuture::from(resp.array_buffer().map_err(value_to_error)?)
89            .await
90            .map_err(value_to_error)?;
91
92        assert!(buffer_value.is_instance_of::<ArrayBuffer>());
93        let buffer: ArrayBuffer = buffer_value.dyn_into().unwrap();
94
95        let byte_array =
96            Uint8Array::new_with_byte_offset_and_length(&buffer, 0, buffer.byte_length());
97
98        Ok(byte_array.to_vec())
99    }
100
101    async fn request_string(path: &str) -> Result<String> {
102        let resp = request(path).await?;
103
104        // Convert this other `Promise` into a rust `Future`.
105        let string_value = JsFuture::from(resp.text().map_err(value_to_error)?)
106            .await
107            .map_err(value_to_error)?;
108
109        let string = string_value.as_string().unwrap();
110
111        Ok(string)
112    }
113
114    /// Reads a file and returns its contents as bytes.
115    pub async fn read_bytes(path: impl AsRef<Path>) -> Result<Vec<u8>> {
116        request_bytes(path.as_ref())
117            .await
118            .context("Request bytes error")
119    }
120
121    /// Reads a file and returns its contents as a string.
122    pub async fn read_string(path: impl AsRef<Path>) -> Result<String> {
123        request_string(path.as_ref())
124            .await
125            .context("Request string error")
126    }
127}
128
129#[cfg(feature = "web")]
130pub use web::{read_bytes, read_string};