stack_algebra/
num.rs

1//! Abstractions over number types.
2
3/// Defines the absolute value for a type.
4pub trait Abs {
5    /// Returns the absolute value of this type.
6    fn abs(self) -> Self;
7}
8
9/// Defines the square-root value for a type.
10pub trait Sqrt {
11    /// Returns the square-root value of this type.
12    fn sqrt(self) -> Self;
13}
14
15/// Defines a multiplicative identity element for a type.
16pub trait One {
17    /// Returns the multiplicative identity element of this type.
18    fn one() -> Self;
19}
20
21/// Defines a additive identity element for a type.
22pub trait Zero {
23    /// Returns the additive identity element of this type.
24    fn zero() -> Self;
25}
26
27macro_rules! impl_one {
28    ($one:literal $($ty:ty)+) => ($(
29        impl One for $ty {
30            #[inline]
31            fn one() -> $ty {
32                $one
33            }
34        }
35    )+)
36}
37
38macro_rules! impl_zero {
39    ($zero:literal $($ty:ty)+) => ($(
40        impl Zero for $ty {
41            #[inline]
42            fn zero() -> $ty {
43                $zero
44            }
45        }
46    )+)
47}
48
49macro_rules! impl_abs {
50    ($($ty:ident)+) => ($(
51        impl Abs for $ty {
52            #[inline]
53            fn abs(self) -> $ty {
54                $ty::abs(self)
55            }
56        }
57    )+)
58}
59
60impl Abs for f32 {
61    fn abs(self) -> Self {
62        libm::fabsf(self)
63    }
64}
65
66impl Abs for f64 {
67    fn abs(self) -> Self {
68        libm::fabs(self)
69    }
70}
71
72impl Sqrt for f32 {
73    fn sqrt(self) -> Self {
74        libm::sqrtf(self)
75    }
76}
77
78impl Sqrt for f64 {
79    fn sqrt(self) -> Self {
80        libm::sqrt(self)
81    }
82}
83
84macro_rules! impl_abs_self {
85    ($($ty:ident)+) => ($(
86        impl Abs for $ty {
87            #[inline]
88            fn abs(self) -> $ty {
89                self
90            }
91        }
92    )+)
93}
94
95impl_one! { true bool }
96impl_one! { 1 usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
97impl_one! { 1.0 f32 f64 }
98
99impl_zero! { false bool }
100impl_zero! { 0 usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
101impl_zero! { 0.0 f32 f64 }
102
103impl_abs_self! { usize u8 u16 u32 u64 u128 }
104impl_abs! { isize i8 i16 i32 i64 i128 }