github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/p2p/util.go (about)

     1  // Copyright 2019 The go-simplechain Authors
     2  // This file is part of the go-simplechain library.
     3  //
     4  // The go-simplechain 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-simplechain 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-simplechain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package p2p
    18  
    19  import (
    20  	"container/heap"
    21  	"time"
    22  )
    23  
    24  // expHeap tracks strings and their expiry time.
    25  type expHeap []expItem
    26  
    27  // expItem is an entry in addrHistory.
    28  type expItem struct {
    29  	item string
    30  	exp  time.Time
    31  }
    32  
    33  // nextExpiry returns the next expiry time.
    34  func (h *expHeap) nextExpiry() time.Time {
    35  	return (*h)[0].exp
    36  }
    37  
    38  // add adds an item and sets its expiry time.
    39  func (h *expHeap) add(item string, exp time.Time) {
    40  	heap.Push(h, expItem{item, exp})
    41  }
    42  
    43  // contains checks whether an item is present.
    44  func (h expHeap) contains(item string) bool {
    45  	for _, v := range h {
    46  		if v.item == item {
    47  			return true
    48  		}
    49  	}
    50  	return false
    51  }
    52  
    53  // expire removes items with expiry time before 'now'.
    54  func (h *expHeap) expire(now time.Time) {
    55  	for h.Len() > 0 && h.nextExpiry().Before(now) {
    56  		heap.Pop(h)
    57  	}
    58  }
    59  
    60  // heap.Interface boilerplate
    61  func (h expHeap) Len() int            { return len(h) }
    62  func (h expHeap) Less(i, j int) bool  { return h[i].exp.Before(h[j].exp) }
    63  func (h expHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
    64  func (h *expHeap) Push(x interface{}) { *h = append(*h, x.(expItem)) }
    65  func (h *expHeap) Pop() interface{} {
    66  	old := *h
    67  	n := len(old)
    68  	x := old[n-1]
    69  	*h = old[0 : n-1]
    70  	return x
    71  }