ArrayBuilder<T>
Array based collection that tries to avoid copying the internal array and caps the maximum capacity.
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
[NullableContext(1)]
[Nullable(0)]
internal class ArrayBuilder<[Nullable(2)] T>
{
private const int MaxInitialArrayLength = 10240;
private T[] _items;
private readonly int _maxCount;
private int _count;
internal ArrayBuilder(int expectedCount)
{
_items = new T[Math.Min(expectedCount, 10240)];
_maxCount = expectedCount;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(T item)
{
T[] items = _items;
int count = _count;
if ((uint)count < (uint)_items.Length) {
_count = count + 1;
items[count] = item;
} else
AddWithResize(item);
}
private void AddWithResize(T item)
{
if (_items.Length == _maxCount)
throw new ArgumentOutOfRangeException("item", "Collection is at max capacity.");
int count = _count;
int newSize = Math.Min(_maxCount, 2 * _items.Length);
Array.Resize<T>(ref _items, newSize);
_count = count + 1;
_items[count] = item;
}
public T[] ToArray()
{
return _items;
}
}
}