github.com/iotexproject/iotex-core@v1.14.1-rc1/actpool/priorityqueue.go (about)

     1  // Copyright (c) 2019 IoTeX Foundation
     2  // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
     3  // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
     4  // This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
     5  
     6  package actpool
     7  
     8  import "time"
     9  
    10  type (
    11  	nonceWithTTL struct {
    12  		ascIdx   int
    13  		descIdx  int
    14  		nonce    uint64
    15  		deadline time.Time
    16  	}
    17  
    18  	ascNoncePriorityQueue  []*nonceWithTTL
    19  	descNoncePriorityQueue []*nonceWithTTL
    20  )
    21  
    22  func (h ascNoncePriorityQueue) Len() int           { return len(h) }
    23  func (h ascNoncePriorityQueue) Less(i, j int) bool { return h[i].nonce < h[j].nonce }
    24  func (h ascNoncePriorityQueue) Swap(i, j int) {
    25  	h[i], h[j] = h[j], h[i]
    26  	h[i].ascIdx = i
    27  	h[j].ascIdx = j
    28  }
    29  
    30  func (h *ascNoncePriorityQueue) Push(x interface{}) {
    31  	if in, ok := x.(*nonceWithTTL); ok {
    32  		in.ascIdx = len(*h)
    33  		*h = append(*h, in)
    34  	}
    35  }
    36  
    37  func (h *ascNoncePriorityQueue) Pop() interface{} {
    38  	old := *h
    39  	n := len(old)
    40  	if n == 0 {
    41  		return nil
    42  	}
    43  	x := old[n-1]
    44  	old[n-1] = nil // avoid memory leak
    45  	*h = old[0 : n-1]
    46  	return x
    47  }
    48  
    49  func (h descNoncePriorityQueue) Len() int           { return len(h) }
    50  func (h descNoncePriorityQueue) Less(i, j int) bool { return h[i].nonce > h[j].nonce }
    51  func (h descNoncePriorityQueue) Swap(i, j int) {
    52  	h[i], h[j] = h[j], h[i]
    53  	h[i].descIdx = i
    54  	h[j].descIdx = j
    55  }
    56  
    57  func (h *descNoncePriorityQueue) Push(x interface{}) {
    58  	if in, ok := x.(*nonceWithTTL); ok {
    59  		in.descIdx = len(*h)
    60  		*h = append(*h, in)
    61  	}
    62  }
    63  
    64  func (h *descNoncePriorityQueue) Pop() interface{} {
    65  	old := *h
    66  	n := len(old)
    67  	if n == 0 {
    68  		return nil
    69  	}
    70  	x := old[n-1]
    71  	old[n-1] = nil // avoid memory leak
    72  	*h = old[0 : n-1]
    73  	return x
    74  }