vasi / positioned-io

Read and write from offsets in Rust.
MIT License
74 stars 18 forks source link

Add wasm support #26

Open dtbuchholz opened 4 months ago

dtbuchholz commented 4 months ago

It'd be nice if you if you could use this library when compiling to wasm. E.g., in raf.rs, it starts off with these imports:

#[cfg(windows)]
use std::io::{Seek, SeekFrom};
#[cfg(unix)]
use std::os::unix::fs::FileExt;
#[cfg(windows)]
use std::os::windows::fs::FileExt;
use std::{fs::File, io, io::Write, path::Path, sync::Arc};

This is problematic since a wasm build will try to use the #[cfg(windows)] flag and cause errors downstream.

vasi commented 4 months ago

I don't know anything about wasm, no idea how I'd test it. But patches are very welcome!

dtbuchholz commented 4 months ago

@vasi no worries, i can try to take a stab when i have some time! the gist of it is that there would need to be target arch flags for #[cfg(target_arch = "wasm32")], and then wasm-bindgen enables wasm modules to be interoperable with JavaScript. filesystem access would be provided with with js-sys and web-sys to provide the APIs needed for reading/writing files.

e.g., something like:

// raf.rs
#[cfg(target_arch = "wasm32")]
use js_sys::{ArrayBuffer, Uint8Array};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
#[cfg(target_arch = "wasm32")]
use web_sys::{File, FileReader};

...

#[cfg(target_arch = "wasm32")]
impl ReadAt for RandomAccessFile {
    fn read_at(&self, pos: u64, buf: &mut [u8]) -> io::Result<usize> {
        // WASM implementation for reading from a file...just leaving empty as an example
        unimplemented!("read_at not implemented for WASM")
    }
}

// Cargo.toml
[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = "0.3.69"
wasm-bindgen = "0.2.92"
wasm-bindgen-futures = "0.4.42"
web-sys = { version = "0.3.69", features = ["File", "FileReader"] }