#random #enums #rand #struct #derive

enum-derived

Generate random instances of your enums and structs

21 releases (7 breaking)

0.8.2 Mar 7, 2023
0.7.0 Mar 2, 2023

#1162 in Rust patterns

Download history 130/week @ 2024-03-13 284/week @ 2024-03-20 340/week @ 2024-03-27 155/week @ 2024-04-03 182/week @ 2024-04-10 365/week @ 2024-04-17 487/week @ 2024-04-24 476/week @ 2024-05-01 528/week @ 2024-05-08 278/week @ 2024-05-15 294/week @ 2024-05-22 437/week @ 2024-05-29 741/week @ 2024-06-05 528/week @ 2024-06-12 801/week @ 2024-06-19 736/week @ 2024-06-26

2,953 downloads per month

MIT license

9KB

Enum-Derived

Use Enum-Derived's Rand macro to generate random variants of your enums and structs. All fields are populated with independent random values.

Need custom constraints applied to a variant or field? Use the #[custom_rand(your_function)] attribute to override the default behavior or extend support to types without default support.

Need some variants to be generated more ofter? Use the #[weight(VARIANT_WEIGHT)] to change the distribution.

crates.io Build

Rand

Rand allows for a random variant of an enum, or struct, to be generated.

The [rand] crates rand::random method is used for the default implementation of [Rand]. Unsupported variants can us the #[custom_rand(your_function)] to extend the functionality.

use enum_derived::Rand;

#[derive(Rand)]
struct Weather {
    wind_speed: u8,
    #[custom_rand(rand_temp)]
    temperature: f32,
    cloudy: bool
}

#[derive(Rand)]
enum TravelLog {
    Airplane {
        weather: Weather,
        altitude: u16
    },
    Boat(
        Weather,
        #[custom_rand()]
        u32,
    ),
    #[custom_rand(always_has_sunroof)]
    Car {
        has_sunroof: bool,
    },
    #[weight(3)]
    SpaceShip,
}

fn main() {
    let travel_log = TravelLog::rand();
}

fn always_has_sunroof() -> TravelLog {
    TravelLog::Car { has_sunroof: true }
}

fn rand_boat_speed() -> u32 {
    thread_rng().gen_range(5..50)
}

fn rand_temp() -> f32 {
   thread_rng().gen_range(-20.0..120.0)
}

use rand::{thread_rng, Rng};

Dependencies

~1.5MB
~39K SLoC