forked from Unity-Technologies/com.unity.netcode.gameobjects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFixedQueue.cs
More file actions
78 lines (71 loc) · 2.24 KB
/
Copy pathFixedQueue.cs
File metadata and controls
78 lines (71 loc) · 2.24 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
using System;
namespace MLAPI.Collections
{
/// <summary>
/// Queue with a fixed size
/// </summary>
/// <typeparam name="T">The type of the queue</typeparam>
public sealed class FixedQueue<T>
{
private readonly T[] queue;
private int queueCount = 0;
private int queueStart;
/// <summary>
/// The amount of enqueued objects
/// </summary>
public int Count { get => queueCount; }
/// <summary>
/// Gets the element at a given virtual index
/// </summary>
/// <param name="index">The virtual index to get the item from</param>
/// <returns>The element at the virtual index</returns>
public T this[int index]
{
get
{
return queue[(queueStart + index) % queue.Length];
}
}
/// <summary>
/// Creates a new FixedQueue with a given size
/// </summary>
/// <param name="maxSize">The size of the queue</param>
public FixedQueue(int maxSize)
{
queue = new T[maxSize];
queueStart = 0;
}
/// <summary>
/// Enqueues an object
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public bool Enqueue(T t)
{
queue[(queueStart + queueCount) % queue.Length] = t;
if (++queueCount > queue.Length)
{
--queueCount;
return true;
}
return false;
}
/// <summary>
/// Dequeues an object
/// </summary>
/// <returns></returns>
public T Dequeue()
{
if (--queueCount == -1) throw new IndexOutOfRangeException("Cannot dequeue empty queue!");
T res = queue[queueStart];
queueStart = (queueStart + 1) % queue.Length;
return res;
}
/// <summary>
/// Gets the element at a given virtual index
/// </summary>
/// <param name="index">The virtual index to get the item from</param>
/// <returns>The element at the virtual index</returns>
public T ElementAt(int index) => queue[(queueStart + index) % queue.Length];
}
}