This repository has been archived by the owner on Apr 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashmap.go
105 lines (83 loc) · 1.91 KB
/
hashmap.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
// go-hashmap provides a mechanism to log maps as a string of key/value pairs
package hashmap
import (
"fmt"
"reflect"
"sort"
"strings"
"sync"
)
// Key-value pairs for semantic logging
type HashMap struct {
sync.RWMutex
kv map[string]interface{}
}
func (hm *HashMap) Get(key string) interface{} {
hm.RLock()
defer hm.RUnlock()
return hm.kv[key]
}
func (hm *HashMap) Set(key string, value interface{}) {
hm.Lock()
defer hm.Unlock()
hm.kv[key] = value
}
func (hm *HashMap) SetFromMap(m map[string]interface{}) {
hm.Lock()
defer hm.Unlock()
for key, value := range m {
hm.kv[key] = value
}
}
func (hm *HashMap) Contains(key string) bool {
hm.Lock()
defer hm.Unlock()
_, exists := hm.kv[key]
return exists
}
func NewHashMap() *HashMap {
m := make(map[string]interface{})
return &HashMap{kv: m}
}
// Sanitize the key for logging purposes
func encodeKey(k string) (key string) {
// Keys may not have any spaces
key = strings.Replace(k, " ", "_", -1)
return key
}
// Encode the value of the map for certain supported types.
func encodeValue(i interface{}) (buf []byte, err error) {
v := reflect.ValueOf(i)
switch v.Kind() {
case reflect.String:
buf = append(buf, fmt.Sprintf("%q", i)...)
case reflect.Array, reflect.Chan, reflect.Func, reflect.Interface,
reflect.Map, reflect.Ptr, reflect.Struct:
err = fmt.Errorf("Unable to encode %s value: type=%s value=%v",
v.Kind(), reflect.TypeOf(i), i)
default:
buf = append(buf, fmt.Sprintf("%v", i)...)
}
return buf, err
}
func (hm *HashMap) String() string {
var buf []byte
var keys []string
hm.RLock()
defer hm.RUnlock()
for k := range hm.kv {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
value, err := encodeValue(hm.kv[k])
if err != nil {
continue
}
key := encodeKey(k)
buf = append(buf, fmt.Sprintf(" %s=%s", key, value)...)
}
// Remove leading space
buf = buf[1:len(buf)]
return string(buf)
}