2019-03-17 06:52:39 +00:00
|
|
|
package queue
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Queue is a simple concurrent safe queue
|
|
|
|
type Queue struct {
|
2022-03-16 04:10:13 +00:00
|
|
|
items []any
|
2019-03-17 06:52:39 +00:00
|
|
|
lock sync.RWMutex
|
|
|
|
}
|
|
|
|
|
|
|
|
// Put add the item to the queue.
|
2022-03-16 04:10:13 +00:00
|
|
|
func (q *Queue) Put(items ...any) {
|
2019-03-17 06:52:39 +00:00
|
|
|
if len(items) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
q.lock.Lock()
|
|
|
|
q.items = append(q.items, items...)
|
|
|
|
q.lock.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Pop returns the head of items.
|
2022-03-16 04:10:13 +00:00
|
|
|
func (q *Queue) Pop() any {
|
2019-03-17 06:52:39 +00:00
|
|
|
if len(q.items) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
q.lock.Lock()
|
|
|
|
head := q.items[0]
|
|
|
|
q.items = q.items[1:]
|
|
|
|
q.lock.Unlock()
|
|
|
|
return head
|
|
|
|
}
|
|
|
|
|
2019-09-26 02:08:50 +00:00
|
|
|
// Last returns the last of item.
|
2022-03-16 04:10:13 +00:00
|
|
|
func (q *Queue) Last() any {
|
2019-03-17 06:52:39 +00:00
|
|
|
if len(q.items) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
q.lock.RLock()
|
2019-09-26 02:08:50 +00:00
|
|
|
last := q.items[len(q.items)-1]
|
2019-03-17 06:52:39 +00:00
|
|
|
q.lock.RUnlock()
|
2019-09-26 02:08:50 +00:00
|
|
|
return last
|
2019-03-17 06:52:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Copy get the copy of queue.
|
2022-03-16 04:10:13 +00:00
|
|
|
func (q *Queue) Copy() []any {
|
|
|
|
items := []any{}
|
2019-03-17 06:52:39 +00:00
|
|
|
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{
|
2022-03-16 04:10:13 +00:00
|
|
|
items: make([]any, 0, hint),
|
2019-03-17 06:52:39 +00:00
|
|
|
}
|
|
|
|
}
|