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.wyrand
|
||||
|
||||
import time
|
||||
|
||||
// Configuration struct for creating a new instance of the default RNG.
|
||||
|
@ -196,10 +195,13 @@ const(
|
|||
// users or business transactions.
|
||||
// (https://news.ycombinator.com/item?id=14526173)
|
||||
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
|
||||
mut buf := malloc(27)
|
||||
// time section
|
||||
mut t := time.utc().unix_time_milli()
|
||||
mut t := unix_time_milli
|
||||
mut i := 9
|
||||
for i >= 0 {
|
||||
unsafe{
|
||||
|
@ -230,5 +232,5 @@ pub fn ulid() string {
|
|||
unsafe{
|
||||
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() {
|
||||
mut t1 := time.utc()
|
||||
mut t2 := time.utc()
|
||||
t := time.utc().unix_time_milli()
|
||||
mut ulid1 := ''
|
||||
mut ulid2 := ''
|
||||
mut ulid3 := ''
|
||||
for {
|
||||
t1 = time.utc()
|
||||
ulid1 = rand.ulid()
|
||||
ulid2 = rand.ulid()
|
||||
ulid3 = rand.ulid()
|
||||
t2 = time.utc()
|
||||
if t1.unix_time_milli() == t2.unix_time_milli() {
|
||||
break
|
||||
}
|
||||
}
|
||||
mut ulid3 := ''
|
||||
ulid1 = rand.ulid_at_millisecond(t)
|
||||
ulid2 = rand.ulid_at_millisecond(t)
|
||||
ulid3 = rand.ulid_at_millisecond(t)
|
||||
ulid1_prefix := ulid1[0..10]
|
||||
ulid2_prefix := ulid2[0..10]
|
||||
ulid3_prefix := ulid3[0..10]
|
||||
|
|
Loading…
Reference in New Issue