Random Constructible
The random-constructible crate provides a trait for creating random instances of enums with weighted probabilities. It's designed to work seamlessly with the companion crate random-constructible-derive, which provides a procedural macro to automatically implement the trait for your enums.
Features
- Generate random enum variants based on default or custom probability distributions.
- Support for both uniform and weighted random selection.
- Flexible API allowing the use of custom random number generators (RNGs).
- Ability to define custom probability providers for different contexts or environments.
Installation
Add the following to your Cargo.toml:
[]
= "0.1.0"
Ensure you also include the rand crate if you're not already using it:
[]
= "0.8"
Usage
First, define your enum and implement the RandomConstructible trait. You can do this manually or by using the random-constructible-derive crate to automatically generate the implementation (recommended).
Example with Manual Implementation
use ;
use Rng;
use HashMap;
use Arc;
Example with random-constructible-derive Crate
Using the random-constructible-derive crate simplifies the process by automatically generating the required implementations.
[]
= "0.1.0"
= "0.1.0"
= "0.8"
use ;
use RandomConstructible;
use Arc;
use HashMap;
API Overview
Trait: RandomConstructible
The RandomConstructible trait provides methods to generate random instances of an enum.
Methods
random() -> Self: Generates a random instance using the default probability distribution.random_with_rng<RNG: Rng + ?Sized>(rng: &mut RNG) -> Self: Same asrandom, but uses the provided RNG.random_with_probabilities(provider: &dyn RandomConstructibleProbabilityMapProvider<Self>) -> Self: Generates a random instance using a custom probability provider.random_with_probabilities_rng<RNG: Rng + ?Sized>(provider: &dyn RandomConstructibleProbabilityMapProvider<Self>, rng: &mut RNG) -> Self: Same asrandom_with_probabilities, but uses the provided RNG.uniform() -> Self: Generates a random instance with a uniform distribution across all variants.all_variants() -> Vec<Self>: Returns a vector of all enum variants.default_weight(&self) -> f64: Returns the default weight for the variant.default_probability_provider() -> Arc<dyn RandomConstructibleProbabilityMapProvider<Self>>: Returns the default probability provider.
Trait: RandomConstructibleProbabilityMapProvider
Defines a provider for probability maps used in random generation.
Method
probability_map(&self) -> Arc<HashMap<R, f64>>: Returns anArcto aHashMapcontaining the probabilities for each variant.
Custom Probability Providers
You can define custom probability providers to alter the random generation based on different contexts or environments.
;
License
This project is licensed under the MIT License. See the LICENSE file for details.
Contribution
Contributions are welcome! Please open an issue or submit a pull request on GitHub.