OLD | NEW |
(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 // Factory is a generator function that produces a Clock instnace. |
| 20 type Factory func(context.Context) Clock |
| 21 |
| 22 // SetClockFactory creates a new Context using the supplied Clock factory. |
| 23 func SetClockFactory(ctx context.Context, f Factory) context.Context { |
| 24 return context.WithValue(ctx, clockKey, f) |
| 25 } |
| 26 |
| 27 // SetClock creates a new Context using the supplied Clock. |
| 28 func SetClock(ctx context.Context, c Clock) context.Context { |
| 29 return SetClockFactory(ctx, func(ctx context.Context) Clock { return c }
) |
| 30 } |
| 31 |
| 32 // GetClock returns the Clock set in the supplied Context, defaulting to SystemC
lock() |
| 33 // if none is set. |
| 34 func GetClock(ctx context.Context) (clock Clock) { |
| 35 v := ctx.Value(clockKey) |
| 36 if v != nil { |
| 37 f := v.(func(context.Context) Clock) |
| 38 if f != nil { |
| 39 clock = f(ctx) |
| 40 } |
| 41 } |
| 42 if clock == nil { |
| 43 panic("No Clock instance has been set in this context.") |
| 44 } |
| 45 return |
| 46 } |
| 47 |
| 48 // |
| 49 // "Implement" the Clock interface at the package level. |
| 50 // |
| 51 |
| 52 // Now calls Clock.Now on the Clock instance stored in the supplied Context. |
| 53 func Now(ctx context.Context) time.Time { |
| 54 return GetClock(ctx).Now() |
| 55 } |
| 56 |
| 57 // Sleep calls Clock.Sleep on the Clock instance stored in the supplied Context. |
| 58 func Sleep(ctx context.Context, d time.Duration) { |
| 59 GetClock(ctx).Sleep(d) |
| 60 } |
| 61 |
| 62 // NewTimer calls Clock.NewTimer on the Clock instance stored in the supplied Co
ntext. |
| 63 func NewTimer(ctx context.Context) Timer { |
| 64 return GetClock(ctx).NewTimer() |
| 65 } |
| 66 |
| 67 // After calls Clock.After on the Clock instance stored in the supplied Context. |
| 68 func After(ctx context.Context, d time.Duration) <-chan time.Time { |
| 69 return GetClock(ctx).After(d) |
| 70 } |
OLD | NEW |