-
Notifications
You must be signed in to change notification settings - Fork 26
/
uuidv7.kt
36 lines (29 loc) · 1.02 KB
/
uuidv7.kt
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
import java.security.SecureRandom
import java.time.Instant
object UUIDv7 {
private val random = SecureRandom()
fun generate(): ByteArray {
// random bytes
val value = ByteArray(16)
random.nextBytes(value)
// current timestamp in ms
val timestamp = Instant.now().toEpochMilli()
// timestamp
value[0] = ((timestamp shr 40) and 0xFF).toByte()
value[1] = ((timestamp shr 32) and 0xFF).toByte()
value[2] = ((timestamp shr 24) and 0xFF).toByte()
value[3] = ((timestamp shr 16) and 0xFF).toByte()
value[4] = ((timestamp shr 8) and 0xFF).toByte()
value[5] = (timestamp and 0xFF).toByte()
// version and variant
value[6] = (value[6].toInt() and 0x0F or 0x70).toByte()
value[8] = (value[8].toInt() and 0x3F or 0x80).toByte()
return value
}
@JvmStatic
fun main(args: Array<String>) {
val uuidVal = generate()
uuidVal.forEach { b -> print("%02x".format(b)) }
println()
}
}