-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathvalue.go
93 lines (89 loc) · 1.94 KB
/
value.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
package xmlstruct
import (
"encoding/xml"
"strconv"
"time"
)
// A value describes an observed simple value, either an attribute value or
// chardata.
type value struct {
boolCount int
float64Count int
intCount int
name xml.Name
observations int
optional bool
repeated bool
stringCount int
timeCount int
}
// goType returns the most specific Go type that can represent all of the values
// observed for v.
func (v *value) goType(options *generateOptions) string {
distinctTypes := 0
if v.boolCount > 0 {
distinctTypes++
}
if v.intCount > 0 {
distinctTypes++
}
if v.float64Count > 0 {
distinctTypes++
}
if v.timeCount > 0 {
distinctTypes++
}
if v.stringCount > 0 {
distinctTypes++
}
prefix := ""
if v.repeated {
prefix += "[]"
}
if options.usePointersForOptionalFields && v.optional {
prefix += "*"
}
switch {
case distinctTypes == 0:
if options.emptyElements {
return "struct{}"
}
return prefix + "string"
case distinctTypes == 1 && v.boolCount > 0:
return prefix + "bool"
case distinctTypes == 1 && v.intCount > 0:
return prefix + options.intType
case distinctTypes == 1 && v.float64Count > 0:
return prefix + "float64"
case distinctTypes == 1 && v.timeCount > 0:
options.importPackageNames["time"] = struct{}{}
return prefix + "time.Time"
case distinctTypes == 2 && v.intCount > 0 && v.float64Count > 0:
return prefix + "float64"
default:
return prefix + "string"
}
}
// observe records s as being observed for v.
func (v *value) observe(s string, options *observeOptions) {
v.observations++
if _, err := strconv.ParseInt(s, 10, 64); err == nil {
v.intCount++
return
}
if _, err := strconv.ParseBool(s); err == nil {
v.boolCount++
return
}
if _, err := strconv.ParseFloat(s, 64); err == nil {
v.float64Count++
return
}
if options.timeLayout != "" {
if _, err := time.Parse(options.timeLayout, s); err == nil {
v.timeCount++
return
}
}
v.stringCount++
}