github.com/hslam/atomic@v1.0.0/uint16.go (about)

     1  // Copyright (c) 2020 Meng Huang (mhboy@outlook.com)
     2  // This package is licensed under a MIT license that can be found in the LICENSE file.
     3  
     4  package atomic
     5  
     6  import (
     7  	"sync/atomic"
     8  )
     9  
    10  // Uint16 represents an uint16.
    11  type Uint16 struct {
    12  	v uint32
    13  }
    14  
    15  // NewUint16 returns a new Uint16.
    16  func NewUint16(val uint16) *Uint16 {
    17  	addr := &Uint16{}
    18  	addr.Store(val)
    19  	return addr
    20  }
    21  
    22  // Swap atomically stores new into *addr and returns the previous *addr value.
    23  func (addr *Uint16) Swap(new uint16) (old uint16) {
    24  	var v = atomic.SwapUint32(&addr.v, uint32(new))
    25  	return uint16(v)
    26  }
    27  
    28  // CompareAndSwap executes the compare-and-swap operation for an uint16 value.
    29  func (addr *Uint16) CompareAndSwap(old, new uint16) (swapped bool) {
    30  	return atomic.CompareAndSwapUint32(&addr.v, uint32(old), uint32(new))
    31  }
    32  
    33  // Add atomically adds delta to *addr and returns the new value.
    34  func (addr *Uint16) Add(delta uint16) (new uint16) {
    35  	for {
    36  		old := addr.Load()
    37  		new = old + delta
    38  		if addr.CompareAndSwap(old, new) {
    39  			return
    40  		}
    41  	}
    42  }
    43  
    44  // Load atomically loads *addr.
    45  func (addr *Uint16) Load() (val uint16) {
    46  	var v = atomic.LoadUint32(&addr.v)
    47  	return uint16(v)
    48  }
    49  
    50  // Store atomically stores val into *addr.
    51  func (addr *Uint16) Store(val uint16) {
    52  	atomic.StoreUint32(&addr.v, uint32(val))
    53  }