using System;
using System.Buffers;
namespace Ryujinx.Common.Memory
{
///
/// Provides a pool of re-usable byte array instances.
///
public sealed partial class ByteMemoryPool
{
private static readonly ByteMemoryPool _shared = new();
///
/// Constructs a instance. Private to force access through
/// the instance.
///
private ByteMemoryPool()
{
// No implementation
}
///
/// Retrieves a shared instance.
///
public static ByteMemoryPool Shared => _shared;
///
/// Returns the maximum buffer size supported by this pool.
///
public static int MaxBufferSize => Array.MaxLength;
///
/// Rents a byte memory buffer from .
/// The buffer may contain data from a prior use.
///
/// The buffer's required length in bytes
/// A wrapping the rented memory
///
public static IMemoryOwner Rent(long length)
=> RentImpl(checked((int)length));
///
/// Rents a byte memory buffer from .
/// The buffer may contain data from a prior use.
///
/// The buffer's required length in bytes
/// A wrapping the rented memory
///
public static IMemoryOwner Rent(ulong length)
=> RentImpl(checked((int)length));
///
/// Rents a byte memory buffer from .
/// The buffer may contain data from a prior use.
///
/// The buffer's required length in bytes
/// A wrapping the rented memory
///
public static IMemoryOwner Rent(int length)
=> RentImpl(length);
///
/// Rents a byte memory buffer from .
/// The buffer's contents are cleared (set to all 0s) before returning.
///
/// The buffer's required length in bytes
/// A wrapping the rented memory
///
public static IMemoryOwner RentCleared(long length)
=> RentCleared(checked((int)length));
///
/// Rents a byte memory buffer from .
/// The buffer's contents are cleared (set to all 0s) before returning.
///
/// The buffer's required length in bytes
/// A wrapping the rented memory
///
public static IMemoryOwner RentCleared(ulong length)
=> RentCleared(checked((int)length));
///
/// Rents a byte memory buffer from .
/// The buffer's contents are cleared (set to all 0s) before returning.
///
/// The buffer's required length in bytes
/// A wrapping the rented memory
///
public static IMemoryOwner RentCleared(int length)
{
var buffer = RentImpl(length);
buffer.Memory.Span.Clear();
return buffer;
}
private static ByteMemoryPoolBuffer RentImpl(int length)
{
if ((uint)length > Array.MaxLength)
{
throw new ArgumentOutOfRangeException(nameof(length), length, null);
}
return new ByteMemoryPoolBuffer(length);
}
}
}