dtolnay / typetag

Serde serializable and deserializable trait objects
Apache License 2.0
1.19k stars 38 forks source link

Deserialization fails with "Unknown Variant" error when using `wasm-bindgen` #8

Closed cwhakes closed 5 years ago

cwhakes commented 5 years ago

Example: https://github.com/cwhakes/typetag-test

When using wasm-bindgen v0.2.40, deserializing trait objects fails, while similar code on native targets (in my case Windows) succeeds. Serializing seems to work well.

use wasm_bindgen::prelude::*;

use serde::{Serialize, Deserialize};

#[derive(Debug, Serialize, Deserialize)]
struct Data ( Box<dyn MyTrait> );

#[derive(Debug, Serialize, Deserialize)]
struct MyType(String);

#[typetag::serde(tag = "type")]
trait MyTrait: std::fmt::Debug {}

#[typetag::serde]
impl MyTrait for MyType {}

impl Data {
    fn new(my_trait: Box<dyn MyTrait>) -> Data {
        Data(my_trait)
    }
}

#[wasm_bindgen(start)]
pub fn main() {
    let data = Data::new(Box::new(MyType("foo".to_string())) as Box<MyTrait>);
    alert(&format!("{:?}", &data));
    let text = serde_json::to_string(&data).unwrap();
    alert(&format!("{}", text));
    let new_data = serde_json::from_str::<Data>(&text);
    alert(&format!("{:?}", new_data));

}

#[wasm_bindgen]
extern "C" {
    fn alert(s: &str);
}

#[wasm_bindgen]
pub fn add(a: u32, b: u32) -> u32 {
    a + b
}
<html>
  <head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
  </head>
  <body>
    <script type="module">
      import { add, default as init } from './pkg/typetag_test.js';

      async function run() {
        await init('./pkg/typetag_test_bg.wasm');
        const result = add(1, 2);
        console.log(`1 + 2 = ${result}`);
        if (result !== 3)
          throw new Error("wasm addition doesn't work!");
      }
      run();
    </script>
  </body>
</html>

This creates 3 alerts. The first should be equal to the third, minus a Result wrapper.

Data(MyType("foo"))

{"type":"MyType","value":"foo"}

Err(Error("unknown variant `MyType`, there are no variants", line: 1, column: 16))

dtolnay commented 5 years ago

Thanks! Closing in favor of https://github.com/mmastrac/rust-ctor/issues/14 which is the dependency where this would need to be implemented.

srid commented 1 year ago

@dtolnay Shouldn't this be re-opened since you've closed https://github.com/mmastrac/rust-ctor/issues/14 ?

I'm facing this issue in a Leptos app.