Skip to content

Instantly share code, notes, and snippets.

@hamnis
Last active October 2, 2023 12:43
Show Gist options
  • Save hamnis/de68e2cc88bdcdc58b5ef2a2a02c2ae5 to your computer and use it in GitHub Desktop.
Save hamnis/de68e2cc88bdcdc58b5ef2a2a02c2ae5 to your computer and use it in GitHub Desktop.
import java.util.UUID
import java.security.SecureRandom
import java.time.Instant
object UUIDV7 {
lazy val defaultRandom = new SecureRandom()
def create: UUID = create(defaultRandom)
def create(rnd: SecureRandom): UUID = create(rnd, System.currentTimeMillis)
def createFromInstant(instant: Instant): UUID = createFromInstant(defaultRandom, instant)
def createFromInstant(rnd: SecureRandom, instant: Instant): UUID = create(rnd, instant.toEpochMilli)
private def create(rnd: SecureRandom, now: Long): UUID = {
val msb = (now << 16) | (rnd.nextLong & 0x0fffL) | 0x7000L
val lsb = (rnd.nextLong & 0x3fffffffffffffffL) | 0x8000000000000000L
new UUID(msb, lsb)
}
def min(instant: Instant): UUID = {
val time = instant.toEpochMilli
new UUID((time << 16) | 0x7000L, 0x8000000000000000L)
}
def max(instant: Instant): UUID = {
val time = instant.toEpochMilli
new UUID((time << 16) | 0x7fffL, 0xbfffffffffffffffL)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment