-
Notifications
You must be signed in to change notification settings - Fork 16
/
runtime_map.go
69 lines (59 loc) · 1.58 KB
/
runtime_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
package goflags
import (
"errors"
"fmt"
"strings"
stringsutil "github.com/projectdiscovery/utils/strings"
)
const (
kvSep = "="
)
// RuntimeMap is a runtime only map of interfaces
type RuntimeMap struct {
kv map[string]interface{}
}
func (runtimeMap RuntimeMap) String() string {
defaultBuilder := &strings.Builder{}
defaultBuilder.WriteString("{")
var items string
for k, v := range runtimeMap.kv {
items += fmt.Sprintf("\"%s\"=\"%s\"%s", k, v, kvSep)
}
defaultBuilder.WriteString(stringsutil.TrimSuffixAny(items, ",", "="))
defaultBuilder.WriteString("}")
return defaultBuilder.String()
}
// Set inserts a value to the map. Format: key=value
func (runtimeMap *RuntimeMap) Set(value string) error {
if runtimeMap.kv == nil {
runtimeMap.kv = make(map[string]interface{})
}
var k, v string
if idxSep := strings.Index(value, kvSep); idxSep > 0 {
k = value[:idxSep]
v = value[idxSep+1:]
}
// note:
// - inserting multiple times the same key will override the previous value
// - empty string is legitimate value
if k != "" {
runtimeMap.kv[k] = v
}
return nil
}
// Del removes the specified key
func (runtimeMap *RuntimeMap) Del(key string) error {
if runtimeMap.kv == nil {
return errors.New("empty runtime map")
}
delete(runtimeMap.kv, key)
return nil
}
// IsEmpty specifies if the underlying map is empty
func (runtimeMap *RuntimeMap) IsEmpty() bool {
return runtimeMap.kv == nil || len(runtimeMap.kv) == 0
}
// AsMap returns the internal map as reference - changes are allowed
func (runtimeMap *RuntimeMap) AsMap() map[string]interface{} {
return runtimeMap.kv
}