Skip to main content

mraphics_core/
traits.rs

1//! Shared traits that are used across multiple modules.
2
3pub trait Interpolatable {
4    fn interpolate(&self, to: &Self, p: f32) -> Self;
5}
6
7impl Interpolatable for f32 {
8    fn interpolate(&self, to: &Self, p: f32) -> Self {
9        self + (to - self) * p
10    }
11}
12
13impl Interpolatable for f64 {
14    fn interpolate(&self, to: &Self, p: f32) -> Self {
15        self + (to - self) * (p as f64)
16    }
17}
18
19impl<E: Interpolatable, const N: usize> Interpolatable for [E; N] {
20    fn interpolate(&self, to: &Self, p: f32) -> Self {
21        // SAFETY: The closure passed to `array::from_fn` is only called for indices in the range `0..N`.
22        // Since `N` is the array length, both `self[i]` and `to[i]` are guaranteed to be valid indices.
23
24        std::array::from_fn(|i| unsafe {
25            self.get_unchecked(i).interpolate(to.get_unchecked(i), p)
26        })
27    }
28}
29
30impl<E: Interpolatable> Interpolatable for Vec<E> {
31    fn interpolate(&self, to: &Self, p: f32) -> Self {
32        self.iter()
33            .zip(to.iter())
34            .map(|(from, to)| from.interpolate(to, p))
35            .collect()
36    }
37}