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