github.com/MetalBlockchain/metalgo@v1.11.9/utils/timer/mockable/clock.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package mockable
     5  
     6  import "time"
     7  
     8  // MaxTime was taken from https://stackoverflow.com/questions/25065055/what-is-the-maximum-time-time-in-go/32620397#32620397
     9  var MaxTime = time.Unix(1<<63-62135596801, 0) // 0 is used because we drop the nano-seconds
    10  
    11  // Clock acts as a thin wrapper around global time that allows for easy testing
    12  type Clock struct {
    13  	faked bool
    14  	time  time.Time
    15  }
    16  
    17  // Set the time on the clock
    18  func (c *Clock) Set(time time.Time) { c.faked = true; c.time = time }
    19  
    20  // Sync this clock with global time
    21  func (c *Clock) Sync() { c.faked = false }
    22  
    23  // Time returns the time on this clock
    24  func (c *Clock) Time() time.Time {
    25  	if c.faked {
    26  		return c.time
    27  	}
    28  	return time.Now()
    29  }
    30  
    31  // Time returns the unix time on this clock
    32  func (c *Clock) UnixTime() time.Time {
    33  	resTime := c.Time()
    34  	return resTime.Truncate(time.Second)
    35  }
    36  
    37  // Unix returns the unix timestamp on this clock.
    38  func (c *Clock) Unix() uint64 {
    39  	unix := c.Time().Unix()
    40  	if unix < 0 {
    41  		unix = 0
    42  	}
    43  	return uint64(unix)
    44  }