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

Side by Side Diff: go/src/infra/libs/clock/context.go

Issue 1154213012: Add context-aware "time" library wrapper. (Closed) Base URL: https://chromium.googlesource.com/infra/infra.git@master
Patch Set: 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) 2015 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
6
7 import (
8 "time"
9
10 "golang.org/x/net/context"
11 )
12
13 // Context key for clock.
14 type clockKeyType int
15
16 // Unique value for clock key.
17 var clockKey clockKeyType
18
19 // SetClockFactory creates a new Context using the supplied Clock factory.
20 func SetClockFactory(ctx context.Context, f func(context.Context) Clock) context .Context {
iannucci 2015/06/02 06:15:33 type ClockFactory func(context.Context) Clock f
dnj 2015/06/02 17:03:12 Done.
21 return context.WithValue(ctx, clockKey, f)
22 }
23
24 // SetClock creates a new Context using the supplied Clock.
25 func SetClock(ctx context.Context, c Clock) context.Context {
26 return SetClockFactory(ctx, func(ctx context.Context) Clock { return c } )
27 }
28
29 // GetClock returns the Clock set in the supplied Context, defaulting to SystemC lock()
30 // if none is set.
31 func GetClock(ctx context.Context) (clock Clock) {
32 v := ctx.Value(clockKey)
33 if v != nil {
34 f := v.(func(context.Context) Clock)
35 if f != nil {
36 clock = f(ctx)
37 }
38 }
39 if clock == nil {
40 clock = systemClockInstance
41 }
42 return
43 }
44
45 //
46 // "Implement" the Clock interface at the package level.
47 //
48
49 // Now calls Clock.Now on the Clock instance stored in the supplied Context.
50 func Now(ctx context.Context) time.Time {
51 return GetClock(ctx).Now()
52 }
53
54 // Sleep calls Clock.Sleep on the Clock instance stored in the supplied Context.
55 func Sleep(ctx context.Context, d time.Duration) {
56 GetClock(ctx).Sleep(d)
57 }
58
59 // NewTimer calls Clock.NewTimer on the Clock instance stored in the supplied Co ntext.
60 func NewTimer(ctx context.Context) Timer {
61 return GetClock(ctx).NewTimer()
62 }
63
64 // After calls Clock.After on the Clock instance stored in the supplied Context.
65 func After(ctx context.Context, d time.Duration) <-chan time.Time {
66 return GetClock(ctx).After(d)
67 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698