mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
rand: add rand.ulid() (#5979)
* removed debug println * added newline to the end of the file * time: add .unix_time_milli() method; rand,time: add tests * rand: add more ulid tests; move tests to a separate file random_identifiers_test.v * run vfmt over vlib/rand/random_identifiers_test.v * speed up time.unix_time_milli * simplify and speedup time.unix_time/0 and time.new_time/1 * update comment about rand.ulid() * fix terminating 0 off by 1 issue in rand.ulid() * optimize time.new_time() * restore the master version of vlib/time/parse.v * make test_unix_time more robust Co-authored-by: Delyan Angelov <delian66@gmail.com>
This commit is contained in:
@ -6,6 +6,8 @@ module rand
|
||||
import rand.util
|
||||
import rand.wyrand
|
||||
|
||||
import time
|
||||
|
||||
// Configuration struct for creating a new instance of the default RNG.
|
||||
pub struct PRNGConfigStruct {
|
||||
seed []u32 = util.time_seed_array(2)
|
||||
@ -182,3 +184,51 @@ pub fn uuid_v4() string {
|
||||
}
|
||||
return string(buf, buflen)
|
||||
}
|
||||
|
||||
const(
|
||||
ulid_encoding = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
|
||||
)
|
||||
|
||||
// rand.ulid generates an Unique Lexicographically sortable IDentifier.
|
||||
// See https://github.com/ulid/spec .
|
||||
// NB: ULIDs can leak timing information, if you make them public, because
|
||||
// you can infer the rate at which some resource is being created, like
|
||||
// users or business transactions.
|
||||
// (https://news.ycombinator.com/item?id=14526173)
|
||||
pub fn ulid() string {
|
||||
buflen := 26
|
||||
mut buf := malloc(27)
|
||||
// time section
|
||||
mut t := time.utc().unix_time_milli()
|
||||
mut i := 9
|
||||
for i >= 0 {
|
||||
unsafe{
|
||||
buf[i] = ulid_encoding[t & 0x1F]
|
||||
}
|
||||
t = t >> 5
|
||||
i--
|
||||
}
|
||||
// first rand set
|
||||
mut x := default_rng.u64()
|
||||
i = 10
|
||||
for i < 19 {
|
||||
unsafe{
|
||||
buf[i] = ulid_encoding[x & 0x1F]
|
||||
}
|
||||
x = x >> 5
|
||||
i++
|
||||
}
|
||||
// second rand set
|
||||
x = default_rng.u64()
|
||||
for i < 26 {
|
||||
unsafe{
|
||||
buf[i] = ulid_encoding[x & 0x1F]
|
||||
}
|
||||
x = x >> 5
|
||||
i++
|
||||
}
|
||||
unsafe{
|
||||
buf[26] = 0
|
||||
}
|
||||
return string(buf,buflen)
|
||||
}
|
||||
|
Reference in New Issue
Block a user