Skip to content

Commit 2e1f1fe

Browse files
committed
Add EnsureCapacity to ArrayPool extensions
1 parent 98f450a commit 2e1f1fe

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

CommunityToolkit.HighPerformance/Extensions/ArrayPoolExtensions.cs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,45 @@ public static void Resize<T>(this ArrayPool<T> pool, [NotNull] ref T[]? array, i
5353

5454
array = newArray;
5555
}
56+
57+
/// <summary>
58+
/// Ensures that when the method returns <paramref name="array"/> is not null and is at least <paramref name="capacity"/> in length.
59+
/// Contents of <paramref name="array"/> are not copied if a new array is rented.
60+
/// </summary>
61+
/// <typeparam name="T">The type of items into the target array given as input.</typeparam>
62+
/// <param name="pool">The target <see cref="ArrayPool{T}"/> instance used to rent and/or return the array.</param>
63+
/// <param name="array">The rented <typeparamref name="T"/> array to ensure capacity for, or <see langword="null"/> to rent a new array.</param>
64+
/// <param name="capacity">The minimum length of <paramref name="array"/> when the method returns.</param>
65+
/// <param name="clearArray">Indicates whether the contents of the array should be cleared if returned to the pool.</param>
66+
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="capacity"/> is less than 0.</exception>
67+
/// <remarks>When this method returns, the caller must not use any references to the old array anymore.</remarks>
68+
public static void EnsureCapacity<T>(this ArrayPool<T> pool, [NotNull] ref T[]? array, int capacity, bool clearArray = false)
69+
{
70+
if (capacity < 0)
71+
{
72+
ThrowArgumentOutOfRangeExceptionForNegativeArrayCapacity();
73+
}
74+
75+
if (array is null)
76+
{
77+
array = pool.Rent(capacity);
78+
}
79+
else if (array.Length < capacity)
80+
{
81+
// Ensure rent succeeds before returning the original array to the pool
82+
T[] newArray = pool.Rent(capacity);
83+
84+
pool.Return(array, clearArray);
85+
86+
array = newArray;
87+
}
88+
}
89+
90+
/// <summary>
91+
/// Throws an <see cref="ArgumentOutOfRangeException"/> when the "capacity" parameter is negative.
92+
/// </summary>
93+
private static void ThrowArgumentOutOfRangeExceptionForNegativeArrayCapacity()
94+
{
95+
throw new ArgumentOutOfRangeException("capacity", "The array capacity must be a positive number.");
96+
}
5697
}

0 commit comments

Comments
 (0)