Index: go/src/infra/libs/clock/context.go |
diff --git a/go/src/infra/libs/clock/context.go b/go/src/infra/libs/clock/context.go |
new file mode 100644 |
index 0000000000000000000000000000000000000000..3f8c9e0e693c24f780eedc5f9bc1f16f51b2edd8 |
--- /dev/null |
+++ b/go/src/infra/libs/clock/context.go |
@@ -0,0 +1,70 @@ |
+// Copyright 2015 The Chromium Authors. All rights reserved. |
+// Use of this source code is governed by a BSD-style license that can be |
+// found in the LICENSE file. |
+ |
+package clock |
+ |
+import ( |
+ "time" |
+ |
+ "golang.org/x/net/context" |
+) |
+ |
+// Context key for clock. |
+type clockKeyType int |
+ |
+// Unique value for clock key. |
+var clockKey clockKeyType |
+ |
+// Factory is a generator function that produces a Clock instnace. |
+type Factory func(context.Context) Clock |
+ |
+// SetClockFactory creates a new Context using the supplied Clock factory. |
+func SetClockFactory(ctx context.Context, f Factory) context.Context { |
iannucci
2015/06/03 17:37:20
maybe clock.SetFactory
See 3rd para here: https:/
dnj
2015/06/03 18:21:26
ClockSetTheClockFactoryForContext
(okay)
|
+ return context.WithValue(ctx, clockKey, f) |
+} |
+ |
+// SetClock creates a new Context using the supplied Clock. |
+func SetClock(ctx context.Context, c Clock) context.Context { |
iannucci
2015/06/03 17:37:20
maybe clock.Set
dnj
2015/06/03 18:21:26
Done.
|
+ return SetClockFactory(ctx, func(context.Context) Clock { return c }) |
+} |
+ |
+// GetClock returns the Clock set in the supplied Context, defaulting to SystemClock() |
+// if none is set. |
+func GetClock(ctx context.Context) (clock Clock) { |
iannucci
2015/06/03 17:37:20
maybe clock.Get
dnj
2015/06/03 18:21:26
Done.
|
+ v := ctx.Value(clockKey) |
+ if v != nil { |
+ f := v.(Factory) |
+ if f != nil { |
+ clock = f(ctx) |
+ } |
+ } |
+ if clock == nil { |
+ clock = GetSystemClock() |
+ } |
+ return |
+} |
+ |
+// |
+// "Implement" the Clock interface at the package level. |
+// |
+ |
+// Now calls Clock.Now on the Clock instance stored in the supplied Context. |
+func Now(ctx context.Context) time.Time { |
+ return GetClock(ctx).Now() |
+} |
+ |
+// Sleep calls Clock.Sleep on the Clock instance stored in the supplied Context. |
+func Sleep(ctx context.Context, d time.Duration) { |
+ GetClock(ctx).Sleep(d) |
+} |
+ |
+// NewTimer calls Clock.NewTimer on the Clock instance stored in the supplied Context. |
+func NewTimer(ctx context.Context) Timer { |
+ return GetClock(ctx).NewTimer() |
+} |
+ |
+// After calls Clock.After on the Clock instance stored in the supplied Context. |
+func After(ctx context.Context, d time.Duration) <-chan time.Time { |
+ return GetClock(ctx).After(d) |
+} |