-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
98 lines (88 loc) · 1.97 KB
/
util.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
package bencode
import (
"reflect"
"sort"
"strings"
"unicode"
)
func sortStrings(ss []string) {
if len(ss) <= strSliceLen {
// for i := 1; i < len(ss); i++ {
// for j := i; j > 0 && ss[j] < ss[j-1]; j-- {
// ss[j], ss[j-1] = ss[j-1], ss[j]
// }
// }
// below is the code above, but (almost) without bound checks
for i := 1; i < len(ss); i++ {
for j := i; j > 0; j-- {
if ss[j] >= ss[j-1] {
break
}
ss[j], ss[j-1] = ss[j-1], ss[j]
}
}
} else {
sort.Strings(ss)
}
}
func fieldTag(field reflect.StructField, v reflect.Value) (string, bool) {
tag := field.Tag.Get("bencode")
var opts string
switch {
case tag == "":
return field.Name, true
case tag == "-":
return "", false
default:
if idx := strings.Index(tag, ","); idx != -1 {
tag, opts = tag[:idx], tag[idx:]
}
}
switch {
case strings.Contains(opts, ",omitempty") && isZero(v):
return "", false
case !isValidTag(tag):
return field.Name, true
default:
return tag, true
}
}
func isValidTag(key string) bool {
if key == "" {
return false
}
for _, c := range key {
if c != ' ' && c != '$' && c != '-' && c != '_' && c != '.' &&
!unicode.IsLetter(c) && !unicode.IsDigit(c) {
return false
}
}
return true
}
func isNil(v reflect.Value) bool {
switch v.Kind() {
case reflect.Interface, reflect.Ptr:
return v.IsNil()
default:
return false
}
}
func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Ptr, reflect.Interface:
return v.IsNil()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Bool:
return !v.Bool()
// TODO(cristaloleg): supporting reflect.Struct might be hard.
default:
return false
}
}