Enhance memory management and performance benchmarks

Added a new configuration setting in `.editorconfig` to sort system directives last and increased the maximum line length to 400 characters.
Added a new static class `MathUtilities` in `MathUtilities.cs` with a method `CeilPow2` for computing powers of two.
Added a new benchmark class `CollectionBenchmark` in `CollectionBenchmark.cs` to measure performance of standard versus unsafe arrays.
Added a new benchmark class `HashCodeBenchmark` in `HashCodeBenchmark.cs` to evaluate hash code generation performance.
Added new utility methods in `UnsafeUtilities.cs` for memory allocation and deallocation, including `Malloc`, `AlignedAlloc`, `Realloc`, and `Free`.
Added a new `AllocationType` enum in `AllocationType.cs` to specify memory allocation types.

Changed the project file `Misaki.HighPerformance.Mathematics.csproj` to target .NET 9.0 and enable implicit usings and nullable reference types.
Changed the `ParallelNoiseBenchmark` class in `ParallelNoiseBenchmark.cs` to improve memory allocation strategies and performance.
Changed memory management in `Arena.cs` and `DynamicArena.cs` to use custom `Malloc` and `Free` functions.
Changed the `IUnsafeCollection` interface in `IUnsafeCollection.cs` to include new methods for resizing collections and obtaining unsafe pointers.
Changed the `UnsafeArray.cs` to improve management of unsafe arrays, including constructor and method updates.
Changed the `UnsafeHashMap` and `UnsafeHashSet` classes to enhance performance and memory management.
Changed the `UnsafeCollectionExtensions` class to provide additional methods for copying elements and converting collections.
Changed the `ObjectPool` class in `ObjectPool.cs` to simplify cleanup and remove auto-cleanup functionality.
Changed job scheduling and worker classes in `JobExtensions.cs` and `JobWorker.cs` to improve job scheduling in a thread pool.

Removed commented-out code in `Program.cs` related to previous testing methods.
Removed auto-cleanup functionality from the `ObjectPool` class.
This commit is contained in:
2025-04-03 09:13:07 +09:00
parent 060b4c9477
commit 48f2dce778
27 changed files with 1557 additions and 228 deletions

View File

@@ -4,4 +4,10 @@ public enum AllocationType
{
UnInitialized,
Clear
}
public enum Allocator
{
Temp,
Persistent
}

View File

@@ -1,21 +1,38 @@
namespace Misaki.HighPerformance.Unsafe.Collections.Contracts;
public unsafe interface IUnsafeCollection<T> : IDisposable
public unsafe interface IUnsafeCollection<T> : IEnumerable<T>, IDisposable
where T : unmanaged
{
public T* Buffer
/// <summary>
/// Gets the number of elements in a collection. The value is read-only.
/// </summary>
public int Count
{
get;
}
public int Size
/// <summary>
/// Indicates whether the object has been created. Returns true if the object is created, otherwise false.
/// </summary>
public bool IsCreated
{
get;
}
public ref T this[int index] { get; }
/// <summary>
/// Removes all elements from the collection. The collection will be empty after this operation.
/// </summary>
public void Clear();
public void ReAlloc(int newSize);
}
/// <summary>
/// Changes the size of a collection or array to the specified value.
/// </summary>
/// <param name="newSize">Specifies the new size to which the collection or array should be adjusted.</param>
public void Resize(int newSize);
/// <summary>
/// Returns a pointer to an unmanaged memory location. This pointer can be used for low-level memory operations.
/// </summary>
/// <returns>The method returns a void pointer to the unsafe memory location.</returns>
public void* GetUnsafePtr();
}

View File

