github.com/prysmaticlabs/prysm@v1.4.4/shared/abool/abool.go (about)

     1  // Package abool provides atomic Boolean type for cleaner code and
     2  // better performance.
     3  // All rights reserved to https://github.com/tevino/abool.
     4  package abool
     5  
     6  import "sync/atomic"
     7  
     8  // New creates an AtomicBool with default set to false.
     9  func New() *AtomicBool {
    10  	return new(AtomicBool)
    11  }
    12  
    13  // NewBool creates an AtomicBool with given default value.
    14  func NewBool(ok bool) *AtomicBool {
    15  	ab := New()
    16  	if ok {
    17  		ab.Set()
    18  	}
    19  	return ab
    20  }
    21  
    22  // AtomicBool is an atomic Boolean.
    23  // Its methods are all atomic, thus safe to be called by multiple goroutines simultaneously.
    24  // Note: When embedding into a struct one should always use *AtomicBool to avoid copy.
    25  type AtomicBool int32
    26  
    27  // Set sets the Boolean to true.
    28  func (ab *AtomicBool) Set() {
    29  	atomic.StoreInt32((*int32)(ab), 1)
    30  }
    31  
    32  // UnSet sets the Boolean to false.
    33  func (ab *AtomicBool) UnSet() {
    34  	atomic.StoreInt32((*int32)(ab), 0)
    35  }
    36  
    37  // IsSet returns whether the Boolean is true.
    38  func (ab *AtomicBool) IsSet() bool {
    39  	return atomic.LoadInt32((*int32)(ab))&1 == 1
    40  }
    41  
    42  // IsNotSet returns whether the Boolean is false.
    43  func (ab *AtomicBool) IsNotSet() bool {
    44  	return !ab.IsSet()
    45  }
    46  
    47  // SetTo sets the boolean with given Boolean.
    48  func (ab *AtomicBool) SetTo(yes bool) {
    49  	if yes {
    50  		atomic.StoreInt32((*int32)(ab), 1)
    51  	} else {
    52  		atomic.StoreInt32((*int32)(ab), 0)
    53  	}
    54  }
    55  
    56  // Toggle inverts the Boolean then returns the value before inverting.
    57  func (ab *AtomicBool) Toggle() bool {
    58  	return atomic.AddInt32((*int32)(ab), 1)&1 == 0
    59  }
    60  
    61  // SetToIf sets the Boolean to new only if the Boolean matches the old.
    62  // Returns whether the set was done.
    63  func (ab *AtomicBool) SetToIf(old, curr bool) (set bool) {
    64  	var o, n int32
    65  	if old {
    66  		o = 1
    67  	}
    68  	if curr {
    69  		n = 1
    70  	}
    71  	return atomic.CompareAndSwapInt32((*int32)(ab), o, n)
    72  }