mirror of
https://gitclone.com/github.com/MetaCubeX/Clash.Meta
synced 2024-11-15 13:41:23 +08:00
72 lines
1.2 KiB
Go
72 lines
1.2 KiB
Go
|
package queue
|
||
|
|
||
|
import (
|
||
|
"sync"
|
||
|
)
|
||
|
|
||
|
// Queue is a simple concurrent safe queue
|
||
|
type Queue struct {
|
||
|
items []interface{}
|
||
|
lock sync.RWMutex
|
||
|
}
|
||
|
|
||
|
// Put add the item to the queue.
|
||
|
func (q *Queue) Put(items ...interface{}) {
|
||
|
if len(items) == 0 {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
q.lock.Lock()
|
||
|
q.items = append(q.items, items...)
|
||
|
q.lock.Unlock()
|
||
|
}
|
||
|
|
||
|
// Pop returns the head of items.
|
||
|
func (q *Queue) Pop() interface{} {
|
||
|
if len(q.items) == 0 {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
q.lock.Lock()
|
||
|
head := q.items[0]
|
||
|
q.items = q.items[1:]
|
||
|
q.lock.Unlock()
|
||
|
return head
|
||
|
}
|
||
|
|
||
|
// First returns the head of items without deleting.
|
||
|
func (q *Queue) First() interface{} {
|
||
|
if len(q.items) == 0 {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
q.lock.RLock()
|
||
|
head := q.items[0]
|
||
|
q.lock.RUnlock()
|
||
|
return head
|
||
|
}
|
||
|
|
||
|
// Copy get the copy of queue.
|
||
|
func (q *Queue) Copy() []interface{} {
|
||
|
items := []interface{}{}
|
||
|
q.lock.RLock()
|
||
|
items = append(items, q.items...)
|
||
|
q.lock.RUnlock()
|
||
|
return items
|
||
|
}
|
||
|
|
||
|
// Len returns the number of items in this queue.
|
||
|
func (q *Queue) Len() int64 {
|
||
|
q.lock.Lock()
|
||
|
defer q.lock.Unlock()
|
||
|
|
||
|
return int64(len(q.items))
|
||
|
}
|
||
|
|
||
|
// New is a constructor for a new concurrent safe queue.
|
||
|
func New(hint int64) *Queue {
|
||
|
return &Queue{
|
||
|
items: make([]interface{}, 0, hint),
|
||
|
}
|
||
|
}
|