rand: add rand.ulid_at_millisecond/1, use it in rand.ulid/0
parent
7d52d612ce
commit
dfa01d8877
|
@ -5,7 +5,6 @@ module rand
|
||||||
|
|
||||||
import rand.util
|
import rand.util
|
||||||
import rand.wyrand
|
import rand.wyrand
|
||||||
|
|
||||||
import time
|
import time
|
||||||
|
|
||||||
// Configuration struct for creating a new instance of the default RNG.
|
// Configuration struct for creating a new instance of the default RNG.
|
||||||
|
@ -196,10 +195,13 @@ const(
|
||||||
// users or business transactions.
|
// users or business transactions.
|
||||||
// (https://news.ycombinator.com/item?id=14526173)
|
// (https://news.ycombinator.com/item?id=14526173)
|
||||||
pub fn ulid() string {
|
pub fn ulid() string {
|
||||||
|
return ulid_at_millisecond(time.utc().unix_time_milli())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ulid_at_millisecond(unix_time_milli u64) string {
|
||||||
buflen := 26
|
buflen := 26
|
||||||
mut buf := malloc(27)
|
mut buf := malloc(27)
|
||||||
// time section
|
mut t := unix_time_milli
|
||||||
mut t := time.utc().unix_time_milli()
|
|
||||||
mut i := 9
|
mut i := 9
|
||||||
for i >= 0 {
|
for i >= 0 {
|
||||||
unsafe{
|
unsafe{
|
||||||
|
@ -230,5 +232,5 @@ pub fn ulid() string {
|
||||||
unsafe{
|
unsafe{
|
||||||
buf[26] = 0
|
buf[26] = 0
|
||||||
}
|
}
|
||||||
return string(buf,buflen)
|
return string(buf, buflen)
|
||||||
}
|
}
|
||||||
|
|
|
@ -37,21 +37,13 @@ fn test_ulids_max_start_character_is_ok() {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_ulids_generated_in_the_same_millisecond_have_the_same_prefix() {
|
fn test_ulids_generated_in_the_same_millisecond_have_the_same_prefix() {
|
||||||
mut t1 := time.utc()
|
t := time.utc().unix_time_milli()
|
||||||
mut t2 := time.utc()
|
|
||||||
mut ulid1 := ''
|
mut ulid1 := ''
|
||||||
mut ulid2 := ''
|
mut ulid2 := ''
|
||||||
mut ulid3 := ''
|
mut ulid3 := ''
|
||||||
for {
|
ulid1 = rand.ulid_at_millisecond(t)
|
||||||
t1 = time.utc()
|
ulid2 = rand.ulid_at_millisecond(t)
|
||||||
ulid1 = rand.ulid()
|
ulid3 = rand.ulid_at_millisecond(t)
|
||||||
ulid2 = rand.ulid()
|
|
||||||
ulid3 = rand.ulid()
|
|
||||||
t2 = time.utc()
|
|
||||||
if t1.unix_time_milli() == t2.unix_time_milli() {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ulid1_prefix := ulid1[0..10]
|
ulid1_prefix := ulid1[0..10]
|
||||||
ulid2_prefix := ulid2[0..10]
|
ulid2_prefix := ulid2[0..10]
|
||||||
ulid3_prefix := ulid3[0..10]
|
ulid3_prefix := ulid3[0..10]
|
||||||
|
|
Loading…
Reference in New Issue