/
uint64.go
145 lines (127 loc) · 2.19 KB
/
uint64.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package atomickit
import (
"strconv"
"sync/atomic"
)
func NewUint64(v uint64) Uint64 {
return Uint64{v}
}
type Uint64 struct {
v uint64
}
func (p *Uint64) Load() uint64 {
return atomic.LoadUint64(&p.v)
}
func (p *Uint64) Store(v uint64) {
atomic.StoreUint64(&p.v, v)
}
func (p *Uint64) Swap(v uint64) uint64 {
return atomic.SwapUint64(&p.v, v)
}
func (p *Uint64) CompareAndSwap(old, new uint64) bool {
return atomic.CompareAndSwapUint64(&p.v, old, new)
}
func (p *Uint64) Add(v uint64) uint64 {
return atomic.AddUint64(&p.v, v)
}
func (p *Uint64) Sub(v uint64) uint64 {
return p.Add(^(v - 1))
}
func (p *Uint64) String() string {
return strconv.FormatUint(p.Load(), 10)
}
func (p *Uint64) SetBits(v uint64) uint64 {
for {
switch x := p.Load(); {
case x & v == v:
return x
case p.CompareAndSwap(x, x|v):
return x|v
}
}
}
func (p *Uint64) TrySetBits(v uint64, all bool) bool {
for {
x := p.Load()
switch {
case x & v == 0:
case all:
return false
case x & v == v:
return false
}
if p.CompareAndSwap(x, x|v) {
return true
}
}
}
func (p *Uint64) UnsetBits(v uint64) uint64 {
for {
switch x := p.Load(); {
case x & v == 0:
return x
case p.CompareAndSwap(x, x&^v):
return x&^v
}
}
}
func (p *Uint64) TryUnsetBits(v uint64, all bool) bool {
for {
x := p.Load()
switch {
case x & v == 0:
return false
case x & v == v:
case all:
return false
}
if p.CompareAndSwap(x, x&^v) {
return true
}
}
}
func (p *Uint64) CompareAndSub(v uint64) bool {
for {
switch x := p.Load(); {
case x < v:
return false
case p.CompareAndSwap(x, x-v):
return true
}
}
}
func (p *Uint64) SetLesser(v uint64) uint64 {
for {
switch x := p.Load(); {
case x <= v:
return x
case p.CompareAndSwap(x, v):
return v
}
}
}
func (p *Uint64) SetGreater(v uint64) uint64 {
for {
switch x := p.Load(); {
case x >= v:
return x
case p.CompareAndSwap(x, v):
return v
}
}
}
func (p *Uint64) CompareAndSetBits(maskOut, deny, v uint64) bool {
for {
x := p.Load()
x2 := x &^ maskOut
switch {
case x2 & deny != 0:
return false
case x2 & v != 0:
return false
}
if p.CompareAndSwap(x, x|v) {
return true
}
}
}