github.com/bhameyie/otto@v0.2.1-0.20160406174117-16052efa52ec/helper/localaddr/ip_queue.go (about)

     1  package localaddr
     2  
     3  import (
     4  	"container/heap"
     5  	"net"
     6  	"time"
     7  )
     8  
     9  // ipEntry is an entry in the priority queue of leased IP addresses.
    10  type ipEntry struct {
    11  	LeaseTime time.Time
    12  	Value     net.IP
    13  
    14  	// This is maintained by heap.Push and heap.Pop
    15  	Index int
    16  }
    17  
    18  // ipQueue is an implementation of heap.Interface and holds ipEntrys.
    19  type ipQueue []*ipEntry
    20  
    21  func (q ipQueue) Len() int { return len(q) }
    22  
    23  func (q ipQueue) Less(i, j int) bool {
    24  	return q[i].LeaseTime.Before(q[j].LeaseTime)
    25  }
    26  
    27  func (q ipQueue) Swap(i, j int) {
    28  	q[i], q[j] = q[j], q[i]
    29  	q[i].Index = i
    30  	q[j].Index = j
    31  }
    32  
    33  func (q *ipQueue) Push(x interface{}) {
    34  	item := x.(*ipEntry)
    35  	item.Index = len(*q)
    36  	*q = append(*q, item)
    37  }
    38  
    39  func (q *ipQueue) Pop() interface{} {
    40  	old := *q
    41  	n := len(old)
    42  	item := old[n-1]
    43  	item.Index = -1
    44  	*q = old[0 : n-1]
    45  	return item
    46  }
    47  
    48  // Update updates the given entry. This entry must already be in the queue.
    49  func (q *ipQueue) Update(item *ipEntry) {
    50  	heap.Fix(q, item.Index)
    51  }