github.com/alexdevranger/node-1.8.27@v0.0.0-20221128213301-aa5841e41d2d/swarm/storage/feed/timestampprovider.go (about)

     1  // Copyright 2018 The go-ethereum Authors
     2  // This file is part of the go-dubxcoin library.
     3  //
     4  // The go-dubxcoin library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-dubxcoin library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-dubxcoin library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package feed
    18  
    19  import (
    20  	"encoding/json"
    21  	"time"
    22  )
    23  
    24  // TimestampProvider sets the time source of the feeds package
    25  var TimestampProvider timestampProvider = NewDefaultTimestampProvider()
    26  
    27  // Timestamp encodes a point in time as a Unix epoch
    28  type Timestamp struct {
    29  	Time uint64 `json:"time"` // Unix epoch timestamp, in seconds
    30  }
    31  
    32  // timestampProvider interface describes a source of timestamp information
    33  type timestampProvider interface {
    34  	Now() Timestamp // returns the current timestamp information
    35  }
    36  
    37  // UnmarshalJSON implements the json.Unmarshaller interface
    38  func (t *Timestamp) UnmarshalJSON(data []byte) error {
    39  	return json.Unmarshal(data, &t.Time)
    40  }
    41  
    42  // MarshalJSON implements the json.Marshaller interface
    43  func (t *Timestamp) MarshalJSON() ([]byte, error) {
    44  	return json.Marshal(t.Time)
    45  }
    46  
    47  // DefaultTimestampProvider is a TimestampProvider that uses system time
    48  // as time source
    49  type DefaultTimestampProvider struct {
    50  }
    51  
    52  // NewDefaultTimestampProvider creates a system clock based timestamp provider
    53  func NewDefaultTimestampProvider() *DefaultTimestampProvider {
    54  	return &DefaultTimestampProvider{}
    55  }
    56  
    57  // Now returns the current time according to this provider
    58  func (dtp *DefaultTimestampProvider) Now() Timestamp {
    59  	return Timestamp{
    60  		Time: uint64(time.Now().Unix()),
    61  	}
    62  }