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
use core::ops::{Mul, Sub};

use cast_trait::Cast;
use num_traits::{One, Zero};

#[inline]
pub fn linear<T, F>(p0: &T, p1: &T, t: &F) -> T
where
    T: Clone + Cast<F>,
    F: Clone + One + Zero + PartialOrd + Cast<T> + Sub<F, Output = F> + Mul<F, Output = F>,
    for<'a, 'b> &'a F: Sub<&'b F, Output = F> + Mul<&'b F, Output = F>,
{
    if t <= &F::zero() {
        p0.clone()
    } else if t >= &F::one() {
        p1.clone()
    } else {
        let x0 = p0.clone().cast();
        let x1 = p1.clone().cast();
        (x0.clone() + (x1 - x0) * t.clone()).cast()
    }
}
#[test]
fn test_linear() {
    assert_eq!(linear(&0, &200, &0.25), 50);
    assert_eq!(linear(&0, &200, &0.5), 100);
    assert_eq!(linear(&0, &200, &0.75), 150);
}