#file-reader #wasm-bindgen #web #read #file-read #seek #u64

wasm-bindgen-file-reader

Implement Read+Seek for web_sys::File

1 stable release

1.0.0 Jul 1, 2022

#1110 in WebAssembly

Download history 44/week @ 2024-07-20 55/week @ 2024-07-27 44/week @ 2024-08-03 26/week @ 2024-08-10 18/week @ 2024-08-17 33/week @ 2024-08-24 29/week @ 2024-08-31 29/week @ 2024-09-07 49/week @ 2024-09-14 30/week @ 2024-09-21 32/week @ 2024-09-28 23/week @ 2024-10-05 35/week @ 2024-10-12 59/week @ 2024-10-19 19/week @ 2024-10-26 13/week @ 2024-11-02

128 downloads per month
Used in proofmode

GPL-3.0 license

16KB
100 lines

wasm-bindgen-file-reader

This crate implements a wrapper around a web_sys::File that implements Read and Seek. This is useful when you have a Rust crate that expects a generic reader and want to use it in WebAssembly without loading the entire file into memory and using a std::io::Cursor.

Note: this only works in a web worker context because it uses the synchronous FileReaderSync interface.

Installation

Add to Cargo.toml:

wasm-bindgen-file-reader = "1"

Usage

See the demo for more information.

Rust code:

use wasm_bindgen_file_reader::WebSysFile;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;

/// Read one byte from the file at a given offset.
#[wasm_bindgen]
pub fn read_at_offset_sync(file: web_sys::File, offset: u64) -> u8 {
    let mut wf = WebSysFile::new(file);

    // Now we can seek as if this was a real file
    wf.seek(SeekFrom::Start(offset))
        .expect("failed to seek to offset");

    // Use 1-byte buffer because we only want to read one byte
    let mut buf = [0];

    // The Read API works as with real files
    wf.read_exact(&mut buf).expect("failed to read bytes");

    buf[0]
}

Javascript code (index.html):

let myWorker = new Worker("worker.js");
document.getElementById("filepicker").addEventListener(
    "change",
    function() {
        let file = this.files[0];
        myWorker.postMessage({ file: file, offset: 0 });
        myWorker.onmessage = function(e) {
            console.log("First byte of file is: ", e.data);
        };
    },
    false
);

Javascript code (worker.js):

onmessage = async function(e) {
    let wasm_bindgen_file_reader_test = await Rust.wasm_bindgen_file_reader_test;
    let workerResult = wasm_bindgen_file_reader_test.read_at_offset_sync(
        e.data.file,
        e.data.offset,
    );
    postMessage(workerResult);
};

Dependencies

~7.5–10MB
~182K SLoC