-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.go
More file actions
80 lines (65 loc) · 1.37 KB
/
queue.go
File metadata and controls
80 lines (65 loc) · 1.37 KB
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
package telnet
type queue[T any] struct {
buffer []T
maxSize int
startIndex int
endIndex int
}
func newQueue[T any](size int) *queue[T] {
return &queue[T]{
buffer: make([]T, size),
maxSize: size,
}
}
func (q *queue[T]) straighten() {
if q.startIndex == 0 {
return
}
len := q.endIndex - q.startIndex
if len > 0 {
copy(q.buffer[:len], q.buffer[q.startIndex:q.endIndex])
}
q.startIndex = 0
q.endIndex = len
}
func (q *queue[T]) Queue(elements ...T) {
for i := 0; i < len(elements); i++ {
if q.endIndex < len(q.buffer) {
q.buffer[q.endIndex] = elements[i]
q.endIndex++
continue
}
q.straighten()
if q.endIndex*100/q.maxSize > 80 {
newMaxSize := q.maxSize * 2
newBuffer := make([]T, newMaxSize)
copy(newBuffer, q.buffer)
q.buffer = newBuffer
q.maxSize = newMaxSize
}
i--
}
}
func (q *queue[T]) Dequeue() T {
if q.startIndex == q.endIndex {
var zero T
return zero
}
value := q.buffer[q.startIndex]
q.startIndex++
return value
}
func (q *queue[T]) DropElements(n int) {
newStart := q.startIndex + n
if newStart > q.endIndex {
q.startIndex = q.endIndex
} else {
q.startIndex = newStart
}
}
func (q *queue[T]) Buffer() []T {
return q.buffer[q.startIndex:q.endIndex]
}
func (q *queue[T]) Len() int {
return q.endIndex - q.startIndex
}