@@ -0,0 +1,51 @@
using Misaki.HighPerformance.Unsafe.Buffer;
namespace Misaki.HighPerformance.Unsafe.Collections.Services;
public static unsafe class AllocationManager
{
private static DynamicArena _arena;
private static bool _initialized;
private static readonly Lock _lock = new();
public static void Initialize(uint initialSize)
{
_arena = new DynamicArena(initialSize);
_initialized = true;
}
public static T* Allocate<T>(uint size, uint alignSize, Allocator allocator, AllocationType allocationType)
where T : unmanaged
{
if (!_initialized)
{
throw new InvalidOperationException("The AllocationManager has not been initialized.");
}
lock (_lock)
{
return allocator switch
{
Allocator.Temp => (T*)_arena.Allocate(size * (uint)sizeof(T), alignSize, allocationType),
Allocator.Persistent => (T*)AlignedAlloc((nuint)(size * sizeof(T)), alignSize),
_ => throw new ArgumentOutOfRangeException(nameof(allocator), "Invalid allocator type."),
};
}
}
public static void Reset(bool clear = false)
{
if (!_initialized)
{
throw new InvalidOperationException("The AllocationManager has not been initialized.");
}
_arena.Reset(clear);
}
public static void Dispose()
{
_arena.Dispose();
}
}

View File

