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
/*
Copyright 2025 Owain Davies
SPDX-License-Identifier: Apache-2.0 OR MIT
*/
use crate::{Arbi, Assign};
impl Arbi {
/// If `rhs` is positive, return the smallest value greater than or equal to
/// `self` that is a multiple of `rhs`. If `rhs` is negative, return the
/// largest value less than or equal to `self` that is a multiple of `rhs`.
///
/// # Panic
/// Panics if `rhs` is zero.
///
/// # Examples
/// ```
/// use arbi::Arbi;
/// assert_eq!(Arbi::from(12).next_multiple_of(&Arbi::from(6)), 12);
/// assert_eq!(Arbi::from(19).next_multiple_of(&Arbi::from(7)), 21);
/// assert_eq!(Arbi::from(25).next_multiple_of(&Arbi::from(-5)), 25);
/// assert_eq!(Arbi::from(25).next_multiple_of(&Arbi::from(-7)), 21);
/// assert_eq!(Arbi::from(-21).next_multiple_of(&Arbi::from(7)), -21);
/// assert_eq!(Arbi::from(-25).next_multiple_of(&Arbi::from(7)), -21);
/// assert_eq!(Arbi::from(-21).next_multiple_of(&Arbi::from(-7)), -21);
/// assert_eq!(Arbi::from(-25).next_multiple_of(&Arbi::from(-7)), -28);
/// ```
///
/// Panics if `rhs` is zero:
/// ```should_panic
/// use arbi::Arbi;
/// Arbi::from(123).next_multiple_of(&Arbi::zero());
/// ```
pub fn next_multiple_of(&self, rhs: &Self) -> Self {
let (_, mut r) = self.divrem_floor_ref(rhs);
if r.is_zero() {
r.assign(self);
r
} else {
(rhs - r) + self
}
}
/// If `rhs` is positive, return the largest value less than or equal to
/// `self` that is a multiple of `rhs`. If `rhs` is negative, return the
/// smallest value greater than or equal to `self` that is a multiple of
/// `rhs`.
///
/// # Panic
/// Panics if `rhs` is zero.
///
/// # Examples
/// ```
/// use arbi::Arbi;
/// assert_eq!(Arbi::from(12).prev_multiple_of(&Arbi::from(6)), 12);
/// assert_eq!(Arbi::from(19).prev_multiple_of(&Arbi::from(7)), 14);
/// assert_eq!(Arbi::from(25).prev_multiple_of(&Arbi::from(-5)), 25);
/// assert_eq!(Arbi::from(25).prev_multiple_of(&Arbi::from(-7)), 28);
/// assert_eq!(Arbi::from(-21).prev_multiple_of(&Arbi::from(7)), -21);
/// assert_eq!(Arbi::from(-25).prev_multiple_of(&Arbi::from(7)), -28);
/// assert_eq!(Arbi::from(-21).prev_multiple_of(&Arbi::from(-7)), -21);
/// assert_eq!(Arbi::from(-25).prev_multiple_of(&Arbi::from(-7)), -21);
/// ```
///
/// Panics if `rhs` is zero:
/// ```should_panic
/// use arbi::Arbi;
/// Arbi::from(123).prev_multiple_of(&Arbi::zero());
/// ```
pub fn prev_multiple_of(&self, rhs: &Self) -> Self {
let (_, mut r) = self.divrem_floor_ref(rhs);
if r.is_zero() {
// Potentially avoid memory allocation
r.assign(self);
r
} else {
self - r
}
}
}