-
Notifications
You must be signed in to change notification settings - Fork 61
/
config.go
76 lines (59 loc) · 1.35 KB
/
config.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
package rename
import (
"encoding/json"
"errors"
"fmt"
"strings"
insaneJSON "github.com/vitkovskii/insane-json"
)
type Config []string
const (
NotFoundIdx = -1
)
var _ json.Unmarshaler = (*Config)(nil)
func (c *Config) Find(key string) (string, int) {
keyValues := *c
for i := 0; i < len(keyValues); i += 2 {
if keyValues[i] == key {
return keyValues[i+1], i
}
}
return "", NotFoundIdx
}
func (c *Config) Remove(key string) {
_, idx := c.Find(key)
if idx == NotFoundIdx {
return
}
*c = append((*c)[:idx], (*c)[idx+2:]...)
}
func (c *Config) ForEach(cb func(key, value string)) {
keyValues := *c
for i := 0; i < len(keyValues); i += 2 {
cb((*c)[i], (*c)[i+1])
}
}
func (c *Config) Clone() Config {
return append(Config{}, *c...)
}
func (c *Config) Append(key, value string) {
*c = append(*c, key, value)
}
func (c *Config) UnmarshalJSON(bytes []byte) error {
root := insaneJSON.Spawn()
defer insaneJSON.Release(root)
if err := root.DecodeBytes(bytes); err != nil {
return fmt.Errorf("decoding rename config: %w", err)
}
if !root.IsObject() {
return errors.New("it is not an object")
}
fields := root.AsFields()
*c = make([]string, 0, len(fields)*2)
for _, field := range fields {
key := strings.Clone(field.AsString())
value := strings.Clone(field.AsFieldValue().AsString())
c.Append(key, value)
}
return nil
}