Skip to main content

animato_tween/
modifiers.rs

1//! Value modifier free functions for post-processing tween output.
2
3use animato_core::math::{powi, round};
4
5/// Snap a value to the nearest multiple of `grid`.
6///
7/// # Example
8///
9/// ```rust
10/// use animato_tween::snap_to;
11/// assert_eq!(snap_to(13.4_f32, 5.0), 15.0);
12/// assert_eq!(snap_to(12.0_f32, 5.0), 10.0);
13/// ```
14#[inline]
15pub fn snap_to(value: f32, grid: f32) -> f32 {
16    if grid == 0.0 {
17        return value;
18    }
19    round(value / grid) * grid
20}
21
22/// Round a value to a given number of decimal places.
23///
24/// # Example
25///
26/// ```rust
27/// use animato_tween::round_to;
28/// assert_eq!(round_to(3.14159_f32, 2), 3.14);
29/// ```
30#[inline]
31pub fn round_to(value: f32, decimals: u32) -> f32 {
32    let factor = powi(10.0_f32, decimals as i32);
33    round(value * factor) / factor
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn snap_to_grid() {
42        assert_eq!(snap_to(13.4, 5.0), 15.0);
43        assert_eq!(snap_to(12.0, 5.0), 10.0);
44        assert_eq!(snap_to(7.5, 5.0), 10.0);
45        assert_eq!(snap_to(0.0, 5.0), 0.0);
46    }
47
48    #[test]
49    fn snap_to_zero_grid_noop() {
50        assert_eq!(snap_to(13.4, 0.0), 13.4);
51    }
52
53    #[test]
54    fn round_to_decimals() {
55        assert_eq!(round_to(12.345, 2), 12.35);
56        assert_eq!(round_to(12.345, 0), 12.0);
57        assert_eq!(round_to(98.765, 2), 98.77);
58    }
59}