How to use Trait in combination with WASM

I'm writing an XML Parser (I know that there are already), but I just want to learn and use it from WASM.
The XML Parser would be an event-based parser, but I don't know how to export the types to the browser using Wasm.

The XML Parser would consume a slice of u8, thus the struct is modelled like:

pub struct XMLReader {
    reader: [u8],
}

Since I want to expose this struct to the WASM, I annotate it with the #[wasm_bindgen] directive, but then the fields needs to have a known size at compile time.
Thus, I change the struct to:

#[wasm_bindgen]
pub struct XMLReader<'a> {
    reader: Box<&'a [u8]>,
}

But now it can't be exposed anymore since I can't export structs with lifetimes on it.

I could use something like this:

#[wasm_bindgen]
pub struct XMLReader {
    reader: Box<dyn BufRead>,
}

And then have the implementation:

impl<'a> XMLReader {
    pub fn from_str(input: &'static str) -> XMLReader {
        Self {
            reader: Box::new(input.as_bytes()),
        }
    }
}

But how can I call this function from JS right now since I need again the lifetime parameter?
I just moved the problem to another place.

It seems I miss some fundamental things.
Any resources which are good for learning rust in combination with WASM? I read the official documentation, but it feels that it doesn't cover all these subtle details.

You can Box<[u8]>, I think that's what you want.

Yeah, Box<&'a [u8]> never makes sense. When people write that, they pretty much always want either Box<[u8]> or &'a [u8], and in your case, you are looking for Box<[u8]>. (or maybe Vec<u8>)

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.