Skip to content

Commit

Permalink
Generate UUIDv7 from Instant
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiocostamoreno committed Jul 28, 2024
1 parent 8846a5b commit 1820e48
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/nativeMain/kotlin/Generate.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import kotlin.random.Random
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant

private const val VERSION: Long = 7
private const val VARIANT: Long = 0b10
Expand All @@ -8,8 +9,12 @@ private const val RANDOM_B_TOP_LIMIT: Long = 0x4000000000000000 // 62 random bit

object Generate {

fun now(): String {
val timestamp = Clock.System.now().toEpochMilliseconds()
fun now(): String = Clock.System.now().let(::generateWith)

fun at(instant: Instant): String = generateWith(instant)

private fun generateWith(instant: Instant): String {
val timestamp = instant.toEpochMilliseconds()
val randomA = Random.nextLong(RANDOM_A_TOP_LIMIT)
val randomB = Random.nextLong(RANDOM_B_TOP_LIMIT)
return setOf(
Expand Down

0 comments on commit 1820e48

Please sign in to comment.