mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 04:58:24 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
10 changed files with 768360 additions and 0 deletions
145
brutal.collections/Brutal.Collections/FreeList.cs
Normal file
145
brutal.collections/Brutal.Collections/FreeList.cs
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for a free list index pool, a lightweight allocator that tracks free elements
|
||||
/// See: https://en.wikipedia.org/wiki/Free_list
|
||||
/// </summary>
|
||||
public interface IFreeListIndexPool
|
||||
{
|
||||
/// <summary>
|
||||
/// Total backing capacity
|
||||
/// </summary>
|
||||
public int Capacity { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Add element to list, returns index/key to element
|
||||
/// </summary>
|
||||
/// <returns>Index to element</returns>
|
||||
public int Add();
|
||||
|
||||
/// <summary>
|
||||
/// Check if element at index is empty
|
||||
/// </summary>
|
||||
public bool IsEmpty(int index);
|
||||
|
||||
/// <summary>
|
||||
/// Remove element at index
|
||||
/// </summary>
|
||||
public void Remove(int index);
|
||||
|
||||
/// <summary>
|
||||
/// Reset list as empty
|
||||
/// </summary>
|
||||
public void Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pool/allocator of indices that tracks free elements to avoid reallocation.
|
||||
/// Can be used as the allocator for a FreeList. See: https://en.wikipedia.org/wiki/Free_list
|
||||
/// </summary>
|
||||
public class FreeListIndexPool : IFreeListIndexPool
|
||||
{
|
||||
/// <summary>
|
||||
/// Empty element index not part of linked list of free elements
|
||||
/// </summary>
|
||||
const int OCCUPIED = -1;
|
||||
|
||||
/// <summary>
|
||||
/// Construct a new free list, that is empty and can grow
|
||||
/// </summary>
|
||||
public FreeListIndexPool()
|
||||
{
|
||||
_list = new();
|
||||
AllowResize = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Construct a new free list with a given capacity
|
||||
/// </summary>
|
||||
/// <param name="capacity">Initial capacity</param>
|
||||
/// <param name="allowResize">If false, will throw instead of growing capacity when backing list is full</param>
|
||||
public FreeListIndexPool(int capacity, bool allowResize)
|
||||
{
|
||||
_list = new(capacity);
|
||||
AllowResize = allowResize;
|
||||
}
|
||||
|
||||
private readonly List<int> _list;
|
||||
private int _firstFree = OCCUPIED;
|
||||
|
||||
/// <summary>
|
||||
/// If true, the list will grow when full, if false, it will throw an exception
|
||||
/// </summary>
|
||||
public readonly bool AllowResize;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public int Capacity
|
||||
{
|
||||
get => _list.Capacity;
|
||||
set => _list.Capacity = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Access element by index
|
||||
/// </summary>
|
||||
public int this[int index]
|
||||
{
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
get => _list[index];
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
set => _list[index] = value;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool IsEmpty(int index)
|
||||
{
|
||||
return _list[index] == OCCUPIED;
|
||||
}
|
||||
|
||||
public bool TryAdd(out int index)
|
||||
{
|
||||
if (_firstFree != OCCUPIED)
|
||||
{
|
||||
index = _firstFree;
|
||||
_firstFree = _list[index];
|
||||
_list[index] = OCCUPIED;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!AllowResize && _list.Count == _list.Capacity)
|
||||
{
|
||||
index = -1;
|
||||
return false;
|
||||
}
|
||||
|
||||
_list.Add(OCCUPIED);
|
||||
index = _list.Count - 1;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public int Add()
|
||||
{
|
||||
if (!TryAdd(out var index))
|
||||
throw new Exception("FreeListIndexPool is full, and is not allowed to grow");
|
||||
return index;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Remove(int index)
|
||||
{
|
||||
_list[index] = _firstFree;
|
||||
_firstFree = index;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Clear()
|
||||
{
|
||||
_list.Clear();
|
||||
_firstFree = OCCUPIED;
|
||||
}
|
||||
}
|
||||
102
brutal.collections/Brutal.Collections/Name/Name.cs
Normal file
102
brutal.collections/Brutal.Collections/Name/Name.cs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// A pool-based (see: <see cref="Namespace{T}"/>) unique identifier for various entities in a system.
|
||||
/// </summary>
|
||||
public readonly struct Name<T> : IEquatable<Name<T>>
|
||||
{
|
||||
/// <summary>
|
||||
/// The underlying string value of the Name.
|
||||
/// </summary>
|
||||
public readonly string Value;
|
||||
|
||||
/// <summary>
|
||||
/// Construct a Name from a string, using the shared pool for the type T.
|
||||
/// </summary>
|
||||
public Name(string id)
|
||||
: this(id, Namespace<T>.Shared) { }
|
||||
|
||||
/// <summary>
|
||||
/// Construct a Name from a string, using the given pool.
|
||||
/// </summary>
|
||||
public Name(string id, Namespace<T> pool)
|
||||
{
|
||||
Value = pool.GetOrAdd(id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the underlying string value of the Name.
|
||||
/// </summary> public new string ToString() => Value;
|
||||
/// <summary>
|
||||
/// Checks equality with another Name, based on reference equality of the underlying string.
|
||||
/// </summary>
|
||||
public bool Equals(Name<T> other)
|
||||
{
|
||||
return ReferenceEquals(Value, other.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks equality with another object.
|
||||
/// </summary>
|
||||
public override bool Equals(object? obj)
|
||||
{
|
||||
return obj is Name<T> other && Equals(other);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the hash code for the Name (based on the reference of the Value).
|
||||
/// </summary>
|
||||
public override int GetHashCode()
|
||||
{
|
||||
// Hash the reference of the Value for performance
|
||||
return RuntimeHelpers.GetHashCode(Value);
|
||||
}
|
||||
|
||||
/// <summary>Equality operator for Name.</summary>
|
||||
public static bool operator ==(Name<T> left, Name<T> right)
|
||||
{
|
||||
return left.Equals(right);
|
||||
}
|
||||
|
||||
/// <summary>Inequality operator for Name.</summary>
|
||||
public static bool operator !=(Name<T> left, Name<T> right)
|
||||
{
|
||||
return !left.Equals(right);
|
||||
}
|
||||
|
||||
/// <summary>Equality operator for Name and string.</summary>
|
||||
public static bool operator ==(Name<T> left, string right)
|
||||
{
|
||||
return left.Value == right;
|
||||
}
|
||||
|
||||
/// <summary>Inequality operator for Name and string.</summary>
|
||||
public static bool operator !=(Name<T> left, string right)
|
||||
{
|
||||
return left.Value != right;
|
||||
}
|
||||
|
||||
/// <summary>Equality operator for string and Name.</summary>
|
||||
public static bool operator ==(string left, Name<T> right)
|
||||
{
|
||||
return left == right.Value;
|
||||
}
|
||||
|
||||
/// <summary>Inequality operator for string and Name.</summary>
|
||||
public static bool operator !=(string left, Name<T> right)
|
||||
{
|
||||
return left != right.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Implicitly construct a Name from a string.
|
||||
/// </summary>
|
||||
public static implicit operator Name<T>(string id) => new(id);
|
||||
|
||||
/// <summary>
|
||||
/// Get the underlying string value of the Name.
|
||||
/// </summary>
|
||||
public override string ToString() => Value;
|
||||
}
|
||||
56
brutal.collections/Brutal.Collections/Name/Namespace.cs
Normal file
56
brutal.collections/Brutal.Collections/Name/Namespace.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
using System.Diagnostics.CodeAnalysis;
|
||||
using CommunityToolkit.HighPerformance.Buffers;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// A pool of unique identifiers
|
||||
/// </summary>
|
||||
public class Namespace<T>
|
||||
{
|
||||
private readonly Lock _lock = new();
|
||||
|
||||
/// <summary>
|
||||
/// A global shared pool
|
||||
/// </summary>
|
||||
public static Namespace<T> Shared { get; } = new();
|
||||
|
||||
private readonly StringPool _pool = new();
|
||||
|
||||
internal string GetOrAdd(ReadOnlySpan<char> id)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _pool.GetOrAdd(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Try to get an existing ID from the pool
|
||||
/// </summary>
|
||||
public bool TryGet(ReadOnlySpan<char> id, [NotNullWhen(true)] out Name<T>? existing)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_pool.TryGet(id, out var key))
|
||||
{
|
||||
existing = new Name<T>(key);
|
||||
return true;
|
||||
}
|
||||
|
||||
existing = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check if the pool contains the given ID
|
||||
/// </summary>
|
||||
public bool Contains(ReadOnlySpan<char> id)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _pool.TryGet(id, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
380
brutal.collections/Brutal.Collections/NativeList/NativeList.cs
Normal file
380
brutal.collections/Brutal.Collections/NativeList/NativeList.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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() { }
|
||||
}
|
||||
|
|
@ -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];
|
||||
}
|
||||
}
|
||||
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
using Brutal.Attributes;
|
||||
using Brutal.Memory;
|
||||
using Brutal.Pointers;
|
||||
using Brutal.Pointers.Extensions;
|
||||
|
||||
namespace Brutal.Collections;
|
||||
|
||||
/// <summary>
|
||||
/// An untyped span to unsafe memory, however with a stride.
|
||||
/// </summary>
|
||||
public readonly ref struct NativeStrideSpan(Ptr inData, ElementCount inLength, ByteSize inStride) : ISpanLike
|
||||
{
|
||||
/// <summary>
|
||||
/// The pointer to the first element of the span.
|
||||
/// </summary>
|
||||
public Ptr Ptr => inData;
|
||||
|
||||
/// <summary>
|
||||
/// The length of the span.
|
||||
/// </summary>
|
||||
public ElementCount Length => inLength;
|
||||
|
||||
/// <summary>
|
||||
/// The stride of each element.
|
||||
/// </summary>
|
||||
public ByteSize Stride => inStride;
|
||||
|
||||
public bool IsEmpty => Length == 0;
|
||||
|
||||
/// <summary>
|
||||
/// The total size of the span in bytes.
|
||||
/// </summary>
|
||||
public ByteSize ByteSize => Length * Stride;
|
||||
|
||||
/// <summary>
|
||||
/// Slice the span into a new raw span.
|
||||
/// </summary>
|
||||
public NativeStrideSpan Slice(int start, int length)
|
||||
{
|
||||
return new NativeStrideSpan(Ptr.Offset(start * Stride), length, Stride);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new raw span with a different stride.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentOutOfRangeException"></exception>
|
||||
public NativeStrideSpan WithStride(ByteSize stride)
|
||||
{
|
||||
if (stride <= 0)
|
||||
throw new ArgumentOutOfRangeException(nameof(stride));
|
||||
var prevSize = ByteSize;
|
||||
return new NativeStrideSpan(Ptr, prevSize.ToElementCount(stride), stride);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsNull() => Ptr.IsNull();
|
||||
|
||||
/// <summary>
|
||||
/// Create a new raw span from a managed span.
|
||||
/// </summary>
|
||||
public static unsafe NativeStrideSpan FromSpan<T>([Fixed] ReadOnlySpan<T> span)
|
||||
where T : unmanaged
|
||||
{
|
||||
return new NativeStrideSpan(span.AsPointer(), span.Length, ByteSize.Of<T>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new raw span from a managed span.
|
||||
/// </summary>
|
||||
public static unsafe NativeStrideSpan FromSpan<T>([Fixed] Span<T> span)
|
||||
where T : unmanaged
|
||||
{
|
||||
return new NativeStrideSpan(span.AsPointer(), span.Length, ByteSize.Of<T>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Slice the span into a new raw span.
|
||||
/// </summary>
|
||||
public NativeStrideSpan this[int start, int end] => Slice(start, end - start);
|
||||
|
||||
[return: Fixed]
|
||||
public unsafe Span<T> AsSpan<T>()
|
||||
where T : unmanaged
|
||||
{
|
||||
if (typeof(T) == typeof(byte))
|
||||
return new Span<T>(Ptr.Cast<T>(), ElementCount.Of(Length * Stride));
|
||||
|
||||
var size = ByteSize.Of<T>();
|
||||
if (size != Stride)
|
||||
throw new InvalidOperationException("Stride must be equal to the size of the type, or type must be byte.");
|
||||
|
||||
return new Span<T>(Ptr.Cast<T>(), Length);
|
||||
}
|
||||
|
||||
public NativeStrideSpan this[Range start] => Slice(start.Start.Value, start.End.Value - start.Start.Value);
|
||||
}
|
||||
53
brutal.collections/Brutal.Collections/Span/ScratchSpan.cs
Normal file
53
brutal.collections/Brutal.Collections/Span/ScratchSpan.cs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
using System.Buffers;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Brutal.Collections.Experimental;
|
||||
|
||||
/// <summary>
|
||||
/// Stackalloc-or-rent scratch buffer.
|
||||
/// <see cref="Span"/> is backed by the stack buffer if it's big enough,
|
||||
/// else by an array rented from <see cref="ArrayPool{T}"/>.
|
||||
/// <see cref="Dispose"/> returns any rented array to the pool.
|
||||
/// </summary>
|
||||
/// <remarks>Usage:<code>
|
||||
/// using (var scratch = new ScratchSpan<T>(requiredLength, stackalloc T[256]))
|
||||
/// {
|
||||
/// var buf = scratch.Span; // length == required, backed by stack or pool
|
||||
/// // ...
|
||||
/// }
|
||||
/// </code></remarks>
|
||||
public readonly ref struct ScratchSpan<T>
|
||||
{
|
||||
private readonly T[]? _rented;
|
||||
|
||||
/// <summary>The scratch span of exactly <c>requiredLength</c> elements.</summary>
|
||||
public Span<T> Span { get; }
|
||||
|
||||
public static implicit operator Span<T>(ScratchSpan<T> scratch) => scratch.Span;
|
||||
|
||||
/// <summary>Construct a ScratchSpan, get the result in <see cref="Span"/>.</summary>
|
||||
/// <param name="requiredLength">Number of elements the caller needs.</param>
|
||||
/// <param name="stackBuffer">Stack-allocated tentative buffer to use if large enough, otherwise an array is rented.</param>
|
||||
public ScratchSpan(int requiredLength, Span<T> stackBuffer)
|
||||
{
|
||||
Span = requiredLength <= stackBuffer.Length ? stackBuffer : _rented = ArrayPool<T>.Shared.Rent(requiredLength);
|
||||
Span = Span[..requiredLength];
|
||||
}
|
||||
|
||||
/// <summary>Alternative form where <see cref="Span"/> is output directly to <paramref name="span"/>.</summary>
|
||||
/// <param name="requiredLength">Number of elements the caller needs.</param>
|
||||
/// <param name="stackBuffer">Stack-allocated tentative buffer to use if large enough, otherwise an array is rented.</param>
|
||||
/// <param name="span">Output span of exactly <paramref name="requiredLength"/> elements, backed by either <paramref name="stackBuffer"/> or a rented array.</param>
|
||||
public ScratchSpan(int requiredLength, Span<T> stackBuffer, out Span<T> span)
|
||||
: this(requiredLength, stackBuffer)
|
||||
{
|
||||
span = Span;
|
||||
}
|
||||
|
||||
/// Returns any rented array to the pool. No-op if the stack buffer was used.
|
||||
public void Dispose()
|
||||
{
|
||||
if (_rented != null)
|
||||
ArrayPool<T>.Shared.Return(_rented, clearArray: RuntimeHelpers.IsReferenceOrContainsReferences<T>());
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue