-
Notifications
You must be signed in to change notification settings - Fork 334
/
sort.go
40 lines (35 loc) · 795 Bytes
/
sort.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
package header
import (
"net/textproto"
"sort"
)
type KeyValues struct {
Key string
Values []string
}
type sorter struct {
order map[string]int
kvs []KeyValues
}
func (s *sorter) Len() int { return len(s.kvs) }
func (s *sorter) Swap(i, j int) { s.kvs[i], s.kvs[j] = s.kvs[j], s.kvs[i] }
func (s *sorter) Less(i, j int) bool {
if index, ok := s.order[textproto.CanonicalMIMEHeaderKey(s.kvs[i].Key)]; ok {
i = index
}
if index, ok := s.order[textproto.CanonicalMIMEHeaderKey(s.kvs[j].Key)]; ok {
j = index
}
return i < j
}
func SortKeyValues(kvs []KeyValues, orderedKeys []string) {
order := make(map[string]int)
for i, key := range orderedKeys {
order[textproto.CanonicalMIMEHeaderKey(key)] = i
}
s := &sorter{
order: order,
kvs: kvs,
}
sort.Sort(s)
}