-
Notifications
You must be signed in to change notification settings - Fork 10
/
duration.go
284 lines (241 loc) · 6.84 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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package types
import (
"bytes"
"encoding/json"
"fmt"
"math"
"strconv"
"time"
"unicode"
"github.com/cedar-policy/cedar-go/internal"
"github.com/cedar-policy/cedar-go/internal/consts"
)
var errDuration = internal.ErrDuration
var unitToMillis = map[string]int64{
"d": consts.MillisPerDay,
"h": consts.MillisPerHour,
"m": consts.MillisPerMinute,
"s": consts.MillisPerSecond,
"ms": 1,
}
var unitOrder = []string{"d", "h", "m", "s", "ms"}
// A Duration is a value representing a span of time in milliseconds.
type Duration struct {
value int64
}
// NewDuration returns a Cedar Duration from a Go time.Duration
func NewDuration(d time.Duration) Duration {
return Duration{value: d.Milliseconds()}
}
// NewDurationFromMillis returns a Duration from milliseconds
func NewDurationFromMillis(ms int64) Duration {
return Duration{value: ms}
}
// ParseDuration parses a Cedar Duration from a string
//
// Cedar RFC 80 defines a valid duration string as collapsed sequence
// of quantity-unit pairs, possibly with a leading `-`, indicating a
// negative duration.
// The units must appear in order from longest timeframe to smallest.
// - d: days
// - h: hours
// - m: minutes
// - s: seconds
// - ms: milliseconds
func ParseDuration(s string) (Duration, error) {
// Check for empty string.
if len(s) <= 1 {
return Duration{}, fmt.Errorf("%w: string too short", errDuration)
}
i := 0
unitI := 0
negative := int64(1)
if s[i] == '-' {
negative = int64(-1)
i++
}
var (
total int64
value int64
unit string
hasValue bool
)
// ([0-9]+)(d|h|m|s|ms) ...
for i < len(s) && unitI < len(unitOrder) {
if unicode.IsDigit(rune(s[i])) {
value = value*10 + int64(s[i]-'0')
// check overflow
if value > math.MaxInt32 {
return Duration{}, fmt.Errorf("%w: overflow", errDuration)
}
hasValue = true
i++
} else if s[i] == 'd' || s[i] == 'h' || s[i] == 'm' || s[i] == 's' {
if !hasValue {
return Duration{}, fmt.Errorf("%w: unit found without quantity", errDuration)
}
// is it ms?
if s[i] == 'm' && i+1 < len(s) && s[i+1] == 's' {
unit = "ms"
i++
} else {
unit = s[i : i+1]
}
unitOK := false
for !unitOK && unitI < len(unitOrder) {
if unit == unitOrder[unitI] {
unitOK = true
}
unitI++
}
if !unitOK {
return Duration{}, fmt.Errorf("%w: unexpected unit '%s'", errDuration, unit)
}
total = total + value*unitToMillis[unit]
i++
hasValue = false
value = 0
} else {
return Duration{}, fmt.Errorf("%w: unexpected character %s", errDuration, strconv.QuoteRune(rune(s[i])))
}
}
// We didn't have a trailing unit
if hasValue {
return Duration{}, fmt.Errorf("%w: expected unit", errDuration)
}
// We still have characters left, but no more units to assign.
if i < len(s) {
return Duration{}, fmt.Errorf("%w: invalid duration", errDuration)
}
return Duration{value: negative * total}, nil
}
// Equal returns true if the input represents the same duration
func (a Duration) Equal(bi Value) bool {
b, ok := bi.(Duration)
return ok && a == b
}
// LessThan returns true if value is less than the argument and they
// are both Duration values, or an error indicating they aren't
// comparable otherwise
func (a Duration) LessThan(bi Value) (bool, error) {
b, ok := bi.(Duration)
if !ok {
return false, internal.ErrNotComparable
}
return a.value < b.value, nil
}
// LessThan returns true if value is less than or equal to the
// argument and they are both Duration values, or an error indicating
// they aren't comparable otherwise
func (a Duration) LessThanOrEqual(bi Value) (bool, error) {
b, ok := bi.(Duration)
if !ok {
return false, internal.ErrNotComparable
}
return a.value <= b.value, nil
}
// MarshalCedar produces a valid MarshalCedar language representation of the Duration, e.g. `decimal("12.34")`.
func (v Duration) MarshalCedar() []byte { return []byte(`duration("` + v.String() + `")`) }
// String produces a string representation of the Duration
func (v Duration) String() string {
var res bytes.Buffer
if v.value == 0 {
return "0ms"
}
remaining := v.value
if v.value < 0 {
remaining = -v.value
res.WriteByte('-')
}
days := remaining / consts.MillisPerDay
if days > 0 {
res.WriteString(strconv.FormatInt(days, 10))
res.WriteByte('d')
}
remaining %= consts.MillisPerDay
hours := remaining / consts.MillisPerHour
if hours > 0 {
res.WriteString(strconv.FormatInt(hours, 10))
res.WriteByte('h')
}
remaining %= consts.MillisPerHour
minutes := remaining / consts.MillisPerMinute
if minutes > 0 {
res.WriteString(strconv.FormatInt(minutes, 10))
res.WriteByte('m')
}
remaining %= consts.MillisPerMinute
seconds := remaining / consts.MillisPerSecond
if seconds > 0 {
res.WriteString(strconv.FormatInt(seconds, 10))
res.WriteByte('s')
}
remaining %= consts.MillisPerSecond
if remaining > 0 {
res.WriteString(strconv.FormatInt(remaining, 10))
res.WriteString("ms")
}
return res.String()
}
// UnmarshalJSON implements encoding/json.Unmarshaler for Duration
//
// It is capable of unmarshaling 3 different representations supported by Cedar
// - { "__extn": { "fn": "duration", "arg": "1h10m" }}
// - { "fn": "duration", "arg": "1h10m" }
// - "1h10m"
func (v *Duration) UnmarshalJSON(b []byte) error {
vv, err := unmarshalExtensionValue(b, "duration", ParseDuration)
if err != nil {
return err
}
*v = vv
return nil
}
// MarshalJSON marshals the Duration into JSON using the explicit form.
func (v Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(extValueJSON{
Extn: &extn{
Fn: "duration",
Arg: v.String(),
},
})
}
// ToDays returns the number of days this Duration represents,
// truncating when fractional
func (v Duration) ToDays() int64 {
return v.value / consts.MillisPerDay
}
// ToHours returns the number of hours this Duration represents,
// truncating when fractional
func (v Duration) ToHours() int64 {
return v.value / consts.MillisPerHour
}
// ToMinutes returns the number of minutes this Duration represents,
// truncating when fractional
func (v Duration) ToMinutes() int64 {
return v.value / consts.MillisPerMinute
}
// ToSeconds returns the number of seconds this Duration represents,
// truncating when fractional
func (v Duration) ToSeconds() int64 {
return v.value / consts.MillisPerSecond
}
// ToMilliseconds returns the number of milliseconds this Duration
// represents
func (v Duration) ToMilliseconds() int64 {
return v.value
}
// Duration returns a time.Duration representation of a Duration. An error
// is returned if the duration cannot be converted to a time.Duration.
func (v Duration) Duration() (time.Duration, error) {
if v.value > math.MaxInt64/1000 {
return 0, internal.ErrDurationRange
}
if v.value < math.MinInt64/1000 {
return 0, internal.ErrDurationRange
}
return time.Millisecond * time.Duration(v.value), nil
}
func (v Duration) hash() uint64 {
return uint64(v.value)
}