std::random (v0.2.2)
Random numbers and buffer filling.
Latest
Overview
std::random produces pseudo-random unsigned integers and fills buffers with random bytes.
randomU64 and randomUsize return a random value, fillRandomBytes fills a buffer, and seedRandom seeds the generator.
Source: thrustc/std/v0.2.2/random.thrust
Public Signatures
Exported declarations for this module snapshot.
fn randomU64() u64 @public;
fn randomUsize() usize @public;
fn fillRandomBytes(buffer: ptr, length: usize) void @public;
fn seedRandom(seed: u64) void @public;
Behavior and Use
randomU64 and randomUsize return unsigned pseudo-random values; fillRandomBytes fills a buffer in place.
Call seedRandom before generating values if reproducible output is required.
Examples
import std::random;
import std::io;
// Roll a six-sided die using the low bits of a random number.
fn main() s32 @public {
var roll: u64 = random::randomU64();
io::print("die face: %d\n", ((roll % 6) as s32) + 1);
return 0;
}
import std::random;
import std::io;
// Fill a buffer with random bytes, for example to build a token.
fn main() s32 @public {
var token: array[u8; 4];
random::seedRandom(123456);
random::fillRandomBytes((ref token) as ptr, 4);
io::print("token ready\n");
return 0;
}
import std::random;
import std::io;
// Reuse a seed to reproduce the same random sequence.
fn main() s32 @public {
random::seedRandom(999);
var first: u64 = random::randomU64();
random::seedRandom(999);
var second: u64 = random::randomU64();
if first == second {
io::print("sequence reproduced\n");
}
return 0;
}
Notes
- This is not a cryptographic source of randomness.
- Seed the generator when reproducible output is required.