github.com/maypok86/otter@v1.2.1/internal/s3fifo/queue.go (about)

     1  package s3fifo
     2  
     3  import "github.com/maypok86/otter/internal/generated/node"
     4  
     5  type queue[K comparable, V any] struct {
     6  	head node.Node[K, V]
     7  	tail node.Node[K, V]
     8  	len  int
     9  }
    10  
    11  func newQueue[K comparable, V any]() *queue[K, V] {
    12  	return &queue[K, V]{}
    13  }
    14  
    15  func (q *queue[K, V]) length() int {
    16  	return q.len
    17  }
    18  
    19  func (q *queue[K, V]) isEmpty() bool {
    20  	return q.length() == 0
    21  }
    22  
    23  func (q *queue[K, V]) push(n node.Node[K, V]) {
    24  	if q.isEmpty() {
    25  		q.head = n
    26  		q.tail = n
    27  	} else {
    28  		n.SetPrev(q.tail)
    29  		q.tail.SetNext(n)
    30  		q.tail = n
    31  	}
    32  
    33  	q.len++
    34  }
    35  
    36  func (q *queue[K, V]) pop() node.Node[K, V] {
    37  	if q.isEmpty() {
    38  		return nil
    39  	}
    40  
    41  	result := q.head
    42  	q.remove(result)
    43  	return result
    44  }
    45  
    46  func (q *queue[K, V]) remove(n node.Node[K, V]) {
    47  	next := n.Next()
    48  	prev := n.Prev()
    49  
    50  	if node.Equals(prev, nil) {
    51  		if node.Equals(next, nil) && !node.Equals(q.head, n) {
    52  			return
    53  		}
    54  
    55  		q.head = next
    56  	} else {
    57  		prev.SetNext(next)
    58  		n.SetPrev(nil)
    59  	}
    60  
    61  	if node.Equals(next, nil) {
    62  		q.tail = prev
    63  	} else {
    64  		next.SetPrev(prev)
    65  		n.SetNext(nil)
    66  	}
    67  
    68  	q.len--
    69  }
    70  
    71  func (q *queue[K, V]) clear() {
    72  	for !q.isEmpty() {
    73  		q.pop()
    74  	}
    75  }