-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathFastQueue.cs
More file actions
106 lines (94 loc) · 3.12 KB
/
FastQueue.cs
File metadata and controls
106 lines (94 loc) · 3.12 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
namespace FastCollections
{
public class FastQueue<T> {
private T[] innerArray;
private int head;
private int tail;
public int Count { get; private set; }
public int Capacity { get; private set; }
public FastQueue()
: this(8) {}
public FastQueue(int capacity) {
Capacity = capacity;
head = 0;
tail = 0;
Count = 0;
innerArray = new T[Capacity];
}
public void Add(T item) {
if (tail == head) {
SetCapacity(Count + 1);
}
innerArray[tail++] = item;
if (tail == Capacity) {
tail = 0;
}
Count++;
}
public T Pop() {
T ret = innerArray[head];
innerArray[head] = default(T);
head++;
if (head == Capacity) {
head = 0;
}
Count--;
return ret;
}
public void Remove () {
innerArray[head] = default(T);
head++;
if (head == Capacity) {
head = 0;
}
Count--;
}
public T Peek () {
return innerArray[head];
}
public T PeekTail () {
int tailIndex = tail - 1;
if (tailIndex < 0) tailIndex = this.Capacity - 1;
return innerArray[tailIndex];
}
public void SetCapacity(int min) {
if (Capacity < min) {
int prevLength = Capacity;
Capacity *= 2;
if (Capacity < min) {
Capacity = min;
}
var newArray = new T[Capacity];
if (tail > head) { // If we are not wrapped around...
Array.Copy(innerArray, head, newArray, 0, Count); // ...take from head to head+Count and copy to beginning of new array
} else if (Count > 0) { // Else if we are wrapped around... (tail == head is ambiguous - could be an empty buffer or a full one)
Array.Copy(innerArray, head, newArray, 0, prevLength - head); // ...take head to end and copy to beginning of new array
Array.Copy(innerArray, 0, newArray, prevLength - head, tail); // ...take beginning to tail and copy after previously copied elements
}
head = 0;
tail = Count;
innerArray = newArray;
}
}
public void FullClear () {
Shortcuts.ClearArray(innerArray);
FastClear();
}
public void FastClear() {
Count = 0;
tail = 0;
head = 0;
}
public T[] ToArray() {
var result = new T[Count];
if (tail > head) {
Array.Copy(innerArray, head, result, 0, Count);
} else if (Count > 0) {
Array.Copy(innerArray, head, result, 0, Capacity - head);
Array.Copy(innerArray, 0, result, Capacity - head, tail);
}
return result;
}
}
}