github.com/insolar/vanilla@v0.0.0-20201023172447-248fdf805322/atomickit/int32.go (about) 1 // Copyright 2020 Insolar Network Ltd. 2 // All rights reserved. 3 // This material is licensed under the Insolar License version 1.0, 4 // available at https://github.com/insolar/assured-ledger/blob/master/LICENSE.md. 5 6 package atomickit 7 8 import ( 9 "strconv" 10 "sync/atomic" 11 ) 12 13 func NewInt32(v int32) Int32 { 14 return Int32{v} 15 } 16 17 type Int32 struct { 18 v int32 19 } 20 21 func (p *Int32) Load() int32 { 22 return atomic.LoadInt32(&p.v) 23 } 24 25 func (p *Int32) Store(v int32) { 26 atomic.StoreInt32(&p.v, v) 27 } 28 29 func (p *Int32) Swap(v int32) int32 { 30 return atomic.SwapInt32(&p.v, v) 31 } 32 33 func (p *Int32) CompareAndSwap(old, new int32) bool { 34 return atomic.CompareAndSwapInt32(&p.v, old, new) 35 } 36 37 func (p *Int32) Add(v int32) int32 { 38 return atomic.AddInt32(&p.v, v) 39 } 40 41 func (p *Int32) Sub(v int32) int32 { 42 return p.Add(-v) 43 } 44 45 func (p *Int32) String() string { 46 return strconv.FormatInt(int64(p.Load()), 10) 47 } 48 49 func (p *Int32) SetLesser(v int32) int32 { 50 for { 51 switch x := p.Load(); { 52 case x <= v: 53 return x 54 case p.CompareAndSwap(x, v): 55 return v 56 } 57 } 58 } 59 60 func (p *Int32) SetGreater(v int32) int32 { 61 for { 62 switch x := p.Load(); { 63 case x >= v: 64 return x 65 case p.CompareAndSwap(x, v): 66 return v 67 } 68 } 69 }