File: queue.go

package info (click to toggle)
golang-github-marstr-collection 2.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 208 kB
  • sloc: makefile: 2
file content (85 lines) | stat: -rw-r--r-- 1,805 bytes parent folder | download
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
85
package collection

import (
	"context"
	"sync"
)

// Queue implements a basic FIFO structure.
type Queue[T any] struct {
	underlyer *LinkedList[T]
	key       sync.RWMutex
}

// NewQueue instantiates a new FIFO structure.
func NewQueue[T any](entries ...T) *Queue[T] {
	retval := &Queue[T]{
		underlyer: NewLinkedList[T](entries...),
	}
	return retval
}

// Add places an item at the back of the Queue.
func (q *Queue[T]) Add(entry T) {
	q.key.Lock()
	defer q.key.Unlock()
	if nil == q.underlyer {
		q.underlyer = NewLinkedList[T]()
	}
	q.underlyer.AddBack(entry)
}

// Enumerate peeks at each element of this queue without mutating it.
func (q *Queue[T]) Enumerate(ctx context.Context) Enumerator[T] {
	q.key.RLock()
	defer q.key.RUnlock()
	return q.underlyer.Enumerate(ctx)
}

// IsEmpty tests the Queue to determine if it is populate or not.
func (q *Queue[T]) 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[T]) 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[T]) Next() (T, bool) {
	q.key.Lock()
	defer q.key.Unlock()
	if q.underlyer == nil {
		return *new(T), false
	}
	return q.underlyer.RemoveFront()
}

// Peek returns the next item in the Queue without removing it.
func (q *Queue[T]) Peek() (T, bool) {
	q.key.RLock()
	defer q.key.RUnlock()
	if q.underlyer == nil {
		return *new(T), false
	}
	return q.underlyer.PeekFront()
}

// ToSlice converts a Queue into a slice.
func (q *Queue[T]) ToSlice() []T {
	q.key.RLock()
	defer q.key.RUnlock()

	if q.underlyer == nil {
		return []T{}
	}
	return q.underlyer.ToSlice()
}