Merge branch 'crunch-job_finds_newer_docker_hashes' of https://github.com/tmooney...
[arvados.git] / sdk / go / arvados / duration.go
1 package arvados
2
3 import (
4         "encoding/json"
5         "fmt"
6         "time"
7 )
8
9 // Duration is time.Duration but looks like "12s" in JSON, rather than
10 // a number of nanoseconds.
11 type Duration time.Duration
12
13 // UnmarshalJSON implements json.Unmarshaler
14 func (d *Duration) UnmarshalJSON(data []byte) error {
15         if data[0] == '"' {
16                 return d.Set(string(data[1 : len(data)-1]))
17         }
18         return fmt.Errorf("duration must be given as a string like \"600s\" or \"1h30m\"")
19 }
20
21 // MarshalJSON implements json.Marshaler
22 func (d *Duration) MarshalJSON() ([]byte, error) {
23         return json.Marshal(d.String())
24 }
25
26 // String implements fmt.Stringer
27 func (d Duration) String() string {
28         return time.Duration(d).String()
29 }
30
31 // Duration returns a time.Duration
32 func (d Duration) Duration() time.Duration {
33         return time.Duration(d)
34 }
35
36 // Value implements flag.Value
37 func (d *Duration) Set(s string) error {
38         dur, err := time.ParseDuration(s)
39         *d = Duration(dur)
40         return err
41 }