| 1 |
//! Implementation of [`Distribution`] for various structs. |
| 2 |
|
| 3 |
use rand::distributions::{Distribution, Standard}; |
| 4 |
use rand::Rng; |
| 5 |
|
| 6 |
use crate::{Date, Duration, Month, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset, Weekday}; |
| 7 |
|
| 8 |
impl Distribution<Time> for Standard { |
| 9 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Time { |
| 10 |
Time::from_hms_nanos_ranged(rng.gen(), rng.gen(), rng.gen(), rng.gen()) |
| 11 |
} |
| 12 |
} |
| 13 |
|
| 14 |
impl Distribution<Date> for Standard { |
| 15 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Date { |
| 16 |
Date::from_julian_day_unchecked( |
| 17 |
rng.gen_range(Date::MIN.to_julian_day()..=Date::MAX.to_julian_day()), |
| 18 |
) |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
impl Distribution<UtcOffset> for Standard { |
| 23 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> UtcOffset { |
| 24 |
UtcOffset::from_hms_ranged(rng.gen(), rng.gen(), rng.gen()) |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
impl Distribution<PrimitiveDateTime> for Standard { |
| 29 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> PrimitiveDateTime { |
| 30 |
PrimitiveDateTime::new(Self.sample(rng), Self.sample(rng)) |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
impl Distribution<OffsetDateTime> for Standard { |
| 35 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> OffsetDateTime { |
| 36 |
let date_time: PrimitiveDateTime = Self.sample(rng); |
| 37 |
date_time.assume_offset(Self.sample(rng)) |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
impl Distribution<Duration> for Standard { |
| 42 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Duration { |
| 43 |
Duration::new_ranged(rng.gen(), rng.gen()) |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
impl Distribution<Weekday> for Standard { |
| 48 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Weekday { |
| 49 |
use Weekday::*; |
| 50 |
|
| 51 |
match rng.gen_range(0u8..7) { |
| 52 |
0 => Monday, |
| 53 |
1 => Tuesday, |
| 54 |
2 => Wednesday, |
| 55 |
3 => Thursday, |
| 56 |
4 => Friday, |
| 57 |
5 => Saturday, |
| 58 |
val => { |
| 59 |
debug_assert!(val == 6); |
| 60 |
Sunday |
| 61 |
} |
| 62 |
} |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
impl Distribution<Month> for Standard { |
| 67 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Month { |
| 68 |
use Month::*; |
| 69 |
match rng.gen_range(1u8..=12) { |
| 70 |
1 => January, |
| 71 |
2 => February, |
| 72 |
3 => March, |
| 73 |
4 => April, |
| 74 |
5 => May, |
| 75 |
6 => June, |
| 76 |
7 => July, |
| 77 |
8 => August, |
| 78 |
9 => September, |
| 79 |
10 => October, |
| 80 |
11 => November, |
| 81 |
val => { |
| 82 |
debug_assert!(val == 12); |
| 83 |
December |
| 84 |
} |
| 85 |
} |
| 86 |
} |
| 87 |
} |