Skip to content

Commit

Permalink
* uuid: added uuid v7, can be used as db friendly primary key
Browse files Browse the repository at this point in the history
Signed-off-by: neo <1100909+neowu@users.noreply.github.com>
  • Loading branch information
neowu committed Aug 1, 2024
1 parent dff7f45 commit b75b5b9
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ try (EventSource source = client.sse(request)) {
}
```

* uuid: added uuid v7, can be used as db friendly primary key

### 9.1.0 (6/12/2024 - 7/9/2024)

* jre: published neowu/jre:21.0.3
Expand Down
41 changes: 41 additions & 0 deletions core-ng/src/main/java/core/framework/util/UUIDv7.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package core.framework.util;

import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.UUID;

/**
* @author neo
*/
public class UUIDv7 {
// refer to https://www.ietf.org/archive/id/draft-peabody-dispatch-new-uuid-format-04.html#name-uuid-version-7
private static final SecureRandom RANDOM = new SecureRandom();

public static UUID randomUUID() {
byte[] value = randomBytes();
ByteBuffer buf = ByteBuffer.wrap(value);
long high = buf.getLong();
long low = buf.getLong();
return new UUID(high, low);
}

private static byte[] randomBytes() {
byte[] value = new byte[16];
RANDOM.nextBytes(value);

long timestamp = System.currentTimeMillis();
// timestamp
value[0] = (byte) ((timestamp >> 40) & 0xFF);
value[1] = (byte) ((timestamp >> 32) & 0xFF);
value[2] = (byte) ((timestamp >> 24) & 0xFF);
value[3] = (byte) ((timestamp >> 16) & 0xFF);
value[4] = (byte) ((timestamp >> 8) & 0xFF);
value[5] = (byte) (timestamp & 0xFF);

// version and variant
value[6] = (byte) ((value[6] & 0x0F) | 0x70);
value[8] = (byte) ((value[8] & 0x3F) | 0x80);

return value;
}
}
15 changes: 15 additions & 0 deletions core-ng/src/test/java/core/framework/util/UUIDv7Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package core.framework.util;

import org.junit.jupiter.api.Test;

import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;

class UUIDv7Test {
@Test
void randomUUID() {
UUID uuid = UUIDv7.randomUUID();
assertThat(uuid.version()).isEqualTo(7);
}
}

0 comments on commit b75b5b9

Please sign in to comment.