randomrustembedded

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


I'm doing embedded game development for the Sega Megadrive with Rust and would like a random number generator to increase replayability. It can be pseudo-random: there's no security stuff required.

I've been looking at the rand crate which falls in the "No standard library" department, but I'm not sure on how to use it with this in my Crate Cargo.toml:

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

When I disable default-features, there's no random function in the prelude anymore. There is the Rng trait but I'm too inexperienced to figure out how to use it.


Solution

  • To use the rand crate without std you need to manually use one of the generators that work without it. Those generators are the OsRng and the SmallRng structs. As the name suggests the first one uses the operating system's generator, which requires the getrandom crate, which probably isn't supported on SEGA Megadrive.

    SmallRng should work without problems though. We cannot use the random() function, we need to manually create the generator and then call its methods.

    To do this we first have to create a generator, like this:

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

    You can also use the seed_from_u32, whose documentation you can find here.

    Then we can use it as such:

    let rand_num = small_rng.next_u64();
    

    Importantly, we have to import the RngCore trait to use these functions, this way:

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

    SmallRng relies on the small_rng crate feature, so you should import it this way (in the Cargo.toml file):

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

    I should also leave a disclaimer: SmallRng's generator isn't cryptographically secure.