-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathFastStack.cs
More file actions
101 lines (87 loc) · 1.95 KB
/
FastStack.cs
File metadata and controls
101 lines (87 loc) · 1.95 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
using System.Collections;
using System;
namespace FastCollections
{
public class FastStack<T>
{
private const int DefaultCapacity = 8;
public T[] innerArray;
public int Count = 0;
public int Capacity;
public FastStack (int StartCapacity)
{
Capacity = StartCapacity;
Initialize ();
}
public FastStack ()
{
Capacity = DefaultCapacity;
Initialize ();
}
private void Initialize ()
{
#if UNITY_EDITOR
if (Capacity <= 0)
{
UnityEngine.Debug.LogError ("Initializing list with capacity less than or equal to zero isn't supported");
}
#endif
innerArray = new T[Capacity];
}
public void Add (T item)
{
EnsureCapacity ();
innerArray [Count++] = item;
}
public T Pop ()
{
return (innerArray[--Count]);
}
public T Peek ()
{
return innerArray[Count - 1];
}
private void EnsureCapacity ()
{
EnsureCapacity (Count + 1);
}
public void EnsureCapacity (int min) {
if (Capacity < min) {
Capacity *= 2;
if (Capacity < min)
Capacity = min;
T[] newItems = new T[Capacity];
Array.Copy (innerArray, 0, newItems, 0, Count);
innerArray = newItems;
}
}
public T this [int index] {
get {
return innerArray [index];
}
set {
innerArray [index] = value;
}
}
public void Clear ()
{
innerArray = new T[Capacity];
}
/// <summary>
/// Marks elements for overwriting. Note: After using FastClear(), this list will still keep any references to objects it previously had.
/// </summary>
public void FastClear ()
{
Count = 0;
}
public override string ToString ()
{
if (Count <= 0)
return base.ToString ();
string output = string.Empty;
for (int i = 0; i < Count - 1; i++)
output += innerArray [i] + ", ";
return base.ToString () + ": " + output + innerArray [Count - 1];
}
}
}