| 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 // SetFactory creates a new Context using the supplied Clock factory. | |
| 23 func SetFactory(ctx context.Context, f Factory) context.Context { | |
| 24 return context.WithValue(ctx, clockKey, f) | |
| 25 } | |
| 26 | |
| 27 // Set creates a new Context using the supplied Clock. | |
| 28 func Set(ctx context.Context, c Clock) context.Context { | |
| 29 return SetFactory(ctx, func(context.Context) Clock { return c }) | |
| 30 } | |
| 31 | |
| 32 // Get returns the Clock set in the supplied Context, defaulting to | |
| 33 // SystemClock() if none is set. | |
| 34 func Get(ctx context.Context) (clock Clock) { | |
| 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 Get(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 Get(ctx).Sleep(d) | |
| 60 } | |
| 61 | |
| 62 // NewTimer calls Clock.NewTimer on the Clock instance stored in the supplied | |
| 63 // Context. | |
| 64 func NewTimer(ctx context.Context) Timer { | |
| 65 return Get(ctx).NewTimer() | |
| 66 } | |
| 67 | |
| 68 // After calls Clock.After on the Clock instance stored in the supplied Context. | |
| 69 func After(ctx context.Context, d time.Duration) <-chan time.Time { | |
| 70 return Get(ctx).After(d) | |
| 71 } | |
| OLD | NEW |