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
/// Returns the sign of a value.
///
/// Contract (minimum): produce a type-specific representation of the sign. If
/// the value is positive, return the positive unit; if negative, the negative
/// unit; otherwise the zero/neutral value. Implementers must document how they
/// treat incomparable values (`NaN`, signed zero) and infinities.
pub trait Signum: Sized {
/// Produces -1, 0, or 1 (or their type-specific equivalents).
fn signum(self) -> Self;
}
macro_rules! impl_signum_for_signed {
($($ty:ty),+ $(,)?) => {
$(impl Signum for $ty {
fn signum(self) -> Self {
if self > 0 {
1 as $ty
} else if self < 0 {
-1 as $ty
} else {
0 as $ty
}
}
})+
};
}
macro_rules! impl_signum_for_float {
($($ty:ty),+ $(,)?) => {
$(impl Signum for $ty {
fn signum(self) -> Self {
<$ty>::signum(self)
}
})+
};
}
impl_signum_for_signed!(i8, i16, i32, i64, i128, isize);
impl_signum_for_float!(f32, f64);