Skip to main content

animate_core/spring/
distance.rs

1pub trait Distance {
2    fn distance(&self, other: &Self) -> f64;
3}
4
5macro_rules! impl_distance {
6    ($($t:ty),* $(,)?) => {
7        $(
8            impl Distance for $t {
9                #[inline]
10                fn distance(&self, other: &$t) -> f64 {
11                    (*self as f64 - *other as f64).abs()
12                }
13            }
14        )*
15    };
16}
17
18impl_distance!(f64, f32, usize, isize, u64, i64, u32, i32, u16, i16, u8, i8);
19
20impl Distance for String {
21    #[inline]
22    fn distance(&self, other: &String) -> f64 {
23        let prefix = self
24            .chars()
25            .zip(other.chars())
26            .take_while(|(a, b)| a == b)
27            .count();
28        let rem_self = self.chars().count() - prefix;
29        let rem_other = other.chars().count() - prefix;
30        (rem_self + rem_other) as f64
31    }
32}
33
34#[cfg(feature = "ratatui")]
35impl Distance for ratatui::style::Color {
36    #[inline]
37    fn distance(&self, other: &ratatui::style::Color) -> f64 {
38        use ratatui::style::Color;
39        match (self, other) {
40            (Color::Rgb(r1, g1, b1), Color::Rgb(r2, g2, b2)) => {
41                let dr = *r1 as f64 - *r2 as f64;
42                let dg = *g1 as f64 - *g2 as f64;
43                let db = *b1 as f64 - *b2 as f64;
44                (dr * dr + dg * dg + db * db).sqrt()
45            }
46            _ => 0.0,
47        }
48    }
49}