forked from diamondburned/gtkcord3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.go
50 lines (41 loc) · 1003 Bytes
/
time.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package moreatomic
import (
"sync/atomic"
"time"
)
type Time struct {
unixnano int64
}
func Now() *Time {
return &Time{
unixnano: time.Now().UnixNano(),
}
}
func (t *Time) Get() time.Time {
nano := atomic.LoadInt64(&t.unixnano)
return time.Unix(0, nano)
}
func (t *Time) Set(time time.Time) {
atomic.StoreInt64(&t.unixnano, time.UnixNano())
}
func (t *Time) Reset() {
t.Set(time.Time{})
}
// HasBeen checks if it has been this long since the last time. If yes, it will
// set the time.
func (t *Time) HasBeen(dura time.Duration) bool {
now := time.Now()
nano := atomic.LoadInt64(&t.unixnano)
// We have to be careful of zero values.
if nano != 0 {
// Subtract the duration to now. If subtracted now is before the stored
// time, that means it hasn't been that long yet. We also have to be careful
// of an unitialized time.
if now.Add(-dura).Before(time.Unix(0, nano)) {
return false
}
}
// It has been that long, so store the variable.
t.Set(now)
return true
}