/
keyvalues.go
154 lines (111 loc) · 2.45 KB
/
keyvalues.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
package common
import (
"fmt"
"sort"
"strings"
)
type KeyValue string
func (kv KeyValue) Key() string {
p := strings.Index(string(kv), "=")
if p != -1 {
return string(kv)[:p]
}
return string(kv)
}
func (kv KeyValue) Value() string {
p := strings.Index(string(kv), "=")
if p != -1 {
return string(kv)[p+1:]
}
return ""
}
type KeyValues []KeyValue
func NewKeyValues(list []string) *KeyValues {
kvs := &KeyValues{}
for _, item := range list {
kvs.Add(KeyValue(item).Key(), KeyValue(item).Value())
}
return kvs
}
func (kvs *KeyValues) Index(key string) int {
for i, item := range *kvs {
if item.Key() == key {
return i
}
}
return -1
}
func (kvs *KeyValues) getValue(line string) string {
return line[strings.Index(line, "=")+1:]
}
func (kvs *KeyValues) getKey(line string) string {
return line[:strings.Index(line, "=")]
}
func (kvs *KeyValues) Add(key string, value string) error {
if key == "" {
return fmt.Errorf("key cannot be null")
}
*kvs = append(*kvs, KeyValue(key+"="+value))
return nil
}
func (kvs *KeyValues) Put(key string, value string) error {
if key == "" {
return fmt.Errorf("key cannot be null")
}
item := KeyValue(key + "=" + value)
index := kvs.Index(key)
if index == -1 {
*kvs = append(*kvs, item)
} else {
(*kvs)[index] = item
}
return nil
}
func (kvs *KeyValues) Sort() {
sort.SliceStable(*kvs, func(i, j int) bool {
return strings.ToUpper((*kvs)[i].Key()) < strings.ToUpper((*kvs)[i].Key())
})
}
func (kvs *KeyValues) Contains(key string) bool {
_, err := kvs.Get(key)
return err == nil
}
func (kvs *KeyValues) Get(key string) (string, error) {
if key == "" {
return "", fmt.Errorf("key cannot be null")
}
index := kvs.Index(key)
if index == -1 {
return "", fmt.Errorf("key not found")
}
return (*kvs)[index].Value(), nil
}
func (kvs *KeyValues) Remove(key string) (string, error) {
if key == "" {
return "", fmt.Errorf("key cannot be null")
}
index := kvs.Index(key)
if index == -1 {
return "", fmt.Errorf("key not found")
}
item := (*kvs)[index].Value()
*kvs = append((*kvs)[:index], (*kvs)[index+1:]...)
return item, nil
}
func (kvs *KeyValues) Keys() []string {
keys := make([]string, 0)
for _, kv := range *kvs {
keys = append(keys, kv.Key())
}
return keys
}
func (kvs *KeyValues) Values() []string {
keys := make([]string, 0)
for _, kv := range *kvs {
keys = append(keys, kv.Value())
}
return keys
}
func (kvs *KeyValues) Clear() {
*kvs = nil
}