This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit b578433e37
5 changed files with 784842 additions and 0 deletions

View file

@ -0,0 +1,69 @@
using Brutal.Memory;
namespace Brutal.Collections;
/// <summary>
/// Base class for native-memory backed lists
/// </summary>
public interface INativeList : ISpanLike, IDisposable
{
public ElementCount Count { get; set; }
public ElementCount Capacity { get; set; }
/// <summary>
/// Matching C# List's Clear(), zeroes count but preserves capacity
/// </summary>
public void Clear();
/// <summary>
/// Set the capacity to the actual number of elements in the list, if the current
/// </summary>
public void TrimExcess();
/// <summary>
/// Increase the capacity of the vector (the total number of elements that the vector can hold without requiring
/// reallocation) to a value that's greater or equal to newCapacity. If new_cap is greater than the current
/// Capacity, new storage is then allocated; otherwise the function does nothing.
/// </summary>
/// <param name="capacity">The new max size</param>
public void EnsureCapacity(ElementCount capacity);
/// <summary>
/// Reset the array and free memory
/// </summary>
public void Free();
}
public interface INativeList<T> : INativeList, ISpanLike<T>, IEnumerable<T>
where T : unmanaged
{
/// <summary>
/// Get or set an element at an index
/// </summary>
public ref T this[Index index] { get; }
/// <summary>
/// Add an element to the end of the list
/// </summary>
/// <param name="item">The item to add</param>
public void Add(T item);
/// <summary>
/// Add a range of elements to the end of the list
/// </summary>
/// <param name="items">The items to add</param>
public void AddRange(ReadOnlySpan<T> items);
/// <summary>
/// Insert an element at an index, shifting all later elements up by one
/// </summary>
/// <param name="index">The index to insert at</param>
/// <param name="item">The item to insert</param>
public void Insert(ElementCount index, T item);
/// <summary>
/// Remove an element at an index, shifting all later elements down by one
/// </summary>
/// <param name="index">The index to remove at</param>
public void RemoveAt(ElementCount index);
}

View file

