github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/common/mclock/mclock.go (about)

     1  //  Copyright 2018 The go-ethereum Authors
     2  //  Copyright 2019 The go-aigar Authors
     3  //  This file is part of the go-aigar library.
     4  //
     5  //  The go-aigar library is free software: you can redistribute it and/or modify
     6  //  it under the terms of the GNU Lesser General Public License as published by
     7  //  the Free Software Foundation, either version 3 of the License, or
     8  //  (at your option) any later version.
     9  //
    10  //  The go-aigar library is distributed in the hope that it will be useful,
    11  //  but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  //  GNU Lesser General Public License for more details.
    14  //
    15  //  You should have received a copy of the GNU Lesser General Public License
    16  //  along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  // Package mclock is a wrapper for a monotonic clock source
    19  package mclock
    20  
    21  import (
    22  	"time"
    23  
    24  	"github.com/aristanetworks/goarista/monotime"
    25  )
    26  
    27  // AbsTime represents absolute monotonic time.
    28  type AbsTime time.Duration
    29  
    30  // Now returns the current absolute monotonic time.
    31  func Now() AbsTime {
    32  	return AbsTime(monotime.Now())
    33  }
    34  
    35  // Add returns t + d.
    36  func (t AbsTime) Add(d time.Duration) AbsTime {
    37  	return t + AbsTime(d)
    38  }
    39  
    40  // The Clock interface makes it possible to replace the monotonic system clock with
    41  // a simulated clock.
    42  type Clock interface {
    43  	Now() AbsTime
    44  	Sleep(time.Duration)
    45  	After(time.Duration) <-chan time.Time
    46  	AfterFunc(d time.Duration, f func()) Timer
    47  }
    48  
    49  // Timer represents a cancellable event returned by AfterFunc
    50  type Timer interface {
    51  	Stop() bool
    52  }
    53  
    54  // System implements Clock using the system clock.
    55  type System struct{}
    56  
    57  // Now returns the current monotonic time.
    58  func (System) Now() AbsTime {
    59  	return AbsTime(monotime.Now())
    60  }
    61  
    62  // Sleep blocks for the given duration.
    63  func (System) Sleep(d time.Duration) {
    64  	time.Sleep(d)
    65  }
    66  
    67  // After returns a channel which receives the current time after d has elapsed.
    68  func (System) After(d time.Duration) <-chan time.Time {
    69  	return time.After(d)
    70  }
    71  
    72  // AfterFunc runs f on a new goroutine after the duration has elapsed.
    73  func (System) AfterFunc(d time.Duration, f func()) Timer {
    74  	return time.AfterFunc(d, f)
    75  }