How to serialize integer to string in wasm-bindgen?

Sorry I know little of JS and WASM.

I used to use wasm-bindgen to generate WASM for JS, but there're errors when JS use big-int or integer overflow or precision lost. I wonder if I could convert integer part of struct into string when send to JS, and convert string to integer when received from JS.

For example:

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Data {
    pub x: Option<u64>,
    pub y: i64,
    pub z: bool,
} 

#[wasm_bindgen]
pub struct Record {
    pub(crate) data: Data,
}

Is there a way to serialize Record's number parts to string? So JS could use string instead of integer to interact with WASM, and there will be no more integer overflow issues or precision lost issues.

And the use case should be:

// JS example
d = {
    x: '123456789',
    y: '-19919',
    z: 'false'
}

record = {d: data}

// Send record to WASM(Rust) side
// Or Get returned record from WASM side

And Rust side can handle string-ed JS sent data, parse it into struct Record.

Yes, it is possible to write a module usable with #[serde(with = "...")] that will do this by going through the corresponding impl for String.

2 Likes

Thanks for reply. What if there are many structs contains number field, do I need impl String for each of them? Does wasm-bindgen have some attribute that can take care this situation?

You would need to put the attribute on each field.

1 Like

There are many crates available which can be used with serde's with if you don't want reimplement the logic. For String serialization there are serde_str and serde_with and also serde-aux for deserialization.