github.com/aergoio/aergo@v1.3.1/p2p/p2putil/pressqueue.go (about)

     1  package p2putil
     2  
     3  // PressableQueue non-threadsafe fixed size queue, implemented like circular queue
     4  type PressableQueue struct {
     5  	arr    []interface{}
     6  	cap    int
     7  	size   int
     8  	offset int
     9  }
    10  
    11  // NewPressableQueue create a new queue
    12  func NewPressableQueue(capacity int) *PressableQueue {
    13  	return &PressableQueue{cap: capacity, arr: make([]interface{}, capacity)}
    14  }
    15  
    16  // Empty returns true if queue has no element, or false if not
    17  func (q *PressableQueue) Empty() bool {
    18  	return q.size == 0
    19  }
    20  
    21  // Full returns true if queue has maximum number of elements, or false if not
    22  func (q *PressableQueue) Full() bool {
    23  	return q.size == q.cap
    24  }
    25  
    26  // Size return the number of element queue has
    27  func (q *PressableQueue) Size() int {
    28  	return q.size
    29  }
    30  
    31  // Offer is adding element to queue, it returns true if add success, or false if queue if add fail.
    32  func (q *PressableQueue) Offer(e interface{}) bool {
    33  	if q.size < q.cap {
    34  		idx := (q.offset + q.size) % q.cap
    35  		q.arr[idx] = e
    36  		q.size++
    37  		return true
    38  	}
    39  	return false
    40  }
    41  
    42  // Press is adding element to queue and return nil fi queue is not full, or drop first element and return dropped element if queue is full.
    43  func (q *PressableQueue) Press(e interface{}) interface{} {
    44  	if q.size < q.cap {
    45  		idx := (q.offset + q.size) % q.cap
    46  		q.arr[idx] = e
    47  		q.size++
    48  		return nil
    49  	}
    50  	idx := (q.offset + q.size) % q.cap
    51  	toDrop := q.arr[idx]
    52  	q.arr[idx] = e
    53  	q.offset = (idx + 1) % q.cap
    54  	return toDrop
    55  }
    56  
    57  // Peek return first element but not delete in queue. It returns nil if queue is empty
    58  func (q *PressableQueue) Peek() interface{} {
    59  	if q.size == 0 {
    60  		return nil
    61  	}
    62  	return q.arr[q.offset]
    63  }
    64  
    65  // Poll return first element and remove it in queue. It returns nil if queue is empty
    66  func (q *PressableQueue) Poll() interface{} {
    67  	if q.size == 0 {
    68  		return nil
    69  	}
    70  	e := q.arr[q.offset]
    71  	q.arr[q.offset] = nil
    72  	q.offset = (q.offset + 1) % q.cap
    73  	q.size--
    74  	return e
    75  }