Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,43 @@ public int EnsureCapacity(int capacity)
/// </summary>
/// <param name="capacity">The minimum capacity to ensure.</param>
internal void Grow(int capacity)
{
Capacity = GetNewCapacity(capacity);
}

/// <summary>
/// Enlarge this list so it may contain at least <paramref name="insertionCount"/> more elements
/// And copy data to their after-insertion positions.
/// This method is specifically for insertion, as it avoids 1 extra array copy.
/// You should only call this method when Count + insertionCount > Capacity.
/// </summary>
/// <param name="indexToInsert">Index of the first insertion.</param>
/// <param name="insertionCount">How many elements will be inserted.</param>
private void GrowForInsertion(int indexToInsert, int insertionCount = 1)
{
Debug.Assert(insertionCount > 0);

int requiredCapacity = checked(_size + insertionCount);
int newCapacity = GetNewCapacity(requiredCapacity);

// Inline and adapt logic from set_Capacity

T[] newItems = new T[newCapacity];
if (indexToInsert != 0)
{
Array.Copy(_items, newItems, length: indexToInsert);
}

if (_size != indexToInsert)
{
Array.Copy(_items, indexToInsert, newItems, indexToInsert + insertionCount, _size - indexToInsert);
}

_items = newItems;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int GetNewCapacity(int capacity)
{
Debug.Assert(_items.Length < capacity);

Expand All @@ -462,7 +499,7 @@ internal void Grow(int capacity)
// Capacities exceeding Array.MaxLength will be surfaced as OutOfMemoryException by Array.Resize.
if (newCapacity < capacity) newCapacity = capacity;

Capacity = newCapacity;
return newCapacity;
}

public bool Exists(Predicate<T> match)
Expand Down Expand Up @@ -737,8 +774,11 @@ public void Insert(int index, T item)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);
}
if (_size == _items.Length) Grow(_size + 1);
if (index < _size)
if (_size == _items.Length)
{
GrowForInsertion(index, 1);
}
else if (index < _size)
{
Array.Copy(_items, index, _items, index + 1, _size - index);
}
Expand Down Expand Up @@ -785,9 +825,9 @@ public void InsertRange(int index, IEnumerable<T> collection)
{
if (_items.Length - _size < count)
{
Grow(checked(_size + count));
GrowForInsertion(index, count);
}
if (index < _size)
else if (index < _size)
{
Array.Copy(_items, index, _items, index + count, _size - index);
}
Expand Down