-
Notifications
You must be signed in to change notification settings - Fork 41
/
taper.go
35 lines (30 loc) · 937 Bytes
/
taper.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
package loghelper
// LogarithmicTaper provides logarithmic tapering of an event sequence.
// For example, if the taper is Triggered 50 times with a function that
// simply prints the provided count, the output would be 1,2,4,8,16,32.
type LogarithmicTaper struct {
count uint64
}
// Trigger increments a count and calls f iff the new count is a power of two
func (tap *LogarithmicTaper) Trigger(f func(newCount uint64)) {
tap.count++
if f != nil && isPowerOfTwo(tap.count) {
f(tap.count)
}
}
// Count returns the internal count of the taper
func (tap *LogarithmicTaper) Count() uint64 {
return tap.count
}
// Reset resets the count to 0 and then calls f with the previous count
// iff it wasn't already 0
func (tap *LogarithmicTaper) Reset(f func(oldCount uint64)) {
if tap.count != 0 {
oldCount := tap.count
tap.count = 0
f(oldCount)
}
}
func isPowerOfTwo(num uint64) bool {
return num != 0 && (num&(num-1)) == 0
}