-
Notifications
You must be signed in to change notification settings - Fork 26
/
uuidv7.java
39 lines (31 loc) · 1.06 KB
/
uuidv7.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.UUID;
public class UUIDv7 {
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);
}
public static byte[] randomBytes() {
// random bytes
byte[] value = new byte[16];
random.nextBytes(value);
// current timestamp in ms
ByteBuffer timestamp = ByteBuffer.allocate(Long.BYTES);
timestamp.putLong(System.currentTimeMillis());
// timestamp
System.arraycopy(timestamp.array(), 2, value, 0, 6);
// version and variant
value[6] = (byte) ((value[6] & 0x0F) | 0x70);
value[8] = (byte) ((value[8] & 0x3F) | 0x80);
return value;
}
public static void main(String[] args) {
var uuid = UUIDv7.randomUUID();
System.out.println(uuid);
}
}