[uuid] diegotorres/dtorres.py@gmail.com Improvements for UUIDv5 generation (#10978)

* [uuid] Added method to generate UUID identifiers for version 5

Signed-off-by: Diego Torres <dtorres.py@gmail.com>

* [uuid] Small improvements for UUIDv5 generation

Signed-off-by: Diego Torres <dtorres.py@gmail.com>
This commit is contained in:
Diego Torres 2021-06-29 04:46:32 -04:00 committed by GitHub
parent 9b5d2b8077
commit 0d722c1d90
2 changed files with 8 additions and 15 deletions

View File

@ -176,8 +176,8 @@ public class UUIDGenerator {
byte[] hash = md.digest(bytes);
long msb = peekLong(hash, 0, ByteOrder.BIG_ENDIAN);
long lsb = peekLong(hash, 8, ByteOrder.BIG_ENDIAN);
long msb = getLeastAndMostSignificantBitsVersion5(hash, 0);
long lsb = getLeastAndMostSignificantBitsVersion5(hash, 8);
// Set the version field
msb &= ~(0xfL << 12);
msb |= ((long) 5) << 12;
@ -191,18 +191,11 @@ public class UUIDGenerator {
}
}
private static long peekLong(final byte[] src, final int offset, final ByteOrder order) {
private static long getLeastAndMostSignificantBitsVersion5(final byte[] src, final int offset) {
long ans = 0;
if (order == ByteOrder.BIG_ENDIAN) {
for (int i = offset; i < offset + 8; i += 1) {
ans <<= 8;
ans |= src[i] & 0xffL;
}
} else {
for (int i = offset + 7; i >= offset; i -= 1) {
ans <<= 8;
ans |= src[i] & 0xffL;
}
for (int i = offset + 7; i >= offset; i -= 1) {
ans <<= 8;
ans |= src[i] & 0xffL;
}
return ans;
}

View File

@ -63,11 +63,11 @@ class UUIDGeneratorUnitTest {
}
@Test
public void version_5_UUID_is_correctly_generated_for_domain_baeldung_com_without_namespace() throws UnsupportedEncodingException {
public void version_5_UUID_is_correctly_generated_for_domain_baeldung_name() {
UUID uuid = UUIDGenerator.generateType5UUID("baeldung.com");
assertEquals("a3c27ab0-2b46-55ef-b50e-0e5c57bfea94", uuid.toString());
assertEquals("efd5462b-b07a-52a3-94ea-bf575c0e0e75", uuid.toString());
assertEquals(5, uuid.version());
assertEquals(2, uuid.variant());
}