update experiment

This commit is contained in:
@hangga 2024-02-11 18:38:26 +07:00
parent b25bc0e655
commit ae5bf3ddb1
1 changed files with 43 additions and 27 deletions

View File

@ -1,43 +1,59 @@
package com.baeldung.uuid; package com.baeldung.uuid;
import com.fasterxml.uuid.impl.UUIDUtil;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.lang.reflect.Method; import java.util.UUID;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
public class UUIDPositiveLongGeneratorUnitTest { public class UUIDPositiveLongGeneratorUnitTest {
private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator(); private void verifyUUID(UUID uuid) {
byte[] bytes = toByteArray(uuid);
private final Set<Long> uniqueValues = new HashSet<>(); // assert that byte at index 6 is 0x40 (version 4)
byte byte6 = bytes[6];
assertThat(byte6 & 0xF0).isEqualTo(0x40);
// assert that the byte at index 8 is 0x80 (IETF type variant)
byte byte8 = bytes[8];
assertThat(byte8 & 0xC0).isEqualTo(0x80);
}
private boolean[] getFirst122Bits(UUID uuid) {
long msb = uuid.getMostSignificantBits();
boolean[] bits = new boolean[122]; // Untuk menyimpan 122 bit pertama dari UUID
// Konversi 64 bit pertama (Most Significant Bits) menjadi bit
for (int i = 0; i < 64; i++) {
bits[i] = ((msb >> (63 - i)) & 1) == 1; // Mendapatkan nilai bit ke-i
}
return bits;
}
private byte[] toByteArray(UUID uuid) {
long msb = uuid.getMostSignificantBits();
long lsb = uuid.getLeastSignificantBits();
byte[] buffer = new byte[16];
for (int i = 0; i < 8; i++) {
buffer[i] = (byte) (msb >>> 8 * (7 - i));
}
for (int i = 8; i < 16; i++) {
buffer[i] = (byte) (lsb >>> 8 * (7 - i));
}
return buffer;
}
@Test @Test
void whenForeachMethods_thenRetryWhileNotUnique() throws Exception { public void whenGivenUUID_thenVerified() {
for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) { for (int i = 0; i < 100; i++) {
long uniqueValue; UUID uuid = UUID.randomUUID();
do uniqueValue = (long) method.invoke(uuidLongGenerator); while (!isUnique(uniqueValue)); verifyUUID(uuid);
assertThat(uniqueValue).isPositive();
long msbfirst = uuid.getMostSignificantBits() >>> 6;
System.out.println(msbfirst);
} }
} }
@Test
void whenGivenLongValue_thenCheckUniqueness() {
long uniqueValue = generateUniqueLong();
assertThat(uniqueValue).isPositive();
}
private long generateUniqueLong() {
long uniqueValue;
do uniqueValue = uuidLongGenerator.combineBitwise(); while (!isUnique(uniqueValue));
return uniqueValue;
}
private boolean isUnique(long value) {
// Implement uniqueness checking logic, for example, by checking in the database
return uniqueValues.add(value);
}
} }