using System.Buffers;
namespace GFramework.Core.Extensions;
///
/// ArrayPool 扩展方法,提供更便捷的数组池操作
///
public static class ArrayPoolExtensions
{
///
/// 从数组池中租用数组
///
/// 数组元素类型
/// 数组池实例
/// 最小长度
/// 租用的数组
///
///
/// var pool = ArrayPool<int>.Shared;
/// var array = pool.RentArray(100);
/// try
/// {
/// // 使用数组
/// }
/// finally
/// {
/// pool.ReturnArray(array);
/// }
///
///
public static T[] RentArray(this ArrayPool pool, int minimumLength)
{
ArgumentNullException.ThrowIfNull(pool);
return pool.Rent(minimumLength);
}
///
/// 将数组归还到数组池
///
/// 数组元素类型
/// 数组池实例
/// 要归还的数组
/// 是否清空数组内容
///
///
/// var pool = ArrayPool<int>.Shared;
/// var array = pool.RentArray(100);
/// try
/// {
/// // 使用数组
/// }
/// finally
/// {
/// pool.ReturnArray(array, clearArray: true);
/// }
///
///
public static void ReturnArray(this ArrayPool pool, T[] array, bool clearArray = false)
{
ArgumentNullException.ThrowIfNull(pool);
ArgumentNullException.ThrowIfNull(array);
pool.Return(array, clearArray);
}
///
/// 获取一个作用域数组,使用完后自动归还
///
/// 数组元素类型
/// 数组池实例
/// 最小长度
/// 归还时是否清空数组
/// 可自动释放的数组包装器
///
///
/// var pool = ArrayPool<int>.Shared;
/// using var scopedArray = pool.GetScoped(100);
/// var array = scopedArray.Array;
/// // 使用数组
/// // 自动归还
///
///
public static ScopedArray GetScoped(this ArrayPool pool, int minimumLength, bool clearOnReturn = false)
{
ArgumentNullException.ThrowIfNull(pool);
return new ScopedArray(pool, minimumLength, clearOnReturn);
}
///
/// 可自动释放的数组包装器
///
/// 数组元素类型
public readonly struct ScopedArray : IDisposable
{
private readonly ArrayPool _pool;
private readonly bool _clearOnReturn;
///
/// 获取租用的数组
///
public T[] Array { get; }
///
/// 获取数组的长度
///
public int Length => Array.Length;
internal ScopedArray(ArrayPool pool, int minimumLength, bool clearOnReturn)
{
_pool = pool;
_clearOnReturn = clearOnReturn;
Array = pool.Rent(minimumLength);
}
///
/// 释放数组并归还到池中
///
public void Dispose()
{
_pool.Return(Array, _clearOnReturn);
}
///
/// 获取数组的 Span 视图
///
/// 数组的 Span
public Span AsSpan() => Array.AsSpan();
///
/// 获取数组指定范围的 Span 视图
///
/// 起始索引
/// 长度
/// 数组指定范围的 Span
public Span AsSpan(int start, int length) => Array.AsSpan(start, length);
}
}