Merge pull request 'develop' (#3) from develop into main

Reviewed-on: #3
This commit was merged in pull request #3.
This commit is contained in:
2025-11-18 14:25:25 +00:00
27 changed files with 530 additions and 398 deletions

1
.gitignore vendored
View File

@@ -35,6 +35,7 @@ bld/
# Visual Studio 2015/2017 cache/options directory # Visual Studio 2015/2017 cache/options directory
.vs/ .vs/
.vscode/
# Uncomment if you have tasks that create the project's static files in wwwroot # Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/ #wwwroot/

View File

View File

@@ -3,7 +3,7 @@
<TargetFrameworks></TargetFrameworks> <TargetFrameworks></TargetFrameworks>
<PackageLicenseUrl>Public Domain</PackageLicenseUrl> <PackageLicenseUrl>Public Domain</PackageLicenseUrl>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFramework>net9.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<Authors>Misaki</Authors> <Authors>Misaki</Authors>
<AssemblyVersion>1.0.0</AssemblyVersion> <AssemblyVersion>1.0.0</AssemblyVersion>
<Version>$(AssemblyVersion)</Version> <Version>$(AssemblyVersion)</Version>

View File

@@ -30,10 +30,10 @@ public sealed unsafe class JobScheduler : IDisposable
private bool _disposed = false; private bool _disposed = false;
public int WorkerCount => _workerThreads.Length;
internal bool IsCancellationRequested => _cts.IsCancellationRequested; internal bool IsCancellationRequested => _cts.IsCancellationRequested;
public int WorkerCount => _workerThreads.Length;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="JobScheduler"/> class with the specified number of worker threads. /// Initializes a new instance of the <see cref="JobScheduler"/> class with the specified number of worker threads.
/// </summary> /// </summary>
@@ -481,7 +481,7 @@ public sealed unsafe class JobScheduler : IDisposable
var completedCount = 0; var completedCount = 0;
foreach (var handle in handles) foreach (var handle in handles)
{ {
if (!_jobInfoPool.Contain(handle._id, handle._generation)) if (!_jobInfoPool.Contains(handle._id, handle._generation))
{ {
completedCount++; completedCount++;
} }
@@ -514,7 +514,7 @@ public sealed unsafe class JobScheduler : IDisposable
{ {
foreach (var handle in handles) foreach (var handle in handles)
{ {
if (!_jobInfoPool.Contain(handle._id, handle._generation)) if (!_jobInfoPool.Contains(handle._id, handle._generation))
{ {
return handle; return handle;
} }
@@ -542,6 +542,7 @@ public sealed unsafe class JobScheduler : IDisposable
_jobQueue.Clear(); _jobQueue.Clear();
_jobDataAllocator.Dispose(); _jobDataAllocator.Dispose();
_workSignal.Dispose();
_cts.Dispose(); _cts.Dispose();
_disposed = true; _disposed = true;

View File

@@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
<TargetFramework>net9.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks> <AllowUnsafeBlocks>True</AllowUnsafeBlocks>
@@ -14,8 +14,17 @@
<RepositoryUrl>https://git.personalnas.com/Misaki/Misaki.HighPerformance.git</RepositoryUrl> <RepositoryUrl>https://git.personalnas.com/Misaki/Misaki.HighPerformance.git</RepositoryUrl>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<IsAotCompatible>True</IsAotCompatible>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<IsAotCompatible>True</IsAotCompatible>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Misaki.HighPerformance.LowLevel\Misaki.HighPerformance.LowLevel.csproj" /> <ProjectReference Include="..\Misaki.HighPerformance.LowLevel\Misaki.HighPerformance.LowLevel.csproj" />
<ProjectReference Include="..\Misaki.HighPerformance\Misaki.HighPerformance.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -8,7 +8,7 @@ namespace Misaki.HighPerformance.LowLevel.Buffer;
/// <summary> /// <summary>
/// Holds information about a memory allocation. /// Holds information about a memory allocation.
/// </summary> /// </summary>
public readonly unsafe struct AllocationInfo public readonly struct AllocationInfo
{ {
/// <summary> /// <summary>
/// Get the size of the allocation in bytes. /// Get the size of the allocation in bytes.
@@ -69,7 +69,7 @@ public static unsafe class AllocationManager
{ {
var selfPtr = (ArenaAllocator*)instance; var selfPtr = (ArenaAllocator*)instance;
var newPtr = selfPtr->_arena.Allocate(newSize, alignment, allocationOption); var newPtr = selfPtr->_arena.Allocate(newSize, alignment, allocationOption);
MemCpy(newPtr, ptr, newSize); MemCpy(newPtr, ptr, Math.Min(oldSize, newSize));
if (allocationOption.HasFlag(AllocationOption.Clear)) if (allocationOption.HasFlag(AllocationOption.Clear))
{ {
@@ -149,7 +149,7 @@ public static unsafe class AllocationManager
private static void* Reallocate(void* instance, void* ptr, nuint oldSize, nuint newSize, nuint alignment, AllocationOption allocationOption) private static void* Reallocate(void* instance, void* ptr, nuint oldSize, nuint newSize, nuint alignment, AllocationOption allocationOption)
{ {
var newPtr = s_stack.Allocate(newSize, alignment, AllocationOption.None); var newPtr = s_stack.Allocate(newSize, alignment, AllocationOption.None);
MemCpy(newPtr, ptr, newSize); MemCpy(newPtr, ptr, Math.Min(oldSize, newSize));
if (allocationOption.HasFlag(AllocationOption.Clear)) if (allocationOption.HasFlag(AllocationOption.Clear))
{ {
@@ -174,7 +174,7 @@ public static unsafe class AllocationManager
} }
} }
private const uint _DEFAULT_MEMORY_POOL_SIZE = 512 * 1024; private const uint _DEFAULT_MEMORY_POOL_SIZE = 512 * 1024; // 512 KB
private static readonly ArenaAllocator* s_pArenaAllocator; private static readonly ArenaAllocator* s_pArenaAllocator;
private static readonly HeapAllocator* s_pHeapAllocator; private static readonly HeapAllocator* s_pHeapAllocator;
@@ -438,13 +438,11 @@ public static unsafe class AllocationManager
} }
var newPtr = AlignedRealloc(ptr, newSize, alignment); var newPtr = AlignedRealloc(ptr, newSize, alignment);
if (allocationOption.HasFlag(AllocationOption.Clear)) if (allocationOption.HasFlag(AllocationOption.Clear)
{ && newSize > oldSize)
if (newSize > oldSize)
{ {
MemClear((byte*)newPtr + oldSize, newSize - oldSize); MemClear((byte*)newPtr + oldSize, newSize - oldSize);
} }
}
return newPtr; return newPtr;
} }
@@ -535,7 +533,7 @@ public static unsafe class AllocationManager
if (unfreeBytes > 0u) if (unfreeBytes > 0u)
{ {
throw new MemoryLeakException(snapshot); throw new MemoryLeakException(CollectionsMarshal.AsSpan(snapshot));
} }
} }
else if (s_activeHeapAllocations != 0) else if (s_activeHeapAllocations != 0)

View File

@@ -0,0 +1,31 @@
namespace Misaki.HighPerformance.LowLevel.Buffer;
public unsafe struct SafeHandle
{
private const nuint _ALIGNMENT = 16u;
public int valid;
public static nuint GetAlignWithHeader(nuint baseAlign)
{
return Math.Max(_ALIGNMENT, baseAlign);
}
public static nuint GetPaddedHeaderSize(nuint baseAlign)
{
var headerBaseSize = (nuint)sizeof(SafeHandle);
var dataAlignment = Math.Max(_ALIGNMENT, baseAlign);
return (headerBaseSize + (dataAlignment - 1u)) & ~(dataAlignment - 1u);
}
public static SafeHandle* GetSafeHandle(void* ptr, nuint baseAlign)
{
if (ptr == null)
{
return null;
}
var alignedHeaderSize = GetPaddedHeaderSize(baseAlign);
return (SafeHandle*)((byte*)ptr - alignedHeaderSize);
}
}

View File

@@ -24,7 +24,7 @@ public unsafe interface IUnsafeCollection : IDisposable
void* GetUnsafePtr(); void* GetUnsafePtr();
} }
public unsafe interface IUnsafeCollection<T> : IUnsafeCollection, IEnumerable<T> public interface IUnsafeCollection<T> : IUnsafeCollection, IEnumerable<T>
where T : unmanaged where T : unmanaged
{ {
/// <summary> /// <summary>
@@ -44,7 +44,40 @@ public unsafe interface IUnsafeCollection<T> : IUnsafeCollection, IEnumerable<T>
void Resize(int newSize, AllocationOption option); 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> /// <summary>
/// The total size of the buffer in bytes. /// The total size of the buffer in bytes.

View File

@@ -1,4 +1,4 @@
using Misaki.HighPerformance.LowLevel.Utilities; using Misaki.HighPerformance.LowLevel.Utilities;
using System.Collections; using System.Collections;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
@@ -20,36 +20,21 @@ public readonly unsafe struct ReadOnlyUnsafeCollection<T> : IEnumerable<T>
{ {
private readonly ReadOnlyUnsafeCollection<T> _collection; private readonly ReadOnlyUnsafeCollection<T> _collection;
private int _index; private int _index;
private T _value;
public readonly T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _value;
}
public readonly T Current => _collection[_index];
readonly object IEnumerator.Current => Current; readonly object IEnumerator.Current => Current;
public Enumerator(ref readonly ReadOnlyUnsafeCollection<T> array) public Enumerator(ref readonly ReadOnlyUnsafeCollection<T> array)
{ {
_collection = array; _collection = array;
_index = -1; _index = -1;
_value = default;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext() public bool MoveNext()
{ {
_index++; _index++;
return _index < _collection.Count;
if (_index < _collection.Count)
{
_value = UnsafeUtility.ReadArrayElement<T>(_collection._buffer, _index);
return true;
}
_value = default;
return false;
} }
public void Reset() public void Reset()
@@ -79,7 +64,8 @@ public readonly unsafe struct ReadOnlyUnsafeCollection<T> : IEnumerable<T>
get => UnsafeUtility.ReadArrayElement<T>(_buffer, index); get => UnsafeUtility.ReadArrayElement<T>(_buffer, index);
} }
public IEnumerator<T> GetEnumerator() => new Enumerator(in this); public Enumerator GetEnumerator() => new Enumerator(in this);
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public ReadOnlyUnsafeCollection(T* buffer, int count) public ReadOnlyUnsafeCollection(T* buffer, int count)

View File

@@ -3,6 +3,7 @@ using Misaki.HighPerformance.LowLevel.Collections.Contracts;
using Misaki.HighPerformance.LowLevel.Contracts; using Misaki.HighPerformance.LowLevel.Contracts;
using Misaki.HighPerformance.LowLevel.Utilities; using Misaki.HighPerformance.LowLevel.Utilities;
using System.Collections; using System.Collections;
using System.Diagnostics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
namespace Misaki.HighPerformance.LowLevel.Collections; namespace Misaki.HighPerformance.LowLevel.Collections;
@@ -57,13 +58,7 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
get get
{ {
#if ENABLE_COLLECTION_CHECKS CheckIndexBounds(index);
if (index < 0 || index >= _count)
{
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
}
#endif
return ref UnsafeUtility.ReadArrayElementRef<T>(_buffer, index); return ref UnsafeUtility.ReadArrayElementRef<T>(_buffer, index);
} }
} }
@@ -73,24 +68,21 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
get get
{ {
#if ENABLE_COLLECTION_CHECKS CheckIndexBounds((int)index);
if (index >= _count)
{
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
}
#endif
return ref UnsafeUtility.ReadArrayElementRef<T>(_buffer, index); return ref UnsafeUtility.ReadArrayElementRef<T>(_buffer, index);
} }
} }
public readonly bool IsCreated public readonly bool IsCreated
{ {
[MethodImpl(MethodImplOptions.AggressiveInlining)] get
get => _buffer != null; {
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<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.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> /// <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) 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); _handle = (AllocationHandle*)Unsafe.AsPointer(ref handle);
_buffer = (T*)handle.Alloc(_handle->Allocator, (uint)count * (uint)sizeof(T), (uint)AlignOf<T>(), allocationOption);
_count = count; _count = count;
} }
@@ -149,7 +148,32 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
_count = count; _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); return new ReadOnlyUnsafeCollection<T>(_buffer, _count);
} }
@@ -157,6 +181,8 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
/// <inheritdoc/> /// <inheritdoc/>
public void Resize(int newSize, AllocationOption option = AllocationOption.None) public void Resize(int newSize, AllocationOption option = AllocationOption.None)
{ {
ThrowIfNotCreated();
if (newSize == Count) if (newSize == Count)
{ {
return; return;
@@ -171,6 +197,7 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void Clear() public readonly void Clear()
{ {
ThrowIfNotCreated();
MemClear(_buffer, (nuint)(Count * sizeof(T))); MemClear(_buffer, (nuint)(Count * sizeof(T)));
} }
@@ -178,6 +205,7 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void* GetUnsafePtr() public readonly void* GetUnsafePtr()
{ {
ThrowIfNotCreated();
return _buffer; return _buffer;
} }
@@ -190,6 +218,8 @@ public unsafe struct UnsafeArray<T> : IUnsafeCollection<T>
public readonly UnsafeArray<U> Reinterpret<U>() public readonly UnsafeArray<U> Reinterpret<U>()
where U : unmanaged where U : unmanaged
{ {
ThrowIfNotCreated();
var totalSize = (nuint)(Count * sizeof(T)); var totalSize = (nuint)(Count * sizeof(T));
if (totalSize % (nuint)sizeof(U) != 0) if (totalSize % (nuint)sizeof(U) != 0)
{ {

View File

@@ -14,47 +14,38 @@ public unsafe struct UnsafeBitSet : IDisposable
private const int _MASK = (1 << 5) - 1; // 0x1F, the mask to get the bit index inside a uint private const int _MASK = (1 << 5) - 1; // 0x1F, the mask to get the bit index inside a uint
private static readonly int s_padding = Vector<uint>.Count; // The padding used for vectorization, the amount of uints required for being vectorized basically private static readonly int s_padding = Vector<uint>.Count; // The padding used for vectorization, the amount of uints required for being vectorized basically
/// <summary>
/// Determines the required length of an <see cref="UnsafeBitSet"/> to hold the passed id or bit.
/// </summary>
/// <param name="id">The id or bit.</param>
/// <returns>A size of required <see cref="uint"/>s for the bitset.</returns>
public static int RequiredLength(int id)
{
return (id >> 5) + int.Sign(id & _BIT_SIZE);
}
/// <summary>
/// Rounds the given length to the next padding size.
/// </summary>
/// <param name="length">The length to round.</param>
/// <returns>The rounded length.</returns>
public static int RoundToPadding(int length)
{
return (length + s_padding - 1) / s_padding * s_padding;
}
/// <summary>
/// The bits from the bitset.
/// </summary>
private UnsafeArray<uint> _bits; private UnsafeArray<uint> _bits;
private int _highestBit;
private int _max;
/// <summary>
/// The highest uint index in use inside the <see cref="_bits"/>-array.
/// </summary>
public readonly int HighestIndex => _max;
/// <summary> /// <summary>
/// The highest bit set. /// The highest bit set.
/// </summary> /// </summary>
private int _highestBit; public readonly int HighestBit => _highestBit;
/// <summary> /// <summary>
/// The maximum <see cref="_bits"/>-index current in use. /// Returns the count of the bitset, how many uints it consists of.
/// </summary> /// </summary>
private int _max; public readonly int Count => _bits.Count;
/// <summary>
/// Gets the total number of bits represented by the current instance.
/// </summary>
public readonly int BitCount => _bits.Count << _INDEX_SIZE;
public readonly bool IsCreated => _bits.IsCreated;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="UnsafeBitSet" /> class. /// Initializes a new instance of the <see cref="UnsafeBitSet" /> class.
/// </summary> /// </summary>
public UnsafeBitSet() public UnsafeBitSet()
{ {
_bits = new UnsafeArray<uint>(s_padding, Allocator.Persistent, AllocationOption.None); _bits = new UnsafeArray<uint>(0, Allocator.Invalid, AllocationOption.None);
} }
/// <summary> /// <summary>
@@ -94,33 +85,19 @@ public unsafe struct UnsafeBitSet : IDisposable
} }
} }
/// <summary> private static int RoundToPadding(int length)
/// The highest uint index in use inside the <see cref="_bits"/>-array.
/// </summary>
public int HighestIndex
{ {
get => _max; return (length + s_padding - 1) / s_padding * s_padding;
} }
/// <summary> /// <summary>
/// The highest bit set. /// Determines the required length of an <see cref="UnsafeBitSet"/> to hold the passed id or bit.
/// </summary> /// </summary>
public int HighestBit /// <param name="id">The id or bit.</param>
/// <returns>A size of required <see cref="uint"/>s for the bitset.</returns>
public static int RequiredLength(int id)
{ {
get => _highestBit; return (id >> _INDEX_SIZE) + int.Sign(id & _BIT_SIZE);
}
/// <summary>
/// Returns the length of the bitset, how many ints it consists of.
/// </summary>
public int Length
{
get => _bits.Count;
}
public bool IsCreated
{
get => _bits.IsCreated;
} }
/// <summary> /// <summary>
@@ -128,7 +105,7 @@ public unsafe struct UnsafeBitSet : IDisposable
/// </summary> /// </summary>
/// <param name="index">The index.</param> /// <param name="index">The index.</param>
/// <returns>True if it is, otherwise false</returns> /// <returns>True if it is, otherwise false</returns>
public bool IsSet(int index) public readonly bool IsSet(int index)
{ {
var b = index >> _INDEX_SIZE; var b = index >> _INDEX_SIZE;
if (b >= _bits.Count) if (b >= _bits.Count)
@@ -149,9 +126,10 @@ public unsafe struct UnsafeBitSet : IDisposable
var b = index >> _INDEX_SIZE; var b = index >> _INDEX_SIZE;
if (b >= _bits.Count) if (b >= _bits.Count)
{ {
_bits.Resize(RoundToPadding(b)); _bits.Resize(index);
} }
// Track highest set bit // Track highest set bit
_highestBit = Math.Max(_highestBit, index); _highestBit = Math.Max(_highestBit, index);
_max = _highestBit / (_BIT_SIZE + 1) + 1; _max = _highestBit / (_BIT_SIZE + 1) + 1;
@@ -228,9 +206,12 @@ public unsafe struct UnsafeBitSet : IDisposable
public void Resize(int minimalLength, AllocationOption option = AllocationOption.None) public void Resize(int minimalLength, AllocationOption option = AllocationOption.None)
{ {
var oldSize = _bits.Count;
var uints = (minimalLength >> _INDEX_SIZE) + int.Sign(minimalLength & _BIT_SIZE); var uints = (minimalLength >> _INDEX_SIZE) + int.Sign(minimalLength & _BIT_SIZE);
var length = RoundToPadding(uints); var length = RoundToPadding(uints);
_bits.Resize(length, option); _bits.Resize(length, option);
_bits.AsSpan()[oldSize..].Clear();
} }
/// <summary> /// <summary>
@@ -238,10 +219,9 @@ public unsafe struct UnsafeBitSet : IDisposable
/// </summary> /// </summary>
/// <param name="other">The other <see cref="UnsafeBitSet"/>.</param> /// <param name="other">The other <see cref="UnsafeBitSet"/>.</param>
/// <returns>True if they match, false if not.</returns> /// <returns>True if they match, false if not.</returns>
[SkipLocalsInit] public readonly bool All(UnsafeBitSet other)
public bool All(UnsafeBitSet other)
{ {
var min = Math.Min(Math.Min(Length, other.Length), _max); var min = Math.Min(Math.Min(Count, other.Count), _max);
if (!Vector.IsHardwareAccelerated || min < s_padding) if (!Vector.IsHardwareAccelerated || min < s_padding)
{ {
var bits = _bits.AsSpan(); var bits = _bits.AsSpan();
@@ -300,9 +280,9 @@ public unsafe struct UnsafeBitSet : IDisposable
/// </summary> /// </summary>
/// <param name="other">The other <see cref="UnsafeBitSet"/>.</param> /// <param name="other">The other <see cref="UnsafeBitSet"/>.</param>
/// <returns>True if they match, false if not.</returns> /// <returns>True if they match, false if not.</returns>
public bool Any(UnsafeBitSet other) public readonly bool Any(UnsafeBitSet other)
{ {
var min = Math.Min(Math.Min(Length, other.Length), _max); var min = Math.Min(Math.Min(Count, other.Count), _max);
if (!Vector.IsHardwareAccelerated || min < s_padding) if (!Vector.IsHardwareAccelerated || min < s_padding)
{ {
var bits = _bits.AsSpan(); var bits = _bits.AsSpan();
@@ -361,9 +341,9 @@ public unsafe struct UnsafeBitSet : IDisposable
/// </summary> /// </summary>
/// <param name="other">The other <see cref="UnsafeBitSet"/>.</param> /// <param name="other">The other <see cref="UnsafeBitSet"/>.</param>
/// <returns>True if none match, false if not.</returns> /// <returns>True if none match, false if not.</returns>
public bool None(UnsafeBitSet other) public readonly bool None(UnsafeBitSet other)
{ {
var min = Math.Min(Math.Min(Length, other.Length), _max); var min = Math.Min(Math.Min(Count, other.Count), _max);
if (!Vector.IsHardwareAccelerated || min < s_padding) if (!Vector.IsHardwareAccelerated || min < s_padding)
{ {
var bits = _bits.AsSpan(); var bits = _bits.AsSpan();
@@ -403,9 +383,9 @@ public unsafe struct UnsafeBitSet : IDisposable
/// </summary> /// </summary>
/// <param name="other">The other <see cref="UnsafeBitSet"/>.</param> /// <param name="other">The other <see cref="UnsafeBitSet"/>.</param>
/// <returns>True if they match, false if not.</returns> /// <returns>True if they match, false if not.</returns>
public bool Exclusive(UnsafeBitSet other) public readonly bool Exclusive(UnsafeBitSet other)
{ {
var min = Math.Min(Math.Min(Length, other.Length), _max); var min = Math.Min(Math.Min(Count, other.Count), _max);
if (!Vector.IsHardwareAccelerated || min < s_padding) if (!Vector.IsHardwareAccelerated || min < s_padding)
{ {
@@ -460,152 +440,85 @@ public unsafe struct UnsafeBitSet : IDisposable
return true; return true;
} }
public unsafe void AndOperation(UnsafeBitSet other) public void And(UnsafeBitSet other)
{ {
var min = Math.Min(Length, other.Length); if (Count != other.Count)
var temp = stackalloc uint[min]; {
throw new ArgumentException("Bitsets must be of the same length for AND operation.");
}
if (!Vector.IsHardwareAccelerated || min < s_padding) if (!Vector.IsHardwareAccelerated || Count < s_padding)
{ {
for (var i = 0; i < min; i++) for (var i = 0; i < Count; i++)
{ {
temp[i] = _bits[i] & other._bits[i]; _bits[i] &= other._bits[i];
} }
} }
else else
{ {
for (var i = 0; i < min; i += s_padding) for (var i = 0; i < Count; i += s_padding)
{ {
var vectorLeft = new Vector<uint>(_bits.AsSpan()[i..]); var vectorLeft = new Vector<uint>(_bits.AsSpan()[i..]);
var vectorRight = new Vector<uint>(other._bits.AsSpan()[i..]); var vectorRight = new Vector<uint>(other._bits.AsSpan()[i..]);
var resultVector = Vector.BitwiseAnd(vectorLeft, vectorRight); var resultVector = Vector.BitwiseAnd(vectorLeft, vectorRight);
resultVector.CopyTo(new Span<uint>(temp + i, s_padding));
resultVector.CopyTo(_bits.AsSpan(i, s_padding));
}
} }
} }
_bits.CopyFrom(new Span<uint>(temp, min)); public void Or(UnsafeBitSet other)
{
if (Count != other.Count)
{
throw new ArgumentException("Bitsets must be of the same length for AND operation.");
} }
public unsafe void OrOperation(UnsafeBitSet other) if (!Vector.IsHardwareAccelerated || Count < s_padding)
{ {
var min = Math.Min(Length, other.Length); for (var i = 0; i < Count; i++)
var temp = stackalloc uint[min];
if (!Vector.IsHardwareAccelerated || min < s_padding)
{ {
for (var i = 0; i < min; i++) _bits[i] |= other._bits[i];
{
temp[i] = _bits[i] | other._bits[i];
} }
} }
else else
{ {
for (var i = 0; i < min; i += s_padding) for (var i = 0; i < Count; i += s_padding)
{ {
var vectorLeft = new Vector<uint>(_bits.AsSpan()[i..]); var vectorLeft = new Vector<uint>(_bits.AsSpan()[i..]);
var vectorRight = new Vector<uint>(other._bits.AsSpan()[i..]); var vectorRight = new Vector<uint>(other._bits.AsSpan()[i..]);
var resultVector = Vector.BitwiseOr(vectorLeft, vectorRight); var resultVector = Vector.BitwiseOr(vectorLeft, vectorRight);
resultVector.CopyTo(new Span<uint>(temp + i, s_padding));
resultVector.CopyTo(_bits.AsSpan(i, s_padding));
}
} }
} }
_bits.CopyFrom(new Span<uint>(temp, min)); public void Xor(UnsafeBitSet other)
{
if (Count != other.Count)
{
throw new ArgumentException("Bitsets must be of the same length for AND operation.");
} }
public unsafe void XorOperation(UnsafeBitSet other) if (!Vector.IsHardwareAccelerated || Count < s_padding)
{ {
var min = Math.Min(Length, other.Length); for (var i = 0; i < Count; i++)
var temp = stackalloc uint[min];
if (!Vector.IsHardwareAccelerated || min < s_padding)
{ {
for (var i = 0; i < min; i++) _bits[i] ^= other._bits[i];
{
temp[i] = _bits[i] ^ other._bits[i];
} }
} }
else else
{ {
for (var i = 0; i < min; i += s_padding) for (var i = 0; i < Count; i += s_padding)
{ {
var vectorLeft = new Vector<uint>(_bits.AsSpan()[i..]); var vectorLeft = new Vector<uint>(_bits.AsSpan()[i..]);
var vectorRight = new Vector<uint>(other._bits.AsSpan()[i..]); var vectorRight = new Vector<uint>(other._bits.AsSpan()[i..]);
var resultVector = Vector.Xor(vectorLeft, vectorRight); var resultVector = Vector.Xor(vectorLeft, vectorRight);
resultVector.CopyTo(new Span<uint>(temp + i, s_padding));
}
}
_bits.CopyFrom(new Span<uint>(temp, min)); resultVector.CopyTo(_bits.AsSpan(i, s_padding));
}
public static UnsafeBitSet operator &(UnsafeBitSet left, UnsafeBitSet right)
{
var min = Math.Min(left.Length, right.Length);
var result = new UnsafeBitSet(min, Allocator.Persistent);
if (!Vector.IsHardwareAccelerated || min < s_padding)
{
for (var i = 0; i < min; i++)
{
result._bits[i] = left._bits[i] & right._bits[i];
} }
} }
else
{
for (var i = 0; i < min; i += s_padding)
{
var vectorLeft = new Vector<uint>(left._bits.AsSpan()[i..]);
var vectorRight = new Vector<uint>(right._bits.AsSpan()[i..]);
var resultVector = Vector.BitwiseAnd(vectorLeft, vectorRight);
resultVector.CopyTo(result._bits.AsSpan(i, s_padding));
}
}
return result;
}
public static UnsafeBitSet operator |(UnsafeBitSet left, UnsafeBitSet right)
{
var min = Math.Min(left.Length, right.Length);
var result = new UnsafeBitSet(min, Allocator.Persistent);
if (!Vector.IsHardwareAccelerated || min < s_padding)
{
for (var i = 0; i < min; i++)
{
result._bits[i] = left._bits[i] | right._bits[i];
}
}
else
{
for (var i = 0; i < min; i += s_padding)
{
var vectorLeft = new Vector<uint>(left._bits.AsSpan()[i..]);
var vectorRight = new Vector<uint>(right._bits.AsSpan()[i..]);
var resultVector = Vector.BitwiseOr(vectorLeft, vectorRight);
resultVector.CopyTo(result._bits.AsSpan(i, s_padding));
}
}
return result;
}
public static UnsafeBitSet operator ~(UnsafeBitSet bitSet)
{
if (!Vector.IsHardwareAccelerated || bitSet.Length < s_padding)
{
for (var i = 0; i < bitSet.Length; i++)
{
bitSet._bits[i] = ~bitSet._bits[i];
}
}
else
{
for (var i = 0; i < bitSet.Length; i += s_padding)
{
var vector = new Vector<uint>(bitSet._bits.AsSpan()[i..]);
var resultVector = ~vector;
resultVector.CopyTo(bitSet._bits.AsSpan(i, s_padding));
}
}
return bitSet;
} }
/// <summary> /// <summary>
@@ -624,10 +537,10 @@ public unsafe struct UnsafeBitSet : IDisposable
/// <param name="span">The <see cref="Span{T}"/> to copy into.</param> /// <param name="span">The <see cref="Span{T}"/> to copy into.</param>
/// <param name="zero">If true, it will zero the unused space from the <see cref="span"/>.</param> /// <param name="zero">If true, it will zero the unused space from the <see cref="span"/>.</param>
/// <returns>The <see cref="Span{T}"/>.</returns> /// <returns>The <see cref="Span{T}"/>.</returns>
public Span<uint> AsSpan(Span<uint> span, bool zero = true) public readonly Span<uint> AsSpan(Span<uint> span, bool zero = true)
{ {
// Copy everything thats possible from one to another // Copy everything thats possible from one to another
var length = Math.Min(Length, span.Length); var length = Math.Min(Count, span.Length);
for (var index = 0; index < length; index++) for (var index = 0; index < length; index++)
{ {
span[index] = _bits[index]; span[index] = _bits[index];
@@ -639,10 +552,10 @@ public unsafe struct UnsafeBitSet : IDisposable
span[index] = 0; span[index] = 0;
} }
return span[..Length]; return span[..Count];
} }
public override string ToString() public readonly override string ToString()
{ {
// Convert uint to binary form for pretty printing // Convert uint to binary form for pretty printing
var binaryBuilder = new StringBuilder(); var binaryBuilder = new StringBuilder();
@@ -652,7 +565,7 @@ public unsafe struct UnsafeBitSet : IDisposable
} }
binaryBuilder.Length--; binaryBuilder.Length--;
return $"{nameof(_bits)}: {binaryBuilder}, {nameof(Length)}: {Length}"; return $"{nameof(_bits)}: {binaryBuilder}, {nameof(Count)}: {Count}";
} }
public void Dispose() public void Dispose()

View File

@@ -7,7 +7,7 @@ using System.Runtime.CompilerServices;
namespace Misaki.HighPerformance.LowLevel.Collections; 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 where TKey : unmanaged, IEquatable<TKey> where TValue : unmanaged
{ {
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>> 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 Count => _helper.Count;
public readonly int Capacity => _hashMap.Capacity; public readonly int Capacity => _helper.Capacity;
public readonly bool IsCreated => _hashMap.IsCreated; public readonly bool IsCreated => _helper.IsCreated;
/// <summary> /// <summary>
/// Gets and sets values by key. /// Gets and sets values by key.
@@ -49,7 +49,7 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
{ {
get 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."); throw new ArgumentException($"Key: {key} is not present.");
} }
@@ -59,10 +59,10 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
set set
{ {
var idx = _hashMap.Find(key); var idx = _helper.Find(key);
if (-1 != idx) if (-1 != idx)
{ {
UnsafeUtility.WriteArrayElement(_hashMap.Buffer, idx, value); UnsafeUtility.WriteArrayElement(_helper.Buffer, idx, value);
return; return;
} }
@@ -84,7 +84,7 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
public UnsafeHashMap(int capacity, ref AllocationHandle handle, AllocationOption allocationOption = AllocationOption.None) 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) 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> /// <returns>True if the key-value pair was added.</returns>
public bool TryAdd(TKey key, TValue item) public bool TryAdd(TKey key, TValue item)
{ {
var idx = _hashMap.TryAdd(key); var idx = _helper.TryAdd(key);
if (idx != -1) if (idx != -1)
{ {
UnsafeUtility.WriteArrayElement(_hashMap.Buffer, idx, item); UnsafeUtility.WriteArrayElement(_helper.Buffer, idx, item);
return true; return true;
} }
@@ -134,7 +134,7 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
/// <returns>True if the value was present.</returns> /// <returns>True if the value was present.</returns>
public bool Remove(TKey key) public bool Remove(TKey key)
{ {
return -1 != _hashMap.TryRemove(key); return -1 != _helper.TryRemove(key);
} }
/// <summary> /// <summary>
@@ -145,7 +145,7 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
/// <returns>True if the key was present.</returns> /// <returns>True if the key was present.</returns>
public bool TryGetValue(TKey key, out TValue item) public bool TryGetValue(TKey key, out TValue item)
{ {
return _hashMap.TryGetValue(key, out item); return _helper.TryGetValue(key, out item);
} }
/// <summary> /// <summary>
@@ -155,51 +155,51 @@ public unsafe struct UnsafeHashMap<TKey, TValue> : IUnsafeCollection<KeyValuePai
/// <returns>True if the key was present.</returns> /// <returns>True if the key was present.</returns>
public bool ContainsKey(TKey key) public bool ContainsKey(TKey key)
{ {
return -1 != _hashMap.Find(key); return -1 != _helper.Find(key);
} }
/// <summary> /// <summary>
/// Sets the capacity to match what it would be if it had been originally initialized with all its entries. /// Sets the capacity to match what it would be if it had been originally initialized with all its entries.
/// </summary> /// </summary>
public void TrimExcess() => _hashMap.TrimExcess(); public void TrimExcess() => _helper.TrimExcess();
public void Resize(int newSize, AllocationOption option = AllocationOption.None) public void Resize(int newSize, AllocationOption option = AllocationOption.None)
{ {
_hashMap.Resize(newSize); _helper.Resize(newSize);
} }
public void Clear() public void Clear()
{ {
_hashMap.Clear(); _helper.Clear();
} }
/// <summary> /// <summary>
/// Retrieves an array of keys from the hash map. /// Retrieves an array of keys from the hash map.
/// </summary> /// </summary>
/// <returns>An array containing the keys stored in the hash map.</returns> /// <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> /// <summary>
/// Retrieves an array of values from the underlying hash map. /// Retrieves an array of values from the underlying hash map.
/// </summary> /// </summary>
/// <returns>An UnsafeArray containing the values stored in the hash map.</returns> /// <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> /// <summary>
/// Retrieves an array of key-value pairs from the hash map. The keys are of type TKey and the values are of type /// Retrieves an array of key-value pairs from the hash map. The keys are of type TKey and the values are of type
/// TValue. /// TValue.
/// </summary> /// </summary>
/// <returns>Returns an UnsafeArray containing KeyValuePair objects.</returns> /// <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)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void* GetUnsafePtr() public readonly void* GetUnsafePtr()
{ {
return _hashMap.Buffer; return _helper.Buffer;
} }
public void Dispose() public void Dispose()
{ {
_hashMap.Dispose(); _helper.Dispose();
} }
} }

View File

@@ -12,7 +12,7 @@ namespace Misaki.HighPerformance.LowLevel.Collections;
/// removing, and checking for values. /// removing, and checking for values.
/// </summary> /// </summary>
/// <typeparam name="T">Represents an unmanaged type that can be compared for equality.</typeparam> /// <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> where T : unmanaged, IEquatable<T>
{ {
public struct Enumerator : IEnumerator<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 Count => _helper.Count;
public readonly int Capacity => _hashMap.Capacity; public readonly int Capacity => _helper.Capacity;
public readonly bool IsCreated => _hashMap.IsCreated; public readonly bool IsCreated => _helper.IsCreated;
public Enumerator GetEnumerator() => new((HashMapHelper<T>*)UnsafeUtility.AddressOf(ref this)); public Enumerator GetEnumerator() => new((HashMapHelper<T>*)UnsafeUtility.AddressOf(ref this));
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator(); 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) 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) 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> /// <returns>True if the value was not already present.</returns>
public bool Add(T item) public bool Add(T item)
{ {
return -1 != _hashMap.TryAdd(item); return -1 != _helper.TryAdd(item);
} }
/// <summary> /// <summary>
@@ -82,7 +82,7 @@ public unsafe struct UnsafeHashSet<T> : IUnsafeCollection<T>, IEnumerable<T>
/// <returns>True if the value was present.</returns> /// <returns>True if the value was present.</returns>
public bool Remove(T item) public bool Remove(T item)
{ {
return -1 != _hashMap.TryRemove(item); return -1 != _helper.TryRemove(item);
} }
/// <summary> /// <summary>
@@ -92,13 +92,13 @@ public unsafe struct UnsafeHashSet<T> : IUnsafeCollection<T>, IEnumerable<T>
/// <returns>True if the value was present.</returns> /// <returns>True if the value was present.</returns>
public bool Contains(T item) public bool Contains(T item)
{ {
return -1 != _hashMap.Find(item); return -1 != _helper.Find(item);
} }
/// <summary> /// <summary>
/// Sets the capacity to match what it would be if it had been originally initialized with all its entries. /// Sets the capacity to match what it would be if it had been originally initialized with all its entries.
/// </summary> /// </summary>
public void TrimExcess() => _hashMap.TrimExcess(); public void TrimExcess() => _helper.TrimExcess();
/// <summary> /// <summary>
/// Returns an array with a copy of this set's values (in no particular order). /// 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> /// <returns>An array with a copy of the set's values.</returns>
public UnsafeArray<T> ToNativeArray(Allocator allocator) public UnsafeArray<T> ToNativeArray(Allocator allocator)
{ {
return _hashMap.GetKeyArray(allocator); return _helper.GetKeyArray(allocator);
} }
public void Resize(int newSize, AllocationOption option = AllocationOption.None) public void Resize(int newSize, AllocationOption option = AllocationOption.None)
{ {
_hashMap.Resize(newSize); _helper.Resize(newSize);
} }
public void Clear() public void Clear()
{ {
_hashMap.Clear(); _helper.Clear();
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly void* GetUnsafePtr() public readonly void* GetUnsafePtr()
{ {
return _hashMap.Buffer; return _helper.Buffer;
} }
public void Dispose() public void Dispose()
{ {
_hashMap.Dispose(); _helper.Dispose();
} }
} }

View File

@@ -57,7 +57,7 @@ public unsafe struct UnsafeSlotMap<T> : IUnsafeCollection<T>
public readonly int Count => _count; public readonly int Count => _count;
public readonly int Capacity => _capacity; public readonly int Capacity => _capacity;
public readonly bool IsCreated => _data.IsCreated && _freeSlots.IsCreated; public readonly bool IsCreated => _data.IsCreated && _generations.IsCreated && _freeSlots.IsCreated && _validBits.IsCreated;
public Enumerator GetEnumerator() => new((UnsafeSlotMap<T>*)UnsafeUtility.AddressOf(ref this)); public Enumerator GetEnumerator() => new((UnsafeSlotMap<T>*)UnsafeUtility.AddressOf(ref this));
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator(); IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
@@ -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 /// <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> /// 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> /// <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) if (slotIndex < 0 || slotIndex >= _capacity)
{ {
@@ -232,14 +232,14 @@ public unsafe struct UnsafeSlotMap<T> : IUnsafeCollection<T>
/// <returns>The element of type <see cref="T"/> stored at the specified slot and generation.</returns> /// <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="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> /// <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) if (slotIndex < 0 || slotIndex >= _capacity)
{ {
throw new ArgumentOutOfRangeException(nameof(slotIndex), "Slot index is out of range."); throw new ArgumentOutOfRangeException(nameof(slotIndex), "Slot index is out of range.");
} }
if (!_validBits.IsSet(slotIndex)|| _generations[slotIndex] != generation) if (!_validBits.IsSet(slotIndex) || _generations[slotIndex] != generation)
{ {
throw new InvalidOperationException($"Slot {slotIndex} is not occupied."); throw new InvalidOperationException($"Slot {slotIndex} is not occupied.");
} }
@@ -294,7 +294,7 @@ public unsafe struct UnsafeSlotMap<T> : IUnsafeCollection<T>
_count = 0; _count = 0;
} }
public readonly unsafe void* GetUnsafePtr() public readonly void* GetUnsafePtr()
{ {
return _data.GetUnsafePtr(); return _data.GetUnsafePtr();
} }
@@ -303,6 +303,7 @@ public unsafe struct UnsafeSlotMap<T> : IUnsafeCollection<T>
{ {
_data.Dispose(); _data.Dispose();
_freeSlots.Dispose(); _freeSlots.Dispose();
_validBits.Dispose();
_count = 0; _count = 0;
_capacity = 0; _capacity = 0;

View File

@@ -10,12 +10,21 @@ namespace Misaki.HighPerformance.LowLevel;
/// <param name="Infos">An array of AllocationInfo containing details about the memory leaks.</param> /// <param name="Infos">An array of AllocationInfo containing details about the memory leaks.</param>
public class MemoryLeakException : Exception public class MemoryLeakException : Exception
{ {
private readonly IEnumerable<AllocationInfo>? _infos; private readonly string _message;
private readonly string _message = string.Empty;
public MemoryLeakException(IEnumerable<AllocationInfo> infos) public override string Message => _message;
public MemoryLeakException(ReadOnlySpan<AllocationInfo> infos)
{ {
_infos = infos; var stringBuilder = new StringBuilder();
stringBuilder.AppendLine($"Found {infos.Length} memory lakes!");
foreach (var info in infos)
{
stringBuilder.AppendLine(GetMessage(info.StackTrace));
}
_message = stringBuilder.ToString();
} }
public MemoryLeakException(string message) public MemoryLeakException(string message)
@@ -44,25 +53,4 @@ public class MemoryLeakException : Exception
return stringBuilder.ToString(); return stringBuilder.ToString();
} }
public override string Message
{
get
{
if (_infos == null)
{
return _message;
}
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine($"Found {_infos.Count()} memory lakes!");
foreach (var info in _infos)
{
stringBuilder.AppendLine(GetMessage(info.StackTrace));
}
return stringBuilder.ToString();
}
}
} }

View File

@@ -1,12 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net9.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks> <AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<Authors>Misaki</Authors> <Authors>Misaki</Authors>
<AssemblyVersion>1.1.2</AssemblyVersion> <AssemblyVersion>1.1.3</AssemblyVersion>
<Version>$(AssemblyVersion)</Version> <Version>$(AssemblyVersion)</Version>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild> <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<PackageProjectUrl>https://git.personalnas.com/Misaki/Misaki.HighPerformance.git</PackageProjectUrl> <PackageProjectUrl>https://git.personalnas.com/Misaki/Misaki.HighPerformance.git</PackageProjectUrl>
@@ -21,10 +21,6 @@
<IsAotCompatible>True</IsAotCompatible> <IsAotCompatible>True</IsAotCompatible>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Misaki.HighPerformance\Misaki.HighPerformance.csproj" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<None Update="Collections\FixedText.tt"> <None Update="Collections\FixedText.tt">
<Generator>TextTemplatingFileGenerator</Generator> <Generator>TextTemplatingFileGenerator</Generator>

View File

@@ -16,7 +16,7 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
public int bucketIndex; public int bucketIndex;
public int nextIndex; public int nextIndex;
public unsafe Enumerator(HashMapHelper<TKey>* data) public Enumerator(HashMapHelper<TKey>* data)
{ {
buffer = data; buffer = data;
index = -1; index = -1;
@@ -73,6 +73,7 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
private int _allocatedIndex; private int _allocatedIndex;
private int _firstFreeIndex; private int _firstFreeIndex;
private readonly int _alignment;
private readonly int _sizeOfTValue; private readonly int _sizeOfTValue;
private readonly int _log2MinGrowth; private readonly int _log2MinGrowth;
@@ -86,55 +87,90 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
public readonly int Capacity => _capacity; public readonly int Capacity => _capacity;
public readonly bool IsCreated => _buffer != null;
public readonly bool IsEmpty => !IsCreated || _count == 0; public readonly bool IsEmpty => !IsCreated || _count == 0;
private static int CalculateDataSize(int capacity, int bucketCapacity, int sizeOfTValue, out int outKeyOffset, out int outNextOffset, out int outBucketOffset) public readonly bool IsCreated
{ {
var sizeOfTKey = sizeof(TKey); get
var sizeOfInt = sizeof(int); {
var handle = SafeHandle.GetSafeHandle(_buffer, (nuint)_alignment);
return handle != null && Volatile.Read(ref handle->valid) == 1;
}
}
var valuesSize = sizeOfTValue * capacity; private static int CalculateDataSize(int capacity, int bucketCapacity, int sizeOfTValue, int alignment, out int outValueOffset, out int outKeyOffset, out int outNextOffset, out int outBucketOffset)
var keysSize = sizeOfTKey * capacity; {
var nextSize = sizeOfInt * capacity; static int AlignUp(int size, int align)
var bucketSize = sizeOfInt * bucketCapacity; {
var totalSize = valuesSize + keysSize + nextSize + bucketSize; return (size + (align - 1)) & ~(align - 1);
}
outKeyOffset = 0 + valuesSize; var headerSize = SafeHandle.GetPaddedHeaderSize((nuint)alignment);
outNextOffset = outKeyOffset + keysSize;
outBucketOffset = outNextOffset + nextSize; var valuesSize = (sizeOfTValue * capacity);
var valuesSizePadded = AlignUp(valuesSize, alignment);
var keysSize = (sizeof(TKey) * capacity);
var keysSizePadded = AlignUp(keysSize, alignment);
var nextSize = (sizeof(int) * capacity);
var nextSizePadded = AlignUp(nextSize, alignment);
// Buckets are the last item, doesn't need padding after it
var bucketSize = (sizeof(int) * bucketCapacity);
outValueOffset = (int)headerSize;
outKeyOffset = outValueOffset + valuesSizePadded;
outNextOffset = outKeyOffset + keysSizePadded;
outBucketOffset = outNextOffset + nextSizePadded;
// Total size is header + all buffers
var totalSize = (int)headerSize + outKeyOffset + keysSizePadded + nextSizePadded + bucketSize;
return totalSize; return totalSize;
} }
public HashMapHelper(int capacity, int sizeOfTValue, uint minGrowth, ref AllocationHandle handle, AllocationOption allocationOption) public HashMapHelper(int capacity, int sizeOfTValue, int alignOfTValue, uint minGrowth, ref AllocationHandle handle, AllocationOption allocationOption)
{ {
if (capacity <= 0) if (capacity <= 0)
{ {
throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be greater than zero."); throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be greater than zero.");
} }
if (sizeOfTValue <= 0) if (sizeOfTValue < 0 || alignOfTValue < 0)
{ {
throw new ArgumentOutOfRangeException(nameof(sizeOfTValue), "Size of TValue must be greater than zero."); throw new ArgumentOutOfRangeException(nameof(sizeOfTValue), "Size or alignment of TValue can not be less than zero.");
} }
_capacity = CalcCapacityCeilPow2(capacity); _capacity = CalcCapacityCeilPow2(capacity);
_bucketCapacity = _capacity * 2; _bucketCapacity = _capacity * 2;
var alignOfKey = (int)AlignOf<TKey>();
var alignOfInt = (int)AlignOf<int>();
var maxDataAlign = Math.Max(Math.Max(alignOfTValue, alignOfKey), alignOfInt);
_alignment = (int)SafeHandle.GetAlignWithHeader((nuint)maxDataAlign);
_sizeOfTValue = sizeOfTValue; _sizeOfTValue = sizeOfTValue;
_log2MinGrowth = BitOperations.Log2(minGrowth); _log2MinGrowth = BitOperations.Log2(minGrowth);
_handle = (AllocationHandle*)Unsafe.AsPointer(ref handle); _handle = (AllocationHandle*)Unsafe.AsPointer(ref handle);
var totalSize = CalculateDataSize(_capacity, _bucketCapacity, sizeOfTValue, var totalSize = CalculateDataSize(_capacity, _bucketCapacity, sizeOfTValue, _alignment,
out var keyOffset, out var nextOffset, out var bucketOffset); out var valueOffset, out var keyOffset, out var nextOffset, out var bucketOffset);
AllocateBuffer(totalSize, keyOffset, nextOffset, bucketOffset, allocationOption); AllocateBuffer(totalSize, valueOffset, keyOffset, nextOffset, bucketOffset, _alignment, allocationOption);
Clear(); Clear();
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private readonly void ThrowIfNotCreated()
{
if (!IsCreated)
{
throw new InvalidOperationException("The HashMapHelper is not created.");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int CeilPow2(int x) private static int CeilPow2(int x)
{ {
@@ -174,20 +210,20 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private void AllocateBuffer(int totalSize, int keyOffset, int nextOffset, int bucketOffset, AllocationOption allocationOption) private void AllocateBuffer(int totalSize, int valueOffset, int keyOffset, int nextOffset, int bucketOffset, int alignment, AllocationOption allocationOption)
{ {
var alignSize = sizeof(TKey) > sizeof(int) ? AlignOf<TKey>() : AlignOf<int>(); var buf = (byte*)_handle->Alloc(_handle->Allocator, (uint)totalSize, (nuint)alignment, allocationOption);
_buffer = (byte*)_handle->Alloc(_handle->Allocator, (uint)totalSize, (uint)alignSize, allocationOption); _buffer = buf + valueOffset;
_keys = (TKey*)(_buffer + keyOffset); _keys = (TKey*)(_buffer + keyOffset);
_next = (int*)(_buffer + nextOffset); _next = (int*)(_buffer + nextOffset);
_buckets = (int*)(_buffer + bucketOffset); _buckets = (int*)(_buffer + bucketOffset);
} }
internal void ResizeExact(int newCapacity, int newBucketCapacity) private void ResizeExact(int newCapacity, int newBucketCapacity)
{ {
var totalSize = CalculateDataSize(newCapacity, newBucketCapacity, _sizeOfTValue, var totalSize = CalculateDataSize(newCapacity, newBucketCapacity, _sizeOfTValue, _alignment,
out var keyOffset, out var nextOffset, out var bucketOffset); out var valueOffset, out var keyOffset, out var nextOffset, out var bucketOffset);
var oldBuffer = _buffer; var oldBuffer = _buffer;
var oldKeys = _keys; var oldKeys = _keys;
@@ -195,7 +231,7 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
var oldBuckets = _buckets; var oldBuckets = _buckets;
var oldBucketCapacity = _bucketCapacity; var oldBucketCapacity = _bucketCapacity;
AllocateBuffer(totalSize, keyOffset, nextOffset, bucketOffset, AllocationOption.None); AllocateBuffer(totalSize, valueOffset, keyOffset, nextOffset, bucketOffset, _alignment, AllocationOption.None);
_capacity = newCapacity; _capacity = newCapacity;
_bucketCapacity = newBucketCapacity; _bucketCapacity = newBucketCapacity;
@@ -213,8 +249,10 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
_handle->Free(_handle->Allocator, oldBuffer); _handle->Free(_handle->Allocator, oldBuffer);
} }
internal void Resize(int newCapacity) public void Resize(int newCapacity)
{ {
ThrowIfNotCreated();
newCapacity = Math.Max(newCapacity, _count); newCapacity = Math.Max(newCapacity, _count);
var newBucketCapacity = CeilPow2(newCapacity * 2); var newBucketCapacity = CeilPow2(newCapacity * 2);
@@ -228,12 +266,16 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
public void TrimExcess() public void TrimExcess()
{ {
ThrowIfNotCreated();
var capacity = CalcCapacityCeilPow2(_count); var capacity = CalcCapacityCeilPow2(_count);
ResizeExact(capacity, capacity * 2); ResizeExact(capacity, capacity * 2);
} }
public int Find(in TKey key) public int Find(in TKey key)
{ {
ThrowIfNotCreated();
if (_allocatedIndex <= 0) if (_allocatedIndex <= 0)
{ {
return -1; return -1;
@@ -263,6 +305,8 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
public int TryAdd(in TKey key) public int TryAdd(in TKey key)
{ {
ThrowIfNotCreated();
var k = key; var k = key;
if (Find(in key) != -1) if (Find(in key) != -1)
{ {
@@ -306,6 +350,8 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
public int TryRemove(in TKey key) public int TryRemove(in TKey key)
{ {
ThrowIfNotCreated();
if (_capacity == 0) if (_capacity == 0)
{ {
return -1; return -1;
@@ -357,6 +403,8 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
public bool TryGetValue<TValue>(in TKey key, out TValue item) public bool TryGetValue<TValue>(in TKey key, out TValue item)
where TValue : unmanaged where TValue : unmanaged
{ {
ThrowIfNotCreated();
var idx = Find(key); var idx = Find(key);
if (idx != -1) if (idx != -1)
@@ -371,6 +419,8 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
public bool MoveNextSearch(ref int bucketIndex, ref int nextIndex, out int index) public bool MoveNextSearch(ref int bucketIndex, ref int nextIndex, out int index)
{ {
ThrowIfNotCreated();
for (int i = bucketIndex, num = _bucketCapacity; i < num; ++i) for (int i = bucketIndex, num = _bucketCapacity; i < num; ++i)
{ {
var idx = _buckets[i]; var idx = _buckets[i];
@@ -394,6 +444,8 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext(ref int bucketIndex, ref int nextIndex, out int index) public bool MoveNext(ref int bucketIndex, ref int nextIndex, out int index)
{ {
ThrowIfNotCreated();
if (nextIndex != -1) if (nextIndex != -1)
{ {
index = nextIndex; index = nextIndex;
@@ -406,6 +458,8 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
internal UnsafeArray<TKey> GetKeyArray(Allocator allocator) internal UnsafeArray<TKey> GetKeyArray(Allocator allocator)
{ {
ThrowIfNotCreated();
var result = new UnsafeArray<TKey>(_count, allocator); var result = new UnsafeArray<TKey>(_count, allocator);
for (int i = 0, count = 0, max = result.Count, capacity = _bucketCapacity; i < capacity && count < max; i++) for (int i = 0, count = 0, max = result.Count, capacity = _bucketCapacity; i < capacity && count < max; i++)
@@ -425,6 +479,8 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
internal UnsafeArray<TValue> GetValueArray<TValue>(Allocator allocator) internal UnsafeArray<TValue> GetValueArray<TValue>(Allocator allocator)
where TValue : unmanaged where TValue : unmanaged
{ {
ThrowIfNotCreated();
var result = new UnsafeArray<TValue>(_count, allocator); var result = new UnsafeArray<TValue>(_count, allocator);
for (int i = 0, count = 0, max = result.Count, capacity = _bucketCapacity; i < capacity && count < max; ++i) for (int i = 0, count = 0, max = result.Count, capacity = _bucketCapacity; i < capacity && count < max; ++i)
@@ -444,6 +500,8 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
public UnsafeArray<KeyValuePair<TKey, TValue>> GetKeyValueArrays<TValue>(Allocator allocator) public UnsafeArray<KeyValuePair<TKey, TValue>> GetKeyValueArrays<TValue>(Allocator allocator)
where TValue : unmanaged where TValue : unmanaged
{ {
ThrowIfNotCreated();
var result = new UnsafeArray<KeyValuePair<TKey, TValue>>(_count, allocator); var result = new UnsafeArray<KeyValuePair<TKey, TValue>>(_count, allocator);
for (int i = 0, count = 0, max = result.Count, capacity = _bucketCapacity; i < capacity && count < max; i++) for (int i = 0, count = 0, max = result.Count, capacity = _bucketCapacity; i < capacity && count < max; i++)
@@ -465,6 +523,8 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
public void Clear() public void Clear()
{ {
ThrowIfNotCreated();
MemSet(_buckets, 0xff, (nuint)_bucketCapacity * sizeof(int)); MemSet(_buckets, 0xff, (nuint)_bucketCapacity * sizeof(int));
MemSet(_next, 0xff, (nuint)_capacity * sizeof(int)); MemSet(_next, 0xff, (nuint)_capacity * sizeof(int));
@@ -475,9 +535,15 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
public void Dispose() public void Dispose()
{ {
if (IsCreated) if (!IsCreated)
{
return;
}
if (_handle != null)
{ {
_handle->Free(_handle->Allocator, _buffer); _handle->Free(_handle->Allocator, _buffer);
}
_buffer = null; _buffer = null;
_keys = null; _keys = null;
@@ -488,5 +554,4 @@ public unsafe struct HashMapHelper<TKey> : IDisposable
_capacity = 0; _capacity = 0;
_bucketCapacity = 0; _bucketCapacity = 0;
} }
}
} }

View File

@@ -422,7 +422,7 @@ namespace Misaki.HighPerformance.Mathematics.CodeGen.Generators
return new {typeName}({string.Join(", ", s_vectorComponents.Take(typeInfo.Row).Select(c => $"lhs + rhs.{c}"))}); return new {typeName}({string.Join(", ", s_vectorComponents.Take(typeInfo.Row).Select(c => $"lhs + rhs.{c}"))});
}} }}
#if false //NET10_0_OR_GREATER #if NET10_0_OR_GREATER
{INLINE_METHOD_ATTRIBUTE} {INLINE_METHOD_ATTRIBUTE}
public void operator +=({typeName} other) public void operator +=({typeName} other)
{{"); {{");

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net9.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks> <AllowUnsafeBlocks>True</AllowUnsafeBlocks>
@@ -13,6 +13,14 @@
<RepositoryUrl>https://git.personalnas.com/Misaki/Misaki.HighPerformance.git</RepositoryUrl> <RepositoryUrl>https://git.personalnas.com/Misaki/Misaki.HighPerformance.git</RepositoryUrl>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<IsAotCompatible>True</IsAotCompatible>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<IsAotCompatible>True</IsAotCompatible>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Misaki.HighPerformance.Mathematics.CodeGen\Misaki.HighPerformance.Mathematics.CodeGen.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" /> <ProjectReference Include="..\Misaki.HighPerformance.Mathematics.CodeGen\Misaki.HighPerformance.Mathematics.CodeGen.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup> </ItemGroup>

View File

@@ -1,55 +1,49 @@
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes;
using Misaki.HighPerformance.LowLevel.Buffer; using Misaki.HighPerformance.LowLevel.Buffer;
using Misaki.HighPerformance.LowLevel.Collections; using Misaki.HighPerformance.LowLevel.Collections;
using System.Runtime.Intrinsics;
namespace Misaki.HighPerformance.Test.Benchmark; namespace Misaki.HighPerformance.Test.Benchmark;
[MemoryDiagnoser] public class CollectionBenchmark
public unsafe class CollectionBenchmark
{ {
private UnsafeArray<Vector256<int>> _array;
[Params(10, 100, 1000)] [Params(10, 100, 1000)]
public int count; public int count;
[GlobalSetup] [GlobalSetup]
public void Setup() public void Setup()
{ {
} _array = new UnsafeArray<Vector256<int>>(count, Allocator.Persistent);
[Benchmark]
public void Array()
{
var array = new int[count];
for (var i = 0; i < count; i++)
{
array[i] = i;
}
}
[Benchmark(Baseline = true)]
public void UnsafeArray()
{
var array = new UnsafeArray<int>(count, Allocator.Temp);
for (var i = 0; i < count; i++)
{
array[i] = i;
}
AllocationManager.ResetTempAllocator();
}
[Benchmark]
public void StackArray()
{
var array = stackalloc int[count];
for (var i = 0; i < count; i++)
{
array[i] = i;
}
} }
[GlobalCleanup] [GlobalCleanup]
public void Cleanup() public void Cleanup()
{ {
AllocationManager.Dispose(); _array.Dispose();
}
[Benchmark]
public void WithCapacityChecks()
{
for (var i = 0; i < _array.Count; i++)
{
if (i < 0 || i >= _array.Count)
{
throw new IndexOutOfRangeException();
}
_array[i] = default;
}
}
[Benchmark]
public void WithoutCapacityChecks()
{
for (var i = 0; i < _array.Count; i++)
{
_array[i] = default;
}
} }
} }

View File

@@ -1,7 +1,6 @@
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes;
using Misaki.HighPerformance.Mathematics; using Misaki.HighPerformance.Mathematics;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics; using System.Runtime.Intrinsics;
namespace Misaki.HighPerformance.Test.Benchmark; namespace Misaki.HighPerformance.Test.Benchmark;
@@ -25,7 +24,7 @@ public unsafe class MathematicsBenchmark
public static f4 operator +(f4 a, f4 b) public static f4 operator +(f4 a, f4 b)
{ {
var result = a._vec + b._vec; var result = a._vec + b._vec;
return Unsafe.As<Vector128<float>, f4>(ref result); return new f4(result);
} }
} }
@@ -108,7 +107,7 @@ public unsafe class MathematicsBenchmark
} }
[Benchmark] [Benchmark]
public unsafe Vector128<float> v128Add() public Vector128<float> v128Add()
{ {
var a = Vector128.Create(1f, 2f, 3f, 4f); var a = Vector128.Create(1f, 2f, 3f, 4f);
var b = Vector128.Create(5f, 6f, 7f, 8f); var b = Vector128.Create(5f, 6f, 7f, 8f);

View File

@@ -2,13 +2,17 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<PublishAot>True</PublishAot> <PublishAot>True</PublishAot>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks> <AllowUnsafeBlocks>True</AllowUnsafeBlocks>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'" />
<ItemGroup> <ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.15.2" /> <PackageReference Include="BenchmarkDotNet" Version="0.15.2" />
<PackageReference Include="MSTest" Version="3.10.1" /> <PackageReference Include="MSTest" Version="3.10.1" />

View File

@@ -18,9 +18,7 @@
//Console.WriteLine($"Count should be {threadCount * 990}, actual: {map.Count}"); //Console.WriteLine($"Count should be {threadCount * 990}, actual: {map.Count}");
//using Misaki.HighPerformance.Test.Benchmark; BenchmarkDotNet.Running.BenchmarkRunner.Run<Misaki.HighPerformance.Test.Benchmark.CollectionBenchmark>();
//BenchmarkDotNet.Running.BenchmarkRunner.Run<MathematicsBenchmark>();
//using Misaki.HighPerformance.LowLevel.Buffer; //using Misaki.HighPerformance.LowLevel.Buffer;
//using Misaki.HighPerformance.LowLevel.Collections; //using Misaki.HighPerformance.LowLevel.Collections;
@@ -40,17 +38,16 @@
// } // }
//} //}
using Misaki.HighPerformance.LowLevel.Buffer; //var arr1 = new Misaki.HighPerformance.LowLevel.Collections.UnsafeArray<int>(10, Misaki.HighPerformance.LowLevel.Buffer.Allocator.Persistent);
using Misaki.HighPerformance.LowLevel.Collections; //var arr2 = arr1;
//AllocationManager.EnableDebugLayer(); //arr1.Dispose();
//var array = new UnsafeArray<int>(10, Allocator.Persistent); //try
//var array2 = new UnsafeArray<int>(10, Allocator.Persistent); //{
//array.Dispose(); // arr2[0] = 42; // This should throw an exception because arr1 has been disposed.
//array2.Dispose(); //}
//AllocationManager.Dispose(); //catch (Exception ex)
//{
using (AllocationManager.CreateStackScope()) // Console.WriteLine($"Caught expected exception: {ex.Message}");
{ //}
var arr = new UnsafeArray<int>(10, Allocator.Stack); //arr2.Dispose(); // This should not cause a double free error because of safe handle.
}

View File

@@ -0,0 +1,78 @@
using Misaki.HighPerformance.LowLevel.Buffer;
using Misaki.HighPerformance.LowLevel.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace Misaki.HighPerformance.Test.UnitTest.Collections;
[TestClass]
public class TestUnsafeBitSet
{
private UnsafeBitSet _set1;
private UnsafeBitSet _set2;
[TestInitialize]
public void Initialize()
{
_set1 = new UnsafeBitSet(16, Allocator.Persistent, AllocationOption.Clear);
_set2 = new UnsafeBitSet(16, Allocator.Persistent, AllocationOption.Clear);
}
[TestCleanup]
public void Cleanup()
{
_set1.Dispose();
_set2.Dispose();
}
[TestMethod]
public void TestBitCount()
{
Assert.AreEqual(256, _set1.BitCount);
}
[TestMethod]
public void TestSetAndGet()
{
Assert.IsFalse(_set1.IsSet(0));
_set1.SetBit(0);
Assert.IsTrue(_set1.IsSet(0));
_set1.ClearBit(0);
Assert.IsFalse(_set1.IsSet(0));
}
[TestMethod]
public void TestClearAll()
{
for (int i = 0; i < _set1.BitCount; i++)
{
_set1.SetBit(i);
}
_set1.ClearAll();
for (int i = 0; i < _set1.BitCount; i++)
{
Assert.IsFalse(_set1.IsSet(i));
}
}
[TestMethod]
public void TestAndOperation()
{
_set1.SetBit(0);
_set1.SetBit(1);
_set2.SetBit(1);
_set2.SetBit(2);
_set1.And(_set2);
Assert.IsFalse(_set1.IsSet(0));
Assert.IsTrue(_set1.IsSet(1));
Assert.IsFalse(_set1.IsSet(2));
}
}

View File

@@ -11,7 +11,7 @@ public class TestUnsafeSlotMap
[TestInitialize] [TestInitialize]
public void Initialize() public void Initialize()
{ {
_slotMap = new UnsafeSlotMap<int>(16, Allocator.Persistent, AllocationOption.Clear); _slotMap = new UnsafeSlotMap<int>(16, Allocator.Persistent);
} }
[TestCleanup] [TestCleanup]

View File

@@ -1,4 +1,4 @@
using System.Collections; using System.Collections;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
@@ -207,7 +207,7 @@ public class ConcurrentSlotMap<T> : IEnumerable<T>
return false; // Another thread already removed it return false; // Another thread already removed it
} }
public bool Contain(int slotIndex, int generation) public bool Contains(int slotIndex, int generation)
{ {
if (slotIndex < 0 || slotIndex >= Volatile.Read(ref _capacity)) if (slotIndex < 0 || slotIndex >= Volatile.Read(ref _capacity))
{ {

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net9.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks> <AllowUnsafeBlocks>True</AllowUnsafeBlocks>