af_core/
math.rs

1// Copyright © 2020 Alexandra Frydl
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7//! Utilties for working with numerical values.
8
9mod float;
10
11pub use self::float::FloatExt;
12pub use num_traits::identities::{one, zero, One, Zero};
13pub use num_traits::AsPrimitive;
14use num_traits::{NumAssignOps, NumOps};
15use rand::distributions::uniform::SampleUniform;
16
17use crate::prelude::*;
18
19/// A trait for types that implement all the basic operations of a number.
20///
21/// This trait is implemented for all primitive integer and floating-point
22/// types.
23pub trait Number:
24  PartialOrd + PartialEq + Zero + One + NumOps + NumAssignOps + SampleUniform
25{
26}
27
28/// Clamps a number so that it is between a minimum and maximum bound.
29pub fn clamp<T: Number>(mut value: T, min: T, max: T) -> T {
30  clamp_mut(&mut value, min, max);
31
32  value
33}
34
35/// Clamps a number in-place so that it is between a minimum and maximum bound.
36pub fn clamp_mut<T: Number>(value: &mut T, min: T, max: T) {
37  if *value < min {
38    *value = min;
39  } else if *value > max {
40    *value = max;
41  }
42}
43
44// Implement Number for all types that implement the required traits.
45
46impl<T> Number for T where
47  T: PartialOrd + PartialEq + Zero + One + NumOps + NumAssignOps + SampleUniform
48{
49}