我如何在没有标准库的情况下使用 rand crate?

How do I use the rand crate without the standard library?

我正在使用 Rust 为 Sega Megadrive 进行嵌入式游戏开发,并且想要一个随机数生成器来提高重玩性。它可以是伪随机的:不需要任何安全措施。

我一直在查看属于“无标准库”部门的 rand crate,但我不确定如何在我的 Crate.toml 中使用它:

[dependencies]
rand = {version = "0.8.3", default-features = false}

当我禁用 default-features 时,prelude 中就没有 random 功能了。有 Rng 特性,但我太缺乏经验,不知道如何使用它。

要在没有 std 的情况下使用 rand crate,您需要手动使用其中一个没有它的生成器。这些生成器是 OsRngSmallRng 结构。顾名思义,第一个使用操作系统的生成器,它需要 getrandom crate,SEGA Megadrive 可能不支持它。

SmallRng 应该可以正常工作。我们不能使用random()函数,我们需要手动创建生成器然后调用它的方法。

为此,我们首先必须创建一个生成器,如下所示:

let mut small_rng = SmallRng::seed_from_u64([insert your seed here]);

您还可以使用seed_from_u32whose documentation you can find here

那么我们就可以这样使用了:

let rand_num = small_rng.next_u64();

重要的是,我们必须导入 RngCore 特性才能使用这些函数,这样:

use rand::{Rng, SeedableRng};
use rand::rngs::SmallRng;
use rand::RngCore;

SmallRng 依赖于 small_rng crate 特性,所以你应该这样导入它(在 Cargo.toml 文件中):

rand = { version = "0.8.3", features = ["small_rng"], default-features = false }

我还应该发表免责声明:SmallRng 的生成器在密码学上不安全。