Skip to content

Error when using Shuffle in a wasm project #990

@will-sloan

Description

@will-sloan

When I try to shuffle a vec, it causes an error when passing it to JS. Without using rand, the problem goes away.
The error:
Error importing index.js: RuntimeError: unreachable

To reproduce the error:
Cargo.toml

[dependencies]
rand = "0.7.3"
serde = "1.0.114"
serde_derive = "1.0.114"

[dependencies.wasm-bindgen]
wasm-bindgen = "0.2.63"
features = ["serde-serialize"]

lib.rs

mod utils;

use rand::seq::SliceRandom;
use rand::thread_rng;
use serde::de::{self, Deserialize, Deserializer, MapAccess,, Visitor};
use serde::ser::{Serialize, SerializeStruct, Serializer};
use std::fmt;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsValue;

#[macro_use]
extern crate serde_derive;

struct Person {
    name: String,
    age: u8,
    phones: Vec<String>,
}

// Impl serialize for struct
impl Serialize for Person {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut s = serializer.serialize_struct("Person", 3)?;
        s.serialize_field("name", &self.name)?;
        s.serialize_field("age", &self.age)?;
        s.serialize_field("phones", &self.phones)?;
        s.end()
    }
}
#[wasm_bindgen]
pub fn pass_value_to_js() -> JsValue {
    let mut p = Person {
        name: String::from("Hello"),
        age: 13,
        phones: vec![
            String::from("phone"),
            String::from("AAAAA"),
            String::from("Guacamole"),
        ],
    };
    p.phones.shuffle(&mut thread_rng()); // this causes the error
    JsValue::from_serde(&p).unwrap()
}

Without the line p.phones.shuffle(&mut thread_rng());, the program works.
Is this the right place for this kind of error?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions