using Misaki.HighPerformance.Collections;
using System.Runtime.CompilerServices;
namespace Misaki.HighPerformance.Jobs;
///
/// This class manages pools of job data for different types. It allows allocating, retrieving, and freeing job data instances using unique IDs and generations to ensure safe access and reuse of resources.
///
public static class JobDataPool
where T : struct
{
private static readonly ConcurrentSlotMap s_slots = new ConcurrentSlotMap(8);
///
/// Allocates a new instance of type T in the pool and returns its ID and generation.
///
/// The type of the data to allocate.
/// The data to allocate.
/// The generation of the allocated data.
/// The ID of the allocated data.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Allocate(ref readonly T data, out int generation)
{
return s_slots.Add(data, out generation);
}
///
/// Gets a reference to the data of type T associated with the given ID and generation. The 'exists' output parameter indicates whether the data exists in the pool.
///
/// The type of the data to retrieve.
/// The ID of the data to retrieve.
/// The generation of the data to retrieve.
/// A value indicating whether the data exists in the pool.
/// A reference to the requested data. Undefined if 'exists' is false.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T GetReference(int id, int generation, out bool exists)
{
return ref s_slots.GetElementReferenceAt(id, generation, out exists);
}
///
/// Frees the data of type T associated with the given ID and generation, making it available for future allocations. After calling this method, the ID and generation can be reused for new data.
///
/// The type of the data to free.
/// The ID of the data to free.
/// The generation of the data to free.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Free(int id, int generation)
{
s_slots.Remove(id, generation);
}
}