namespace Brutal.JoltApi;
///
/// An owned native buffer of objects Jolt stores by value and C# sees as handles - a query's
/// hits, for one. Dispose it when done.
///
///
///
/// The buffer owns its elements, and whatever they reference: a holds a reference to
/// its shape, so the shapes stay alive until the buffer is disposed even if the bodies they came from are gone.
///
///
/// The handles it hands out are borrowed - each points at an element inside the buffer, so never Dispose one, and
/// don't use one after the buffer is disposed.
///
///
/// There is no finalizer, so an undisposed buffer leaks rather than being freed behind a handle that's still in
/// use. Dispose every one, typically with using, and before /
/// , since the block is freed through Jolt's allocator.
///
///
public sealed class NativeHandleArray : IDisposable, INullable
where T : unmanaged
{
private nint _block;
// Read once: data, count and stride are fixed for the life of the block
private readonly nint _data;
private readonly int _length;
private readonly int _stride;
internal unsafe NativeHandleArray(nint block)
{
_block = block;
if (block == 0)
return;
var header = (NativeArrayBlock*)block;
_data = header->Data;
_length = checked((int)header->Count);
_stride = checked((int)header->Stride);
}
/// Whether this is the empty (never allocated, or already disposed) buffer.
public bool IsNull() => _block == 0;
/// The number of elements; 0 once the buffer has been disposed.
public int Length => _block == 0 ? 0 : _length;
/// A borrowed handle onto element .
/// The index is outside the buffer.
public T this[int index] => AsSpan()[index];
/// The elements as borrowed handles, valid until ; empty afterwards.
public NativeHandleSpan AsSpan() => _block == 0 ? default : new NativeHandleSpan(_data, _length, _stride);
/// Walks the elements in order, as borrowed handles.
public NativeHandleSpan.Enumerator GetEnumerator() => AsSpan().GetEnumerator();
/// Frees the buffer and releases what its elements reference. Idempotent.
public void Dispose()
{
var block = Interlocked.Exchange(ref _block, 0);
if (block != 0)
Jolt.PInvoke.NativeArrayDestroy(block);
}
}