-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
types.go
229 lines (201 loc) · 5.82 KB
/
types.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/*
*
* k6 - a next-generation load testing tool
* Copyright (C) 2016 Load Impact
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package types
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"gopkg.in/guregu/null.v3"
)
// NullDecoder converts data with expected type f to a guregu/null value
// of equivalent type t. It returns an error if a type mismatch occurs.
func NullDecoder(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
typeFrom := f.String()
typeTo := t.String()
expectedType := ""
switch typeTo {
case "null.String":
if typeFrom == reflect.String.String() {
return null.StringFrom(data.(string)), nil
}
expectedType = reflect.String.String()
case "null.Bool":
if typeFrom == reflect.Bool.String() {
return null.BoolFrom(data.(bool)), nil
}
expectedType = reflect.Bool.String()
case "null.Int":
if typeFrom == reflect.Int.String() {
return null.IntFrom(int64(data.(int))), nil
}
if typeFrom == reflect.Int32.String() {
return null.IntFrom(int64(data.(int32))), nil
}
if typeFrom == reflect.Int64.String() {
return null.IntFrom(data.(int64)), nil
}
expectedType = reflect.Int.String()
case "null.Float":
if typeFrom == reflect.Float32.String() {
return null.FloatFrom(float64(data.(float32))), nil
}
if typeFrom == reflect.Float64.String() {
return null.FloatFrom(data.(float64)), nil
}
expectedType = reflect.Float32.String() + " or " + reflect.Float64.String()
case "types.NullDuration":
if typeFrom == reflect.String.String() {
var d NullDuration
err := d.UnmarshalText([]byte(data.(string)))
return d, err
}
expectedType = reflect.String.String()
}
if expectedType != "" {
return data, fmt.Errorf("expected '%s', got '%s'", expectedType, typeFrom)
}
return data, nil
}
//TODO: something better that won't require so much boilerplate and casts for NullDuration values...
// Duration is an alias for time.Duration that de/serialises to JSON as human-readable strings.
type Duration time.Duration
func (d Duration) String() string {
return time.Duration(d).String()
}
// ParseExtendedDuration is a helper function that allows for string duration
// values containing days. If no units are provided, milliseconds are assumed.
func ParseExtendedDuration(data string) (result time.Duration, err error) {
if t, errp := strconv.ParseFloat(data, 32); errp == nil {
data = fmt.Sprintf("%.2fms", t)
}
dPos := strings.IndexByte(data, 'd')
if dPos < 0 {
return time.ParseDuration(data)
}
var hours time.Duration
if dPos+1 < len(data) { // case "12d"
hours, err = time.ParseDuration(data[dPos+1:])
if err != nil {
return
}
if hours < 0 {
return 0, fmt.Errorf("invalid time format '%s'", data[dPos+1:])
}
}
days, err := strconv.ParseInt(data[:dPos], 10, 64)
if err != nil {
return
}
if days < 0 {
hours = -hours
}
return time.Duration(days)*24*time.Hour + hours, nil
}
// UnmarshalText converts text data to Duration
func (d *Duration) UnmarshalText(data []byte) error {
v, err := ParseExtendedDuration(string(data))
if err != nil {
return err
}
*d = Duration(v)
return nil
}
// UnmarshalJSON converts JSON data to Duration
func (d *Duration) UnmarshalJSON(data []byte) error {
if len(data) > 0 && data[0] == '"' {
var str string
if err := json.Unmarshal(data, &str); err != nil {
return err
}
v, err := ParseExtendedDuration(str)
if err != nil {
return err
}
*d = Duration(v)
} else {
var v time.Duration
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*d = Duration(v)
}
return nil
}
// MarshalJSON returns the JSON representation of d
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(d.String())
}
// NullDuration is a nullable Duration, in the same vein as the nullable types provided by
// package gopkg.in/guregu/null.v3.
type NullDuration struct {
Duration
Valid bool
}
// NewNullDuration is a simple helper constructor function
func NewNullDuration(d time.Duration, valid bool) NullDuration {
return NullDuration{Duration(d), valid}
}
// NullDurationFrom returns a new valid NullDuration from a time.Duration.
func NullDurationFrom(d time.Duration) NullDuration {
return NullDuration{Duration(d), true}
}
// UnmarshalText converts text data to a valid NullDuration
func (d *NullDuration) UnmarshalText(data []byte) error {
if len(data) == 0 {
*d = NullDuration{}
return nil
}
if err := d.Duration.UnmarshalText(data); err != nil {
return err
}
d.Valid = true
return nil
}
// UnmarshalJSON converts JSON data to a valid NullDuration
func (d *NullDuration) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, []byte(`null`)) {
d.Valid = false
return nil
}
if err := json.Unmarshal(data, &d.Duration); err != nil {
return err
}
d.Valid = true
return nil
}
// MarshalJSON returns the JSON representation of d
func (d NullDuration) MarshalJSON() ([]byte, error) {
if !d.Valid {
return []byte(`null`), nil
}
return d.Duration.MarshalJSON()
}
// ValueOrZero returns the underlying Duration value of d if valid or
// its zero equivalent otherwise. It matches the existing guregu/null API.
func (d NullDuration) ValueOrZero() Duration {
if !d.Valid {
return Duration(0)
}
return d.Duration
}