github.com/kelleygo/clashcore@v1.0.2/common/queue/queue.go (about)

     1  package queue
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/samber/lo"
     7  )
     8  
     9  // Queue is a simple concurrent safe queue
    10  type Queue[T any] struct {
    11  	items []T
    12  	lock  sync.RWMutex
    13  }
    14  
    15  // Put add the item to the queue.
    16  func (q *Queue[T]) Put(items ...T) {
    17  	if len(items) == 0 {
    18  		return
    19  	}
    20  
    21  	q.lock.Lock()
    22  	q.items = append(q.items, items...)
    23  	q.lock.Unlock()
    24  }
    25  
    26  // Pop returns the head of items.
    27  func (q *Queue[T]) Pop() T {
    28  	if len(q.items) == 0 {
    29  		return lo.Empty[T]()
    30  	}
    31  
    32  	q.lock.Lock()
    33  	head := q.items[0]
    34  	q.items = q.items[1:]
    35  	q.lock.Unlock()
    36  	return head
    37  }
    38  
    39  // Last returns the last of item.
    40  func (q *Queue[T]) Last() T {
    41  	if len(q.items) == 0 {
    42  		return lo.Empty[T]()
    43  	}
    44  
    45  	q.lock.RLock()
    46  	last := q.items[len(q.items)-1]
    47  	q.lock.RUnlock()
    48  	return last
    49  }
    50  
    51  // Copy get the copy of queue.
    52  func (q *Queue[T]) Copy() []T {
    53  	items := []T{}
    54  	q.lock.RLock()
    55  	items = append(items, q.items...)
    56  	q.lock.RUnlock()
    57  	return items
    58  }
    59  
    60  // Len returns the number of items in this queue.
    61  func (q *Queue[T]) Len() int64 {
    62  	q.lock.Lock()
    63  	defer q.lock.Unlock()
    64  
    65  	return int64(len(q.items))
    66  }
    67  
    68  // New is a constructor for a new concurrent safe queue.
    69  func New[T any](hint int64) *Queue[T] {
    70  	return &Queue[T]{
    71  		items: make([]T, 0, hint),
    72  	}
    73  }