concision_core/math/
arith.rs

1/*
2    Appellation: arith <module>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5use num::integer::Roots;
6use num::traits::FromPrimitive;
7
8pub trait Root {
9    type Output;
10
11    fn nth_root(&self, n: u32) -> Self::Output;
12
13    fn sqrt(&self) -> Self::Output {
14        self.nth_root(2)
15    }
16
17    fn cbrt(&self) -> Self::Output {
18        self.nth_root(3)
19    }
20}
21
22macro_rules! impl_root {
23    (float $($T:ty),* $(,)?) => {
24        $(
25            impl_root!(@float $T);
26        )*
27    };
28    ($($T:ty),* $(,)?) => {
29        $(
30            impl_root!(@impl $T);
31        )*
32    };
33
34    (@impl $T:ty) => {
35        impl Root for $T {
36            type Output = $T;
37
38            fn nth_root(&self, n: u32) -> Self::Output {
39                Roots::nth_root(self, n)
40            }
41        }
42    };
43    (@float $T:ty) => {
44        impl Root for $T {
45            type Output = $T;
46
47            fn nth_root(&self, n: u32) -> Self::Output {
48                self.powf(<$T>::from_u32(n).unwrap().recip())
49            }
50        }
51    };
52}
53
54impl_root!(float f32, f64);
55impl_root! {
56    i8,
57    i16,
58    i32,
59    i64,
60    i128,
61    isize,
62    u8,
63    u16,
64    u32,
65    u64,
66    u128,
67    usize,
68}