Enhance HashSet AddRange with typed source detection

This commit is contained in:
Marek Lemańczyk committed 2025-07-17 15:37:04 +02:00
1 parent aa48407bba
commit 26f2920f33
1 file changed
+185 -35
@@ -1,6 +1,8 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Numerics;
@@ -10,6 +12,96 @@ namespace Recyclable.Collections
{
internal static class zRecyclableHashSetAddRange
{
private static class AddRangeHelper<T>
{
private static readonly Action<RecyclableHashSet<T>, object>? _dictionaryAdder;
private static readonly Action<RecyclableHashSet<T>, object>? _sortedListAdder;
private static readonly Action<RecyclableHashSet<T>, object>? _sortedDictionaryAdder;
private static readonly Type? _dictionaryType;
private static readonly Type? _sortedListType;
private static readonly Type? _sortedDictionaryType;
static AddRangeHelper()
{
Type elementType = typeof(T);
if (elementType.IsGenericType && elementType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
Type[] args = elementType.GetGenericArguments();
_dictionaryType = typeof(RecyclableDictionary<,>).MakeGenericType(args);
_sortedDictionaryType = typeof(RecyclableSortedDictionary<,>).MakeGenericType(args);
MethodInfo? method = typeof(zRecyclableHashSetAddRange).GetMethod(
nameof(AddRange),
BindingFlags.NonPublic | BindingFlags.Static,
binder: null,
types: new[] { typeof(RecyclableHashSet<>).MakeGenericType(elementType), _dictionaryType },
modifiers: null);
if (method != null)
{
var setParam = Expression.Parameter(typeof(RecyclableHashSet<T>));
var objParam = Expression.Parameter(typeof(object));
var call = Expression.Call(method, setParam, Expression.Convert(objParam, _dictionaryType));
_dictionaryAdder = Expression.Lambda<Action<RecyclableHashSet<T>, object>>(call, setParam, objParam).Compile();
}
method = typeof(zRecyclableHashSetAddRange).GetMethod(
nameof(AddRange),
BindingFlags.NonPublic | BindingFlags.Static,
binder: null,
types: new[] { typeof(RecyclableHashSet<>).MakeGenericType(elementType), _sortedDictionaryType },
modifiers: null);
if (method != null)
{
var setParam = Expression.Parameter(typeof(RecyclableHashSet<T>));
var objParam = Expression.Parameter(typeof(object));
var call = Expression.Call(method, setParam, Expression.Convert(objParam, _sortedDictionaryType));
_sortedDictionaryAdder = Expression.Lambda<Action<RecyclableHashSet<T>, object>>(call, setParam, objParam).Compile();
}
}
else if (elementType.IsGenericType && elementType.GetGenericTypeDefinition() == typeof(ValueTuple<,>))
{
Type[] args = elementType.GetGenericArguments();
_sortedListType = typeof(RecyclableSortedList<,>).MakeGenericType(args);
MethodInfo? method = typeof(zRecyclableHashSetAddRange).GetMethod(
nameof(AddRange),
BindingFlags.NonPublic | BindingFlags.Static,
binder: null,
types: new[] { typeof(RecyclableHashSet<>).MakeGenericType(elementType), _sortedListType },
modifiers: null);
if (method != null)
{
var setParam = Expression.Parameter(typeof(RecyclableHashSet<T>));
var objParam = Expression.Parameter(typeof(object));
var call = Expression.Call(method, setParam, Expression.Convert(objParam, _sortedListType));
_sortedListAdder = Expression.Lambda<Action<RecyclableHashSet<T>, object>>(call, setParam, objParam).Compile();
}
}
}
internal static bool TryAddRange(RecyclableHashSet<T> set, IEnumerable<T> items)
{
if (_dictionaryAdder != null && _dictionaryType!.IsInstanceOfType(items))
{
_dictionaryAdder(set, items);
return true;
}
if (_sortedDictionaryAdder != null && _sortedDictionaryType!.IsInstanceOfType(items))
{
_sortedDictionaryAdder(set, items);
return true;
}
if (_sortedListAdder != null && _sortedListType!.IsInstanceOfType(items))
{
_sortedListAdder(set, items);
return true;
}
return false;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ref RecyclableHashSet<T>.Entry GetEntry<T>(RecyclableHashSet<T> set, int index)
where T : notnull
@@ -1434,48 +1526,106 @@ namespace Recyclable.Collections
internal static void AddRange<T>(this RecyclableHashSet<T> set, IEnumerable<T> items)
where T : notnull
{
foreach (T value in items)
if (items is RecyclableList<T> recyclableList)
{
int requiredCount = set._count + 1;
if (requiredCount > set._entries.Length * set._blockSize)
AddRange(set, recyclableList);
}
else if (items is RecyclableLongList<T> recyclableLongList)
{
AddRange(set, recyclableLongList);
}
else if (items is T[] array)
{
AddRange(set, array);
}
else if (items is List<T> list)
{
AddRange(set, list);
}
else if (items is ICollection<T> iCollection)
{
AddRange(set, iCollection);
}
else if (items is ICollection collection)
{
AddRange(set, collection);
}
else if (items is RecyclableHashSet<T> hashSet)
{
AddRange(set, hashSet);
}
else if (items is RecyclableStack<T> stack)
{
AddRange(set, stack);
}
else if (items is RecyclableSortedSet<T> sortedSet)
{
AddRange(set, sortedSet);
}
else if (items is RecyclableLinkedList<T> linkedList)
{
AddRange(set, linkedList);
}
else if (items is RecyclablePriorityQueue<T> priorityQueue)
{
AddRange(set, priorityQueue);
}
else if (items is RecyclableQueue<T> queue)
{
AddRange(set, queue);
}
else if (AddRangeHelper<T>.TryAddRange(set, items))
{
}
else if (items is IReadOnlyList<T> readOnlyList)
{
AddRange(set, readOnlyList);
}
else
{
foreach (T value in items)
{
EnsureCapacity(set, requiredCount);
}
if (set._count >= (set._buckets.Length * 3) / 4)
{
ResizeBuckets(set, set._buckets.Length << 1);
}
int hash = value?.GetHashCode() & int.MaxValue ?? 0;
int bucketMask = set._buckets.Length - 1;
int bucket = hash & bucketMask;
int index = set._buckets[bucket];
bool exists = false;
while (index >= 0)
{
ref var check = ref GetEntry(set, index);
if (check.HashCode == hash && EqualityComparer<T>.Default.Equals(check.Value, value))
int requiredCount = set._count + 1;
if (requiredCount > set._entries.Length * set._blockSize)
{
exists = true;
break;
EnsureCapacity(set, requiredCount);
}
index = check.Next;
}
if (set._count >= (set._buckets.Length * 3) / 4)
{
ResizeBuckets(set, set._buckets.Length << 1);
}
if (exists)
{
continue;
}
int hash = value?.GetHashCode() & int.MaxValue ?? 0;
int bucketMask = set._buckets.Length - 1;
int bucket = hash & bucketMask;
int insertIndex = set._count++;
ref var entry = ref GetEntry(set, insertIndex);
entry.HashCode = hash;
entry.Value = value!;
entry.Next = set._buckets[bucket];
set._buckets[bucket] = insertIndex;
int index = set._buckets[bucket];
bool exists = false;
while (index >= 0)
{
ref var check = ref GetEntry(set, index);
if (check.HashCode == hash && EqualityComparer<T>.Default.Equals(check.Value, value))
{
exists = true;
break;
}
index = check.Next;
}
if (exists)
{
continue;
}
int insertIndex = set._count++;
ref var entry = ref GetEntry(set, insertIndex);
entry.HashCode = hash;
entry.Value = value!;
entry.Next = set._buckets[bucket];
set._buckets[bucket] = insertIndex;
}
}
}
}