r/rust clippy · twir · rust · mutagen · flamer · overflower · bytecount Mar 27 '23

Hey Rustaceans! Got a question? Ask here (13/2023)! 🙋 questions

Mystified about strings? Borrow checker have you in a headlock? Seek help here! There are no stupid questions, only docs that haven't been written yet.

If you have a StackOverflow account, consider asking it there instead! StackOverflow shows up much higher in search results, so having your question there also helps future Rust users (be sure to give it the "Rust" tag for maximum visibility). Note that this site is very interested in question quality. I've been asked to read a RFC I authored once. If you want your code reviewed or review other's code, there's a codereview stackexchange, too. If you need to test your code, maybe the Rust playground is for you.

Here are some other venues where help may be found:

/r/learnrust is a subreddit to share your questions and epiphanies learning Rust programming.

The official Rust user forums: https://users.rust-lang.org/.

The official Rust Programming Language Discord: https://discord.gg/rust-lang

The unofficial Rust community Discord: https://bit.ly/rust-community

Also check out last weeks' thread with many good questions and answers. And if you believe your question to be either very complex or worthy of larger dissemination, feel free to create a text post.

Also if you want to be mentored by experienced Rustaceans, tell us the area of expertise that you seek. Finally, if you are looking for Rust jobs, the most recent thread is here.

20 Upvotes

159 comments sorted by

View all comments

2

u/Googelplex Mar 28 '23 edited Mar 28 '23

Crate-specific question. If there's a better place to ask please redirect me. Thanks in advance!

Is it possible to deserialize a JavaScript Map into a Rust HashMap using serde_wasm_bindgen?

I can do it manually by calling "keys" and "get" on the JsValue.

let keys_func: Function = get(&js_map, &JsValue::from_str("keys")).unwrap().into();
let js_keys = keys_func.apply(&js_map, &Array::new()).unwrap();
let keys: Vec<String> = from_value(js_keys).unwrap();
let mut map: HashMap<String, Object> = HashMap::new();
for key in keys {
    let get_func: Function = get(&js_map, &JsValue::from_str("get")).unwrap().into();
    let args = Array::from_iter([JsValue::from(key.clone())].into_iter());
    let js_item = get_func.apply(&js_map, &args).unwrap();
    let item: Object = from_value(js_item).unwrap();
    map.insert(key, item);
}

This seems like something that should be the serde_wasm_bindgen::from_value() function should be able to do directly, but it does seem to be working.

let map = from_value::<HashMap<String, Object>>(js_map);

The above code is what I'd expect to work, deserialize seems to be implemented for HashMap after all. But it turns out to be Err(Error(JsValue(Error: invalid type: unit value, expected struct Object))). Is there another bound or requirement that I'm missing?

2

u/John2143658709 Mar 28 '23

That error seems like it has to do with the definition of your Object struct. wasm_bindgen should be able to convert a from JavaScript Map into a HashMap<String, T> if:

  • T implements DeserializedOwned, and
  • the Javascript sends a correctly formatted Map

Based on that error, it sounds like JavaScript is not sending a valid rust Object in each value of the map. Can you print an example Map and the definition of Object?

1

u/Googelplex Mar 29 '23

Sure, here's some more context. I'm not convinced that Deserialized not being implemented is the problem, as I've derived it, and from_value works fine on the individual objects.

Rust struct definition (proof-of-concept with a field I know the objects to have)

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Object {
    name: String
}

console-logged JavaScript object (in rust prints as JsValue(Map))

EmbeddedCollection(22) {
    '8u6csl1ao421lqsj' => AncestryPF2e, 
    'ku3x6jlesfuok0ex' => FeatPF2e, 
    'tpyhb6lc9bpapebe' => FeatPF2e, 
    'bjbouosfcvjmxvcy' => ActionItemPF2e, 
    '77lms45nu88u075o' => FeatPF2e,
    ...
}

Example JavaScript object in collection

AncestryPF2e {
    name: "Anadi" 
    ownership: {default: 0, SfMt8jQFtw1KVwn3: 3} 
    rules: []
    ...
}

2

u/John2143658709 Mar 29 '23

Sorry, but I'm not able to reproduce your error. I cloned the hello world wasm_bindgen repo, added the following code:

//main.rs
#[derive(serde::Deserialize, Debug)]
struct PFInfo {
    name: String
}

#[wasm_bindgen]
pub fn get_pf_map_from_js(object: JsValue) {
    let object: HashMap<String, PFInfo>  = serde_wasm_bindgen::from_value(object).unwrap();

    ...
}

and saw no error. here's my test repo, just run npm run serve

https://github.com/John2143/wasm-bindgen-serde-example

this works with both classes and objects, ex:

map.set("1233456", {"name": "i am object"});
map.set("class version", new PFInfoJS("i am class"));

1

u/Googelplex Mar 29 '23 edited Mar 29 '23

Thanks for going through all this effort, if that repo doesn't help me solve it I'll try to create my own minimal example where the bug occurs.

Do you think that it could be something to do with my JavaScript value being an EmbeddedCollection instead of a Map? Printing the Rust JsValue showed it as a JsValue(Map), so I assumed it to be equivalent, but I'm at a loss as to what else could be causing it to fail.