Skip to content

Commit

Permalink
airframe-ulid: #2106 Add ULID.ofMillis(unix time milliseconds) (#2400)
Browse files Browse the repository at this point in the history
  • Loading branch information
xerial committed Sep 7, 2022
1 parent 4eab8bd commit 23c1b3a
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
14 changes: 13 additions & 1 deletion airframe-ulid/src/main/scala/wvlet/airframe/ulid/ULID.scala
Expand Up @@ -151,6 +151,15 @@ object ULID {
*/
def newULIDString: String = _generator.newULIDString

/**
* Create a new ULID from a given unix time in milli seconds
* @param unixTimeMillis
* @return
*/
def ofMillis(unixTimeMillis: Long): ULID = {
ULID(_generator.newULIDFromMillis(unixTimeMillis))
}

/**
* Create a new ULID from a given string of size 26
*/
Expand Down Expand Up @@ -262,10 +271,13 @@ object ULID {
*/
def newULIDString: String = {
val unixTimeMillis: Long = currentTimeInMillis
newULIDFromMillis(unixTimeMillis)
}

def newULIDFromMillis(unixTimeMillis: Long): String = {
if (unixTimeMillis > MaxTime) {
throw new IllegalStateException(f"unixtime should be less than: ${MaxTime}%,d: ${unixTimeMillis}%,d")
}

// Add a guard so that only a single-thread can generate ULID based on the previous value
synchronized {
val (hi, low) = lastValue.get()
Expand Down
Expand Up @@ -116,6 +116,11 @@ class ULIDTest extends AirSpec with PropertyCheck {
} finally {
ULID.useDefaultULIDGenerator
}
}

test("generate ULID from a given unix time") {
val unixTime = System.currentTimeMillis() - 10000
val u = ULID.ofMillis(unixTime)
u.epochMillis shouldBe unixTime
}
}
9 changes: 9 additions & 0 deletions docs/airframe-ulid.md
Expand Up @@ -70,15 +70,24 @@ val ulid: ULID = ULID.newULID
println(ulid) // 01F3J0G1M4WQRBHGZ6HCF6JA0K
println(ulid.epochMillis) // 1618733434500

// You can generate a ULID string at ease with newULIDString
ULID.newULIDString

// Parse the string representation of ULIDs
val ulid2 = ULID.fromString("01F3J0G1MD4QX7Z5QB148QNH4R")
ulid2.epochMillis // 1618733434509

// Parse the binary representation of ULIDs
ULID.fromBytes(...)


// Create an ULID from a given unixtime (milliseconds)
val unixTimeMillis = System.currentTimeMillis() - 1000
ULID.ofMillis(unixTimeMillis)

// Create an ULID from a given unixtime (48-bits, milliseconds) and a random value (80-bits)
ULID.of(unixTimeMillis, randHi, randLow)

```


Expand Down

0 comments on commit 23c1b3a

Please sign in to comment.