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

     1  // Copyright (c) 2024 Alexey Mayshev. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package expiry
    16  
    17  import "github.com/maypok86/otter/internal/generated/node"
    18  
    19  type queue[K comparable, V any] struct {
    20  	head node.Node[K, V]
    21  	tail node.Node[K, V]
    22  	len  int
    23  }
    24  
    25  func newQueue[K comparable, V any]() *queue[K, V] {
    26  	return &queue[K, V]{}
    27  }
    28  
    29  func (q *queue[K, V]) length() int {
    30  	return q.len
    31  }
    32  
    33  func (q *queue[K, V]) isEmpty() bool {
    34  	return q.length() == 0
    35  }
    36  
    37  func (q *queue[K, V]) push(n node.Node[K, V]) {
    38  	if q.isEmpty() {
    39  		q.head = n
    40  		q.tail = n
    41  	} else {
    42  		n.SetPrevExp(q.tail)
    43  		q.tail.SetNextExp(n)
    44  		q.tail = n
    45  	}
    46  
    47  	q.len++
    48  }
    49  
    50  func (q *queue[K, V]) pop() node.Node[K, V] {
    51  	if q.isEmpty() {
    52  		return nil
    53  	}
    54  
    55  	result := q.head
    56  	q.remove(result)
    57  	return result
    58  }
    59  
    60  func (q *queue[K, V]) remove(n node.Node[K, V]) {
    61  	next := n.NextExp()
    62  	prev := n.PrevExp()
    63  
    64  	if node.Equals(prev, nil) {
    65  		if node.Equals(next, nil) && !node.Equals(q.head, n) {
    66  			return
    67  		}
    68  
    69  		q.head = next
    70  	} else {
    71  		prev.SetNextExp(next)
    72  		n.SetPrevExp(nil)
    73  	}
    74  
    75  	if node.Equals(next, nil) {
    76  		q.tail = prev
    77  	} else {
    78  		next.SetPrevExp(prev)
    79  		n.SetNextExp(nil)
    80  	}
    81  
    82  	q.len--
    83  }
    84  
    85  func (q *queue[K, V]) clear() {
    86  	for !q.isEmpty() {
    87  		q.pop()
    88  	}
    89  }