-
Notifications
You must be signed in to change notification settings - Fork 8
/
ArrayList.cs
515 lines (428 loc) · 17 KB
/
ArrayList.cs
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Martin Bustos @FronkonGames <fronkongames@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of
// the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace FronkonGames.GameWork.Foundation
{
/// <summary> Generic array-based list. </summary>
public class ArrayList<T> : IEnumerable<T>
{
/// <summary> Number of elements. </summary>
public int Count => size;
/// <summary> Capacity of list. </summary>
public int Capacity => data.Length;
/// <summary> Is empty? </summary>
public bool IsEmpty => Count == 0;
/// <summary> First element in the list. </summary>
public T First
{
get
{
if (IsEmpty == true)
Log.ExceptionArgumentOutOfRange("The list is empty.");
return data[0];
}
}
/// <summary> Last element in the list. </summary>
public T Last
{
get
{
if (IsEmpty == true)
Log.ExceptionIndexOutOfRange("The list is empty.");
return data[Count - 1];
}
}
/// <summary> Gets or sets the item at the specified index. </summary>
public T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (index < 0 || index >= size)
Log.ExceptionIndexOutOfRange($"Index {index} out of size {size}.");
return data[index];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
if (index < 0 || index >= size)
Log.ExceptionIndexOutOfRange($"Index {index} out of size {size}.");
data[index] = value;
}
}
private bool IsMaximumCapacityReached = false;
// http://referencesource.microsoft.com/#mscorlib/system/array.cs,2d2b551eabe74985
private int MaxArrayCapacity => Environment.Is64BitOperatingSystem == true ? 0X7FEFFFFF : 0x8000000;
private const int DefaultCapacity = 8;
private T[] data;
private int size;
private static readonly T[] EmptyArray = new T[0];
/// <summary> Constructor. </summary>
public ArrayList() : this(capacity: 0) { }
/// <summary> Constructor. </summary>
public ArrayList(int capacity)
{
if (capacity < 0)
Log.ExceptionArgumentOutOfRange("Capacity cant be negative.");
data = capacity == 0 ? EmptyArray : new T[capacity];
size = 0;
}
/// <summary> Add item. </summary>
/// <param name="item">Item.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(T item)
{
if (size == data.Length)
EnsureCapacity(size + 1);
data[size++] = item;
}
/// <summary> Adds an collection of items. </summary>
/// <param name="items">Items</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AddRange(IEnumerable<T> items)
{
if (items is null)
Log.ExceptionArgumentNull("Null items.");
int count = items != null ? items.Count() : 0;
if (size + count > MaxArrayCapacity)
throw new OverflowException();
if (count > 0 && items != null)
{
EnsureCapacity(size + count);
foreach (T element in items)
Add(element);
}
}
/// <summary> Inserts a new element at an index. </summary>
/// <param name="index">Index of insertion.</param>
/// <param name="item">Item to insert.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Insert(int index, T item)
{
if (index < 0 || index > size)
Log.ExceptionIndexOutOfRange($"Index {index} out of range [0, {size - 1}].");
if (size == data.Length)
EnsureCapacity(size + 1);
if (index < size)
Array.Copy(data, index, data, index + 1, size - index);
data[index] = item;
size++;
}
/// <summary> Removes a specified item. </summary>
/// <param name="item">Item.</param>
/// <returns>True if removed successfully, false otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Remove(T item)
{
int index = IndexOf(item);
if (index >= 0)
RemoveAt(index);
return index >= 0;
}
/// <summary> Removes item at the specified index. </summary>
/// <param name="index">Index of element.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void RemoveAt(int index)
{
if (index < 0 || index >= size)
Log.ExceptionIndexOutOfRange($"Index {index} out of range [0, {size - 1}].");
size--;
// O(N).
if (index < size)
Array.Copy(data, index + 1, data, index, size - index);
data[size] = default;
}
/// <summary> Clear list. </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear()
{
if (size > 0)
{
size = 0;
Array.Clear(data, 0, size);
data = EmptyArray;
}
}
/// <summary> Resize the List to a new size. </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Resize(int newSize) => Resize(newSize, default);
/// <summary> Resize the list to a new size. </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Resize(int newSize, T defaultValue)
{
int currentSize = Count;
if (newSize < currentSize)
EnsureCapacity(newSize);
else if (newSize > currentSize)
{
if (newSize > data.Length)
EnsureCapacity(newSize + 1);
T[] fill = new T[newSize - currentSize];
Array.Fill(fill, defaultValue);
AddRange(fill);
}
}
/// <summary> Reverses this list. </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reverse() => Reverse(0, size);
/// <summary> Reverses the order of a number of elements. </summary>
/// <param name="start">Start index.</param>
/// <param name="count">Count of elements to reverse.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reverse(int start, int count)
{
if (start < 0 || start >= size)
Log.ExceptionIndexOutOfRange($"Index {start} out of range [0, {size - 1}].");
if (count < 0 || start > (size - count))
Log.ExceptionIndexOutOfRange($"Index {start} out of range [0, {size - 1}].");
// Array.Reverse uses TrySZReverse.
Array.Reverse(data, start, count);
}
/// <summary> For each element in list, apply the specified action to it. </summary>
/// <param name="action">Action.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ForEach(Action<T> action)
{
if (action is null)
Log.ExceptionArgumentNull("Invalid action");
for (int i = 0; i < size; ++i)
action(data[i]);
}
/// <summary> Contains the specified item? </summary>
/// <param name="item">Item.</param>
/// <returns>True if list contains the dataItem, false otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Contains(T item)
{
if (item is null)
{
for (int i = 0; i < size; ++i)
{
if (data[i] is null)
return true;
}
}
else
{
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < size; ++i)
{
if (comparer.Equals(data[i], item))
return true;
}
}
return false;
}
/// <summary> Contains the specified item? </summary>
/// <param name="item">Data item.</param>
/// <param name="comparer">The Equality Comparer object.</param>
/// <returns>True if list contains the item, false otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Contains(T item, IEqualityComparer<T> comparer)
{
if (comparer is null)
Log.ExceptionArgumentNull("Null comparer.");
if (item is null)
{
for (int i = 0; i < size; ++i)
{
if (data[i] is null)
return true;
}
}
else
{
for (int i = 0; i < size; ++i)
{
if (comparer != null && comparer.Equals(data[i], item) == true)
return true;
}
}
return false;
}
/// <summary> Checks whether an item specified via a Predicate<T> function exists in list. </summary>
/// <param name="searchMatch">Match predicate.</param>
/// <returns>True if list contains the item, false otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Exists(Predicate<T> searchMatch) => FindIndex(searchMatch) != -1;
/// <summary> Finds the index of the element that matches the predicate. </summary>
/// <param name="searchMatch">Match predicate.</param>
/// <returns>The index of element if found, -1 otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int FindIndex(Predicate<T> searchMatch) => FindIndex(0, size, searchMatch);
/// <summary> Finds the index of the element that matches the predicate. </summary>
/// <param name="start">Starting index to search from.</param>
/// <param name="searchMatch">Match predicate.</param>
/// <returns>The index of the element if found, -1 otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int FindIndex(int start, Predicate<T> searchMatch) => FindIndex(start, size - start, searchMatch);
/// <summary> Finds the index of the first element that matches the given predicate function. </summary>
/// <param name="start">Starting index of search.</param>
/// <param name="count">Count of elements to search through.</param>
/// <param name="searchMatch">Match predicate function.</param>
/// <returns>The index of element if found, -1 if not found.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int FindIndex(int start, int count, Predicate<T> searchMatch)
{
if (start < 0 || start > size)
Log.ExceptionIndexOutOfRange($"Invalid start index {start}");
if (count < 0 || start > (size - count))
Log.ExceptionArgumentOutOfRange($"Invalid range [{start} - {start + count}]");
if (searchMatch is null)
Log.ExceptionArgumentNull("Invalid searchMach");
int endIndex = start + count;
for (int index = start; index < endIndex; ++index)
{
if (searchMatch(data[index]) == true)
return index;
}
return -1;
}
/// <summary> Returns the index of a item. </summary>
/// <param name="item">Item.</param>
/// <returns>Index of element in list.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int IndexOf(T item) => IndexOf(item, 0, size);
/// <summary> Returns the index of a given dataItem. </summary>
/// <param name="item">Item.</param>
/// <param name="start">The starting index to search from.</param>
/// <returns>Index of element in list.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int IndexOf(T item, int start) => IndexOf(item, start, size);
/// <summary> Returns the index of a given item. </summary>
/// <param name="item">Data item.</param>
/// <param name="start">The starting index to search from.</param>
/// <param name="count">Count of elements to search through.</param>
/// <returns>Index of element in list.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int IndexOf(T item, int start, int count)
{
if (start < 0 || (uint)start > (uint)size)
Log.ExceptionIndexOutOfRange($"Invalid starting index {start}");
if (count < 0 || start > (size - count))
Log.ExceptionArgumentOutOfRange($"Invalid range [{start} - {start + count}]");
return Array.IndexOf(data, item, start, count);
}
/// <summary> Find the specified element that matches the search predication. </summary>
/// <param name="searchMatch">Match predicate.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Find(Predicate<T> searchMatch)
{
if (searchMatch is null)
Log.ExceptionArgumentNull("Invalid searchMatch");
for (int i = 0; i < size; ++i)
{
if (searchMatch(data[i]) == true)
return data[i];
}
return default;
}
/// <summary> Finds all the elements that match the typed search predicate. </summary>
/// <param name="searchMatch">Match predicate.</param>
/// <returns>ArrayList<T> of matched elements. Empty list is returned if not element was found.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ArrayList<T> FindAll(Predicate<T> searchMatch)
{
if (searchMatch is null)
Log.ExceptionArgumentNull("Invalid searchMatch");
ArrayList<T> matchedElements = new();
for (int i = 0; i < size; ++i)
{
if (searchMatch(data[i]))
matchedElements.Add(data[i]);
}
return matchedElements;
}
/// <summary> Get a range of elements, starting from an index. </summary>
/// <param name="start">Start index to get range from.</param>
/// <param name="count">Count of elements.</param>
/// <returns>The range as ArrayList<T>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ArrayList<T> GetRange(int start, int count)
{
if (start < 0 || (uint)start > (uint)size)
Log.ExceptionIndexOutOfRange($"Invalid starting index {start}");
if (count < 0 || start > (size - count))
Log.ExceptionArgumentOutOfRange($"Invalid range [{start} - {start + count}]");
ArrayList<T> newArrayList = new(count);
Array.Copy(data, start, newArrayList.data, 0, count);
newArrayList.size = count;
return newArrayList;
}
/// <summary> Return an array version of this list. </summary>
/// <returns>Array.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T[] ToArray()
{
T[] newArray = new T[Count];
if (Count > 0)
Array.Copy(data, 0, newArray, 0, Count);
return newArray;
}
/// <summary> Return an array version of this list. </summary>
/// <returns>Array.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public List<T> ToList()
{
List<T> newList = new(Count);
if (Count > 0)
{
for (int i = 0; i < Count; ++i)
newList.Add(data[i]);
}
return newList;
}
/// <summary> Return a human readable string. </summary>
/// <returns>The human readable string.</returns>
public override string ToString() => string.Join(",", data);
/// <summary> Ensures the capacity. </summary>
/// <param name="minCapacity">Minimum capacity.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCapacity(int minCapacity)
{
if (data.Length < minCapacity && IsMaximumCapacityReached == false)
{
int newCapacity = data.Length == 0 ? DefaultCapacity : data.Length * 2;
int maxCapacity = MaxArrayCapacity;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
if (newCapacity >= maxCapacity)
{
newCapacity = maxCapacity - 1;
IsMaximumCapacityReached = true;
}
ResizeCapacity(newCapacity);
}
}
/// <summary> Resizes the collection to a new maximum number of capacity. </summary>
/// <param name="newCapacity">New capacity.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ResizeCapacity(int newCapacity)
{
if (newCapacity != data.Length && newCapacity > size)
Array.Resize<T>(ref data, newCapacity);
}
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < Count; ++i)
yield return data[i];
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
}