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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
use crate::num::arithmetic::traits::{RoundToMultiple, RoundToMultipleAssign, UnsignedAbs};
use crate::num::basic::signeds::PrimitiveSigned;
use crate::num::basic::unsigneds::PrimitiveUnsigned;
use crate::num::conversion::traits::ExactFrom;
use crate::rounding_modes::RoundingMode;
use std::cmp::Ordering;

fn round_to_multiple_unsigned<T: PrimitiveUnsigned>(x: T, other: T, rm: RoundingMode) -> T {
    match (x, other) {
        (x, y) if x == y => x,
        (x, y) if y == T::ZERO => match rm {
            RoundingMode::Down | RoundingMode::Floor | RoundingMode::Nearest => T::ZERO,
            _ => panic!("Cannot round {} to zero using RoundingMode {}", x, rm),
        },
        (x, y) => {
            let r = x % y;
            if r == T::ZERO {
                x
            } else {
                let floor = x - r;
                match rm {
                    RoundingMode::Down | RoundingMode::Floor => floor,
                    RoundingMode::Up | RoundingMode::Ceiling => floor.checked_add(y).unwrap(),
                    RoundingMode::Nearest => {
                        match r.cmp(&(y >> 1)) {
                            Ordering::Less => floor,
                            Ordering::Greater => floor.checked_add(y).unwrap(),
                            Ordering::Equal => {
                                if y.odd() {
                                    floor
                                } else {
                                    // The even multiple of y will have more trailing zeros.
                                    let (ceiling, overflow) = floor.overflowing_add(y);
                                    if floor.trailing_zeros() > ceiling.trailing_zeros() {
                                        floor
                                    } else if overflow {
                                        panic!(
                                            "Cannot round {} to {} using RoundingMode {}",
                                            x, y, rm
                                        );
                                    } else {
                                        ceiling
                                    }
                                }
                            }
                        }
                    }
                    RoundingMode::Exact => {
                        panic!("Cannot round {} to {} using RoundingMode {}", x, y, rm)
                    }
                }
            }
        }
    }
}

macro_rules! impl_round_to_multiple_unsigned {
    ($t:ident) => {
        impl RoundToMultiple<$t> for $t {
            type Output = $t;

            /// Rounds a number to a multiple of another number, according to a specified rounding
            /// mode.
            ///
            /// The only rounding modes that are guaranteed to return without a panic are `Down`
            /// and `Floor`.
            ///
            /// Let $q = \frac{x}{y}$:
            ///
            /// $f(x, y, \mathrm{Down}) = f(x, y, \mathrm{Floor}) = y \lfloor q \rfloor.$
            ///
            /// $f(x, y, \mathrm{Up}) = f(x, y, \mathrm{Ceiling}) = y \lceil q \rceil.$
            ///
            /// $$
            /// f(x, y, \mathrm{Nearest}) = \begin{cases}
            ///     y \lfloor q \rfloor & \text{if} \\quad
            ///         q - \lfloor q \rfloor < \frac{1}{2} \\\\
            ///     y \lceil q \rceil & \text{if} \\quad q - \lfloor q \rfloor > \frac{1}{2} \\\\
            ///     y \lfloor q \rfloor &
            ///     \text{if} \\quad q - \lfloor q \rfloor =
            ///         \frac{1}{2} \\ \text{and} \\ \lfloor q \rfloor
            ///     \\ \text{is even} \\\\
            ///     y \lceil q \rceil &
            ///     \text{if} \\quad q - \lfloor q \rfloor = \frac{1}{2}
            ///         \\ \text{and} \\ \lfloor q \rfloor \\ \text{is odd.}
            /// \end{cases}
            /// $$
            ///
            /// $f(x, y, \mathrm{Exact}) = x$, but panics if $q \notin \N$.
            ///
            /// The following two expressions are equivalent:
            /// - `x.round_to_multiple(other, RoundingMode::Exact)`
            /// - `{ assert!(x.divisible_by(other)); x }`
            ///
            /// but the latter should be used as it is clearer and more efficient.
            ///
            /// # Worst-case complexity
            /// Constant time and additional memory.
            ///
            /// # Panics
            /// - If `rm` is `Exact`, but `self` is not a multiple of `other`.
            /// - If the multiple is outside the representable range.
            /// - If `self` is nonzero, `other` is zero, and `rm` is trying to round away from zero.
            ///
            /// # Examples
            /// See [here](super::round_to_multiple#round_to_multiple).
            #[inline]
            fn round_to_multiple(self, other: $t, rm: RoundingMode) -> $t {
                round_to_multiple_unsigned(self, other, rm)
            }
        }

        impl RoundToMultipleAssign<$t> for $t {
            /// Rounds a number to a multiple of another number in place, according to a specified
            /// rounding mode.
            ///
            /// The only rounding modes that are guaranteed to return without a panic are `Down`
            /// and `Floor`.
            ///
            /// See the [`RoundToMultiple`](super::traits::RoundToMultiple) documentation for
            /// details.
            ///
            /// The following two expressions are equivalent:
            /// - `x.round_to_multiple_assign(other, RoundingMode::Exact);`
            /// - `assert!(x.divisible_by(other));`
            ///
            /// but the latter should be used as it is clearer and more efficient.
            ///
            /// # Worst-case complexity
            /// Constant time and additional memory.
            ///
            /// # Panics
            /// - If `rm` is `Exact`, but `self` is not a multiple of `other`.
            /// - If the multiple is outside the representable range.
            /// - If `self` is nonzero, `other` is zero, and `rm` is trying to round away from zero.
            ///
            /// # Examples
            /// See [here](super::round_to_multiple#round_to_multiple_assign).
            #[inline]
            fn round_to_multiple_assign(&mut self, other: $t, rm: RoundingMode) {
                *self = self.round_to_multiple(other, rm);
            }
        }
    };
}
apply_to_unsigneds!(impl_round_to_multiple_unsigned);

