From c027eae51377e7067b3d4c83002609dedaac14e7 Mon Sep 17 00:00:00 2001 From: Alicja Januszkiewicz Date: Tue, 7 May 2024 01:26:29 +0100 Subject: [PATCH] support wasm32-wasi --- src/file.rs | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/file.rs b/src/file.rs index 28876a3..1d324ba 100644 --- a/src/file.rs +++ b/src/file.rs @@ -14,16 +14,26 @@ use std::fmt::{Debug, Formatter}; use std::io::{BufReader, BufWriter, Cursor, Read, Seek, SeekFrom, Write}; use std::path::Path; +// Workaround the absence of File::try_clone with WASM/WASI without penalizing the other platforms +#[cfg(target_family = "wasm")] +type SharedFile = std::sync::Arc; +#[cfg(not(target_family = "wasm"))] +type SharedFile = std::fs::File; + pub struct BufReadWriteFile { - input: BufReader, - output: BufWriter, + input: BufReader, + output: BufWriter, } impl BufReadWriteFile { - fn new(file: std::fs::File) -> std::io::Result { - let input = BufReader::new(file.try_clone()?); - let output = BufWriter::new(file); + fn new(file: SharedFile) -> std::io::Result { + #[cfg(target_family = "wasm")] + let file_ = file.clone(); + #[cfg(not(target_family = "wasm"))] + let file_ = file.try_clone()?; + let input = BufReader::new(file_); + let output = BufWriter::new(file); Ok(Self { input, output }) } } @@ -706,14 +716,15 @@ impl File { let file = options .open(path) .map_err(|error| Error::io_error(error, 0))?; - File::open(BufReadWriteFile::new(file).unwrap()) + let source = BufReadWriteFile::new(file.into()).unwrap(); + File::open(source) } /// Opens an existing dBase file in read only mode pub fn open_read_only>(path: P) -> Result { let file = std::fs::File::open(path.as_ref()).map_err(|error| Error::io_error(error, 0))?; - let mut file = File::open(BufReadWriteFile::new(file).unwrap())?; + let mut file = File::open(BufReadWriteFile::new(file.into()).unwrap())?; if file.fields_info.at_least_one_field_is_memo() { let p = path.as_ref(); let memo_type = file.header.file_type.supported_memo_type(); @@ -726,7 +737,7 @@ impl File { kind: ErrorKind::ErrorOpeningMemoFile(error), })?; - let memo_reader = BufReadWriteFile::new(memo_file) + let memo_reader = BufReadWriteFile::new(memo_file.into()) .and_then(|memo_file| MemoReader::new(mt, memo_file)) .map_err(|error| Error::io_error(error, 0))?; @@ -760,7 +771,7 @@ impl File { pub fn create>(path: P, table_info: TableInfo) -> Result { let file = std::fs::File::create(path).map_err(|error| Error::io_error(error, 0))?; - File::create_new(BufReadWriteFile::new(file).unwrap(), table_info) + File::create_new(BufReadWriteFile::new(file.into()).unwrap(), table_info) } }