Skip to content

Commit

Permalink
Add validation to Util::log2
Browse files Browse the repository at this point in the history
Changed logic to take advantage of Integer::numberOfLeadingZeros which cuts down the code.

Fixes #443
  • Loading branch information
Palmr committed Mar 15, 2023
1 parent 109e288 commit ae0e471
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
12 changes: 5 additions & 7 deletions src/main/java/com/lmax/disruptor/util/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -91,18 +91,16 @@ public static Sequence[] getSequencesFor(final EventProcessor... processors)
* Calculate the log base 2 of the supplied integer, essentially reports the location
* of the highest bit.
*
* @param i Value to calculate log2 for.
* @param value Positive value to calculate log2 for.
* @return The log2 value
*/
public static int log2(final int i)
public static int log2(final int value)
{
long value = i;
int r = 0;
while ((value >>= 1) != 0)
if (value < 1)
{
++r;
throw new IllegalArgumentException("value must be a positive number");
}
return r;
return Integer.SIZE - Integer.numberOfLeadingZeros(value) - 1;
}

/**
Expand Down
19 changes: 19 additions & 0 deletions src/test/java/com/lmax/disruptor/util/UtilTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

public final class UtilTest
{
Expand Down Expand Up @@ -52,4 +53,22 @@ public void shouldReturnLongMaxWhenNoEventProcessors()

assertEquals(Long.MAX_VALUE, Util.getMinimumSequence(sequences));
}

@Test
void shouldThrowErrorIfValuePassedToLog2FunctionIsNotPositive()
{
assertThrows(IllegalArgumentException.class, () -> Util.log2(0));
assertThrows(IllegalArgumentException.class, () -> Util.log2(-1));
assertThrows(IllegalArgumentException.class, () -> Util.log2(Integer.MIN_VALUE));
}

@Test
void shouldCalculateCorrectlyIntegerFlooredLog2()
{
assertEquals(0, Util.log2(1));
assertEquals(1, Util.log2(2));
assertEquals(1, Util.log2(3));
assertEquals(10, Util.log2(1024));
assertEquals(30, Util.log2(Integer.MAX_VALUE));
}
}

0 comments on commit ae0e471

Please sign in to comment.