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:
@@ -138,27 +138,8 @@ pub fn (t Time) smonth() string {
|
||||
|
||||
// new_time returns a time struct with calculated Unix time.
|
||||
pub fn new_time(t Time) Time {
|
||||
return Time{
|
||||
year: t.year
|
||||
month: t.month
|
||||
day: t.day
|
||||
hour: t.hour
|
||||
minute: t.minute
|
||||
second: t.second
|
||||
unix: u64(t.unix_time())
|
||||
microsecond: t.microsecond
|
||||
}
|
||||
// TODO Use the syntax below when it works with reserved keywords like `unix`
|
||||
// return {
|
||||
// t |
|
||||
// unix:t.unix_time()
|
||||
// }
|
||||
}
|
||||
|
||||
// unix_time returns Unix time.
|
||||
pub fn (t Time) unix_time() int {
|
||||
if t.unix != 0 {
|
||||
return int(t.unix)
|
||||
return t
|
||||
}
|
||||
tt := C.tm{
|
||||
tm_sec: t.second
|
||||
@@ -168,7 +149,20 @@ pub fn (t Time) unix_time() int {
|
||||
tm_mon: t.month - 1
|
||||
tm_year: t.year - 1900
|
||||
}
|
||||
return make_unix_time(tt)
|
||||
utime := u64(make_unix_time(tt))
|
||||
return { t | unix: utime }
|
||||
}
|
||||
|
||||
// unix_time returns Unix time.
|
||||
[inline]
|
||||
pub fn (t Time) unix_time() int {
|
||||
return int(t.unix)
|
||||
}
|
||||
|
||||
// unix_time_milli returns Unix time with millisecond resolution.
|
||||
[inline]
|
||||
pub fn (t Time) unix_time_milli() u64 {
|
||||
return t.unix * 1000 + u64(t.microsecond/1000)
|
||||
}
|
||||
|
||||
// add_seconds returns a new time struct with an added number of seconds.
|
||||
|
||||
@@ -192,3 +192,21 @@ fn test_utc() {
|
||||
assert now.microsecond >= 0
|
||||
assert now.microsecond < 1000000
|
||||
}
|
||||
|
||||
fn test_unix_time() {
|
||||
t1 := time.utc()
|
||||
time.sleep_ms(50)
|
||||
t2 := time.utc()
|
||||
ut1 := t1.unix_time()
|
||||
ut2 := t2.unix_time()
|
||||
assert ut2 - ut1 < 2
|
||||
//
|
||||
utm1 := t1.unix_time_milli()
|
||||
utm2 := t2.unix_time_milli()
|
||||
assert (utm1 - u64(ut1)*1000) < 1000
|
||||
assert (utm2 - u64(ut2)*1000) < 1000
|
||||
//
|
||||
//println('utm1: $utm1 | utm2: $utm2')
|
||||
assert utm2 - utm1 > 2
|
||||
assert utm2 - utm1 < 999
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user