fn round_to_multiple_signed<
    U: PrimitiveUnsigned,
    S: ExactFrom<U> + PrimitiveSigned + UnsignedAbs<Output = U>,
>(
    x: S,
    other: S,
    rm: RoundingMode,
) -> S {
    if x >= S::ZERO {
        S::exact_from(x.unsigned_abs().round_to_multiple(other.unsigned_abs(), rm))
    } else {
        let abs_result = x
            .unsigned_abs()
            .round_to_multiple(other.unsigned_abs(), -rm);
        if abs_result == S::MIN.unsigned_abs() {
            S::MIN
        } else {
            S::exact_from(abs_result).checked_neg().unwrap()
        }
    }
}

macro_rules! impl_round_to_multiple_signed {
    ($t:ident) => {
        impl RoundToMultiple<$t> for $t {
            type Output = $t;

            /// Rounds a number to a multiple of another number, according to a specified rounding
            /// mode.
            ///
            /// The only rounding mode that is guaranteed to return without a panic is `Down`.
            ///
            /// Let $q = \frac{x}{|y|}$:
            ///
            /// $f(x, y, \mathrm{Down}) =  \operatorname{sgn}(q) |y| \lfloor |q| \rfloor.$
            ///
            /// $f(x, y, \mathrm{Up}) = \operatorname{sgn}(q) |y| \lceil |q| \rceil.$
            ///
            /// $f(x, y, \mathrm{Floor}) = |y| \lfloor q \rfloor.$
            ///
            /// $f(x, y, \mathrm{Ceiling}) = |y| \lceil q \rceil.$
            ///
            /// $$
            /// f(x, y, \mathrm{Nearest}) = \begin{cases}
            ///     y \lfloor q \rfloor & \text{if} \\quad
            ///         q - \lfloor q \rfloor < \frac{1}{2} \\\\
            ///     y \lceil q \rceil & \text{if} \\quad q - \lfloor q \rfloor > \frac{1}{2} \\\\
            ///     y \lfloor q \rfloor &
            ///     \text{if} \\quad q - \lfloor q \rfloor =
            ///         \frac{1}{2} \\ \text{and} \\ \lfloor q \rfloor
            ///     \\ \text{is even} \\\\
            ///     y \lceil q \rceil &
            ///     \text{if} \\quad q - \lfloor q \rfloor = \frac{1}{2}
            ///         \\ \text{and} \\ \lfloor q \rfloor \\ \text{is odd.}
            /// \end{cases}
            /// $$
            ///
            /// $f(x, y, \mathrm{Exact}) = q$, but panics if $q \notin \Z$.
            ///
            /// The following two expressions are equivalent:
            /// - `x.round_to_multiple(other, RoundingMode::Exact)`
            /// - `{ assert!(x.divisible_by(other)); x }`
            ///
            /// but the latter should be used as it is clearer and more efficient.
            ///
            /// # Worst-case complexity
            /// Constant time and additional memory.
            ///
            /// # Panics
            /// - If `rm` is `Exact`, but `self` is not a multiple of `other`.
            /// - If the multiple is outside the representable range.
            /// - If `self` is nonzero, `other` is zero, and `rm` is trying to round away from zero.
            ///
            /// # Examples
            /// See [here](super::round_to_multiple#round_to_multiple).
            #[inline]
            fn round_to_multiple(self, other: $t, rm: RoundingMode) -> $t {
                round_to_multiple_signed(self, other, rm)
            }
        }

        impl RoundToMultipleAssign<$t> for $t {
            /// Rounds a number to a multiple of another number in place, according to a specified
            /// rounding mode.
            ///
            /// The only rounding mode that is guaranteed to return without a panic is `Down`.
            ///
            /// See the [`RoundToMultiple`](super::traits::RoundToMultiple) documentation for
            /// details.
            ///
            /// The following two expressions are equivalent:
            /// - `x.round_to_multiple_assign(other, RoundingMode::Exact);`
            /// - `assert!(x.divisible_by(other));`
            ///
            /// but the latter should be used as it is clearer and more efficient.
            ///
            /// # Worst-case complexity
            /// Constant time and additional memory.
            ///
            /// # Panics
            /// - If `rm` is `Exact`, but `self` is not a multiple of `other`.
            /// - If the multiple is outside the representable range.
            /// - If `self` is nonzero, `other` is zero, and `rm` is trying to round away from zero.
            ///
            /// # Examples
            /// See [here](super::round_to_multiple#round_to_multiple_assign).
            #[inline]
            fn round_to_multiple_assign(&mut self, other: $t, rm: RoundingMode) {
                *self = self.round_to_multiple(other, rm);
            }
        }
    };
}
apply_to_signeds!(impl_round_to_multiple_signed);