1
// This file was originally copied from https://github.com/servo/euclid/blob/master/src/num.rs.
2

            
3
/// Returns a zero value.
4
pub trait Zero {
5
    /// Returns a zero value.
6
    fn zero() -> Self;
7
}
8

            
9
impl<T: num_traits::Zero> Zero for T {
10
    fn zero() -> T {
11
        num_traits::Zero::zero()
12
    }
13
}
14

            
15
/// Returns a one value.
16
pub trait One {
17
    /// Returns a one value.
18
    fn one() -> Self;
19
}
20

            
21
impl<T: num_traits::One> One for T {
22
    fn one() -> T {
23
        num_traits::One::one()
24
    }
25
}
26

            
27
/// Defines the nearest integer value to the original value.
28
pub trait Round: Copy {
29
    /// Rounds to the nearest integer value.
30
    ///
31
    /// This behavior is preserved for negative values (unlike the basic cast).
32
    #[must_use]
33
    fn round(self) -> Self;
34
}
35

            
36
/// Defines the biggest integer equal or lower than the original value.
37
pub trait Floor: Copy {
38
    /// Rounds to the biggest integer equal or lower than the original value.
39
    ///
40
    /// This behavior is preserved for negative values (unlike the basic cast).
41
    #[must_use]
42
    fn floor(self) -> Self;
43
}
44

            
45
/// Defines the smallest integer equal or greater than the original value.
46
pub trait Ceil: Copy {
47
    /// Rounds to the smallest integer equal or greater than the original value.
48
    ///
49
    /// This behavior is preserved for negative values (unlike the basic cast).
50
    #[must_use]
51
    fn ceil(self) -> Self;
52
}
53

            
54
macro_rules! num_int {
55
    ($ty:ty) => {
56
        impl Round for $ty {
57
            #[inline]
58
            fn round(self) -> $ty {
59
                self
60
            }
61
        }
62
        impl Floor for $ty {
63
            #[inline]
64
            fn floor(self) -> $ty {
65
                self
66
            }
67
        }
68
        impl Ceil for $ty {
69
            #[inline]
70
            fn ceil(self) -> $ty {
71
                self
72
            }
73
        }
74
    };
75
}
76

            
77
macro_rules! num_float {
78
    ($ty:ty) => {
79
        impl Round for $ty {
80
            #[inline]
81
7
            fn round(self) -> $ty {
82
7
                (self + 0.5).floor()
83
7
            }
84
        }
85
        impl Floor for $ty {
86
            #[inline]
87
7
            fn floor(self) -> $ty {
88
7
                num_traits::Float::floor(self)
89
7
            }
90
        }
91
        impl Ceil for $ty {
92
            #[inline]
93
7
            fn ceil(self) -> $ty {
94
7
                num_traits::Float::ceil(self)
95
7
            }
96
        }
97
    };
98
}
99

            
100
num_int!(i16);
101
num_int!(u16);
102
num_int!(i32);
103
num_int!(u32);
104
num_int!(i64);
105
num_int!(u64);
106
num_int!(isize);
107
num_int!(usize);
108
num_float!(f32);
109
num_float!(f64);