concision_utils/traits/
root.rs

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