github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/swarm/storage/feed/lookup/epoch.go (about)

     1  
     2  //<developer>
     3  //    <name>linapex 曹一峰</name>
     4  //    <email>linapex@163.com</email>
     5  //    <wx>superexc</wx>
     6  //    <qqgroup>128148617</qqgroup>
     7  //    <url>https://jsq.ink</url>
     8  //    <role>pku engineer</role>
     9  //    <date>2019-03-16 19:16:44</date>
    10  //</624450119101583360>
    11  
    12  
    13  package lookup
    14  
    15  import (
    16  	"encoding/binary"
    17  	"errors"
    18  	"fmt"
    19  )
    20  
    21  //epoch表示特定频率级别的时隙
    22  type Epoch struct {
    23  Time  uint64 `json:"time"`  //时间存储更新或查找发生的时间
    24  Level uint8  `json:"level"` //级别表示频率级别,表示2次方的指数。
    25  }
    26  
    27  //epochid是一个时代的唯一标识符,基于它的级别和基准时间。
    28  type EpochID [8]byte
    29  
    30  //epoch length存储epoch的序列化二进制长度
    31  const EpochLength = 8
    32  
    33  //maxtime包含一个epoch可以处理的最大可能时间值
    34  const MaxTime uint64 = (1 << 56) - 1
    35  
    36  //BASE返回纪元的基准时间
    37  func (e *Epoch) Base() uint64 {
    38  	return getBaseTime(e.Time, e.Level)
    39  }
    40  
    41  //id返回这个时代的唯一标识符
    42  func (e *Epoch) ID() EpochID {
    43  	base := e.Base()
    44  	var id EpochID
    45  	binary.LittleEndian.PutUint64(id[:], base)
    46  	id[7] = e.Level
    47  	return id
    48  }
    49  
    50  //MarshalBinary实现Encoding.BinaryMarshaller接口
    51  func (e *Epoch) MarshalBinary() (data []byte, err error) {
    52  	b := make([]byte, 8)
    53  	binary.LittleEndian.PutUint64(b[:], e.Time)
    54  	b[7] = e.Level
    55  	return b, nil
    56  }
    57  
    58  //UnmarshalBinary实现encoding.BinaryUnmarshaller接口
    59  func (e *Epoch) UnmarshalBinary(data []byte) error {
    60  	if len(data) != EpochLength {
    61  		return errors.New("Invalid data unmarshalling Epoch")
    62  	}
    63  	b := make([]byte, 8)
    64  	copy(b, data)
    65  	e.Level = b[7]
    66  	b[7] = 0
    67  	e.Time = binary.LittleEndian.Uint64(b)
    68  	return nil
    69  }
    70  
    71  //如果此纪元发生在另一个纪元之后或正好发生在另一个纪元,则返回true。
    72  func (e *Epoch) After(epoch Epoch) bool {
    73  	if e.Time == epoch.Time {
    74  		return e.Level < epoch.Level
    75  	}
    76  	return e.Time >= epoch.Time
    77  }
    78  
    79  //equals比较两个时期,如果它们引用同一时间段,则返回true。
    80  func (e *Epoch) Equals(epoch Epoch) bool {
    81  	return e.Level == epoch.Level && e.Base() == epoch.Base()
    82  }
    83  
    84  //字符串实现字符串接口。
    85  func (e *Epoch) String() string {
    86  	return fmt.Sprintf("Epoch{Time:%d, Level:%d}", e.Time, e.Level)
    87  }
    88