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