1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
package collection
import (
"sync"
)
// Queue implements a basic FIFO structure.
type Queue struct {
underlyer *LinkedList
key sync.RWMutex
}
// NewQueue instantiates a new FIFO structure.
func NewQueue(entries ...interface{}) *Queue {
retval := &Queue{
underlyer: NewLinkedList(entries...),
}
return retval
}
// Add places an item at the back of the Queue.
func (q *Queue) Add(entry interface{}) {
q.key.Lock()
defer q.key.Unlock()
if nil == q.underlyer {
q.underlyer = NewLinkedList()
}
q.underlyer.AddBack(entry)
}
// Enumerate peeks at each element of this queue without mutating it.
func (q *Queue) Enumerate(cancel <-chan struct{}) Enumerator {
q.key.RLock()
defer q.key.RUnlock()
return q.underlyer.Enumerate(cancel)
}
// IsEmpty tests the Queue to determine if it is populate or not.
func (q *Queue) IsEmpty() bool {
q.key.RLock()
defer q.key.RUnlock()
return q.underlyer == nil || q.underlyer.IsEmpty()
}
// Length returns the number of items in the Queue.
func (q *Queue) Length() uint {
q.key.RLock()
defer q.key.RUnlock()
if nil == q.underlyer {
return 0
}
return q.underlyer.length
}
// Next removes and returns the next item in the Queue.
func (q *Queue) Next() (interface{}, bool) {
q.key.Lock()
defer q.key.Unlock()
if q.underlyer == nil {
return nil, false
}
return q.underlyer.RemoveFront()
}
// Peek returns the next item in the Queue without removing it.
func (q *Queue) Peek() (interface{}, bool) {
q.key.RLock()
defer q.key.RUnlock()
if q.underlyer == nil {
return nil, false
}
return q.underlyer.PeekFront()
}
// ToSlice converts a Queue into a slice.
func (q *Queue) ToSlice() []interface{} {
q.key.RLock()
defer q.key.RUnlock()
if q.underlyer == nil {
return []interface{}{}
}
return q.underlyer.ToSlice()
}
|