Debian Codegraph @

api/v1/lib/time/time.go

raw symbols SCIP
1 package time
2
3 import (
4 "fmt"
5 "strconv"
6 "time"
7 "unicode"
8 )
9
10 type (
11 // UnitError is generated when an unknown unit is parsed from a duration string
12 UnitError struct {
13 Unit string
14 }
15
16 // FormatError is generated when an invalid duration string is parsed; the format
17 // of the duration string is completely unrecognized in this case.
18 FormatError struct {
19 Duration string
20 }
21 )
22
23 func (ue *UnitError) Error() string { return fmt.Sprintf("unknown duration unit %q", ue.Unit) }
24 func (fe *FormatError) Error() string { return fmt.Sprintf("invalid duration %q", fe.Duration) }
25
26 // ParseDuration parses the given string and returns a numeric Duration. The format of the string must
27 // be consistent with that expected by the Mesos stout library; the string should consist of two parts,
28 // a floating-point numeric followed by a unit (no spaces in between).
29 // The following units are recognized: "ns", "us", "ms", "secs", "mins", "hrs", "days", "weeks".
30 // Examples of valid input strings are "10ns" and "1.5days".
31 // see https://github.com/apache/mesos/blob/4d2b1b793e07a9c90b984ca330a3d7bc9e1404cc/3rdparty/libprocess/3rdparty/stout/include/stout/duration.hpp
32 func ParseDuration(value string) (time.Duration, error) {
33 for i, rv := range value {
34 if unicode.IsDigit(rv) || rv == '.' {
35 continue
36 }
37 num, err := strconv.ParseFloat(value[:i], 64)
38 if err != nil {
39 return 0, err
40 }
41 switch unit := value[i:]; unit {
42 case "ns":
43 // golang doesn't support fractional nanoseconds so we'll truncate
44 return time.Duration(num), nil
45 case "us":
46 return time.Duration(num * float64(time.Microsecond)), nil
47 case "ms":
48 return time.Duration(num * float64(time.Millisecond)), nil
49 case "secs":
50 return time.Duration(num * float64(time.Second)), nil
51 case "mins":
52 return time.Duration(num * float64(time.Minute)), nil
53 case "hrs":
54 return time.Duration(num * float64(time.Hour)), nil
55 case "days":
56 return time.Duration(num * float64(time.Hour*24)), nil
57 case "weeks":
58 return time.Duration(num * float64(time.Hour*24*7)), nil
59 default:
60 return 0, &UnitError{unit}
61 }
62 }
63 return 0, &FormatError{value}
64 }