-
-
Notifications
You must be signed in to change notification settings - Fork 296
/
duration.go
134 lines (103 loc) · 2.4 KB
/
duration.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
package types
import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"time"
"github.com/pkg/errors"
)
var simpleDurationRegExp = regexp.MustCompile(`^(\d+)([hdw])$`)
var ErrNotSimpleDuration = errors.New("the given input is not simple duration format, valid format: [1-9][0-9]*[hdw]")
type SimpleDuration struct {
Num int
Unit string
Duration Duration
}
func (d *SimpleDuration) String() string {
return fmt.Sprintf("%d%s", d.Num, d.Unit)
}
func (d *SimpleDuration) Interval() Interval {
switch d.Unit {
case "d":
return Interval1d
case "h":
return Interval1h
case "w":
return Interval1w
}
return ""
}
func (d *SimpleDuration) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
sd, err := ParseSimpleDuration(s)
if err != nil {
return err
}
if sd != nil {
*d = *sd
}
return nil
}
func ParseSimpleDuration(s string) (*SimpleDuration, error) {
if s == "" {
return nil, nil
}
if !simpleDurationRegExp.MatchString(s) {
return nil, errors.Wrapf(ErrNotSimpleDuration, "input %q is not a simple duration", s)
}
matches := simpleDurationRegExp.FindStringSubmatch(s)
numStr := matches[1]
unit := matches[2]
num, err := strconv.Atoi(numStr)
if err != nil {
return nil, err
}
switch unit {
case "d":
d := Duration(time.Duration(num) * 24 * time.Hour)
return &SimpleDuration{num, unit, d}, nil
case "w":
d := Duration(time.Duration(num) * 7 * 24 * time.Hour)
return &SimpleDuration{num, unit, d}, nil
case "h":
d := Duration(time.Duration(num) * time.Hour)
return &SimpleDuration{num, unit, d}, nil
}
return nil, errors.Wrapf(ErrNotSimpleDuration, "input %q is not a simple duration", s)
}
type Duration time.Duration
func (d *Duration) Duration() time.Duration {
return time.Duration(*d)
}
func (d *Duration) UnmarshalJSON(data []byte) error {
var o interface{}
if err := json.Unmarshal(data, &o); err != nil {
return err
}
switch t := o.(type) {
case string:
sd, err := ParseSimpleDuration(t)
if err == nil {
*d = sd.Duration
return nil
}
dd, err := time.ParseDuration(t)
if err != nil {
return err
}
*d = Duration(dd)
case float64:
*d = Duration(int64(t * float64(time.Second)))
case int64:
*d = Duration(t * int64(time.Second))
case int:
*d = Duration(t * int(time.Second))
default:
return fmt.Errorf("unsupported type %T value: %v", t, t)
}
return nil
}