-
Notifications
You must be signed in to change notification settings - Fork 0
/
keys-and-values.go
82 lines (63 loc) · 1.96 KB
/
keys-and-values.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
package commonlog
import (
"fmt"
"github.com/tliron/kutil/util"
)
// Calls [Message.Set] on a provided sequence of key-value pairs.
// Thus keysAndValues must have an even length.
//
// Non-string keys are converted to strings using [util.ToString].
func SetMessageKeysAndValues(message Message, keysAndValues ...any) {
length := len(keysAndValues)
if length == 0 {
return
}
if length%2 != 0 {
panic(fmt.Sprintf("CommonLog message keysAndValues does not have an even number of arguments: %d", length))
}
for index := 0; index < length; index += 2 {
key := util.ToString(keysAndValues[index])
value := keysAndValues[index+1]
message.Set(key, value)
}
}
func GetKeyValue(key any, keysAndValues ...any) (any, bool) {
length := len(keysAndValues)
if length%2 != 0 {
panic(fmt.Sprintf("CommonLog keysAndValues does not have an even number of arguments: %d", length))
}
for index := 0; index < length; index += 2 {
if keysAndValues[index] == key {
return keysAndValues[index+1], true
}
}
return "", false
}
func SetKeyValue(key any, value any, keysAndValues ...any) ([]any, bool) {
length := len(keysAndValues)
if length%2 != 0 {
panic(fmt.Sprintf("CommonLog keysAndValues does not have an even number of arguments: %d", length))
}
for index := 0; index < length; index += 2 {
if keysAndValues[index] == key {
keysAndValues[index+1] = value
return keysAndValues, false
}
}
return append(keysAndValues, key, value), true
}
func MergeKeysAndValues(toKeysAndValues []any, fromKeysAndValues []any) ([]any, bool) {
length := len(fromKeysAndValues)
if length%2 != 0 {
panic(fmt.Sprintf("CommonLog keysAndValues does not have an even number of arguments: %d", length))
}
var changed bool
var changed_ bool
for index := 0; index < length; index += 2 {
toKeysAndValues, changed_ = SetKeyValue(fromKeysAndValues[index], fromKeysAndValues[index+1], toKeysAndValues...)
if changed_ {
changed = true
}
}
return toKeysAndValues, changed
}