rustwasm-bindgenweb-sys

How does one get typed objects or references from js_sys::Objects, and contained wasm_bindgen::JsValues in Rust


I'm trying to get some data out of a ReadableStream I have this Rust code where I'm trying to handle a drop from the desktop on a Mac. I started with a DataTransfer to get to here.

    let stream: ReadableStream = blob.stream();
    let mut opt = ReadableStreamGetReaderOptions::new();
    opt.mode(ReadableStreamReaderMode::Byob);

    let obj = stream.get_reader_with_options(&opt);  

    // this prints Object { obj: JsValue(ReadableStreamByobReader) }
    info!("obj is: {:?}", obj);

Now I need somehow to get a typed item, (ReadableStreamByobReader) from the Object, That I can get a (Future or Promise) for reading a Rust String in from a small < 4k utf8 source (text file).

// OK, seems there are several ways of "casting" buried in there :)
// this retrieves the reader ( Note I am not checking NONES now
// just trying to sus out API will get cleaned up later. )

let dref = jval.dyn_ref::<ReadableStreamByobReader>();

let byob_reader = Some(dref);

info!("reader is: {:?}", byob_reader);

// now this or something like it needs to be done to 
// wait for or async get what it reads.  It needs an argument
// now I need to discover what type that is supposed to be
// either bytes or some sort of string. Or a result of some 
// type or ? I guess ...

//              byob_reader.and_then(   );

The massive auto generated "function signature" list in the docs is not too helpful unless you already know how to use all the pieces :). And it is pretty far removed from Javascript of which there are very few concrete examples :)


Solution

  • You can search for function signatures on docs.rs, and that search does give unchecked_from_js_ref, scrolling a little down from that you'll find dyn_ref which is it's safe, runtime checked alternative:

    use wasm_bindgen::{JsValue, JsCast};
    use web_sys::ReadableStreamByobReader;
    fn foo(r: &JsValue) -> Option<&ReadableStreamByobReader> {
        r.dyn_ref()
    }