Skip to content

Commit

Permalink
Add nextMultipleOf overload for int
Browse files Browse the repository at this point in the history
  • Loading branch information
knokko committed Oct 25, 2024
1 parent b6137cd commit 8ed1f4e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
14 changes: 14 additions & 0 deletions src/main/java/com/github/knokko/boiler/utilities/BoilerMath.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,20 @@ public static long nextMultipleOf(long value, long alignment) {
long quotient = value / alignment;
long reverted = quotient * alignment;
if (reverted < value) reverted += alignment;
if (reverted < 0L) throw new IllegalArgumentException("Long overflow: " + value + " and " + alignment);
return reverted;
}

/**
* @return The smallest integer multiple of <i>alignment</i> that is greater than or equal to <i>value</i>
* @throws IllegalArgumentException If either of the parameters is negative
*/
public static int nextMultipleOf(int value, int alignment) {
if (value < 0 || alignment < 0) throw new IllegalArgumentException("Both parameters must be non-negative");
int quotient = value / alignment;
int reverted = quotient * alignment;
if (reverted < value) reverted += alignment;
if (reverted < 0) throw new IllegalArgumentException("Integer overflow: " + value + " and " + alignment);
return reverted;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,22 @@
public class TestBoilerMath {

@Test
public void testNextMultipleOf() {
public void testNextMultipleOfInt() {
assertEquals(10, nextMultipleOf(10, 1));
assertEquals(10, nextMultipleOf(10, 2));
assertEquals(10, nextMultipleOf(10, 5));
assertEquals(10, nextMultipleOf(10, 10));
assertEquals(12, nextMultipleOf(10, 3));
assertEquals(12, nextMultipleOf(10, 4));
}

@Test
public void testNextMultipleOfLong() {
assertEquals(10L, nextMultipleOf(10L, 1L));
assertEquals(10L, nextMultipleOf(10L, 2L));
assertEquals(10L, nextMultipleOf(10, 5L));
assertEquals(10L, nextMultipleOf(10, 10L));
assertEquals(12L, nextMultipleOf(10L, 3));
assertEquals(12L, nextMultipleOf(10L, 4));
}
}

0 comments on commit 8ed1f4e

Please sign in to comment.