-
Notifications
You must be signed in to change notification settings - Fork 0
/
attrs.go
72 lines (61 loc) · 1.27 KB
/
attrs.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
package sqlcommenter
import (
"bytes"
)
// AttrPairs builds Attrs from multiple key value pairs.
func AttrPairs(pairs ...string) Attrs {
if len(pairs)%2 == 1 {
panic("got odd number of pairs")
}
attrs := make(Attrs, len(pairs)/2)
for i := 0; i < len(pairs); i += 2 {
attrs[pairs[i]] = pairs[i+1]
}
return attrs
}
// Attr represents attribute with key and value.
type Attr struct {
Key string
Value string
}
// Attrs wrap map of attributes.
type Attrs map[string]string
// Update updates map from other Attrs.
func (a Attrs) Update(other Attrs) {
for k, v := range other {
a[k] = v
}
}
func (a Attrs) encode(b *bytes.Buffer) {
total := len(a)
keys := make([]string, 0, total)
for k := range a {
keys = append(keys, k)
}
sortKeys(keys)
for i, key := range keys {
writeQueryEscape(key, b)
b.WriteByte('=')
b.WriteByte('\'')
writePathEscape(a[key], b)
b.WriteByte('\'')
if i < total-1 {
b.WriteByte(',')
}
}
}
// sortKeys implements a simple insertion sort on string slice.
// We save one alloc by not using sort.Strings.
func sortKeys(keys []string) {
for i := 1; i < len(keys); i++ {
if keys[i] < keys[i-1] {
j := i - 1
temp := keys[i]
for j >= 0 && keys[j] > temp {
keys[j+1] = keys[j]
j--
}
keys[j+1] = temp
}
}
}