Skip to content

Commit b535764

Browse files
committed
Add some array extension methods
1 parent 257aa05 commit b535764

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

src/Pooling/PoolingExtensions.cs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
using System;
2+
3+
namespace Oxide.Pooling
4+
{
5+
public static class PoolingExtensions
6+
{
7+
#region Arrays
8+
9+
/// <summary>
10+
/// Copies the source array to a pooled array of the same type
11+
/// </summary>
12+
/// <param name="provider">The pool provider to get the pooled array from</param>
13+
/// <param name="source">The source array containing the <see cref="T"/>'s to copy</param>
14+
/// <param name="offset">The offset to start copying from the source array</param>
15+
/// <param name="count">The total items to copy from the source array</param>
16+
/// <typeparam name="T">The element type of the array</typeparam>
17+
/// <returns>A array of <see cref="T"/> with the length of the total elements copied</returns>
18+
/// <exception cref="System.ArgumentNullException">If the provider or the source array is null</exception>
19+
/// <exception cref="System.IndexOutOfRangeException">If the copy process tries to read outside the bounds of the source array</exception>
20+
public static T[] PooledCopy<T>(this IArrayPoolProvider<T> provider, T[] source, int offset, int count)
21+
{
22+
if (source == null)
23+
{
24+
throw new ArgumentNullException(nameof(source));
25+
}
26+
27+
T[] copy = provider?.Take(count) ?? throw new ArgumentNullException(nameof(provider));
28+
try
29+
{
30+
for (int i = 0; i < copy.Length; i++)
31+
{
32+
copy[i] = source[offset];
33+
offset += 1;
34+
}
35+
36+
return copy;
37+
}
38+
catch
39+
{
40+
provider.Return(copy);
41+
throw;
42+
}
43+
}
44+
45+
/// <summary>
46+
/// Copies the source array to a pooled array of the same type
47+
/// </summary>
48+
/// <param name="factory">The factory to lookup the <see cref="IArrayPoolProvider{T}"/></param>
49+
/// <param name="source">The source array containing the <see cref="T"/>'s to copy</param>
50+
/// <param name="offset">The offset to start copying from the source array</param>
51+
/// <param name="count">The total items to copy from the source array</param>
52+
/// <typeparam name="T">The element type of the array</typeparam>
53+
/// <returns>A array of <see cref="T"/> with the length of the total elements copied</returns>
54+
/// <exception cref="System.ArgumentNullException">factory is null</exception>
55+
public static T[] PooledCopy<T>(this IPoolFactory factory, T[] source, int offset, int count)
56+
{
57+
if (factory == null)
58+
{
59+
throw new ArgumentNullException(nameof(factory));
60+
}
61+
62+
IArrayPoolProvider<T> provider = factory.GetProvider<T[]>() as IArrayPoolProvider<T>;
63+
return PooledCopy(provider, source, offset, count);
64+
}
65+
66+
#endregion
67+
68+
69+
}
70+
}

0 commit comments

Comments
 (0)