fyrox_core/numeric_range.rs
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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use crate::num_traits::Num;
use rand::{distributions::uniform::SampleUniform, Rng};
use std::ops::Range;
fn min<T>(a: T, b: T) -> T
where
T: PartialOrd,
{
if a > b {
b
} else {
a
}
}
fn max<T>(a: T, b: T) -> T
where
T: PartialOrd,
{
if a > b {
a
} else {
b
}
}
pub trait RangeExt<T>
where
T: Num + PartialOrd + SampleUniform + Copy,
{
fn random<R: Rng>(&self, rng: &mut R) -> T;
fn clamp_value(&self, value: &mut T) -> T;
}
impl<T: Num + PartialOrd + SampleUniform + Copy> RangeExt<T> for Range<T> {
#[inline]
fn random<R: Rng>(&self, rng: &mut R) -> T {
let start = min(self.start, self.end);
let end = max(self.start, self.end);
if start == end {
start
} else {
rng.gen_range(Range { start, end })
}
}
#[inline]
fn clamp_value(&self, value: &mut T) -> T {
let start = min(self.start, self.end);
let end = max(self.start, self.end);
if *value < start {
start
} else if *value > end {
end
} else {
*value
}
}
}
#[cfg(test)]
mod test {
use rand::thread_rng;
use super::*;
#[test]
fn test_random() {
let mut rng = thread_rng();
let res = (1..10).random(&mut rng);
assert!((1..=10).contains(&res));
let res = Range { start: 10, end: 1 }.random(&mut rng);
assert!((1..=10).contains(&res));
let res = (1..1).random(&mut rng);
assert!(res == 1);
}
#[test]
fn test_clamp_value() {
let res = (1..10).clamp_value(&mut 5);
assert_eq!(res, 5);
let res = (1..10).clamp_value(&mut 0);
assert_eq!(res, 1);
let res = (1..10).clamp_value(&mut 11);
assert_eq!(res, 10);
}
}