| // Copyright 2018 The Fuchsia 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 fxtime |
| |
| import ( |
| "time" |
| ) |
| |
| // Clock tells the current time. Time is always given in UTC. |
| type Clock interface { |
| Now() time.Time |
| } |
| |
| func NewClock() Clock { |
| return clock{} |
| } |
| |
| // NewFixedClock returns a clock that always tells the same time. This is useful for |
| // testing. |
| func NewFixedClock(moment time.Time) Clock { |
| return fixedClock{moment: moment} |
| } |
| |
| // Stopwatch measures time intervals. |
| type Stopwatch interface { |
| Restart() time.Time |
| Elapsed() time.Duration |
| } |
| |
| // NewStopwatch returns a new stopwatch. The watch's initial time is set to clock.Now() |
| func NewStopwatch(clock Clock) Stopwatch { |
| sw := &stopwatch{clock: clock} |
| sw.Restart() |
| return sw |
| } |
| |
| type stopwatch struct { |
| clock Clock |
| start time.Time |
| } |
| |
| func (s *stopwatch) Restart() time.Time { |
| s.start = s.clock.Now() |
| return s.start |
| } |
| |
| func (s stopwatch) Elapsed() time.Duration { |
| return s.clock.Now().Sub(s.start) |
| } |
| |
| type clock struct{} |
| |
| func (c clock) Now() time.Time { |
| return time.Now().UTC() |
| } |
| |
| type fixedClock struct { |
| moment time.Time |
| } |
| |
| func (c fixedClock) Now() time.Time { |
| return c.moment.UTC() |
| } |