github.com/webmafia/fast@v0.10.0/atomic_int32_pair.go (about)

     1  package fast
     2  
     3  import (
     4  	"sync/atomic"
     5  	"unsafe"
     6  )
     7  
     8  type AtomicInt32Pair struct {
     9  	v int64
    10  }
    11  
    12  type atomicInt32Pair struct {
    13  	a, b int32
    14  }
    15  
    16  //go:inline
    17  func toInt32(v int64) (int32, int32) {
    18  	ab := *(*atomicInt32Pair)(unsafe.Pointer(&v))
    19  	return ab.a, ab.b
    20  }
    21  
    22  //go:inline
    23  func toInt64(a, b int32) int64 {
    24  	return *(*int64)(unsafe.Pointer(&atomicInt32Pair{
    25  		a: a,
    26  		b: b,
    27  	}))
    28  }
    29  
    30  // Load atomically loads and returns the value stored in x.
    31  func (x *AtomicInt32Pair) Load() (int32, int32) {
    32  	return toInt32(atomic.LoadInt64(&x.v))
    33  }
    34  
    35  // Store atomically stores val into x.
    36  func (x *AtomicInt32Pair) Store(a, b int32) {
    37  	atomic.StoreInt64(&x.v, toInt64(a, b))
    38  }
    39  
    40  // Swap atomically stores new into x and returns the previous value.
    41  func (x *AtomicInt32Pair) Swap(newA, newB int32) (oldA, oldB int32) {
    42  	return toInt32(atomic.SwapInt64(&x.v, toInt64(newA, newB)))
    43  }
    44  
    45  // CompareAndSwap executes the compare-and-swap operation for x.
    46  func (x *AtomicInt32Pair) CompareAndSwap(oldA, oldB, newA, newB int32) (swapped bool) {
    47  	return atomic.CompareAndSwapInt64(&x.v, toInt64(oldA, oldB), toInt64(newA, newB))
    48  }
    49  
    50  // Add atomically adds delta to x and returns the new value.
    51  func (x *AtomicInt32Pair) Add(deltaA, deltaB int32) (newA, newB int32) {
    52  	return toInt32(atomic.AddInt64(&x.v, toInt64(deltaA, deltaB)))
    53  }