#random #rand #random-rs

no-std random-trait

Rust library for a random trait meant to produce random generic types

2 releases

Uses old Rust 2015

0.1.1 Aug 26, 2019
0.1.0 Aug 26, 2019

#2139 in Algorithms

Download history 99/week @ 2023-12-19 45/week @ 2023-12-26 45/week @ 2024-01-02 72/week @ 2024-01-09 44/week @ 2024-01-16 108/week @ 2024-01-23 51/week @ 2024-01-30 127/week @ 2024-02-06 97/week @ 2024-02-13 197/week @ 2024-02-20 205/week @ 2024-02-27 160/week @ 2024-03-05 135/week @ 2024-03-12 116/week @ 2024-03-19 112/week @ 2024-03-26 117/week @ 2024-04-02

516 downloads per month
Used in 8 crates (via random-fast-rng)

MIT/Apache

15KB
265 lines

random-trait

Latest version Documentation License

A Rust library random-trait that helps generating random values in an easy and convinient way while still being a very thin library without dependencies.

This crate is inspired by the rand crate, but with the purpose of providing a very thin library, and support old compilers.

Usage

Add this to your Cargo.toml:

[dependencies]
random-trait = "0.1"

and for Rust Edition 2015 add this to your crate root:

extern crate random_trait;
use random_trait::{GenerateRand, Random};

In Rust Edition 2018 you can simply do:

use random_trait::{GenerateRand, Random};

After that you'll need to implement Random for your source of randomness,
And optionally also add GenerateRand implementations for your custom types.

Examples

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(())
     }
 }

struct MyStuff {
    a: u64,
    b: char,
}

impl GenerateRand for MyStuff {
    fn generate<R: Random + ?Sized>(rand: &mut R) -> Self {
        MyStuff {a: rand.gen(), b: rand.gen() }
    }
}

fn get_random_stuff() -> MyStuff {
    let mut rand = MyRandomGenerator::default();
    rand.gen()
}

fn get_random_u128() -> u128 {
    let mut rand = MyRandomGenerator::default();
    rand.gen()
}

Dependencies