forked from RAttab/gometer
/
meter_state.go
52 lines (39 loc) · 1.1 KB
/
meter_state.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
// Copyright (c) 2014 Datacratic. All rights reserved.
package meter
import (
"sync"
"time"
)
// State reports the value 1.0 for a given state until a new state is
// recorded. This can be useful to record infrequent changes in program state.
type State struct {
value string
mutex sync.Mutex
}
// Change changes the recorded state. An empty string will not output any
// values.
func (state *State) Change(value string) {
state.mutex.Lock()
state.value = value
state.mutex.Unlock()
}
// Reset disables any values outputed by this state.
func (state *State) Reset() {
state.Change("")
}
// ReadMeter returns the currently set state with a value of 1.0 or nothing if
// the state is an empty string.
func (state *State) ReadMeter(delta time.Duration) map[string]float64 {
result := make(map[string]float64)
state.mutex.Lock()
if state.value != "" {
result[state.value] = 1.0
}
state.mutex.Unlock()
return result
}
// GetState returns the state registered with the given key or creates a new one
// and registers it.
func GetState(prefix string) *State {
return GetOrAdd(prefix, new(State)).(*State)
}