#概要
Wasmの練習として、GAによる組合せ最適化を解いたら乱数生成(randクレート)をWasmにする所ではまった。
結論としては、Cargo.tomlからos_rng
を外すために、以下の記載が必要となる。
rand = { version = "0.9.0", default-features = false, features = ["small_rng"] }
また、よくあるサンプルのうち以下の部分を変える必要がある。
// let mut rng = rand::rng(); // NG
let mut rng = SmallRng::seed_from_u64(0); // OK
公式には以下の記載があることは早々に確認したのだが、意外と苦戦した。default-features=false
も知っていたが、defaultのThreadRng
からそれ以外に差し替えるという点に頭が回らなかった。
(rand_pcgならWasm化できることをCopilotが提案してきたので、実際にできることを確認した後Rngの再実装をし始めてた(結局、あきらめたが)。)
WASM support
Seeding entropy from OS on WASM target wasm32-unknown-unknown is not automatically supported by rand or getrandom. If you are fine with seeding the generator manually, you can disable the os_rng feature and use the methods on the SeedableRng trait. To enable seeding from OS, either use a different target such as wasm32-wasi or add a direct dependency on getrandom with the js feature (if the target supports JavaScript). See getrandom#WebAssembly support.
日本語の記事では以下の2つが非常に参考になった。
本題
成果物は以下。
GA部分の実装はGrok3がほぼ完ぺきにしてくれた。
免責事項
RustもWasmも最適化も、ぜ~んぶ初心者なので、信用しないでください。
(GAはユーザーとして使ったことはあるけれども)