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