1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
pub trait Constant: Clone + PartialEq + PartialOrd {
fn max_value() -> Option<Self>;
fn min_value() -> Option<Self>;
fn zero() -> Self;
fn checked_add(&self, other: &Self) -> Option<Self>;
fn checked_neg(&self) -> Option<Self>;
}
macro_rules! int_constant_impl {
($int_type:ty) => {
impl Constant for $int_type {
#[inline(always)]
fn max_value() -> Option<Self> {
Some(<$int_type>::MAX)
}
#[inline(always)]
fn min_value() -> Option<Self> {
Some(<$int_type>::MIN)
}
#[inline(always)]
fn zero() -> Self {
0
}
#[inline(always)]
fn checked_add(&self, other: &Self) -> Option<Self> {
<$int_type>::checked_add(*self, *other)
}
#[inline(always)]
fn checked_neg(&self) -> Option<Self> {
<$int_type>::checked_neg(*self)
}
}
};
}
int_constant_impl!(i8);
int_constant_impl!(i16);
int_constant_impl!(i32);
int_constant_impl!(i64);
int_constant_impl!(i128);
#[cfg(feature = "float")]
mod float {
use ordered_float::NotNan;
use super::*;
macro_rules! float_constant_impl {
($float_type:ty) => {
impl Constant for NotNan<$float_type> {
#[inline(always)]
fn max_value() -> Option<Self> {
Some(NotNan::new(<$float_type>::MAX).unwrap())
}
#[inline(always)]
fn min_value() -> Option<Self> {
Some(NotNan::new(<$float_type>::MIN).unwrap())
}
#[inline(always)]
fn zero() -> Self {
NotNan::new(0.0).unwrap()
}
#[inline(always)]
fn checked_add(&self, other: &Self) -> Option<Self> {
let result = *self + *other;
if result.is_infinite() {
None
} else {
Some(result)
}
}
#[inline(always)]
fn checked_neg(&self) -> Option<Self> {
Some(-*self)
}
}
};
}
float_constant_impl!(f32);
float_constant_impl!(f64);
}
#[cfg(feature = "float")]
pub use float::*;