Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright 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 { | |
|
iannucci
2015/06/03 17:37:20
maybe clock.SetFactory
See 3rd para here: https:/
dnj
2015/06/03 18:21:26
ClockSetTheClockFactoryForContext
(okay)
| |
| 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 { | |
|
iannucci
2015/06/03 17:37:20
maybe clock.Set
dnj
2015/06/03 18:21:26
Done.
| |
| 29 return SetClockFactory(ctx, func(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) { | |
|
iannucci
2015/06/03 17:37:20
maybe clock.Get
dnj
2015/06/03 18:21:26
Done.
| |
| 35 v := ctx.Value(clockKey) | |
| 36 if v != nil { | |
| 37 f := v.(Factory) | |
| 38 if f != nil { | |
| 39 clock = f(ctx) | |
| 40 } | |
| 41 } | |
| 42 if clock == nil { | |
| 43 clock = GetSystemClock() | |
| 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 |