-
Notifications
You must be signed in to change notification settings - Fork 13
/
types.go
89 lines (76 loc) · 1.7 KB
/
types.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
package config
import (
"bytes"
"fmt"
"strconv"
"time"
"github.com/alecthomas/units"
)
// Duration is a time.Duration
type Duration time.Duration
// Size is an int64
type Size int64
// UnmarshalTOML parses the duration from the TOML config file
func (d *Duration) UnmarshalTOML(b []byte) error {
var err error
b = bytes.Trim(b, `'`)
// see if we can directly convert it
dur, err := time.ParseDuration(string(b))
if err == nil {
*d = Duration(dur)
return nil
}
// Parse string duration, ie, "1s"
if uq, err := strconv.Unquote(string(b)); err == nil && len(uq) > 0 {
dur, err := time.ParseDuration(uq)
if err == nil {
*d = Duration(dur)
return nil
}
}
// First try parsing as integer seconds
sI, err := strconv.ParseInt(string(b), 10, 64)
if err == nil {
dur := time.Second * time.Duration(sI)
*d = Duration(dur)
return nil
}
// Second try parsing as float seconds
sF, err := strconv.ParseFloat(string(b), 64)
if err == nil {
dur := time.Second * time.Duration(sF)
*d = Duration(dur)
return nil
}
return nil
}
func (d *Duration) UnmarshalText(text []byte) error {
return d.UnmarshalTOML(text)
}
func (s *Size) UnmarshalTOML(b []byte) error {
var err error
if len(b) == 0 {
return nil
}
str := string(b)
if b[0] == '"' || b[0] == '\'' {
str, err = strconv.Unquote(str)
if err != nil {
return fmt.Errorf("unquote (%s): %w", str, err)
}
}
val, err := strconv.ParseInt(str, 10, 64)
if err == nil {
*s = Size(val)
return nil
}
val, err = units.ParseStrictBytes(str)
if err != nil {
return fmt.Errorf("parsestrictbytes (%s): %w", str, err)
}
*s = Size(val)
return nil
}
func (s *Size) UnmarshalText(text []byte) error {
return s.UnmarshalTOML(text)
}