Chromium Code Reviews| 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..619391651456ed67ac57e316523da8f476b9b025 |
| --- /dev/null |
| +++ b/go/src/infra/libs/clock/context.go |
| @@ -0,0 +1,67 @@ |
| +// Copyright (c) 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 |
| + |
| +// SetClockFactory creates a new Context using the supplied Clock factory. |
| +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.
|
| + return context.WithValue(ctx, clockKey, f) |
| +} |
| + |
| +// SetClock creates a new Context using the supplied Clock. |
| +func SetClock(ctx context.Context, c Clock) context.Context { |
| + return SetClockFactory(ctx, func(ctx 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) { |
| + v := ctx.Value(clockKey) |
| + if v != nil { |
| + f := v.(func(context.Context) Clock) |
| + if f != nil { |
| + clock = f(ctx) |
| + } |
| + } |
| + if clock == nil { |
| + clock = systemClockInstance |
| + } |
| + 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) |
| +} |