Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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