Skip to main content

proptest/arbitrary/_std/
time.rs

1//-
2// Copyright 2017, 2018 The proptest developers
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10//! Arbitrary implementations for `std::time`.
11
12use core::ops::Range;
13use std::time::*;
14
15use crate::arbitrary::*;
16use crate::num;
17use crate::strategy::statics::{self, static_map};
18
19arbitrary!(Duration, SMapped<(u64, u32), Self>;
20    static_map(any::<(u64, u32)>(), |(a, b)| {
21        let carry = u64::from(b / 1_000_000_000);
22        let b = if a.checked_add(carry).is_none() {
23            b % 1_000_000_000
24        } else {
25            b
26        };
27        Duration::new(a, b)
28    })
29);
30
31// Instant::now() "never" returns the same Instant, so no shrinking may occur!
32arbitrary!(Instant; Self::now());
33
34arbitrary!(
35    // We can't use `any::<Duration>()` because the addition to `SystemTime`
36    // can overflow and panic. To be conservative, we only allow seconds to go
37    // to i32::MAX since a certain popular OS still uses `i32` to represent the
38    // seconds counter.
39    SystemTime, statics::Map<(num::i32::Any, Range<u32>),
40                             fn ((i32, u32)) -> SystemTime>;
41    static_map((num::i32::ANY, 0..1_000_000_000u32),
42                |(sec, ns)| {
43                    if sec >= 0 {
44                        UNIX_EPOCH + Duration::new(sec as u64, ns)
45                    } else {
46                        UNIX_EPOCH - Duration::new((-(sec as i64)) as u64, ns)
47                    }
48                })
49);
50
51#[cfg(test)]
52mod test {
53    no_panic_test!(
54        duration => Duration,
55        instant  => Instant,
56        system_time => SystemTime
57    );
58
59    #[test]
60    fn duration_tolerates_nanosecond_carry_at_max_seconds() {
61        use crate::strategy::{Strategy, ValueTree};
62        use crate::test_runner::{Config, RngAlgorithm, TestRng, TestRunner};
63        use std::time::Duration;
64
65        let mut runner = TestRunner::new_with_rng(
66            Config::default(),
67            TestRng::from_seed(RngAlgorithm::PassThrough, &[0xFF; 12]),
68        );
69        let value = crate::arbitrary::any::<Duration>()
70            .new_tree(&mut runner)
71            .unwrap()
72            .current();
73        assert_eq!(Duration::new(u64::MAX, u32::MAX % 1_000_000_000), value);
74    }
75}