-
Notifications
You must be signed in to change notification settings - Fork 4
/
int.go
90 lines (76 loc) · 1.54 KB
/
int.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package atomickit
import (
"math/bits"
"strconv"
"sync/atomic"
"unsafe"
)
func NewInt(v int) Int {
return Int{v}
}
type Int struct {
v int
}
func (p *Int) ptr32() *int32 {
return (*int32)(unsafe.Pointer(&p.v))
}
func (p *Int) ptr64() *int64 {
return (*int64)(unsafe.Pointer(&p.v))
}
func (p *Int) Load() int {
if bits.UintSize == 32 {
return int(atomic.LoadInt32(p.ptr32()))
}
return int(atomic.LoadInt64(p.ptr64()))
}
func (p *Int) Store(v int) {
if bits.UintSize == 32 {
atomic.StoreInt32(p.ptr32(), int32(v))
return
}
atomic.StoreInt64(p.ptr64(), int64(v))
}
func (p *Int) Swap(v int) int {
if bits.UintSize == 32 {
return int(atomic.SwapInt32(p.ptr32(), int32(v)))
}
return int(atomic.SwapInt64(p.ptr64(), int64(v)))
}
func (p *Int) CompareAndSwap(old, new int) bool {
if bits.UintSize == 32 {
return atomic.CompareAndSwapInt32(p.ptr32(), int32(old), int32(new))
}
return atomic.CompareAndSwapInt64(p.ptr64(), int64(old), int64(new))
}
func (p *Int) Add(v int) int {
if bits.UintSize == 32 {
return int(atomic.AddInt32(p.ptr32(), int32(v)))
}
return int(atomic.AddInt64(p.ptr64(), int64(v)))
}
func (p *Int) Sub(v int) int {
return p.Add(-v)
}
func (p *Int) String() string {
return strconv.FormatInt(int64(p.Load()), 10)
}
func (p *Int) SetLesser(v int) int {
for {
switch x := p.Load(); {
case x <= v:
return x
case p.CompareAndSwap(x, v):
return v
}
}
}
func (p *Int) SetGreater(v int) int {
for {
switch x := p.Load(); {
case x >= v:
return x
case p.CompareAndSwap(x, v):
return v
}
}
}