Rust Quickie: random generator pattern

pub struct Things { pub elements: Vec<Stuff> }
pub enum Stuff { Simple(usize), Complex(Things) }
fn random_stuff<R: Rng + ?Sized>(rng: &mut R, gen_weight: &mut Weight) -> Stuff {
if rng.gen() {
Stuff::Simple(rng.gen())
} else {
let want_length = rng.gen_range(0..=gen_weight.allowed_len());
Stuff::Complex((0..=want_length).map(|_| {
gen_weight.step();
random_stuff(rng, &mut gen_weight.recurse())
}).collect())
}
}
impl Distribution<Stuff> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Stuff {
random_stuff(rng, &mut Default::default())
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store