/
util.go
141 lines (115 loc) Β· 2.37 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package api
import (
"fmt"
"net/url"
"strconv"
"strings"
"time"
)
func toUTF8(iso8859 []byte) []byte {
buf := make([]rune, len(iso8859))
for i, b := range iso8859 {
buf[i] = rune(b)
}
return []byte(string(buf))
}
type floatToInt struct {
value int
}
func (f *floatToInt) UnmarshalJSON(data []byte) error {
value, err := strconv.Atoi(string(data))
if err != nil {
fv, err := strconv.ParseFloat(string(data), 64)
if err != nil {
return err
}
value = int(fv)
}
*f = floatToInt{int(value)}
return nil
}
func (f floatToInt) IntValue() int {
return f.value
}
type unixTime struct {
time.Time
}
func (u *unixTime) UnmarshalJSON(data []byte) error {
unix, err := strconv.ParseInt(string(data), 10, 64)
if err != nil {
return err
}
*u = unixTime{time.Unix(unix/1000, 0)}
return nil
}
type weekStartDate struct {
time.Time
}
func (w *weekStartDate) UnmarshalJSON(data []byte) error {
input := strings.Replace(decode(string(data)), `"`, "", -1)
t, err := time.Parse("2006-01-02", input)
if err != nil {
return err
}
*w = weekStartDate{t}
return nil
}
type encodedTime struct {
Time time.Time
}
func (e *encodedTime) UnmarshalJSON(data []byte) error {
input := strings.Replace(decode(string(data)), `"`, "", -1)
if strings.Count(input, ":") == 1 {
input = input + ":00"
}
t, err := time.Parse("2006-01-02 15:04:05", input)
if err != nil {
return err
}
*e = encodedTime{t}
return nil
}
type encodedString string
func (e encodedString) String() string {
return decode(string(e))
}
func (e encodedString) Laptime() int {
input := e.String()
if len(input) == 0 {
return -1
}
input = strings.Replace(input, ":", "m", -1)
input = strings.Replace(input, ".", "s", -1)
input = input + "ms"
d, err := time.ParseDuration(input)
if err != nil {
return -1
}
return int(d.Nanoseconds() / 1000 / 100)
}
func decode(value string) string {
decodedValue, err := url.QueryUnescape(value)
if err != nil {
return value
}
return decodedValue
}
type laptime int
func (l laptime) String() string {
if l == 0 {
return ""
}
return fmt.Sprintf("%s", time.Duration(l*100)*time.Microsecond)
}
func (l laptime) Seconds() int {
if l == 0 {
return 0
}
return int((time.Duration(l*100) * time.Microsecond).Seconds())
}
func (l laptime) Milliseconds() int64 {
if l == 0 {
return 0
}
return (time.Duration(l*100) * time.Microsecond).Milliseconds()
}