Debian Codegraph @

duration.go

raw symbols SCIP
1 package duration
2
3 import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "math"
8 "strconv"
9 "strings"
10 "time"
11 "unicode"
12 )
13
14 // Duration holds all the smaller units that make up the duration
15 type Duration struct {
16 Years float64
17 Months float64
18 Weeks float64
19 Days float64
20 Hours float64
21 Minutes float64
22 Seconds float64
23 Negative bool
24 }
25
26 const (
27 parsingPeriod = iota
28 parsingTime
29
30 hoursPerDay = 24
31 hoursPerWeek = hoursPerDay * 7
32 hoursPerMonth = hoursPerYear / 12
33 hoursPerYear = hoursPerDay * 365
34
35 nsPerSecond = 1000000000
36 nsPerMinute = nsPerSecond * 60
37 nsPerHour = nsPerMinute * 60
38 nsPerDay = nsPerHour * hoursPerDay
39 nsPerWeek = nsPerHour * hoursPerWeek
40 nsPerMonth = nsPerHour * hoursPerMonth
41 nsPerYear = nsPerHour * hoursPerYear
42 )
43
44 var (
45 // ErrUnexpectedInput is returned when an input in the duration string does not match expectations
46 ErrUnexpectedInput = errors.New("unexpected input")
47 // ErrIncompleteExpr is returned when the expression is incomplete, (e.g. missing unit).
48 ErrIncompleteExpr = errors.New("incomplete expression")
49 )
50
51 // Parse attempts to parse the given duration string into a *Duration,
52 // if parsing fails an error is returned instead.
53 func Parse(d string) (*Duration, error) {
54 state := parsingPeriod
55 duration := &Duration{}
56 num := ""
57 var err error
58
59 switch {
60 case strings.HasPrefix(d, "P"): // standard duration
61 case strings.HasPrefix(d, "-P"): // negative duration
62 duration.Negative = true
63 d = strings.TrimPrefix(d, "-") // remove the negative sign
64 default:
65 return nil, ErrUnexpectedInput
66 }
67
68 for _, char := range d {
69 switch char {
70 case 'P':
71 if state != parsingPeriod {
72 return nil, ErrUnexpectedInput
73 }
74 case 'T':
75 state = parsingTime
76 case 'Y':
77 if state != parsingPeriod {
78 return nil, ErrUnexpectedInput
79 }
80
81 duration.Years, err = strconv.ParseFloat(num, 64)
82 if err != nil {
83 return nil, err
84 }
85 num = ""
86 case 'M':
87 if state == parsingPeriod {
88 duration.Months, err = strconv.ParseFloat(num, 64)
89 if err != nil {
90 return nil, err
91 }
92 num = ""
93 } else if state == parsingTime {
94 duration.Minutes, err = strconv.ParseFloat(num, 64)
95 if err != nil {
96 return nil, err
97 }
98 num = ""
99 }
100 case 'W':
101 if state != parsingPeriod {
102 return nil, ErrUnexpectedInput
103 }
104
105 duration.Weeks, err = strconv.ParseFloat(num, 64)
106 if err != nil {
107 return nil, err
108 }
109 num = ""
110 case 'D':
111 if state != parsingPeriod {
112 return nil, ErrUnexpectedInput
113 }
114
115 duration.Days, err = strconv.ParseFloat(num, 64)
116 if err != nil {
117 return nil, err
118 }
119 num = ""
120 case 'H':
121 if state != parsingTime {
122 return nil, ErrUnexpectedInput
123 }
124
125 duration.Hours, err = strconv.ParseFloat(num, 64)
126 if err != nil {
127 return nil, err
128 }
129 num = ""
130 case 'S':
131 if state != parsingTime {
132 return nil, ErrUnexpectedInput
133 }
134
135 duration.Seconds, err = strconv.ParseFloat(num, 64)
136 if err != nil {
137 return nil, err
138 }
139 num = ""
140 default:
141 if unicode.IsNumber(char) || char == '.' {
142 num += string(char)
143 continue
144 }
145
146 return nil, ErrUnexpectedInput
147 }
148 }
149 if num != "" {
150 return nil, ErrIncompleteExpr
151 }
152
153 return duration, nil
154 }
155
156 // FromTimeDuration converts the given time.Duration into duration.Duration.
157 // Note that for *Duration's with period values of a month or year that the duration becomes a bit fuzzy
158 // since obviously those things vary month to month and year to year.
159 func FromTimeDuration(d time.Duration) *Duration {
160 duration := &Duration{}
161 if d == 0 {
162 return duration
163 }
164
165 if d < 0 {
166 d = -d
167 duration.Negative = true
168 }
169
170 if d.Hours() >= hoursPerYear {
171 duration.Years = math.Floor(d.Hours() / hoursPerYear)
172 d -= time.Duration(duration.Years) * nsPerYear
173 }
174 if d.Hours() >= hoursPerMonth {
175 duration.Months = math.Floor(d.Hours() / hoursPerMonth)
176 d -= time.Duration(duration.Months) * nsPerMonth
177 }
178 if d.Hours() >= hoursPerWeek {
179 duration.Weeks = math.Floor(d.Hours() / hoursPerWeek)
180 d -= time.Duration(duration.Weeks) * nsPerWeek
181 }
182 if d.Hours() >= hoursPerDay {
183 duration.Days = math.Floor(d.Hours() / hoursPerDay)
184 d -= time.Duration(duration.Days) * nsPerDay
185 }
186 if d.Hours() >= 1 {
187 duration.Hours = math.Floor(d.Hours())
188 d -= time.Duration(duration.Hours) * nsPerHour
189 }
190 if d.Minutes() >= 1 {
191 duration.Minutes = math.Floor(d.Minutes())
192 d -= time.Duration(duration.Minutes) * nsPerMinute
193 }
194 duration.Seconds = d.Seconds()
195
196 return duration
197 }
198
199 // Format formats the given time.Duration into an ISO 8601 duration string (e.g., P1DT6H5M),
200 // negative durations are prefixed with a minus sign, for a zero duration "PT0S" is returned.
201 // Note that for *Duration's with period values of a month or year that the duration becomes a bit fuzzy
202 // since obviously those things vary month to month and year to year.
203 func Format(d time.Duration) string {
204 return FromTimeDuration(d).String()
205 }
206
207 // ToTimeDuration converts the *Duration to the standard library's time.Duration.
208 // Note that for *Duration's with period values of a month or year that the duration becomes a bit fuzzy
209 // since obviously those things vary month to month and year to year.
210 func (duration *Duration) ToTimeDuration() time.Duration {
211 var timeDuration time.Duration
212
213 // zero checks are here to avoid unnecessary math operations, on a duration such as `PT5M`
214 if duration.Years != 0 {
215 timeDuration += time.Duration(math.Round(duration.Years * nsPerYear))
216 }
217 if duration.Months != 0 {
218 timeDuration += time.Duration(math.Round(duration.Months * nsPerMonth))
219 }
220 if duration.Weeks != 0 {
221 timeDuration += time.Duration(math.Round(duration.Weeks * nsPerWeek))
222 }
223 if duration.Days != 0 {
224 timeDuration += time.Duration(math.Round(duration.Days * nsPerDay))
225 }
226 if duration.Hours != 0 {
227 timeDuration += time.Duration(math.Round(duration.Hours * nsPerHour))
228 }
229 if duration.Minutes != 0 {
230 timeDuration += time.Duration(math.Round(duration.Minutes * nsPerMinute))
231 }
232 if duration.Seconds != 0 {
233 timeDuration += time.Duration(math.Round(duration.Seconds * nsPerSecond))
234 }
235 if duration.Negative {
236 timeDuration = -timeDuration
237 }
238
239 return timeDuration
240 }
241
242 // String returns the ISO8601 duration string for the *Duration
243 func (duration *Duration) String() string {
244 d := "P"
245 hasTime := false
246
247 appendD := func(designator string, value float64, isTime bool) {
248 if !hasTime && isTime {
249 d += "T"
250 hasTime = true
251 }
252
253 d += strconv.FormatFloat(value, 'f', -1, 64) + designator
254 }
255
256 if duration.Years != 0 {
257 appendD("Y", duration.Years, false)
258 }
259
260 if duration.Months != 0 {
261 appendD("M", duration.Months, false)
262 }
263
264 if duration.Weeks != 0 {
265 appendD("W", duration.Weeks, false)
266 }
267
268 if duration.Days != 0 {
269 appendD("D", duration.Days, false)
270 }
271
272 if duration.Hours != 0 {
273 appendD("H", duration.Hours, true)
274 }
275
276 if duration.Minutes != 0 {
277 appendD("M", duration.Minutes, true)
278 }
279
280 if duration.Seconds != 0 {
281 appendD("S", duration.Seconds, true)
282 }
283
284 // if the duration is zero, return "PT0S"
285 if d == "P" {
286 d += "T0S"
287 }
288
289 if duration.Negative {
290 return "-" + d
291 }
292
293 return d
294 }
295
296 // MarshalJSON satisfies the Marshaler interface by return a valid JSON string representation of the duration
297 func (duration Duration) MarshalJSON() ([]byte, error) {
298 return json.Marshal(duration.String())
299 }
300
301 // UnmarshalJSON satisfies the Unmarshaler interface by return a valid JSON string representation of the duration
302 func (duration *Duration) UnmarshalJSON(source []byte) error {
303 durationString := ""
304 err := json.Unmarshal(source, &durationString)
305 if err != nil {
306 return err
307 }
308
309 parsed, err := Parse(durationString)
310 if err != nil {
311 return fmt.Errorf("failed to parse duration: %w", err)
312 }
313
314 *duration = *parsed
315 return nil
316 }
317
318 // MarshalText implements [encoding.TextMarshaler].
319 func (duration Duration) MarshalText() ([]byte, error) {
320 return []byte(duration.String()), nil
321 }
322
323 // UnmarshalText implements [encoding.TextUnmarshaler].
324 func (duration *Duration) UnmarshalText(text []byte) error {
325 parsed, err := Parse(string(text))
326 if err != nil {
327 return fmt.Errorf("failed to parse duration: %w", err)
328 }
329
330 *duration = *parsed
331 return nil
332 }