Files
Misaki.HighPerformance/Misaki.HighPerformance.Unsafe/Collections/UnsafeHashMap.cs
Misaki 48f2dce778 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.
2025-04-03 09:13:07 +09:00

206 lines
6.8 KiB
C#

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));
}
}