-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathduration.go
More file actions
115 lines (89 loc) · 2.14 KB
/
duration.go
File metadata and controls
115 lines (89 loc) · 2.14 KB
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
package microtime
import (
"strconv"
"time"
"github.com/proemergotech/errors/v2"
)
const (
Nanosecond = Duration(time.Nanosecond)
Microsecond = Duration(time.Microsecond)
Millisecond = Duration(time.Millisecond)
Second = Duration(time.Second)
Minute = Duration(time.Minute)
Hour = Duration(time.Hour)
)
type Duration time.Duration
func (d Duration) Round(m Duration) Duration {
return Duration(time.Duration(d).Round(time.Duration(m)))
}
func (d Duration) RedisArg() interface{} {
return strconv.FormatInt(int64(d), 10)
}
func (d *Duration) RedisScan(src interface{}) error {
if src == nil {
return nil
}
var str string
switch val := src.(type) {
case []byte:
str = string(val)
case string:
str = val
default:
return errors.Errorf("schema.RedisScan: invalid duration: %v", src)
}
dur, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return errors.Errorf("schema.RedisScan: invalid time: %v", str)
}
*d = Duration(dur)
return nil
}
func (d Duration) MarshalJSON() ([]byte, error) {
if d == Duration(0) {
return []byte("null"), nil
}
return []byte(strconv.Quote(d.String())), nil
}
func (d *Duration) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return nil
}
unquoted, err := strconv.Unquote(string(data))
if err != nil {
return errors.Wrap(err, "duration must be valid json string")
}
duration, err := time.ParseDuration(unquoted)
if err != nil {
return errors.WithStack(err)
}
*d = Duration(duration)
return nil
}
func (d *Duration) UnmarshalParam(data string) error {
quotedData := data
if _, err := strconv.Unquote(data); err != nil {
quotedData = strconv.Quote(data)
}
return d.UnmarshalJSON([]byte(quotedData))
}
func (d Duration) MarshalBinary() (data []byte, err error) {
if d == Duration(0) {
return nil, nil
}
return []byte(d.String()), nil
}
func (d *Duration) UnmarshalBinary(data []byte) error {
if len(data) == 0 {
return nil
}
duration, err := time.ParseDuration(string(data))
if err != nil {
return errors.WithStack(err)
}
*d = Duration(duration)
return nil
}
func (d Duration) String() string {
return time.Duration(d).String()
}