-
Notifications
You must be signed in to change notification settings - Fork 0
/
accumulator.go
111 lines (97 loc) · 2.33 KB
/
accumulator.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
package aggregator
import (
"math"
"sync/atomic"
"unsafe"
)
type Float64Accumulator struct {
prevSum float64
curSum float64
}
func (a *Float64Accumulator) Type() string {
return "Float64Accumulator"
}
func (a *Float64Accumulator) Get() interface{} {
return loadFloat64(&a.curSum)
}
func loadFloat64(v *float64) float64 {
return math.Float64frombits(atomic.LoadUint64((*uint64)(unsafe.Pointer(v))))
}
func (a *Float64Accumulator) Set(v interface{}) {
for v64 := v.(float64); ; {
oldCur := loadFloat64(&a.curSum)
oldPrev := loadFloat64(&a.prevSum)
swappedCur := atomic.CompareAndSwapUint64(
(*uint64)(unsafe.Pointer(&a.curSum)),
math.Float64bits(oldCur),
math.Float64bits(v64),
)
swappedPrev := atomic.CompareAndSwapUint64(
(*uint64)(unsafe.Pointer(&a.prevSum)),
math.Float64bits(oldPrev),
math.Float64bits(v64),
)
if swappedCur && swappedPrev {
return
}
}
}
func (a *Float64Accumulator) Aggregate(v interface{}) {
for v64 := v.(float64); ; {
oldV := loadFloat64(&a.curSum)
newV := oldV + v64
if atomic.CompareAndSwapUint64(
(*uint64)(unsafe.Pointer(&a.curSum)),
math.Float64bits(oldV),
math.Float64bits(newV),
) {
return
}
}
}
func (a *Float64Accumulator) Delta() interface{} {
for {
curSUm := loadFloat64(&a.curSum)
prevSum := loadFloat64(&a.prevSum)
if atomic.CompareAndSwapUint64(
(*uint64)(unsafe.Pointer(&a.prevSum)),
math.Float64bits(prevSum),
math.Float64bits(curSUm),
) {
return curSUm - prevSum
}
}
}
type IntAccumulator struct {
prevSum int64
curSum int64
}
func (a *IntAccumulator) Type() string {
return "IntAccumulator"
}
func (a *IntAccumulator) Get() interface{} {
return int(atomic.LoadInt64(&a.curSum))
}
func (a *IntAccumulator) Set(v interface{}) {
for v64 := int64(v.(int)); ; {
oldCur := a.curSum
oldPrev := a.prevSum
swappedCur := atomic.CompareAndSwapInt64(&a.curSum, oldCur, v64)
swappedPrev := atomic.CompareAndSwapInt64(&a.prevSum, oldPrev, v64)
if swappedCur && swappedPrev {
return
}
}
}
func (a *IntAccumulator) Aggregate(v interface{}) {
_ = atomic.AddInt64(&a.curSum, int64(v.(int)))
}
func (a *IntAccumulator) Delta() interface{} {
for {
curSum := atomic.LoadInt64(&a.curSum)
prevSum := atomic.LoadInt64(&a.prevSum)
if atomic.CompareAndSwapInt64(&a.prevSum, prevSum, curSum) {
return int(curSum - prevSum)
}
}
}