This repository has been archived by the owner on Nov 5, 2021. It is now read-only.
/
map.go
202 lines (180 loc) · 5 KB
/
map.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metrics
import (
"errors"
"fmt"
"sort"
"strconv"
"strings"
"sync"
)
// Map implements a key-value store where keys are of type string and values are
// of type NumValue.
// It satisfies the Value interface.
type Map struct {
MapName string // Map key name
mu sync.RWMutex
m map[string]NumValue
keys []string
// We use this to initialize new keys
defaultKeyValue NumValue
}
// NewMap returns a new Map
func NewMap(mapName string, defaultValue NumValue) *Map {
return &Map{
MapName: mapName,
defaultKeyValue: defaultValue,
m: make(map[string]NumValue),
}
}
// GetKey returns the given key's value.
// TODO(manugarg): We should probably add a way to get the list of all the keys in the
// map.
func (m *Map) GetKey(key string) NumValue {
m.mu.RLock()
defer m.mu.RUnlock()
return m.m[key]
}
// Clone creates a clone of the Map. Clone makes sure that underlying data
// storage is properly cloned.
func (m *Map) Clone() Value {
m.mu.RLock()
defer m.mu.RUnlock()
newMap := &Map{
MapName: m.MapName,
defaultKeyValue: m.defaultKeyValue.Clone().(NumValue),
m: make(map[string]NumValue),
}
newMap.keys = make([]string, len(m.keys))
for i, k := range m.keys {
newMap.m[k] = m.m[k].Clone().(NumValue)
newMap.keys[i] = m.keys[i]
}
return newMap
}
// Keys returns the list of keys
func (m *Map) Keys() []string {
m.mu.RLock()
defer m.mu.RUnlock()
return append([]string{}, m.keys...)
}
// newKey adds a new key to the map, with its value set to defaultKeyValue
// This is an unsafe function, callers should take care of protecting the map
// from race conditions.
func (m *Map) newKey(key string) {
m.keys = append(m.keys, key)
sort.Strings(m.keys)
m.m[key] = m.defaultKeyValue.Clone().(NumValue)
}
// IncKey increments the given key's value by one.
func (m *Map) IncKey(key string) {
m.mu.Lock()
defer m.mu.Unlock()
if m.m[key] == nil {
m.newKey(key)
}
m.m[key].Inc()
}
// IncKeyBy increments the given key's value by NumValue.
func (m *Map) IncKeyBy(key string, delta NumValue) {
m.mu.Lock()
defer m.mu.Unlock()
if m.m[key] == nil {
m.newKey(key)
}
m.m[key].IncBy(delta)
}
// Add adds a value (type Value) to the receiver Map. A non-Map value returns an error.
// This is part of the Value interface.
func (m *Map) Add(val Value) error {
delta, ok := val.(*Map)
if !ok {
return errors.New("incompatible value to add")
}
m.mu.Lock()
defer m.mu.Unlock()
delta.mu.RLock()
defer delta.mu.RUnlock()
var sortRequired bool
for k, v := range delta.m {
if m.m[k] == nil {
sortRequired = true
m.keys = append(m.keys, k)
m.m[k] = v
continue
}
m.m[k].Add(v)
}
if sortRequired {
sort.Strings(m.keys)
}
return nil
}
// AddInt64 generates a panic for the Map type. This is added only to satisfy
// the Value interface.
func (m *Map) AddInt64(i int64) {
panic("Map type doesn't implement AddInt64()")
}
// AddFloat64 generates a panic for the Map type. This is added only to
// satisfy the Value interface.
func (m *Map) AddFloat64(f float64) {
panic("Map type doesn't implement AddFloat64()")
}
// String returns the string representation of the receiver Map.
// This is part of the Value interface.
// map:key,k1:v1,k2:v2
func (m *Map) String() string {
m.mu.RLock()
defer m.mu.RUnlock()
var b strings.Builder
b.WriteString("map:")
b.WriteString(m.MapName)
for _, k := range m.keys {
b.WriteByte(',')
b.WriteString(k)
b.WriteByte(':')
b.WriteString(m.m[k].String())
}
return b.String()
}
// ParseMapFromString parses a map value string into a map object.
// Note that the values are always parsed as floats, so even a map with integer
// values will become a float map.
// For example:
// "map:code,200:10123,404:21" will be parsed as:
// "map:code 200:10123.000 404:21.000".
func ParseMapFromString(mapValue string) (*Map, error) {
tokens := strings.Split(mapValue, ",")
if len(tokens) < 1 {
return nil, errors.New("bad map value")
}
kv := strings.Split(tokens[0], ":")
if kv[0] != "map" {
return nil, errors.New("map value doesn't start with map:<key>")
}
m := NewMap(kv[1], NewFloat(0))
for _, tok := range tokens[1:] {
kv := strings.Split(tok, ":")
if len(kv) != 2 {
return nil, errors.New("bad map value token: " + tok)
}
f, err := strconv.ParseFloat(kv[1], 64)
if err != nil {
return nil, fmt.Errorf("could not convert map key value %s to a float: %v", kv[1], err)
}
m.IncKeyBy(kv[0], NewFloat(f))
}
return m, nil
}