gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

time.go (1407B)


      1 package atomics
      2 
      3 import (
      4 	"sync/atomic"
      5 	"time"
      6 	"unsafe"
      7 )
      8 
      9 // Time provides user-friendly means of performing atomic operations on time.Time types.
     10 type Time struct{ ptr unsafe.Pointer }
     11 
     12 // NewTime will return a new Time instance initialized with zero value.
     13 func NewTime() *Time {
     14 	var v time.Time
     15 	return &Time{
     16 		ptr: unsafe.Pointer(&v),
     17 	}
     18 }
     19 
     20 // Store will atomically store time.Time value in address contained within v.
     21 func (v *Time) Store(val time.Time) {
     22 	atomic.StorePointer(&v.ptr, unsafe.Pointer(&val))
     23 }
     24 
     25 // Load will atomically load time.Time value at address contained within v.
     26 func (v *Time) Load() time.Time {
     27 	return *(*time.Time)(atomic.LoadPointer(&v.ptr))
     28 }
     29 
     30 // CAS performs a compare-and-swap for a(n) time.Time value at address contained within v.
     31 func (v *Time) CAS(cmp, swp time.Time) bool {
     32 	for {
     33 		// Load current value at address
     34 		ptr := atomic.LoadPointer(&v.ptr)
     35 		cur := *(*time.Time)(ptr)
     36 
     37 		// Perform comparison against current
     38 		if !(cur.Equal(cmp)) {
     39 			return false
     40 		}
     41 
     42 		// Attempt to replace pointer
     43 		if atomic.CompareAndSwapPointer(
     44 			&v.ptr,
     45 			ptr,
     46 			unsafe.Pointer(&swp),
     47 		) {
     48 			return true
     49 		}
     50 	}
     51 }
     52 
     53 // Swap atomically stores new time.Time value into address contained within v, and returns previous value.
     54 func (v *Time) Swap(swp time.Time) time.Time {
     55 	ptr := unsafe.Pointer(&swp)
     56 	ptr = atomic.SwapPointer(&v.ptr, ptr)
     57 	return *(*time.Time)(ptr)
     58 }