using System.Diagnostics;
using Brutal.Attributes;
using Brutal.Memory;
using Brutal.Pointers;
using Brutal.Pointers.Extensions;
using CommunityToolkit.HighPerformance;
namespace Brutal.Collections;
///
/// A native-memory backed list with no fixed type or stride
///
public sealed class NativeList : INativeList
{
///
/// The default capacity of the array (in elements) when first growing from 0
///
private const int DEFAULT_CAPACITY = 4;
///
/// The capacity of the array (in elements) we can hold without reallocating
///
private ByteSize _byteCapacity;
///
/// The actual number of elements in the array
///
private ByteSize _byteSize;
///
/// Free memory
///
~NativeList()
{
Free();
}
///
public bool IsNull()
{
return Ptr.IsNull();
}
private void _Reallocate(ByteSize byteSize)
{
unsafe
{
if (byteSize == 0)
{
Free();
_byteCapacity = ByteSize.Zero;
_byteSize = ByteSize.Zero;
return;
}
void* oldMem = Ptr;
Ptr = Mem.Alloc(byteSize);
if (oldMem != null)
{
Mem.Copy(oldMem, Ptr, _byteSize);
Mem.Free(oldMem);
}
_byteCapacity = byteSize;
}
}
internal void GrowInternal(ByteSize bytes)
{
Debug.Assert(_byteCapacity < bytes);
var newCapacity = _byteCapacity == 0 ? ByteSize.Of(DEFAULT_CAPACITY) : 2 * _byteCapacity;
// Allow the list to grow to the maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > Array.MaxLength)
newCapacity = ByteSize.Of(Array.MaxLength);
// If the computed capacity is still less than specified, set to the original argument.
// Capacities exceeding Array.MaxLength will be surfaced as OutOfMemoryException by Array.Resize.
if (newCapacity < bytes)
newCapacity = bytes;
Capacity = newCapacity;
}
///
/// Reallocate the array to match the number of elements
///
public void TrimExcess()
{
if (_byteSize != _byteCapacity)
_Reallocate(_byteSize);
}
void INativeList.EnsureCapacity(ElementCount capacity)
{
EnsureCapacity(ByteSize.Of(capacity));
}
///
/// Frees any unmanaged resources.
///
///
/// This function MUST not cause problems if called more than once on the same instance.
/// This class does not implement the Dispose pattern which is fine, but only because
/// Free is able to handle being called from Dispose() and then called from the finaliser.
///
public void Free()
{
Mem.Free(Ptr);
Ptr = null;
_byteCapacity = ByteSize.Zero;
_byteSize = ByteSize.Zero;
}
///
/// Dispose of the resources. This function can be called multiple times safely.
///
public void Dispose()
{
Free();
GC.SuppressFinalize(this);
}
///
public Ptr Ptr { get; private set; }
ElementCount ISpanLike.Length => ElementCount.Of(Size);
ElementCount INativeList.Count
{
get => ElementCount.Of(_byteSize.Bytes);
set => Size = ByteSize.Of(value);
}
ElementCount INativeList.Capacity
{
get => ElementCount.Of(_byteSize.Bytes);
set => Size = ByteSize.Of(value);
}
///
/// The number of elements in the list
///
public ByteSize Size
{
get => new(_byteSize.Bytes);
set
{
if (value == Size)
return;
if (value > Capacity)
GrowInternal(value);
if (value > Size)
{
Mem.Fill(Ptr.Offset(Size), value - Size, 0);
}
_byteSize = value;
}
}
///
/// The capacity of the array
///
/// If the new capacity is less than Count
public ByteSize Capacity
{
get => _byteCapacity;
set
{
if (_byteCapacity == value)
return;
if (value < Size)
{
throw new ArgumentOutOfRangeException(
nameof(value),
"Capacity must be greater than or equal to Count."
);
}
_byteCapacity = value;
_Reallocate(_byteCapacity);
}
}
///
/// Create an untyped native list with a given stride and initial capacity
///
public NativeList(ByteSize initialCapacity = default)
{
Capacity = initialCapacity;
}
///
/// Constructs a new NativeList and copies the contents of the given span
///
public unsafe NativeList(ReadOnlySpan initialData)
{
if (initialData.Length > 0)
{
_byteCapacity = ByteSize.Of(initialData.Length);
_byteSize = ByteSize.Of(initialData.Length);
Ptr = Mem.AllocAndCopy(initialData).AsPointer();
}
}
///
/// Adds any unmanaged type to the list
///
///
/// Does not check for stride, use it with caution
///
/// Unmanaged struct to copy over
/// Data type, size should match the list's size
public void Add(T data)
where T : unmanaged
{
var offset = Size;
var stride = ByteSize.Of();
if (Capacity - Size < stride)
{
GrowInternal(Size == 0 ? ByteSize.Of(DEFAULT_CAPACITY) : Size * 2);
}
_byteSize = _byteSize + stride;
Ptr.Offset(offset).Cast().Value = data;
}
ByteSize ISpanLike.Stride => ByteSize.Zero;
public bool IsEmpty => Size == 0;
[return: Fixed]
public Span AsSpan()
where T : unmanaged
{
return Ptr.AsSpan(ElementCount.Of(Size)).Cast();
}
///
/// Get an element at index as a specific unmanaged type
///
///
/// Does not check for stride, use it with caution
///
/// If the index is out of range
public byte this[int index]
{
get
{
if (index < 0 || index >= (int)Size.Bytes)
throw new IndexOutOfRangeException();
return Ptr.Offset(ByteSize.Of(index)).Cast().Value;
}
set => throw new NotImplementedException();
}
public void AddRange(ReadOnlySpan items)
where T : unmanaged
{
var byteSize = ByteSize.Of(items);
var newCount = Size + byteSize;
if (Capacity < newCount)
GrowInternal(newCount);
Mem.Copy(items, Ptr.Offset(Size).AsSpan(items.Length));
_byteSize += byteSize;
}
public void AddRange(T items)
where T : ISpanLike, allows ref struct
{
var byteSize = ByteSize.Of(items);
var newCount = Size + byteSize;
if (Capacity < newCount)
GrowInternal(newCount);
Mem.Copy(items.AsSpan(), Ptr.Offset(Size).AsSpan(ElementCount.Of(byteSize)));
_byteSize += byteSize;
}
public void Add(byte item)
{
Add(item);
}
public void Insert(ByteSize index, byte item)
{
if (index.Bytes < 0 || index.Bytes > Size)
throw new IndexOutOfRangeException();
if (Size + 1 <= Capacity)
{
Mem.Copy(Ptr.Offset(index), Ptr.Offset(index + 1), Size - index);
Ptr.Offset(index).Cast().Value = item;
}
else
{
var newPtr = Mem.Alloc(Size + 1);
Mem.Copy(Ptr, newPtr, index);
newPtr.Offset(index).Cast().Value = item;
Mem.Copy(Ptr.Offset(index), newPtr.Offset(index + 1), Size - index);
Mem.Free(Ptr);
Ptr = newPtr;
}
}
///
/// Insert an item at the given index, shifting all later elements up
///
public void Insert(ByteSize index, T item)
where T : unmanaged
{
if (index > Size)
throw new IndexOutOfRangeException();
var stride = ByteSize.Of();
if (Size + stride <= Capacity)
{
Mem.Copy(Ptr.Offset(index), Ptr.Offset(index + stride), Size - index);
Ptr.Offset(index).Cast().Value = item;
}
else
{
var newPtr = Mem.Alloc(Size + stride);
Mem.Copy(Ptr, newPtr, index);
newPtr.Offset(index).Cast().Value = item;
Mem.Copy(Ptr.Offset(index), newPtr.Offset(index + stride), Size - index);
Mem.Free(Ptr);
Ptr = newPtr;
}
_byteSize += stride;
}
///
/// Remove a byte at an index, shifting all later elements down
///
public void RemoveAt(ByteSize index)
{
RemoveAt(index, ByteSize.One);
}
///
/// Remove a number of bytes at an index, shifting all later elements down
///
public void RemoveAt(ByteSize index, ByteSize numBytes)
{
if (index >= Size)
throw new IndexOutOfRangeException();
if (index < Size - numBytes)
{
Mem.Copy(Ptr.Offset(index + numBytes), Ptr.Offset(index), Size - index - numBytes);
}
_byteSize -= numBytes;
}
///
/// Clear NativeList and optionally change the element stride.
///
/// If newStride is less than or equal to zero
public void Clear()
{
_byteSize = ByteSize.Zero;
}
///
/// Ensure the list has enough capacity to hold the given number of elements
///
public void EnsureCapacity(ByteSize capacity)
{
if (_byteCapacity < capacity)
GrowInternal(capacity);
}
}