| OLD | NEW |
| (Empty) |
| 1 // Copyright 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 clockflag | |
| 6 | |
| 7 import ( | |
| 8 "errors" | |
| 9 "flag" | |
| 10 "fmt" | |
| 11 "time" | |
| 12 ) | |
| 13 | |
| 14 // Duration is a Flag- and JSON-compatible Duration value. | |
| 15 type Duration time.Duration | |
| 16 | |
| 17 var _ flag.Value = (*Duration)(nil) | |
| 18 | |
| 19 // Set implements flag.Value. | |
| 20 func (d *Duration) Set(value string) error { | |
| 21 duration, err := time.ParseDuration(value) | |
| 22 if err != nil { | |
| 23 return err | |
| 24 } | |
| 25 *d = Duration(duration) | |
| 26 return nil | |
| 27 } | |
| 28 | |
| 29 func (d *Duration) String() string { | |
| 30 return time.Duration(*d).String() | |
| 31 } | |
| 32 | |
| 33 // Duration returns the Duration value of the flag. | |
| 34 func (d Duration) Duration() time.Duration { | |
| 35 return time.Duration(d) | |
| 36 } | |
| 37 | |
| 38 // IsZero tests if this Duration is the zero value. | |
| 39 func (d Duration) IsZero() bool { | |
| 40 return time.Duration(d) == time.Duration(0) | |
| 41 } | |
| 42 | |
| 43 // UnmarshalJSON implements json.Unmarshaler. | |
| 44 // | |
| 45 // Unmarshals a JSON entry into the underlying type. The entry is expected to | |
| 46 // contain a string corresponding to one of the enum's keys. | |
| 47 func (d *Duration) UnmarshalJSON(data []byte) error { | |
| 48 // Strip off leading and trailing quotes. | |
| 49 s := string(data) | |
| 50 if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' { | |
| 51 return errors.New("Duration JSON must be a valid JSON string.") | |
| 52 } | |
| 53 return d.Set(s[1 : len(s)-1]) | |
| 54 } | |
| 55 | |
| 56 // MarshalJSON implements json.Marshaler. | |
| 57 // | |
| 58 // Marshals a Duration into a duration string. | |
| 59 func (d Duration) MarshalJSON() ([]byte, error) { | |
| 60 return []byte(fmt.Sprintf(`"%s"`, d.Duration().String())), nil | |
| 61 } | |
| OLD | NEW |