| 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..3a760d24da1388fb534f32a186259a2e4171e039
|
| --- /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 {
|
| + 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 = 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)
|
| +}
|
|
|