Wasm-bindgen: Troubles with random numbers in WASM

Created on 28 Apr 2018  路  2Comments  路  Source: rustwasm/wasm-bindgen

I'm trying to generate random numbers with this function:

    pub fn set_random(&mut self) {

        let max_max;

        if self.true_size.x * self.true_size.y / 2 > 10000 {
            max_max = 10000;
        } else {
            max_max = self.true_size.x * self.true_size.y / 2;
        }

        let max_range = Range::new(0, max_max);
        let mut rng = rand::thread_rng();
        let max = max_range.ind_sample(&mut rng) as i32;

        let mut coords : Vec<i32> = Vec::new();

        for _ in 0..max {
            let range_x = Range::new(0usize, self.true_size.x as usize);
            let range_y = Range::new(0usize, self.true_size.y as usize);

            let x = range_x.ind_sample(&mut rng) as i32;
            let y = range_y.ind_sample(&mut rng) as i32;

            coords.push(self.get_pos(&Coords {x, y}));
        }

        self.set_alive(coords);
    }

When I use it on Rust only, it works fine, but in WASM it throws this error:
image

There are any way to generate a random number in WASM?

Most helpful comment

Thanks for the report! Unfortunately the rand crate doesn't work natively on wasm because its OsRng doesn't have an implementation. In the meantime though I've just published a crate, wbg-rand, which should allow you to use the rand crate on wasm32-unknown-unknown!

All 2 comments

Thanks for the report! Unfortunately the rand crate doesn't work natively on wasm because its OsRng doesn't have an implementation. In the meantime though I've just published a crate, wbg-rand, which should allow you to use the rand crate on wasm32-unknown-unknown!

You鈥檙e amazing buddy, thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

hunterlester picture hunterlester  路  4Comments

d3lm picture d3lm  路  3Comments

kurbaniec picture kurbaniec  路  3Comments

gitmko0 picture gitmko0  路  3Comments

MarcAntoine-Arnaud picture MarcAntoine-Arnaud  路  3Comments