@@ -68,6 +68,42 @@ pub type Rational64 = Ratio<i64>;
68
68
/// Alias for arbitrary precision rationals.
69
69
pub type BigRational = Ratio < BigInt > ;
70
70
71
+ macro_rules! maybe_const {
72
+ ( $( $( #[ $attr: meta] ) * pub fn $name: ident $args: tt -> $ret: ty $body: block ) * ) => { $(
73
+ #[ cfg( has_const_fn) ]
74
+ $( #[ $attr] ) * pub const fn $name $args -> $ret $body
75
+
76
+ #[ cfg( not( has_const_fn) ) ]
77
+ $( #[ $attr] ) * pub fn $name $args -> $ret $body
78
+ ) * }
79
+ }
80
+
81
+ /// These method are `const` for Rust 1.31 and later.
82
+ impl < T > Ratio < T > {
83
+ maybe_const ! {
84
+ /// Creates a `Ratio` without checking for `denom == 0` or reducing.
85
+ #[ inline]
86
+ pub fn new_raw( numer: T , denom: T ) -> Ratio <T > {
87
+ Ratio {
88
+ numer: numer,
89
+ denom: denom,
90
+ }
91
+ }
92
+
93
+ /// Gets an immutable reference to the numerator.
94
+ #[ inline]
95
+ pub fn numer( & self ) -> & T {
96
+ & self . numer
97
+ }
98
+
99
+ /// Gets an immutable reference to the denominator.
100
+ #[ inline]
101
+ pub fn denom( & self ) -> & T {
102
+ & self . denom
103
+ }
104
+ }
105
+ }
106
+
71
107
impl < T : Clone + Integer > Ratio < T > {
72
108
/// Creates a new `Ratio`. Fails if `denom` is zero.
73
109
#[ inline]
@@ -86,33 +122,12 @@ impl<T: Clone + Integer> Ratio<T> {
86
122
Ratio :: new_raw ( t, One :: one ( ) )
87
123
}
88
124
89
- /// Creates a `Ratio` without checking for `denom == 0` or reducing.
90
- #[ inline]
91
- pub fn new_raw ( numer : T , denom : T ) -> Ratio < T > {
92
- Ratio {
93
- numer : numer,
94
- denom : denom,
95
- }
96
- }
97
-
98
125
/// Converts to an integer, rounding towards zero.
99
126
#[ inline]
100
127
pub fn to_integer ( & self ) -> T {
101
128
self . trunc ( ) . numer
102
129
}
103
130
104
- /// Gets an immutable reference to the numerator.
105
- #[ inline]
106
- pub fn numer < ' a > ( & ' a self ) -> & ' a T {
107
- & self . numer
108
- }
109
-
110
- /// Gets an immutable reference to the denominator.
111
- #[ inline]
112
- pub fn denom < ' a > ( & ' a self ) -> & ' a T {
113
- & self . denom
114
- }
115
-
116
131
/// Returns true if the rational number is an integer (denominator is 1).
117
132
#[ inline]
118
133
pub fn is_integer ( & self ) -> bool {
@@ -2071,4 +2086,19 @@ mod test {
2071
2086
r. set_one ( ) ;
2072
2087
assert ! ( r. is_one( ) ) ;
2073
2088
}
2089
+
2090
+ #[ cfg( has_const_fn) ]
2091
+ #[ test]
2092
+ fn test_const ( ) {
2093
+ const N : Ratio < i32 > = Ratio :: new_raw ( 123 , 456 ) ;
2094
+ const N_NUMER : & i32 = N . numer ( ) ;
2095
+ const N_DENOM : & i32 = N . denom ( ) ;
2096
+
2097
+ assert_eq ! ( N_NUMER , & 123 ) ;
2098
+ assert_eq ! ( N_DENOM , & 456 ) ;
2099
+
2100
+ let r = N . reduced ( ) ;
2101
+ assert_eq ! ( r. numer( ) , & ( 123 / 3 ) ) ;
2102
+ assert_eq ! ( r. denom( ) , & ( 456 / 3 ) ) ;
2103
+ }
2074
2104
}
0 commit comments