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