time/
rand.rs

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