Skip to content

Commit

Permalink
Add impl Distribution<Sex> for Standard
Browse files Browse the repository at this point in the history
  • Loading branch information
bouzuya committed Dec 5, 2023
1 parent 3d939e0 commit 14a2d7a
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/model/sex.rs
@@ -1,6 +1,6 @@
use rand::{thread_rng, Rng};

#[derive(Clone, Copy, Debug, serde::Serialize)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Sex {
Female,
Expand All @@ -12,3 +12,27 @@ impl Sex {
[Self::Female, Self::Male][thread_rng().gen_range(0..1)]
}
}

impl rand::distributions::Distribution<Sex> for rand::distributions::Standard {
fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> Sex {
if rng.gen::<bool>() {
Sex::Female
} else {
Sex::Male
}
}
}

#[cfg(test)]
mod tests {
use std::collections::HashSet;

use super::*;

#[test]
fn test_sample() {
let mut rng = rand::thread_rng();
let set = (0..100).map(|_| rng.gen::<Sex>()).collect::<HashSet<Sex>>();
assert_eq!(set.len(), 2);
}
}

0 comments on commit 14a2d7a

Please sign in to comment.