@ -0,0 +1,380 @@
using System.Diagnostics;
using Brutal.Attributes;
using Brutal.Memory;
using Brutal.Pointers;
using Brutal.Pointers.Extensions;
using CommunityToolkit.HighPerformance;
namespace Brutal.Collections;
/// <summary>
/// A native-memory backed list with no fixed type or stride
/// </summary>
public sealed class NativeList : INativeList
{
/// <summary>
/// The default capacity of the array (in elements) when first growing from 0
/// </summary>
private const int DEFAULT_CAPACITY = 4;
/// <summary>
/// The capacity of the array (in elements) we can hold without reallocating
/// </summary>
private ByteSize _byteCapacity;
/// <summary>
/// The actual number of elements in the array
/// </summary>
private ByteSize _byteSize;
/// <summary>
/// Free memory
/// </summary>
~NativeList()
{
Free();
}
/// <inheritdoc />
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;
}
/// <summary>
/// Reallocate the array to match the number of elements
/// </summary>
public void TrimExcess()
{
if (_byteSize != _byteCapacity)
_Reallocate(_byteSize);
}
void INativeList.EnsureCapacity(ElementCount capacity)
{
EnsureCapacity(ByteSize.Of(capacity));
}
/// <summary>
/// Frees any unmanaged resources.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public void Free()
{
Mem.Free(Ptr);
Ptr = null;
_byteCapacity = ByteSize.Zero;
_byteSize = ByteSize.Zero;
}
/// <summary>
/// Dispose of the resources. This function can be called multiple times safely.
/// </summary>
public void Dispose()
{
Free();
GC.SuppressFinalize(this);
}
/// <inheritdoc />
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);
}
/// <summary>
/// The number of elements in the list
/// </summary>
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;
}
}
/// <summary>
/// The capacity of the array
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">If the new capacity is less than Count</exception>
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);
}
}
/// <summary>
/// Create an untyped native list with a given stride and initial capacity
/// </summary>
public NativeList(ByteSize initialCapacity = default)
{
Capacity = initialCapacity;
}
/// <summary>
/// Constructs a new NativeList and copies the contents of the given span
/// </summary>
public unsafe NativeList(ReadOnlySpan<byte> initialData)
{
if (initialData.Length > 0)
{
_byteCapacity = ByteSize.Of(initialData.Length);
_byteSize = ByteSize.Of(initialData.Length);
Ptr = Mem.AllocAndCopy(initialData).AsPointer();
}
}
/// <summary>
/// Adds any unmanaged type to the list
/// </summary>
/// <remarks>
/// Does not check for stride, use it with caution
/// </remarks>
/// <param name="data">Unmanaged struct to copy over</param>
/// <typeparam name="T">Data type, size should match the list's size</typeparam>
public void Add<T>(T data)
where T : unmanaged
{
var offset = Size;
var stride = ByteSize.Of<T>();
if (Capacity - Size < stride)
{
GrowInternal(Size == 0 ? ByteSize.Of<T>(DEFAULT_CAPACITY) : Size * 2);
}
_byteSize = _byteSize + stride;
Ptr.Offset(offset).Cast<T>().Value = data;
}
ByteSize ISpanLike.Stride => ByteSize.Zero;
public bool IsEmpty => Size == 0;
[return: Fixed]
public Span<T> AsSpan<T>()
where T : unmanaged
{
return Ptr.AsSpan<byte>(ElementCount.Of(Size)).Cast<byte, T>();
}
/// <summary>
/// Get an element at index as a specific unmanaged type
/// </summary>
/// <remarks>
/// Does not check for stride, use it with caution
/// </remarks>
/// <exception cref="IndexOutOfRangeException">If the index is out of range</exception>
public byte this[int index]
{
get
{
if (index < 0 || index >= (int)Size.Bytes)
throw new IndexOutOfRangeException();
return Ptr.Offset(ByteSize.Of(index)).Cast<byte>().Value;
}
set => throw new NotImplementedException();
}
public void AddRange<T>(ReadOnlySpan<T> 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<T>(items.Length));
_byteSize += byteSize;
}
public void AddRange<T>(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<byte>(), Ptr.Offset(Size).AsSpan<byte>(ElementCount.Of(byteSize)));
_byteSize += byteSize;
}
public void Add(byte item)
{
Add<byte>(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<byte>().Value = item;
}
else
{
var newPtr = Mem.Alloc(Size + 1);
Mem.Copy(Ptr, newPtr, index);
newPtr.Offset(index).Cast<byte>().Value = item;
Mem.Copy(Ptr.Offset(index), newPtr.Offset(index + 1), Size - index);
Mem.Free(Ptr);
Ptr = newPtr;
}
}
/// <summary>
/// Insert an item at the given index, shifting all later elements up
/// </summary>
public void Insert<T>(ByteSize index, T item)
where T : unmanaged
{
if (index > Size)
throw new IndexOutOfRangeException();
var stride = ByteSize.Of<T>();
if (Size + stride <= Capacity)
{
Mem.Copy(Ptr.Offset(index), Ptr.Offset(index + stride), Size - index);
Ptr.Offset(index).Cast<T>().Value = item;
}
else
{
var newPtr = Mem.Alloc(Size + stride);
Mem.Copy(Ptr, newPtr, index);
newPtr.Offset(index).Cast<T>().Value = item;
Mem.Copy(Ptr.Offset(index), newPtr.Offset(index + stride), Size - index);
Mem.Free(Ptr);
Ptr = newPtr;
}
_byteSize += stride;
}
/// <summary>
/// Remove a byte at an index, shifting all later elements down
/// </summary>
public void RemoveAt(ByteSize index)
{
RemoveAt(index, ByteSize.One);
}
/// <summary>
/// Remove a number of bytes at an index, shifting all later elements down
/// </summary>
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;
}
/// <summary>
/// Clear NativeList and optionally change the element stride.
/// </summary>
/// <exception cref="DivideByZeroException">If newStride is less than or equal to zero</exception>
public void Clear()
{
_byteSize = ByteSize.Zero;
}
/// <summary>
/// Ensure the list has enough capacity to hold the given number of elements
/// </summary>
public void EnsureCapacity(ByteSize capacity)
{
if (_byteCapacity < capacity)
GrowInternal(capacity);
}
}

View file

@ -0,0 +1,53 @@
using System.Collections;
namespace Brutal.Collections;
/// <summary>
/// Enumerator class for generic NativeList
/// </summary>
public struct NativeListEnumerator<T> : IEnumerator<T>
where T : unmanaged
{
private readonly NativeList<T> _list;
private int _index;
/// <summary>
/// Construct enumerator from the list
/// </summary>
/// <param name="list">Source list</param>
public NativeListEnumerator(NativeList<T> list)
{
_list = list;
_index = -1;
}
/// <summary>
/// Iterate next element
/// </summary>
/// <returns>True if enumerator still running</returns>
public bool MoveNext()
{
_index++;
return _index < _list.Count;
}
/// <summary>
/// Reset enumerator
/// </summary>
public void Reset()
{
_index = -1;
}
/// <summary>
/// Index enumerator
/// </summary>
public T Current => _list[_index];
object IEnumerator.Current => Current;
/// <summary>
/// Dispose of enumerator
/// </summary>
public void Dispose() { }
}

View file

