Improve memory safety and alignment handling
Some checks failed
Publish NuGet Packages / publish (pull_request) Failing after 1m5s

- Updated `.gitignore` to include `.vscode/` and clarified comments.
- Introduced `SafeHandle` for managing memory alignment and safe access.
- Refactored `UnsafeArray<T>` to add bounds checking and alignment logic.
- Added `IUnsafeHashCollection<T>` for specialized hash-based collections.
- Refactored `UnsafeHashMap<TKey, TValue>` and `UnsafeHashSet<T>` to use `HashMapHelper<TKey>` with alignment support.
- Made `UnsafeSlotMap<T>` methods `readonly` for immutability.
- Enhanced `HashMapHelper<TKey>` with alignment-aware buffer management and validation.
- Updated benchmarks to use `UnsafeArray<Vector256<int>>` and added capacity checks.
- Incremented assembly version to `1.1.3` in `Misaki.HighPerformance.LowLevel.csproj`.
- Updated `Program.cs` to run `CollectionBenchmark` and demonstrate safe disposal handling.
This commit is contained in:
2025-11-18 01:25:40 +09:00
parent 57725369f9
commit c0a0861897
13 changed files with 309 additions and 140 deletions

View File

@@ -24,7 +24,7 @@ public unsafe interface IUnsafeCollection : IDisposable
void* GetUnsafePtr();
}
public unsafe interface IUnsafeCollection<T> : IUnsafeCollection, IEnumerable<T>
public interface IUnsafeCollection<T> : IUnsafeCollection, IEnumerable<T>
where T : unmanaged
{
/// <summary>
@@ -44,7 +44,40 @@ public unsafe interface IUnsafeCollection<T> : IUnsafeCollection, IEnumerable<T>
void Resize(int newSize, AllocationOption option);
}
public unsafe interface IUnTypedCollection : IUnsafeCollection
public interface IUnsafeHashCollection<T> : IEnumerable<T>, IDisposable
where T : unmanaged
{
/// <summary>
/// Indicates whether the object has been created. Returns true if the object is created, otherwise false.
/// </summary>
bool IsCreated
{
get;
}
/// <summary>
/// Gets the number of elements in a collection. The value is read-only.
/// </summary>
int Count
{
get;
}
/// <summary>
/// Removes all elements from the collection. The collection will be empty after this operation.
/// </summary>
void Clear();
/// <summary>
/// Changes the size of a collection to the specified value.
/// </summary>
/// <remarks>This is to adjust the element count of the collection, not the size of the underlying buffer in memory.</remarks>
/// <param name="newSize">Specifies the new size to which the collection should be adjusted.</param>
/// <param name="option">Specifies allocation options that may affect how memory is managed during the resize operation.</param>
void Resize(int newSize, AllocationOption option);
}
public interface IUnTypedCollection : IUnsafeCollection
{
/// <summary>
/// The total size of the buffer in bytes.

View File

@@ -3,6 +3,7 @@ using Misaki.HighPerformance.LowLevel.Collections.Contracts;
using Misaki.HighPerformance.LowLevel.Contracts;
using Misaki.HighPerformance.LowLevel.Utilities;
using System.Collections;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Misaki.HighPerformance.LowLevel.Collections;
@@ -57,13 +58,7 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
#if ENABLE_COLLECTION_CHECKS
if (index < 0 || index >= _count)
{
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
}
#endif
CheckIndexBounds(index);
return ref UnsafeUtility.ReadArrayElementRef<T>(_buffer, index);
}
}
@@ -73,24 +68,21 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
#if ENABLE_COLLECTION_CHECKS
if (index >= _count)
{
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
}
#endif
CheckIndexBounds((int)index);
return ref UnsafeUtility.ReadArrayElementRef<T>(_buffer, index);
}
}
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _buffer != null;
get
{
var handle = SafeHandle.GetSafeHandle(_buffer, AlignOf<T>());
return handle != null && Volatile.Read(ref handle->valid) == 1;
}
}
public Enumerator GetEnumerator() => new ((UnsafeArray<T>*)UnsafeUtility.AddressOf(ref this));
public Enumerator GetEnumerator() => new((UnsafeArray<T>*)UnsafeUtility.AddressOf(ref this));
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
@@ -111,13 +103,20 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the specified number of elements is less than or equal to zero.</exception>
public UnsafeArray(int count, ref AllocationHandle handle, AllocationOption allocationOption = AllocationOption.None)
{
if (count <= 0)
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), "Count must be greater than zero.");
throw new ArgumentOutOfRangeException(nameof(count), "Count can not be less than zero.");
}
var tAlign = AlignOf<T>();
var headerSize = SafeHandle.GetPaddedHeaderSize(tAlign);
var sizeWithHeader = (nuint)(count * sizeof(T)) + headerSize;
var alignment = SafeHandle.GetAlignWithHeader(tAlign);
var buff = handle.Alloc(handle.Allocator, sizeWithHeader, alignment, allocationOption);
_buffer = (T*)((byte*)buff + headerSize);
_handle = (AllocationHandle*)Unsafe.AsPointer(ref handle);
_buffer = (T*)handle.Alloc(_handle->Allocator, (uint)count * (uint)sizeof(T), (uint)AlignOf<T>(), allocationOption);
_count = count;
}
@@ -149,7 +148,32 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
_count = count;
}
public ReadOnlyUnsafeCollection<T> AsReadOnly()
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private readonly void ThrowIfNotCreated()
{
if (!IsCreated)
{
throw new InvalidOperationException("The UnsafeArray is not created.");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[Conditional("ENABLE_COLLECTION_CHECKS")]
private readonly void CheckIndexBounds(int index)
{
ThrowIfNotCreated();
if (index >= _count)
{
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
}
}
/// <summary>
/// Returns a read-only view of the current collection.
/// </summary>
/// <returns>A <see cref="ReadOnlyUnsafeCollection{T}"/> that provides a read-only view of the elements in the current collection.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ReadOnlyUnsafeCollection<T> AsReadOnly()
{
return new ReadOnlyUnsafeCollection<T>(_buffer, _count);
}
@@ -157,6 +181,8 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
/// <inheritdoc/>
public void Resize(int newSize, AllocationOption option = AllocationOption.None)
{
ThrowIfNotCreated();
if (newSize == Count)
{
return;
@@ -171,6 +197,7 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Clear()
{
ThrowIfNotCreated();
MemClear(_buffer, (nuint)(Count * sizeof(T)));
}
@@ -178,6 +205,7 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void* GetUnsafePtr()
{
ThrowIfNotCreated();
return _buffer;
}
@@ -190,6 +218,8 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
public readonly UnsafeArray<U> Reinterpret<U>()
where U : unmanaged
{
ThrowIfNotCreated();
var totalSize = (nuint)(Count * sizeof(T));
if (totalSize % (nuint)sizeof(U) != 0)
{

View File

@@ -7,7 +7,7 @@ using System.Runtime.CompilerServices;
namespace Misaki.HighPerformance.LowLevel.Collections;
public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePair<TKey, TValue>>
public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeHashCollection<KeyValuePair<TKey, TValue>>
where TKey : unmanaged, IEquatable<TKey> where TValue : unmanaged
{
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>
@@ -32,11 +32,11 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
}
}
private HashMapHelper<TKey> _hashMap;
private HashMapHelper<TKey> _helper;
public readonly int Count => _hashMap.Count;
public readonly int Capacity => _hashMap.Capacity;
public readonly bool IsCreated => _hashMap.IsCreated;
public readonly int Count => _helper.Count;
public readonly int Capacity => _helper.Capacity;
public readonly bool IsCreated => _helper.IsCreated;
/// <summary>
/// Gets and sets values by key.
@@ -49,7 +49,7 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
{
get
{
if (!_hashMap.TryGetValue<TValue>(key, out var result))
if (!_helper.TryGetValue<TValue>(key, out var result))
{
throw new ArgumentException($"Key: {key} is not present.");
}
@@ -59,10 +59,10 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
set
{
var idx = _hashMap.Find(key);
var idx = _helper.Find(key);
if (-1 != idx)
{
UnsafeUtility.WriteArrayElement(_hashMap.Buffer, idx, value);
UnsafeUtility.WriteArrayElement(_helper.Buffer, idx, value);
return;
}
@@ -84,7 +84,7 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
public UnsafeHashMap(int capacity, ref AllocationHandle handle, AllocationOption allocationOption = AllocationOption.None)
{
_hashMap = new HashMapHelper<TKey>(capacity, sizeof(TValue), HashMapHelper<TKey>.MINIMAL_CAPACITY, ref handle, allocationOption);
_helper = new HashMapHelper<TKey>(capacity, sizeof(TValue), (int)AlignOf<TValue>(), HashMapHelper<TKey>.MINIMAL_CAPACITY, ref handle, allocationOption);
}
public UnsafeHashMap(int capacity, Allocator allocator, AllocationOption allocationOption = AllocationOption.None)
@@ -101,10 +101,10 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
/// <returns>True if the key-value pair was added.</returns>
public bool TryAdd(TKey key, TValue item)
{
var idx = _hashMap.TryAdd(key);
var idx = _helper.TryAdd(key);
if (idx != -1)
{
UnsafeUtility.WriteArrayElement(_hashMap.Buffer, idx, item);
UnsafeUtility.WriteArrayElement(_helper.Buffer, idx, item);
return true;
}
@@ -134,7 +134,7 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
/// <returns>True if the value was present.</returns>
public bool Remove(TKey key)
{
return -1 != _hashMap.TryRemove(key);
return -1 != _helper.TryRemove(key);
}
/// <summary>
@@ -145,7 +145,7 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
/// <returns>True if the key was present.</returns>
public bool TryGetValue(TKey key, out TValue item)
{
return _hashMap.TryGetValue(key, out item);
return _helper.TryGetValue(key, out item);
}
/// <summary>
@@ -155,51 +155,51 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
/// <returns>True if the key was present.</returns>
public bool ContainsKey(TKey key)
{
return -1 != _hashMap.Find(key);
return -1 != _helper.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 TrimExcess() => _helper.TrimExcess();
public void Resize(int newSize, AllocationOption option = AllocationOption.None)
{
_hashMap.Resize(newSize);
_helper.Resize(newSize);
}
public void Clear()
{
_hashMap.Clear();
_helper.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);
public UnsafeArray<TKey> GetKeyArray(Allocator allocator) => _helper.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);
public UnsafeArray<TValue> GetValueArray(Allocator allocator) => _helper.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);
public UnsafeArray<KeyValuePair<TKey, TValue>> GetKeyValueArrays(Allocator allocator) => _helper.GetKeyValueArrays<TValue>(allocator);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void* GetUnsafePtr()
{
return _hashMap.Buffer;
return _helper.Buffer;
}
public void Dispose()
{
_hashMap.Dispose();
_helper.Dispose();
}
}

View File

@@ -12,7 +12,7 @@ namespace Misaki.HighPerformance.LowLevel.Collections;
/// 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>
public unsafe struct UnsafeHashSet<T> : IUnsafeHashCollection<T>, IEnumerable<T>
where T : unmanaged, IEquatable<T>
{
public struct Enumerator : IEnumerator<T>
@@ -37,11 +37,11 @@ public unsafe struct UnsafeHashSet<T> : IUnsafeCollection<T>, IEnumerable<T>
}
}
private HashMapHelper<T> _hashMap;
private HashMapHelper<T> _helper;
public readonly int Count => _hashMap.Count;
public readonly int Capacity => _hashMap.Capacity;
public readonly bool IsCreated => _hashMap.IsCreated;
public readonly int Count => _helper.Count;
public readonly int Capacity => _helper.Capacity;
public readonly bool IsCreated => _helper.IsCreated;
public Enumerator GetEnumerator() => new((HashMapHelper<T>*)UnsafeUtility.AddressOf(ref this));
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
@@ -57,7 +57,7 @@ public unsafe struct UnsafeHashSet<T> : IUnsafeCollection<T>, IEnumerable<T>
public UnsafeHashSet(int capacity, ref AllocationHandle handle, AllocationOption allocationOption = AllocationOption.None)
{
_hashMap = new HashMapHelper<T>(capacity, 0, HashMapHelper<T>.MINIMAL_CAPACITY, ref handle, allocationOption);
_helper = new HashMapHelper<T>(capacity, 0, 0, HashMapHelper<T>.MINIMAL_CAPACITY, ref handle, allocationOption);
}
public UnsafeHashSet(int capacity, Allocator allocator, AllocationOption allocationOption = AllocationOption.None)
@@ -72,7 +72,7 @@ public unsafe struct UnsafeHashSet<T> : IUnsafeCollection<T>, IEnumerable<T>
/// <returns>True if the value was not already present.</returns>
public bool Add(T item)
{
return -1 != _hashMap.TryAdd(item);
return -1 != _helper.TryAdd(item);
}
/// <summary>
@@ -82,7 +82,7 @@ public unsafe struct UnsafeHashSet<T> : IUnsafeCollection<T>, IEnumerable<T>
/// <returns>True if the value was present.</returns>
public bool Remove(T item)
{
return -1 != _hashMap.TryRemove(item);
return -1 != _helper.TryRemove(item);
}
/// <summary>
@@ -92,13 +92,13 @@ public unsafe struct UnsafeHashSet<T> : IUnsafeCollection<T>, IEnumerable<T>
/// <returns>True if the value was present.</returns>
public bool Contains(T item)
{
return -1 != _hashMap.Find(item);
return -1 != _helper.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();
public void TrimExcess() => _helper.TrimExcess();
/// <summary>
/// Returns an array with a copy of this set's values (in no particular order).
@@ -107,27 +107,27 @@ public unsafe struct UnsafeHashSet<T> : IUnsafeCollection<T>, IEnumerable<T>
/// <returns>An array with a copy of the set's values.</returns>
public UnsafeArray<T> ToNativeArray(Allocator allocator)
{
return _hashMap.GetKeyArray(allocator);
return _helper.GetKeyArray(allocator);
}
public void Resize(int newSize, AllocationOption option = AllocationOption.None)
{
_hashMap.Resize(newSize);
_helper.Resize(newSize);
}
public void Clear()
{
_hashMap.Clear();
_helper.Clear();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void* GetUnsafePtr()
{
return _hashMap.Buffer;
return _helper.Buffer;
}
public void Dispose()
{
_hashMap.Dispose();
_helper.Dispose();
}
}

View File

@@ -206,7 +206,7 @@ public unsafe struct UnsafeSlotMap<T> : IUnsafeCollection<T>
/// <param name="value">When this method returns, contains the element at the specified slot and generation if found; otherwise, the
/// default value for type <typeparamref name="T"/>.</param>
/// <returns>true if the element at the specified slot index and generation is found; otherwise, false.</returns>
public bool TryGetElementAt(int slotIndex, int generation, out T value)
public readonly bool TryGetElementAt(int slotIndex, int generation, out T value)
{
if (slotIndex < 0 || slotIndex >= _capacity)
{
@@ -232,7 +232,7 @@ public unsafe struct UnsafeSlotMap<T> : IUnsafeCollection<T>
/// <returns>The element of type <see cref="T"/> stored at the specified slot and generation.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="slotIndex"/> is less than zero or greater than or equal to the capacity.</exception>
/// <exception cref="InvalidOperationException">Thrown when the specified slot is not occupied or the generation does not match.</exception>
public T GetElementAt(int slotIndex, int generation)
public readonly T GetElementAt(int slotIndex, int generation)
{
if (slotIndex < 0 || slotIndex >= _capacity)
{