Jiri Simsa | d7616c9 | 2015-03-24 23:44:30 -0700 | [diff] [blame] | 1 | // Copyright 2015 The Vanadium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
Todd Wang | 8c4e5cc | 2015-04-09 11:30:52 -0700 | [diff] [blame] | 5 | // Package timekeeper defines an interface to allow switching between real time |
| 6 | // and simulated time. |
Jiri Simsa | 5293dcb | 2014-05-10 09:56:38 -0700 | [diff] [blame] | 7 | package timekeeper |
| 8 | |
| 9 | import "time" |
| 10 | |
| 11 | // TimeKeeper is meant as a drop-in replacement for using the time package |
| 12 | // directly, and allows testing code to substitute a suitable implementation. |
| 13 | // The meaning of duration and current time depends on the implementation (may |
| 14 | // be a simulated time). |
| 15 | type TimeKeeper interface { |
| 16 | // After waits for the duration to elapse and then sends the current |
| 17 | // time on the returned channel. |
| 18 | After(d time.Duration) <-chan time.Time |
| 19 | // Sleep pauses the current goroutine for at least the duration d. A |
| 20 | // negative or zero duration causes Sleep to return immediately. |
| 21 | Sleep(d time.Duration) |
| 22 | } |
| 23 | |
| 24 | // realTime is the default implementation of TimeKeeper, using the time package. |
| 25 | type realTime struct{} |
| 26 | |
| 27 | var rt realTime |
| 28 | |
| 29 | // After implements TimeKeeper.After. |
| 30 | func (t *realTime) After(d time.Duration) <-chan time.Time { |
| 31 | return time.After(d) |
| 32 | } |
| 33 | |
| 34 | // Sleep implements TimeKeeper.Sleep. |
| 35 | func (t *realTime) Sleep(d time.Duration) { |
| 36 | time.Sleep(d) |
| 37 | } |
| 38 | |
| 39 | // RealTime returns a default instance of TimeKeeper. |
| 40 | func RealTime() TimeKeeper { |
| 41 | return &rt |
| 42 | } |