pub trait Random {
type Error;
// Required method
fn try_fill_bytes(&mut self, buf: &mut [u8]) -> Result<(), Self::Error>;
// Provided methods
fn fill_bytes(&mut self, buf: &mut [u8]) { ... }
fn gen<T: GenerateRand>(&mut self) -> T { ... }
fn get_u8(&mut self) -> u8 { ... }
fn get_u16(&mut self) -> u16 { ... }
fn get_u32(&mut self) -> u32 { ... }
fn get_u64(&mut self) -> u64 { ... }
fn get_usize(&mut self) -> usize { ... }
fn get_u128(&mut self) -> u128 { ... }
fn get_bool(&mut self) -> bool { ... }
}
Expand description
This is the base trait of the crate. By implementing the required method on your random generator source
it will give you a long list of functions, the important of them is Random::gen() -> T
which will produce a random value
for every type which implements GenerateRand
(you can implement this for your own types).
Notice that some random sources can produce non byte-array values with more efficiency, so if you want to use that you can just override a provided method and use the random source directly.
If your random source is fallable in a way that can be handled please also implement fill_bytes
and handle the errors properly.
otherwise it will panic.
§Example
use random_trait::{Random, GenerateRand};
#[derive(Default)]
struct MyRandomGenerator {
ctr: usize,
}
impl Random for MyRandomGenerator {
type Error = ();
fn try_fill_bytes(&mut self, buf: &mut [u8]) -> Result<(), Self::Error> {
for e in buf.iter_mut() {
*e = self.ctr as u8;
self.ctr += 1;
}
Ok(())
}
}
let mut rand = MyRandomGenerator::default();
let rand_u32: u32 = rand.gen();
assert_eq!(rand_u32, 50462976);
let rand_u32: u32 = rand.gen();
assert_eq!(rand_u32, 117835012);
Required Associated Types§
Required Methods§
Provided Methods§
Sourcefn fill_bytes(&mut self, buf: &mut [u8])
fn fill_bytes(&mut self, buf: &mut [u8])
Uses try_fill_bytes
but panics if returns an error.
Override if you can gracefully handle errors in the randomness source.
Sourcefn gen<T: GenerateRand>(&mut self) -> T
fn gen<T: GenerateRand>(&mut self) -> T
Returns a generic random value which implements GenerateRand
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.