LoginSignup
0
0

Rust をwasm バインドする時に、thread_rnd: this target is not supported

Posted at

概要

Rust をWasm化してJSから呼ぼうとしていた時のことでした。

基本的には

こちらのチュートリアルを追っていたのですが、
バインドしたいライブラリの中でrand が使われており

cargo.toml
[dependencies]
rand = "0.7.3"

thread_rng: getrandom: this target is not supported

と言うようなエラーが、JSのランタイムで起きていました。

解決策

バインドするライブラリの依存関係に

cargo.toml
[dependencies]
getrandom = { version = "0.2.2", features = ["js"] }
rand = "0.7.3"

とし、

let mut rng = rand::thread_rng();
rng.gen_range(0, 2)

のように生成していた乱数を、getRandomを用いて生成するように変更します。
具体的には、

    // Define the range
    let lower_bound = 0;
    let upper_bound = 2;
    // Calculate the size of the random byte slice needed
    let range_size = upper_bound - lower_bound + 1;

    let mut random_bytes = [0u8; 4];

    getrandom(&mut random_bytes).expect("Failed to generate random bytes");

のようにして生成します。
これでWASM化すると、
JSからWASM経由で乱数生成を実行することができました。

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0