Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make file loading async on desktop #405

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 14 additions & 15 deletions src/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl From<std::io::Error> for Error {
pub type Response = Result<Vec<u8>, Error>;

/// Filesystem path on desktops or HTTP URL in WASM
pub fn load_file<F: Fn(Response) + 'static>(path: &str, on_loaded: F) {
pub fn load_file<F: Fn(Response) + 'static + Send>(path: &str, on_loaded: F) {
#[cfg(target_arch = "wasm32")]
wasm::load_file(path, on_loaded);

Expand Down Expand Up @@ -116,18 +116,17 @@ mod wasm {
}

#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
fn load_file_desktop<F: Fn(Response)>(path: &str, on_loaded: F) {
fn load_file_sync(path: &str) -> Response {
use std::fs::File;
use std::io::Read;

let mut response = vec![];
let mut file = File::open(path)?;
file.read_to_end(&mut response)?;
Ok(response)
}

let response = load_file_sync(path);

on_loaded(response);
fn load_file_desktop<F: Fn(Response) + Send + 'static>(path: &str, on_loaded: F) {
use std::fs::File;
use std::io::Read;
let file = File::open(path);
std::thread::spawn(move || {
let res = file.map_err(Error::from).and_then(|mut file| {
let mut response = vec![];
file.read_to_end(&mut response)
.map_err(Error::from)
.map(|_| response)
});
on_loaded(res);
});
}
Loading