Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright (c) 2014 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 package clock | |
|
iannucci
2015/06/02 06:15:33
maybe this could go in
clock/clockflag
?
Then
dnj
2015/06/02 17:03:12
Done.
| |
| 6 | |
| 7 import ( | |
| 8 "errors" | |
| 9 "fmt" | |
| 10 "time" | |
| 11 ) | |
| 12 | |
| 13 // DurationFlag is a Flag- and JSON-compatible Duration value. | |
| 14 type DurationFlag time.Duration | |
| 15 | |
| 16 // Set implements flag.Value. | |
| 17 func (d *DurationFlag) Set(value string) error { | |
| 18 duration, err := time.ParseDuration(value) | |
| 19 if err != nil { | |
| 20 return err | |
| 21 } | |
| 22 *d = DurationFlag(duration) | |
| 23 return nil | |
| 24 } | |
| 25 | |
| 26 // String implements flag.Value. | |
| 27 func (d *DurationFlag) String() string { | |
| 28 return time.Duration(*d).String() | |
| 29 } | |
| 30 | |
| 31 // Duration returns the Duration value of the flag. | |
| 32 func (d DurationFlag) Duration() time.Duration { | |
| 33 return time.Duration(d) | |
| 34 } | |
| 35 | |
| 36 // IsZero tests if this DurationFlag is the zero value. | |
| 37 func (d DurationFlag) IsZero() bool { | |
| 38 return time.Duration(d) == time.Duration(0) | |
| 39 } | |
| 40 | |
| 41 // UnmarshalJSON implements json.Unmarshaler. | |
| 42 // | |
| 43 // Unmarshals a JSON entry into the underlying type. The entry is expected to co ntain | |
| 44 // a string corresponding to one of the enum's keys. | |
| 45 func (d *DurationFlag) UnmarshalJSON(data []byte) error { | |
| 46 // Strip off leading and trailing quotes. | |
| 47 s := string(data) | |
| 48 if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' { | |
| 49 return errors.New("Duration JSON must be a valid JSON string.") | |
| 50 } | |
| 51 return d.Set(s[1 : len(s)-1]) | |
| 52 } | |
| 53 | |
| 54 // MarshalJSON implements json.Marshaler. | |
| 55 // | |
| 56 // Marshals a DurationFlag into a duration string. | |
| 57 func (d DurationFlag) MarshalJSON() ([]byte, error) { | |
| 58 return []byte(fmt.Sprintf(`"%s"`, d.Duration().String())), nil | |
| 59 } | |
| OLD | NEW |