-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathconfig.rs
More file actions
67 lines (61 loc) · 1.74 KB
/
config.rs
File metadata and controls
67 lines (61 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use rand::distr::uniform::SampleUniform;
use serde::{Deserialize, Serialize as SerdeSerialize};
use std::cmp;
/// Range expression for configuration
#[derive(Debug, Deserialize, SerdeSerialize, Clone, PartialEq, Copy)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub enum ConfRange<T>
where
T: PartialEq + cmp::PartialOrd + Clone + Copy,
{
/// A constant T
Constant(T),
/// In which a T is chosen between `min` and `max`, inclusive of `max`.
Inclusive {
/// The minimum of the range.
min: T,
/// The maximum of the range.
max: T,
},
}
impl<T> ConfRange<T>
where
T: PartialEq + cmp::PartialOrd + Clone + Copy,
{
/// Returns true if the range provided by the user is valid, false
/// otherwise.
pub(crate) fn valid(&self) -> (bool, &'static str) {
match self {
Self::Constant(_) => (true, ""),
Self::Inclusive { min, max } => (min < max, "min must be less than max"),
}
}
pub(crate) fn start(&self) -> T {
match self {
ConfRange::Constant(c) => *c,
ConfRange::Inclusive { min, .. } => *min,
}
}
pub(crate) fn end(&self) -> T {
match self {
ConfRange::Constant(c) => *c,
ConfRange::Inclusive { max, .. } => *max,
}
}
}
impl<T> ConfRange<T>
where
T: PartialEq + cmp::PartialOrd + Clone + Copy + SampleUniform,
{
pub(crate) fn sample<R>(&self, rng: &mut R) -> T
where
R: rand::Rng + ?Sized,
{
match self {
ConfRange::Constant(c) => *c,
ConfRange::Inclusive { min, max } => rng.random_range(*min..=*max),
}
}
}