github.com/hslam/atomic@v1.0.0/int16.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 // Int16 represents an int16. 11 type Int16 struct { 12 v uint32 13 } 14 15 // NewInt16 returns a new Int16. 16 func NewInt16(val int16) *Int16 { 17 addr := &Int16{} 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 *Int16) Swap(new int16) (old int16) { 24 var v = atomic.SwapUint32(&addr.v, uint32(new)) 25 return int16(v) 26 } 27 28 // CompareAndSwap executes the compare-and-swap operation for an int16 value. 29 func (addr *Int16) CompareAndSwap(old, new int16) (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 *Int16) Add(delta int16) (new int16) { 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 *Int16) Load() (val int16) { 46 var v = atomic.LoadUint32(&addr.v) 47 return int16(v) 48 } 49 50 // Store atomically stores val into *addr. 51 func (addr *Int16) Store(val int16) { 52 atomic.StoreUint32(&addr.v, uint32(val)) 53 }