@ -0,0 +1,178 @@
using System.Collections;
using Brutal.Attributes;
using Brutal.Memory;
using Brutal.Pointers;
namespace Brutal.Collections;
/// <summary>
/// A native-memory backed list with a fixed type
/// </summary>
/// <typeparam name="TValueType">Element type</typeparam>
public class NativeList<TValueType> : INativeList<TValueType>
where TValueType : unmanaged
{
~NativeList()
{
Dispose();
}
private readonly NativeStrideList _nativeList;
public NativeList(ElementCount capacity = default)
{
_nativeList = new NativeStrideList(Stride, capacity);
}
public NativeList(ReadOnlySpan<TValueType> nativeList)
{
_nativeList = NativeStrideList.FromSpan(Stride, nativeList);
}
public void Dispose()
{
_nativeList.Dispose();
GC.SuppressFinalize(this);
}
public bool IsNull()
{
return _nativeList.IsNull();
}
public ByteSize Stride => ByteSize.Of<TValueType>();
public bool IsEmpty => Count == 0;
public ref TValueType this[Index index]
{
get
{
var actualIndex = index.GetOffset(Count);
return ref _nativeList.AsSpan<TValueType>()[actualIndex];
}
}
public void Add(TValueType item)
{
_nativeList.Add(item);
}
public void AddRange(Span<TValueType> items)
{
_nativeList.AddRange(items);
}
public void AddRange(ReadOnlySpan<TValueType> items)
{
_nativeList.AddRange(items);
}
/// <summary>
/// Adds a range of bytes to the end of the list. The length of items must be a multiple of stride
/// </summary>
public void AddRange<T>(T items)
where T : ISpanLike<TValueType>
{
_nativeList.AddRange(items.AsSpan());
}
public void Insert(ElementCount index, TValueType item)
{
_nativeList.Insert(index, item);
}
public void RemoveAt(ElementCount index)
{
_nativeList.RemoveAt<TValueType>(index);
}
public Ptr<TValueType> Ptr => _nativeList.Ptr.Cast<TValueType>();
Ptr ISpanLike.Ptr => Ptr;
ElementCount ISpanLike.Length => Count;
public ElementCount Count
{
get => _nativeList.Count;
set => _nativeList.Count = value;
}
public ElementCount Capacity
{
get => _nativeList.Capacity;
set => _nativeList.Capacity = value;
}
public void Clear()
{
_nativeList.Clear();
}
public void TrimExcess()
{
_nativeList.TrimExcess();
}
public void EnsureCapacity(ElementCount capacity)
{
_nativeList.EnsureCapacity(capacity);
}
public void Free()
{
_nativeList.Free();
}
public IEnumerator<TValueType> GetEnumerator()
{
for (var i = 0; i < Count; ++i)
yield return this[i];
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public Span<TValueType> Slice(ElementCount start, ElementCount length)
{
return AsSpan().Slice(start, length);
}
public Span<TValueType> Slice(ElementCount start)
{
return AsSpan()[(int)start..];
}
[Fixed]
public Span<TValueType> this[Range range] => AsSpan()[range];
[return: Fixed]
public Span<TValueType> AsSpan()
{
return _nativeList.AsSpan<TValueType>();
}
Span<TCastType> ISpanLike.AsSpan<TCastType>()
{
return _nativeList.AsSpan<TCastType>();
}
public NativeStrideSpan AsNativeSpan()
{
return new NativeStrideSpan(Ptr, Count, Stride);
}
protected virtual void Dispose(bool isDisposing)
{
if (!isDisposing)
return;
_nativeList.Dispose();
}
public ref TValueType GetPinnableReference()
{
return ref this[0];
}
}

View file

@ -0,0 +1,253 @@
using Brutal.Attributes;
using Brutal.Memory;
using Brutal.Pointers;
namespace Brutal.Collections;
/// <summary>
/// A native-memory backed list with a fixed stride
/// </summary>
public class NativeStrideList : INativeList
{
~NativeStrideList()
{
Dispose(false);
}
private readonly NativeList _nativeList;
/// <summary>
/// The size of each element in bytes
/// </summary>
public ByteSize Stride { get; }
public bool IsEmpty => Count == 0;
/// <summary>
/// A raw pointer to the underlying memory
/// </summary>
public Ptr Ptr => _nativeList.Ptr;
ElementCount ISpanLike.Length => Count;
/// <summary>
/// The number of elements in the list
/// </summary>
public ElementCount Count
{
get => _nativeList.Size.ToElementCount(Stride);
set => _nativeList.Size = value * Stride;
}
/// <summary>
/// The number of elements that can be stored in the list without resizing
/// </summary>
public ElementCount Capacity
{
get => _nativeList.Capacity.ToElementCount(Stride);
set => _nativeList.Capacity = value * Stride;
}
// ReSharper disable once UnusedMember.Local
private NativeStrideList() => throw new InvalidOperationException("NativeStrideList cannot be default constructed");
/// <summary>
/// Constructs a new NativeStrideList with the given stride and initial capacity
/// </summary>
public NativeStrideList(ByteSize stride, ElementCount capacity = default)
{
Stride = stride;
_nativeList = new NativeList();
if (stride < 1)
throw new ArgumentOutOfRangeException(nameof(stride), stride, "stride must be greater than 0");
_nativeList.EnsureCapacity(Stride * capacity);
}
public static NativeStrideList FromSpan<TSpanLike>(ByteSize stride, TSpanLike span)
where TSpanLike : ISpanLike, allows ref struct
{
var outList = new NativeStrideList(stride);
outList.AddRange(span.AsSpan<byte>());
return outList;
}
public static NativeStrideList FromSpan<TSpanLike>(TSpanLike span)
where TSpanLike : ISpanLike, allows ref struct
{
return FromSpan(span.Stride, span);
}
public static NativeStrideList FromSpan<TValueType>(ByteSize stride, ReadOnlySpan<TValueType> span)
where TValueType : unmanaged
{
var outList = new NativeStrideList(stride);
outList.AddRange(span);
return outList;
}
public static NativeStrideList FromSpan<TValueType>(ReadOnlySpan<TValueType> span)
where TValueType : unmanaged
{
return FromSpan(ByteSize.Of<TValueType>(), span);
}
// This class does not track if it's been disposed of before, because
// _nativeList.Dispose() is idempotent. Should that or out implementation
// change, then you may need to implement the Dispose pattern in this class.
/// <summary>
/// Disposes the native memory.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Checks if the native list is null
/// </summary>
public bool IsNull()
{
return _nativeList.IsNull();
}
/// <summary>
/// Clears the list, setting count to 0 but preserving capacity
/// </summary>
public void Clear()
{
_nativeList.Clear();
}
/// <summary>
/// Trim the capacity to the actual number of elements in the list
/// </summary>
public void TrimExcess()
{
_nativeList.TrimExcess();
}
/// <summary>
/// Ensure the list can hold at least capacity elements without resizing
/// </summary>
public void EnsureCapacity(ElementCount capacity)
{
_nativeList.EnsureCapacity(capacity * Stride);
}
/// <summary>
/// Frees the native memory and resets the list
/// </summary>
public void Free()
{
_nativeList.Free();
}
public NativeStrideSpan AsNativeSpan()
{
return new NativeStrideSpan(Ptr, Count, Stride);
}
public void AddRange(Span<byte> items)
{
AddRange((ReadOnlySpan<byte>)items);
}
/// <summary>
/// Adds a range of bytes to the end of the list. The length of items must be a multiple of stride
/// </summary>
public void AddRange(ReadOnlySpan<byte> items)
{
if (ByteSize.Of(items) % Stride != 0)
throw new ArgumentException("Items length must be a multiple of stride", nameof(items));
_nativeList.AddRange(items);
}
/// <summary>
/// Adds a range of bytes to the end of the list. The length of items must be a multiple of stride
/// </summary>
public void AddRange<T>(T items)
where T : ISpanLike, allows ref struct
{
if (ByteSize.Of(items) % Stride != 0)
throw new ArgumentException("Items length must be a multiple of stride", nameof(items));
_nativeList.AddRange(items);
}
/// <summary>
/// Adds an item to the end of the list
/// </summary>
public void Add<T>(T item)
where T : unmanaged
{
CheckStride<T>();
_nativeList.Add(item);
}
public void AddRange<T>(Span<T> items)
where T : unmanaged
{
AddRange((ReadOnlySpan<T>)items);
}
/// <summary>
/// Adds a range of items to the end of the list
/// </summary>
public void AddRange<T>(ReadOnlySpan<T> items)
where T : unmanaged
{
CheckStride<T>();
_nativeList.AddRange(items);
}
/// <summary>
/// Inserts an item at the given index, shifting all later items up by one
/// </summary>
public void Insert<T>(ElementCount index, T item)
where T : unmanaged
{
CheckStride<T>();
_nativeList.Insert(Stride * index, item);
}
/// <summary>
/// Removes the item at the given index, shifting all later items down by one
/// </summary>
public void RemoveAt<T>(ElementCount index)
where T : unmanaged
{
CheckStride<T>();
_nativeList.RemoveAt(Stride * index, Stride);
}
private void CheckStride<T>()
where T : unmanaged
{
CheckStride(ByteSize.Of<T>());
}
private void CheckStride(ByteSize stride)
{
if (Stride != stride)
throw new ArgumentException($"NativeStrideList expected stride: {Stride}, but got: {stride}");
}
[return: Fixed]
public Span<T> AsSpan<T>()
where T : unmanaged
{
return _nativeList.AsSpan<T>();
}
protected virtual void Dispose(bool isDisposing)
{
if (!isDisposing)
return;
_nativeList.Dispose();
}
}