Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1159)

Side by Side Diff: go/src/infra/libs/clock/clockflag/duration.go

Issue 1154213012: Add context-aware "time" library wrapper. (Closed) Base URL: https://chromium.googlesource.com/infra/infra.git@master
Patch Set: Refactored into sub-packages. Created 5 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(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 clockflag
6
7 import (
8 "errors"
9 "fmt"
10 "time"
11 )
12
13 // Duration is a Flag- and JSON-compatible Duration value.
14 type Duration time.Duration
15
16 // Set implements flag.Value.
17 func (d *Duration) Set(value string) error {
18 duration, err := time.ParseDuration(value)
19 if err != nil {
20 return err
21 }
22 *d = Duration(duration)
23 return nil
24 }
25
26 // String implements flag.Value.
27 func (d *Duration) String() string {
28 return time.Duration(*d).String()
29 }
30
31 // Duration returns the Duration value of the flag.
32 func (d Duration) Duration() time.Duration {
33 return time.Duration(d)
34 }
35
36 // IsZero tests if this Duration is the zero value.
37 func (d Duration) 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 *Duration) 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 Duration into a duration string.
57 func (d Duration) MarshalJSON() ([]byte, error) {
58 return []byte(fmt.Sprintf(`"%s"`, d.Duration().String())), nil
59 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698