argmin_math/primitives/
random.rs

1// Copyright 2018-2024 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use crate::ArgminRandom;
9use rand::Rng;
10
11macro_rules! make_random {
12    ($t:ty) => {
13        impl ArgminRandom for $t {
14            #[inline]
15            fn rand_from_range<R: Rng>(min: &Self, max: &Self, rng: &mut R) -> $t {
16                rng.gen_range(*min..*max)
17            }
18        }
19    };
20}
21
22make_random!(f32);
23make_random!(f64);
24make_random!(i8);
25make_random!(i16);
26make_random!(i32);
27make_random!(i64);
28make_random!(u8);
29make_random!(u16);
30make_random!(u32);
31make_random!(u64);
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36    use paste::item;
37    use rand::SeedableRng;
38
39    macro_rules! make_test {
40        ($t:ty) => {
41            item! {
42                #[test]
43                fn [<test_random_vec_ $t>]() {
44                    let a = 1 as $t;
45                    let b = 2 as $t;
46                    let mut rng = rand::rngs::StdRng::seed_from_u64(42);
47                    let random = $t::rand_from_range(&a, &b, &mut rng);
48                    assert!(random >= a);
49                    assert!(random <= b);
50                }
51            }
52        };
53    }
54
55    make_test!(f32);
56    make_test!(f64);
57    make_test!(i8);
58    make_test!(u8);
59    make_test!(i16);
60    make_test!(u16);
61    make_test!(i32);
62    make_test!(u32);
63    make_test!(i64);
64    make_test!(u64);
65}