comfy_core/
math.rs

1use crate::*;
2
3pub trait F32Extensions {
4    fn signum_zero(self) -> Self;
5    fn spread(self, amount: f32) -> Self;
6    fn spread_in(self, amount: f32) -> Self;
7    fn spread_zero(self, amount: f32) -> Self;
8    fn clamp_scale(self, from: Range<f32>, to: Range<f32>) -> f32;
9}
10
11impl F32Extensions for f32 {
12    fn signum_zero(self) -> Self {
13        if self == 0.0 {
14            0.0
15        } else {
16            self.signum()
17        }
18    }
19
20    /// 0.2 => 0.9..1.1
21    fn spread(self, amount: f32) -> Self {
22        1.0 + self.spread_zero(amount)
23    }
24
25    /// 0.2 => 0.8..1.0
26    fn spread_in(self, amount: f32) -> Self {
27        1.0 + self * amount - amount
28    }
29
30    fn spread_zero(self, amount: f32) -> Self {
31        self * amount - amount / 2.0
32    }
33
34    fn clamp_scale(self, from: Range<f32>, to: Range<f32>) -> f32 {
35        let clamped = self.clamp(from.start, from.end);
36        let pct = (clamped - from.start) / (from.end - from.start);
37        to.start + pct * (to.end - to.start)
38    }
39}
40
41#[test]
42pub fn spread_test() {
43    assert_eq!(1.0.spread(0.0), 1.0);
44}
45
46#[test]
47pub fn clamp_scale_test() {
48    assert_eq!(0.5.clamp_scale(0.0..1.0, 0.0..2.0), 1.0);
49    assert_eq!(0.0.clamp_scale(-1.0..1.0, 0.0..2.0), 1.0);
50}