gtsocial-umbx

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

bool.go (1211B)


      1 package atomics
      2 
      3 import "sync/atomic"
      4 
      5 // Bool provides user-friendly means of performing atomic operations on bool types.
      6 type Bool uint32
      7 
      8 // NewBool will return a new Bool instance initialized with zero value.
      9 func NewBool() *Bool {
     10 	return new(Bool)
     11 }
     12 
     13 // Store will atomically store bool value in address contained within i.
     14 func (b *Bool) Store(val bool) {
     15 	atomic.StoreUint32((*uint32)(b), fromBool(val))
     16 }
     17 
     18 // Load will atomically load bool value at address contained within i.
     19 func (b *Bool) Load() bool {
     20 	return toBool(atomic.LoadUint32((*uint32)(b)))
     21 }
     22 
     23 // CAS performs a compare-and-swap for a(n) bool value at address contained within i.
     24 func (b *Bool) CAS(cmp, swp bool) bool {
     25 	return atomic.CompareAndSwapUint32((*uint32)(b), fromBool(cmp), fromBool(swp))
     26 }
     27 
     28 // Swap atomically stores new bool value into address contained within i, and returns previous value.
     29 func (b *Bool) Swap(swp bool) bool {
     30 	return toBool(atomic.SwapUint32((*uint32)(b), fromBool(swp)))
     31 }
     32 
     33 // toBool converts uint32 value to bool.
     34 func toBool(u uint32) bool {
     35 	if u == 0 {
     36 		return false
     37 	}
     38 	return true
     39 }
     40 
     41 // fromBool converts from bool to uint32 value.
     42 func fromBool(b bool) uint32 {
     43 	if b {
     44 		return 1
     45 	}
     46 	return 0
     47 }