Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions crates/core/src/lottery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,23 @@ impl Lottery {
pub fn draw(self) -> bool {
Context::current()
.and_then(|context| context.lottery_draws().next())
.unwrap_or_else(|| self.random())
.unwrap_or_else(|| self.random(getrandom::u32))
}

fn random(self) -> bool {
let mut bytes = [0; 4];
fn random(self, mut sample: impl FnMut() -> Result<u32, getrandom::Error>) -> bool {
if self.out_of == 0 {
return false;
}

self.out_of > 0 && getrandom::fill(&mut bytes).is_ok() && u32::from_le_bytes(bytes) % self.out_of < self.wins
// Only complete runs of `out_of` give every remainder the same chance.
let range = u64::from(u32::MAX) + 1;
let limit = range - range % u64::from(self.out_of);
while let Ok(number) = sample() {
if u64::from(number) < limit {
return number % self.out_of < self.wins;
}
}
false
}

/// Make every draw in the application win, whatever its odds, until
Expand Down Expand Up @@ -135,3 +145,19 @@ impl Draws {
}
}
}

#[cfg(test)]
mod tests {
use super::Lottery;

#[test]
fn draws_skip_the_incomplete_range_before_applying_the_odds() {
let lottery = Lottery::odds(1_000_000_000, 3_000_000_000);
let mut numbers = [3_000_000_000, u32::MAX, 1_000_000_000, 999_999_999].into_iter();
let mut sample = || Ok(numbers.next().unwrap());

assert!(!lottery.random(&mut sample));
assert!(lottery.random(&mut sample));
assert_eq!(numbers.next(), None);
}
}