Skip to content

Commit

Permalink
Fix for ArrayIndexOutOfBoundsException when random number is Integer.…
Browse files Browse the repository at this point in the history
…MIN_VALUE (#9)
  • Loading branch information
czarekm authored Jul 28, 2024
1 parent c55aa79 commit ec7858e
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/main/java/io/github/thibaultmeyer/cuid/CUID.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public static CUID randomCUID2(final int length) {
}

final String time = Long.toString(System.currentTimeMillis(), NUMBER_BASE);
final char firstLetter = CUIDv2.ALPHABET_ARRAY[Math.abs(Common.nextIntValue()) % CUIDv2.ALPHABET_ARRAY.length];
final char firstLetter = CUIDv2.ALPHABET_ARRAY[safeAbs(Common.nextIntValue()) % CUIDv2.ALPHABET_ARRAY.length];
final String hash = CUIDv2.computeHash(
time + CUIDv2.createEntropy(length) + CUIDv2.nextCounterValue() + Common.MACHINE_FINGERPRINT,
length);
Expand Down Expand Up @@ -177,6 +177,11 @@ public int hashCode() {
return Objects.hash(value);
}

// Always return non-negative value (including Integer.MIN_VALUE)
private static int safeAbs(int a) {
return a == Integer.MIN_VALUE ? 0 : Math.abs(a);
}

/**
* CUID Version 1.
*
Expand Down Expand Up @@ -252,7 +257,7 @@ private static final class CUIDv2 {
*/
private static synchronized int nextCounterValue() {

counter = counter < Integer.MAX_VALUE ? counter : Math.abs(Common.nextIntValue());
counter = counter < Integer.MAX_VALUE ? counter : safeAbs(Common.nextIntValue());
return counter++;
}

Expand All @@ -268,7 +273,7 @@ private static String createEntropy(final int length) {
final StringBuilder stringBuilder = new StringBuilder(length);

while (stringBuilder.length() < length) {
primeNumber = PRIME_NUMBER_ARRAY[Math.abs(Common.nextIntValue()) % PRIME_NUMBER_ARRAY.length];
primeNumber = PRIME_NUMBER_ARRAY[safeAbs(Common.nextIntValue()) % PRIME_NUMBER_ARRAY.length];
stringBuilder.append(Integer.toString(primeNumber * Common.nextIntValue(), NUMBER_BASE));
}

Expand Down

0 comments on commit ec7858e

Please sign in to comment.