@@ -1,21 +1,25 @@
using Misaki.HighPerformance.Unsafe.Collections.Contracts;
using Misaki.HighPerformance.Unsafe.Collections.Services;
using Misaki.HighPerformance.Unsafe.Helpers;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Misaki.HighPerformance.Unsafe.Collections;
public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>, IEnumerable<T>
/// <summary>
/// A structure for managing an array of unmanaged types with unsafe memory operations.
/// </summary>
/// <typeparam name="T">Represents a type that can be stored in an unmanaged memory context.</typeparam>
public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
where T : unmanaged
{
private struct Enumerator : IEnumerator<T>
{
private UnsafeArray<T> _collection;
private UnsafeArray<T>* _collection;
private int _index;
private T _value;
public Enumerator(ref UnsafeArray<T> collection)
public Enumerator(UnsafeArray<T>* collection)
{
_collection = collection;
_index = -1;
@@ -26,9 +30,9 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>, IEnumerable<T>
public bool MoveNext()
{
_index++;
if (_index < _collection.Size)
if (_index < _collection->_count)
{
_value = UnsafeUtilities.ReadArrayElement<T>(_collection.Buffer, _index);
_value = UnsafeUtilities.ReadArrayElement<T>(_collection->_buffer, _index);
return true;
}
@@ -42,22 +46,16 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>, IEnumerable<T>
}
// Let NativeArray indexer check for out of range.
public T Current
public readonly T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return _value;
}
get => _value;
}
object IEnumerator.Current
readonly object IEnumerator.Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return Current;
}
get => Current;
}
public void Dispose()
@@ -66,10 +64,9 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>, IEnumerable<T>
}
private T* _buffer;
private int _size;
private int _count;
public readonly T* Buffer => _buffer;
public readonly int Size => _size;
public readonly int Count => _count;
public readonly ref T this[int index]
{
@@ -77,14 +74,31 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>, IEnumerable<T>
get => ref UnsafeUtilities.ReadArrayElementRef<T>(_buffer, index);
}
public IEnumerator<T> GetEnumerator() => new Enumerator(ref this);
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _buffer != null;
}
public IEnumerator<T> GetEnumerator() => new Enumerator((UnsafeArray<T>*)UnsafeUtilities.AddressOf(ref this));
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public UnsafeArray(int size, AllocationType allocationType)
/// <summary>
/// Initializes a new instance of UnsafeArray with a specified number of elements and an allocation type. It
/// allocates memory and optionally clears it.
/// </summary>
/// <param name="count">Specifies the number of elements to allocate in the array, which must be greater than zero.</param>
/// <param name="allocationType">Determines how the allocated memory should be initialized, either uninitialized or cleared.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the specified number of elements is less than or equal to zero.</exception>
public UnsafeArray(int count, Allocator allocator, AllocationType allocationType = AllocationType.UnInitialized)
{
_size = size;
_buffer = (T*)NativeMemory.AlignedAlloc((nuint)(size * sizeof(T)), AlignOf<T>());
if (count <= 0)
{
throw new ArgumentOutOfRangeException(nameof(count), "Count must be greater than zero.");
}
_buffer = AllocationManager.Allocate<T>((uint)count, (uint)AlignOf<T>(), allocator, allocationType);
_count = count;
if (allocationType == AllocationType.Clear)
{
@@ -92,29 +106,47 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>, IEnumerable<T>
}
}
public void ReAlloc(int newSize)
/// <summary>
/// Initializes an UnsafeArray with a pointer to a buffer and a count of elements. The count is adjusted based on
/// the size of the type T.
/// </summary>
/// <param name="buffer">A pointer to the memory location that holds the elements of the array.</param>
/// <param name="count">The total size of the data in bytes, which is divided by the size of type T to determine the number of elements.</param>
public UnsafeArray(void* buffer, int count)
{
if (newSize == _size)
_buffer = (T*)buffer;
_count = count;
}
public void Resize(int newSize)
{
if (newSize == _count)
{
return;
}
_buffer = (T*)NativeMemory.AlignedRealloc(_buffer, (nuint)(newSize * sizeof(T)), AlignOf<T>());
_size = newSize;
_buffer = (T*)AlignedRealloc(_buffer, (nuint)(newSize * sizeof(T)), AlignOf<T>());
_count = newSize;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear()
public readonly void Clear()
{
MemClear(_buffer, (uint)(_size * sizeof(T)));
MemClear(_buffer, (uint)(_count * sizeof(T)));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void* GetUnsafePtr()
{
return _buffer;
}
public void Dispose()
{
NativeMemory.AlignedFree(_buffer);
AlignedFree(_buffer);
_buffer = null;
_size = 0;
_count = 0;
}
}

View File

@@ -0,0 +1,205 @@
using Misaki.HighPerformance.Unsafe.Collections.Contracts;
using Misaki.HighPerformance.Unsafe.Helpers;
using System.Collections;
using System.Runtime.CompilerServices;
namespace Misaki.HighPerformance.Unsafe.Collections;
public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePair<TKey, TValue>> where TKey : unmanaged, IEquatable<TKey> where TValue : unmanaged
{
private struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
{
internal HashMapHelper<TKey>.Enumerator _enumerator;
public Enumerator(HashMapHelper<TKey>* data)
{
_enumerator = new HashMapHelper<TKey>.Enumerator(data);
}
/// <summary>
/// The current key-value pair.
/// </summary>
/// <value>The current key-value pair.</value>
public KeyValuePair<TKey, TValue> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _enumerator.GetCurrent<TValue>();
}
/// <summary>
/// Gets the element at the current position of the enumerator in the container.
/// </summary>
object IEnumerator.Current => Current;
/// <summary>
/// Advances the enumerator to the next key-value pair.
/// </summary>
/// <returns>True if <see cref="Current"/> is valid to read after the call.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext() => _enumerator.MoveNext();
/// <summary>
/// Resets the enumerator to its initial state.
/// </summary>
public void Reset() => _enumerator.Reset();
/// <summary>
/// Does nothing.
/// </summary>
public void Dispose()
{
}
}
private HashMapHelper<TKey> _hashMap;
public readonly int Count => _hashMap.Count;
public readonly int Capacity => _hashMap.Capacity;
public readonly bool IsCreated => _hashMap.IsCreated;
/// <summary>
/// Gets and sets values by key.
/// </summary>
/// <remarks>Getting a key that is not present will throw. Setting a key that is not already present will add the key.</remarks>
/// <param name="key">The key to look up.</param>
/// <value>The value associated with the key.</value>
/// <exception cref="ArgumentException">For getting, thrown if the key was not present.</exception>
public TValue this[TKey key]
{
get
{
if (!_hashMap.TryGetValue<TValue>(key, out var result))
{
throw new ArgumentException($"Key: {key} is not present.");
}
return result;
}
set
{
var idx = _hashMap.Find(key);
if (-1 != idx)
{
UnsafeUtilities.WriteArrayElement(_hashMap.Buffer, idx, value);
return;
}
TryAdd(key, value);
}
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => new Enumerator((HashMapHelper<TKey>*)UnsafeUtilities.AddressOf(ref _hashMap));
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public UnsafeHashMap(int capacity)
{
_hashMap = new HashMapHelper<TKey>(capacity, sizeof(TValue), HashMapHelper<TKey>.MINIMAL_CAPACITY);
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>If the key is already present, this method returns false without modifying the hash map.</remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
/// <returns>True if the key-value pair was added.</returns>
public bool TryAdd(TKey key, TValue item)
{
var idx = _hashMap.TryAdd(key);
if (idx != -1)
{
UnsafeUtilities.WriteArrayElement(_hashMap.Buffer, idx, item);
return true;
}
return false;
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>If the key is already present, this method throws without modifying the hash map.</remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
/// <exception cref="ArgumentException">Thrown if the key was already present.</exception>
public void Add(TKey key, TValue item)
{
var result = TryAdd(key, item);
if (!result)
{
throw new ArgumentException($"An item with the same key has already been added: {key}");
}
}
/// <summary>
/// Returns the value associated with a key.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <param name="item">Outputs the value associated with the key. Outputs default if the key was not present.</param>
/// <returns>True if the key was present.</returns>
public bool TryGetValue(TKey key, out TValue item)
{
return _hashMap.TryGetValue(key, out item);
}
/// <summary>
/// Returns true if a given key is present in this hash map.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <returns>True if the key was present.</returns>
public bool ContainsKey(TKey key)
{
return -1 != _hashMap.Find(key);
}
/// <summary>
/// Sets the capacity to match what it would be if it had been originally initialized with all its entries.
/// </summary>
public void TrimExcess() => _hashMap.TrimExcess();
public void Resize(int newSize)
{
_hashMap.Resize(newSize);
}
public void Clear()
{
_hashMap.Clear();
}
/// <summary>
/// Retrieves an array of keys from the hash map.
/// </summary>
/// <returns>An array containing the keys stored in the hash map.</returns>
public UnsafeArray<TKey> GetKeyArray(Allocator allocator) => _hashMap.GetKeyArray(allocator);
/// <summary>
/// Retrieves an array of values from the underlying hash map.
/// </summary>
/// <returns>An UnsafeArray containing the values stored in the hash map.</returns>
public UnsafeArray<TValue> GetValueArray(Allocator allocator) => _hashMap.GetValueArray<TValue>(allocator);
/// <summary>
/// Retrieves an array of key-value pairs from the hash map. The keys are of type TKey and the values are of type
/// TValue.
/// </summary>
/// <returns>Returns an UnsafeArray containing KeyValuePair objects.</returns>
public UnsafeArray<KeyValuePair<TKey, TValue>> GetKeyValueArrays(Allocator allocator) => _hashMap.GetKeyValueArrays<TValue>(allocator);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void* GetUnsafePtr()
{
return _hashMap.Buffer;
}
public void Dispose()
{
_hashMap.Dispose();
}
public void Test(ref HashMapHelper<TKey> t)
{
Console.WriteLine(t.Equals(_hashMap));
}
}

View File

@@ -0,0 +1,122 @@
using Misaki.HighPerformance.Unsafe.Collections.Contracts;
using Misaki.HighPerformance.Unsafe.Helpers;
using System.Collections;
using System.Runtime.CompilerServices;
namespace Misaki.HighPerformance.Unsafe.Collections;
/// <summary>
/// A collection that provides fast, unsafe operations for managing a set of unmanaged types. It supports adding,
/// removing, and checking for values.
/// </summary>
/// <typeparam name="T">Represents an unmanaged type that can be compared for equality.</typeparam>
public unsafe struct UnsafeHashSet<T> : IUnsafeCollection<T>, IEnumerable<T>
where T : unmanaged, IEquatable<T>
{
private struct Enumerator : IEnumerator<T>
{
internal HashMapHelper<T>.Enumerator _enumerator;
public Enumerator(HashMapHelper<T>* hashMap)
{
_enumerator = new HashMapHelper<T>.Enumerator(hashMap);
}
public T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _enumerator.buffer->_keys[_enumerator.index];
}
object IEnumerator.Current => Current;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext() => _enumerator.MoveNext();
public void Reset() => _enumerator.Reset();
public readonly void Dispose()
{
}
}
private HashMapHelper<T> _hashMap;
public readonly int Count => _hashMap.Count;
public readonly int Capacity => _hashMap.Capacity;
public readonly bool IsCreated => _hashMap.IsCreated;
public IEnumerator<T> GetEnumerator() => new Enumerator((HashMapHelper<T>*)UnsafeUtilities.AddressOf(ref _hashMap));
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public UnsafeHashSet(int capacity)
{
_hashMap = new HashMapHelper<T>(capacity, 0, HashMapHelper<T>.MINIMAL_CAPACITY);
}
/// <summary>
/// Adds a new value (unless it is already present).
/// </summary>
/// <param name="item">The value to add.</param>
/// <returns>True if the value was not already present.</returns>
public bool Add(T item)
{
return -1 != _hashMap.TryAdd(item);
}
/// <summary>
/// Removes a particular value.
/// </summary>
/// <param name="item">The value to remove.</param>
/// <returns>True if the value was present.</returns>
public bool Remove(T item)
{
return -1 != _hashMap.TryRemove(item);
}
/// <summary>
/// Returns true if a particular value is present.
/// </summary>
/// <param name="item">The value to check for.</param>
/// <returns>True if the value was present.</returns>
public bool Contains(T item)
{
return -1 != _hashMap.Find(item);
}
/// <summary>
/// Sets the capacity to match what it would be if it had been originally initialized with all its entries.
/// </summary>
public void TrimExcess() => _hashMap.TrimExcess();
/// <summary>
/// Returns an array with a copy of this set's values (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of the set's values.</returns>
public UnsafeArray<T> ToNativeArray(Allocator allocator)
{
return _hashMap.GetKeyArray(allocator);
}
public void Resize(int newSize)
{
_hashMap.Resize(newSize);
}
public void Clear()
{
_hashMap.Clear();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void* GetUnsafePtr()
{
return _hashMap.Buffer;
}
public void Dispose()
{
_hashMap.Dispose();
}
}

View File

@@ -5,16 +5,20 @@ using System.Runtime.CompilerServices;
namespace Misaki.HighPerformance.Unsafe.Collections;
public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
/// <summary>
/// A collection that allows for unsafe operations on a list of unmanaged types.
/// </summary>
/// <typeparam name="T">Represents a type that can be stored in the collection, constrained to unmanaged types for performance and safety.</typeparam>
public unsafe struct UnsafeList<T> : IUnsafeCollection<T>
where T : unmanaged
{
private struct Enumerator : IEnumerator<T>
{
private UnsafeList<T> _collection;
private UnsafeList<T>* _collection;
private int _index;
private T _value;
public Enumerator(ref UnsafeList<T> collection)
public Enumerator(UnsafeList<T>* collection)
{
_collection = collection;
_index = -1;
@@ -25,9 +29,9 @@ public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
public bool MoveNext()
{
_index++;
if (_index < _collection.Size)
if (_index < _collection->_count)
{
_value = UnsafeUtilities.ReadArrayElement<T>(_collection.Buffer, _index);
_value = UnsafeUtilities.ReadArrayElement<T>(_collection->_array.GetUnsafePtr(), _index);
return true;
}
@@ -88,9 +92,9 @@ public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
/// <param name="value">The value to be added to the collection.</param>
public void AddNoResize(T value)
{
var idx = Interlocked.Increment(ref listData->_size) - 1;
var idx = Interlocked.Increment(ref listData->_count) - 1;
listData->CheckNoResizeCapacity(idx, 1);
UnsafeUtilities.WriteArrayElement(listData->Buffer, idx, value);
UnsafeUtilities.WriteArrayElement(listData->_array.GetUnsafePtr(), idx, value);
}
/// <summary>
@@ -100,19 +104,19 @@ public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
/// <param name="count">Indicates the number of elements to be added from the source data.</param>
public void AddRangeNoResize(T* ptr, int count)
{
var idx = Interlocked.Add(ref listData->_size, count) - count;
var idx = Interlocked.Add(ref listData->_count, count) - count;
listData->CheckNoResizeCapacity(idx, count);
MemCpy(listData->Buffer + idx, ptr, (uint)(count * sizeof(T)));
MemCpy(UnsafeUtilities.ReadArrayElementUnsafe<T>(listData->_array.GetUnsafePtr(), idx), ptr, (uint)(count * sizeof(T)));
}
}
private UnsafeArray<T> _array;
private int _size;
private int _count;
public readonly T* Buffer => _array.Buffer;
public readonly int Size => _size;
public readonly int Capacity => _array.Size;
public readonly int Count => _count;
public readonly int Capacity => _array.Count;
public readonly bool IsCreated => _array.IsCreated;
public readonly ref T this[int index]
{
@@ -120,17 +124,15 @@ public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
get => ref _array[index];
}
public IEnumerator<T> GetEnumerator() => new Enumerator(ref this);
public IEnumerator<T> GetEnumerator() => new Enumerator((UnsafeList<T>*)UnsafeUtilities.AddressOf(ref this));
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public ParallelWriter AsParallelWriter() =>
new((UnsafeList<T>*)UnsafeUtilities.AddressOf(ref this));
public ParallelWriter AsParallelWriter() => new((UnsafeList<T>*)UnsafeUtilities.AddressOf(ref this));
public UnsafeList(int capacity, AllocationType allocationType)
public UnsafeList(int capacity, Allocator allocator, AllocationType allocationType = AllocationType.UnInitialized)
{
_array = new UnsafeArray<T>(capacity, allocationType);
_size = 0;
_array = new UnsafeArray<T>(capacity, allocator, allocationType);
_count = 0;
if (allocationType == AllocationType.Clear)
{
@@ -140,7 +142,7 @@ public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
private readonly void CheckNoResizeCapacity(int count)
{
CheckNoResizeCapacity(count, Size);
CheckNoResizeCapacity(count, Count);
}
private readonly void CheckNoResizeCapacity(int index, int count)
@@ -148,7 +150,7 @@ public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
if (index + count > Capacity)
{
throw new Exception(
$"AddNoResize assumes that list capacity is sufficient (Capacity {Capacity}, Size {Size}), requested count {count}!"
$"AddNoResize assumes that list capacity is sufficient (Capacity {Capacity}, Size {Count}), requested count {count}!"
);
}
}
@@ -165,12 +167,12 @@ public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
throw new ArgumentOutOfRangeException($"Value for index {index} must be positive.");
}
if (index > Size)
if (index > Count)
{
throw new ArgumentOutOfRangeException($"Value for index {index} is out of bounds.");
}
if (index + count > Size)
if (index + count > Count)
{
throw new ArgumentOutOfRangeException($"Value for count {count} is out of bounds.");
}
@@ -178,37 +180,37 @@ public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
public void Add(T value)
{
if (_size >= Capacity)
if (_count >= Capacity)
{
ReAlloc(Capacity + (int)(Capacity * 0.5f));
Resize(Capacity + (int)(Capacity * 0.5f));
}
UnsafeUtilities.WriteArrayElement(Buffer, _size, value);
_size++;
UnsafeUtilities.WriteArrayElement(_array.GetUnsafePtr(), _count, value);
_count++;
}
public void AddNoResize(T value)
{
CheckNoResizeCapacity(1);
UnsafeUtilities.WriteArrayElement(Buffer, _size, value);
_size++;
UnsafeUtilities.WriteArrayElement(_array.GetUnsafePtr(), _count, value);
_count++;
}
public void AddRange(Span<T> values, int count)
{
var newSize = _size + count;
var newSize = _count + count;
if (newSize > Capacity)
{
ReAlloc(Capacity + count);
Resize(Capacity + count);
}
fixed (T* ptr = values)
{
MemCpy(_array.Buffer + _size, ptr, (uint)(count * sizeof(T)));
MemCpy(UnsafeUtilities.ReadArrayElementUnsafe<T>(_array.GetUnsafePtr(), _count), ptr, (uint)(count * sizeof(T)));
}
_size += count;
_count += count;
}
public void AddRangeNoResize(ReadOnlySpan<T> values)
@@ -217,18 +219,18 @@ public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
fixed (T* ptr = values)
{
MemCpy(_array.Buffer + _size, ptr, (uint)(values.Length * sizeof(T)));
MemCpy(UnsafeUtilities.ReadArrayElementUnsafe<T>(_array.GetUnsafePtr(), _count), ptr, (uint)(values.Length * sizeof(T)));
}
_size += values.Length;
_count += values.Length;
}
public void AddRangeNoResize(T* ptr, int count)
{
CheckNoResizeCapacity(count);
MemCpy(_array.Buffer + _size, ptr, (uint)(count * sizeof(T)));
_size += count;
MemCpy(UnsafeUtilities.ReadArrayElementUnsafe<T>(_array.GetUnsafePtr(), _count), ptr, (uint)(count * sizeof(T)));
_count += count;
}
public void RemoveRange(int start, int length)
@@ -240,13 +242,12 @@ public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
return;
}
var copyFrom = Math.Min(start + length, _size);
MemCpy(
_array.Buffer + start,
_array.Buffer + copyFrom,
(uint)((_size - copyFrom) * sizeof(T))
var copyFrom = Math.Min(start + length, _count);
MemCpy(UnsafeUtilities.ReadArrayElementUnsafe<T>(_array.GetUnsafePtr(), start),
UnsafeUtilities.ReadArrayElementUnsafe<T>(_array.GetUnsafePtr(), copyFrom),
(uint)((_count - copyFrom) * sizeof(T))
);
_size -= length;
_count -= length;
}
public void RemoveAt(int index)
@@ -263,13 +264,12 @@ public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
return;
}
var copyFrom = Math.Min(_size - length, start + length);
MemCpy(
_array.Buffer + start,
_array.Buffer + copyFrom,
(uint)((_size - copyFrom) * sizeof(T))
var copyFrom = Math.Min(_count - length, start + length);
MemCpy(UnsafeUtilities.ReadArrayElementUnsafe<T>(_array.GetUnsafePtr(), start),
UnsafeUtilities.ReadArrayElementUnsafe<T>(_array.GetUnsafePtr(), copyFrom),
(uint)((_count - copyFrom) * sizeof(T))
);
_size -= length;
_count -= length;
}
public void RemoveAtSwapBack(int index)
@@ -277,26 +277,47 @@ public unsafe struct UnsafeList<T> : IUnsafeCollection<T>, IEnumerable<T>
RemoveRangeSwapBack(index, 1);
}
public void ReAlloc(int newSize)
public void Resize(int newSize)
{
_array.ReAlloc(newSize);
_array.Resize(newSize);
if (_size > newSize)
if (_count > newSize)
{
_size = newSize;
_count = newSize;
}
}
public void Clear()
{
_array.Clear();
_size = 0;
_count = 0;
}
/// <summary>
/// Returns a pointer to the underlying data of the array in an unsafe manner. This method is optimized for
/// performance.
/// </summary>
/// <returns>A pointer to the array's data.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void* GetUnsafePtr()
{
return _array.GetUnsafePtr();
}
/// <summary>
/// Converts the current array to an UnsafeArray representation using its pointer and count.
/// </summary>
/// <returns>Returns a new UnsafeArray instance initialized with the array's unsafe pointer and its count.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly UnsafeArray<T> AsUnsafeArray()
{
return new UnsafeArray<T>(_array.GetUnsafePtr(), _count);
}
public void Dispose()
{
_array.Dispose();
_size = 0;
_count = 0;
}
}

View File

@@ -1,20 +1,75 @@
using Misaki.HighPerformance.Unsafe.Collections.Contracts;
using Misaki.HighPerformance.Unsafe.Helpers;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace Misaki.HighPerformance.Unsafe.Collections;
/// <summary>
/// A structure that implements a queue using unmanaged types for efficient memory management.
/// </summary>
/// <typeparam name="T">Represents the type of elements stored in the queue, which must be an unmanaged type for performance and safety.</typeparam>
public unsafe struct UnsafeQueue<T> : IUnsafeCollection<T>
where T : unmanaged
{
private struct Enumerator : IEnumerator<T>
{
private UnsafeQueue<T>* _collection;
private int _index;
private T _value;
public Enumerator(UnsafeQueue<T>* collection)
{
_collection = collection;
_index = -1;
_value = default;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
_index++;
if (_index < _collection->_count)
{
_value = UnsafeUtilities.ReadArrayElement<T>(_collection->_array.GetUnsafePtr(), _index);
return true;
}
_value = default;
return false;
}
public void Reset()
{
_index = -1;
}
// Let NativeArray indexer check for out of range.
public readonly T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _value;
}
readonly object IEnumerator.Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Current;
}
public readonly void Dispose()
{
}
}
private UnsafeArray<T> _array;
private int _size;
private int _count;
private int _offset;
public readonly T* Buffer => _array.Buffer;
public readonly int Size => _size;
public readonly int Capacity => _array.Size;
public readonly int Count => _count;
public readonly int Capacity => _array.Count;
public readonly bool IsCreated => _array.IsCreated;
public readonly ref T this[int index]
{
@@ -22,10 +77,13 @@ public unsafe struct UnsafeQueue<T> : IUnsafeCollection<T>
get => ref _array[index];
}
public UnsafeQueue(int capacity, AllocationType allocationType)
public IEnumerator<T> GetEnumerator() => new Enumerator((UnsafeQueue<T>*)UnsafeUtilities.AddressOf(ref this));
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public UnsafeQueue(int capacity, Allocator allocator, AllocationType allocationType = AllocationType.UnInitialized)
{
_array = new UnsafeArray<T>(capacity, allocationType);
_size = 0;
_array = new UnsafeArray<T>(capacity, allocator, allocationType);
_count = 0;
_offset = 0;
if (allocationType == AllocationType.Clear)
@@ -34,34 +92,49 @@ public unsafe struct UnsafeQueue<T> : IUnsafeCollection<T>
}
}
/// <summary>
/// Adds an element to the end of a collection, resizing if the current capacity is reached. The new element is
/// stored in a circular buffer.
/// </summary>
/// <param name="value">The item to be added to the collection.</param>
public void Enqueue(T value)
{
if (_size >= Capacity)
if (_count >= Capacity)
{
ReAlloc(Capacity + (int)(Capacity * 0.5f));
Resize(Capacity + (int)(Capacity * 0.5f));
}
UnsafeUtilities.WriteArrayElement(Buffer, (_offset + _size) % Capacity, value);
_size++;
UnsafeUtilities.WriteArrayElement(_array.GetUnsafePtr(), (_offset + _count) % Capacity, value);
_count++;
}
/// <summary>
/// Removes and returns the element at the front of the queue. If the queue is empty, an exception is thrown.
/// </summary>
/// <returns>The element that was removed from the front of the queue.</returns>
/// <exception cref="InvalidOperationException">Thrown when attempting to dequeue from an empty queue.</exception>
public T Dequeue()
{
if (_size == 0)
if (_count == 0)
{
throw new InvalidOperationException("Queue is empty.");
}
var value = UnsafeUtilities.ReadArrayElement<T>(Buffer, _offset);
var value = UnsafeUtilities.ReadArrayElement<T>(_array.GetUnsafePtr(), _offset);
_offset = (_offset + 1) % Capacity;
_size--;
_count--;
return value;
}
/// <summary>
/// Attempts to remove and return an item from a collection. Returns a boolean indicating success or failure.
/// </summary>
/// <param name="value">The output variable that will hold the dequeued item if the operation is successful.</param>
/// <returns>True if an item was successfully dequeued, otherwise false.</returns>
public bool TryDequeue([MaybeNullWhen(false)] out T value)
{
if (_size == 0)
if (_count == 0)
{
value = default;
return false;
@@ -71,27 +144,33 @@ public unsafe struct UnsafeQueue<T> : IUnsafeCollection<T>
return true;
}
public void ReAlloc(int newSize)
public void Resize(int newSize)
{
_array.ReAlloc(newSize);
_array.Resize(newSize);
if (_size > newSize)
if (_count > newSize)
{
_size = newSize;
_count = newSize;
}
}
public void Clear()
{
_array.Clear();
_size = 0;
_count = 0;
_offset = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void* GetUnsafePtr()
{
return _array.GetUnsafePtr();
}
public void Dispose()
{
_array.Dispose();
_size = 0;
_count = 0;
_offset = 0;
}
}