< Summary

Information
Class: SwiftCollections.SwiftDictionary<T1, T2>
Assembly: SwiftCollections
File(s): /home/runner/work/SwiftCollections/SwiftCollections/src/SwiftCollections/Collection/SwiftDictionary.cs
Line coverage
95%
Covered lines: 590
Uncovered lines: 30
Coverable lines: 620
Total lines: 1241
Line coverage: 95.1%
Branch coverage
85%
Covered branches: 229
Total branches: 268
Branch coverage: 85.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor()100%11100%
.ctor(...)100%11100%
.ctor(...)100%22100%
.ctor(...)75%44100%
.ctor(...)100%11100%
get_Count()100%11100%
get_Capacity()100%11100%
get_Comparer()100%11100%
get_Item(...)100%11100%
set_Item(...)100%22100%
System.Collections.IDictionary.get_Item(...)100%66100%
System.Collections.IDictionary.set_Item(...)100%11100%
get_Keys()100%22100%
System.Collections.IDictionary.get_Keys()100%22100%
get_Values()100%22100%
System.Collections.IDictionary.get_Values()100%22100%
System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.get_IsReadOnly()100%11100%
System.Collections.IDictionary.get_IsReadOnly()100%11100%
System.Collections.IDictionary.get_IsFixedSize()100%11100%
System.Collections.ICollection.get_IsSynchronized()100%11100%
get_SyncRoot()100%22100%
get_State()100%22100%
set_State(...)83.33%66100%
Add(...)100%11100%
System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(...)100%11100%
System.Collections.Generic.IDictionary<TKey,TValue>.Add(...)100%11100%
System.Collections.IDictionary.Add(...)100%1160%
InsertIfNotExist(...)100%1414100%
Remove(...)100%1616100%
System.Collections.IDictionary.Remove(...)75%44100%
System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Remove(...)75%44100%
Clear()100%44100%
CheckLoadThreshold()100%22100%
EnsureCapacity(...)100%22100%
Resize(...)100%88100%
TrimExcess()83.33%121285.71%
CalculateAdaptiveResizeFactors(...)100%66100%
Initialize(...)100%22100%
ContainsKey(...)100%11100%
System.Collections.IDictionary.Contains(...)100%44100%
System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Contains(...)100%44100%
TryGetValue(...)100%22100%
CopyTo(...)75%88100%
System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.CopyTo(...)100%11100%
System.Collections.ICollection.CopyTo(...)90.9%232286.66%
SetComparer(...)100%2287.5%
SwitchToRandomizedComparer()100%2287.5%
RehashEntries()100%88100%
FindEntry(...)92.85%1414100%
GetEnumerator()100%11100%
System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>.GetEnumerator()100%11100%
System.Collections.IEnumerable.GetEnumerator()100%11100%
System.Collections.IDictionary.GetEnumerator()100%11100%
.ctor(...)100%11100%
System.Collections.IDictionaryEnumerator.get_Key()50%22100%
System.Collections.IDictionaryEnumerator.get_Value()50%22100%
System.Collections.IDictionaryEnumerator.get_Entry()100%22100%
get_Current()100%11100%
System.Collections.IEnumerator.get_Current()75%44100%
MoveNext()83.33%6692.3%
Reset()50%2283.33%
Dispose()100%11100%
.ctor(...)50%22100%
get_Count()100%11100%
System.Collections.ICollection.get_IsSynchronized()100%11100%
System.Collections.ICollection.get_SyncRoot()100%11100%
System.Collections.Generic.ICollection<TKey>.get_IsReadOnly()100%11100%
System.Collections.Generic.ICollection<TKey>.Add(...)100%11100%
System.Collections.Generic.ICollection<TKey>.Clear()100%11100%
System.Collections.Generic.ICollection<TKey>.Contains(...)100%11100%
System.Collections.Generic.ICollection<TKey>.Remove(...)100%11100%
CopyTo(...)75%88100%
System.Collections.ICollection.CopyTo(...)62.5%171687.5%
GetEnumerator()100%11100%
System.Collections.Generic.IEnumerable<TKey>.GetEnumerator()100%11100%
System.Collections.IEnumerable.GetEnumerator()100%11100%
.ctor(...)100%11100%
get_Current()100%11100%
System.Collections.IEnumerator.get_Current()50%22100%
MoveNext()100%66100%
Reset()50%2283.33%
Dispose()100%11100%
.ctor(...)50%22100%
get_Count()100%11100%
System.Collections.Generic.ICollection<TValue>.get_IsReadOnly()100%11100%
System.Collections.ICollection.get_IsSynchronized()100%11100%
System.Collections.ICollection.get_SyncRoot()100%11100%
System.Collections.Generic.ICollection<TValue>.Add(...)100%11100%
System.Collections.Generic.ICollection<TValue>.Clear()100%11100%
System.Collections.Generic.ICollection<TValue>.Contains(...)83.33%6687.5%
System.Collections.Generic.ICollection<TValue>.Remove(...)100%11100%
CopyTo(...)75%88100%
System.Collections.ICollection.CopyTo(...)68.75%181680.95%
GetEnumerator()100%11100%
System.Collections.Generic.IEnumerable<TValue>.GetEnumerator()100%11100%
System.Collections.IEnumerable.GetEnumerator()100%11100%
.ctor(...)100%11100%
get_Current()100%11100%
System.Collections.IEnumerator.get_Current()50%22100%
MoveNext()83.33%6684.61%
Reset()50%2283.33%
Dispose()100%11100%

File(s)

/home/runner/work/SwiftCollections/SwiftCollections/src/SwiftCollections/Collection/SwiftDictionary.cs

#LineLine coverage
 1using MemoryPack;
 2using System;
 3using System.Collections;
 4using System.Collections.Generic;
 5using System.Runtime.CompilerServices;
 6using System.Text.Json.Serialization;
 7
 8namespace SwiftCollections;
 9
 10/// <summary>
 11/// A high-performance, memory-efficient dictionary providing lightning-fast O(1) operations for addition, retrieval, an
 12/// </summary>
 13/// <typeparam name="TKey">Specifies the type of keys in the dictionary.</typeparam>
 14/// <typeparam name="TValue">Specifies the type of values in the dictionary.</typeparam>
 15/// <remarks>
 16/// The comparer is not serialized. After deserialization the dictionary reverts
 17/// to the same default comparer selection used by a new instance. String keys
 18/// use SwiftCollections' deterministic default comparer. Object keys use a
 19/// SwiftCollections comparer that hashes strings deterministically, while other
 20/// object-key determinism still depends on the underlying key type's
 21/// <see cref="object.GetHashCode()"/> implementation. Other key types use
 22/// <see cref="EqualityComparer{TKey}.Default"/>.
 23///
 24/// If a custom comparer is required it can be reapplied using
 25/// <see cref="SetComparer(IEqualityComparer{TKey})"/>.
 26/// </remarks>
 27[Serializable]
 28[JsonConverter(typeof(SwiftStateJsonConverterFactory))]
 29[MemoryPackable]
 30public partial class SwiftDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary
 31{
 32    #region Constants
 33
 34    /// <summary>
 35    /// The default initial capacity of the dictionary.
 36    /// </summary>
 37    public const int DefaultCapacity = 8;
 38
 39    /// <summary>
 40    /// Determines the maximum allowable load factor before resizing the hash set to maintain performance.
 41    /// </summary>
 42    private const double _LoadFactorThreshold = 0.82;
 43
 44    #endregion
 45
 46    #region Fields
 47
 48    /// <summary>
 49    /// The array containing the entries of the dictionary.
 50    /// </summary>
 51    protected Entry[] _entries;
 52
 53    /// <summary>
 54    /// The total number of entries in the dictionary
 55    /// </summary>
 56    private int _count;
 57
 58    /// <summary>
 59    /// The index of the last used entry in the dictionary.
 60    /// </summary>
 61    private int _lastIndex;
 62
 63    /// <summary>
 64    /// A mask used for efficiently computing the entry arrayIndex from a hash code.
 65    /// This is typically the size of the entry array minus one, assuming the size is a power of two.
 66    /// </summary>
 67    private int _entryMask;
 68
 69    /// <summary>
 70    /// The comparer used to determine equality of keys and to generate hash codes.
 71    /// </summary>
 72    protected IEqualityComparer<TKey> _comparer;
 73
 74    /// <summary>
 75    /// Specifies the dynamic growth factor for resizing, adjusted based on recent usage patterns.
 76    /// </summary>
 77    private int _adaptiveResizeFactor;
 78
 79    /// <summary>
 80    /// Tracks the count threshold at which the hash set should resize based on the load factor.
 81    /// </summary>
 82    private uint _nextResizeCount;
 83
 84    /// <summary>
 85    /// Represents the moving average of the fill rate, used to dynamically adjust resizing behavior.
 86    /// </summary>
 87    private double _movingFillRate;
 88
 89    /// <summary>
 90    /// The maximum number of steps allowed during probing to resolve collisions.
 91    /// </summary>
 92    private int _maxStepCount;
 93
 94    /// <summary>
 95    /// A version counter used to track modifications to the dictionary.
 96    /// Incremented on mutations to detect changes during enumeration and ensure enumerator validity.
 97    /// </summary>
 98    [NonSerialized]
 99    protected uint _version;
 100
 101    /// <summary>
 102    /// An object that can be used to synchronize access to the SwiftDictionary.
 103    /// </summary>
 104    [NonSerialized]
 105    private object _syncRoot;
 106
 107    #endregion
 108
 109    #region Nested Types
 110
 111    /// <summary>
 112    /// Represents a single key-value pair in the dictionary, including its hash code for quick access.
 113    /// </summary>
 114    protected struct Entry
 115    {
 116        public TKey Key;
 117        public TValue Value;
 118        public int HashCode;    // Lower 31 bits of hash code, -1 if unused
 119        public bool IsUsed;
 120    }
 121
 122    #endregion
 123
 124    #region Constructors
 125
 126    /// <summary>
 127    /// Initialize a new instance of <see cref="SwiftDictionary{TKey, TValue}"/> with customizable capacity and comparer
 128    /// </summary>
 255129    public SwiftDictionary() : this(DefaultCapacity, null) { }
 130
 131    /// <inheritdoc cref="SwiftDictionary()"/>
 204132    public SwiftDictionary(int capacity, IEqualityComparer<TKey> comparer = null)
 204133    {
 204134        Initialize(capacity, comparer);
 204135    }
 136
 137    /// <inheritdoc cref="SwiftDictionary()"/>
 2138    public SwiftDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer = null)
 2139    {
 2140        SwiftThrowHelper.ThrowIfNull(dictionary, nameof(dictionary));
 141
 1142        Initialize(dictionary.Count, comparer);
 143
 7144        foreach (KeyValuePair<TKey, TValue> kvp in dictionary)
 2145            InsertIfNotExist(kvp.Key, kvp.Value);
 1146    }
 147
 148    /// <inheritdoc cref="SwiftDictionary()"/>
 2149    public SwiftDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer = null)
 2150    {
 2151        SwiftThrowHelper.ThrowIfNull(collection, nameof(collection));
 152
 1153        int count = (collection as ICollection<TKey>)?.Count ?? DefaultCapacity;
 154        // Dynamic padding based on collision estimation
 1155        int size = (int)(count / _LoadFactorThreshold);
 1156        Initialize(size, comparer);
 157
 7158        foreach (KeyValuePair<TKey, TValue> kvp in collection)
 2159            InsertIfNotExist(kvp.Key, kvp.Value);
 1160    }
 161
 162    ///  <summary>
 163    ///  Initializes a new instance of the <see cref="SwiftDictionary{TKey, TValue}"/> class with the specified <see cre
 164    ///  </summary>
 165    ///  <param name="state">The state containing the internal array, count, offset, and version for initialization.</pa
 166    [MemoryPackConstructor]
 10167    public SwiftDictionary(SwiftDictionaryState<TKey, TValue> state)
 10168    {
 10169        State = state;
 10170    }
 171
 172    #endregion
 173
 174    #region Properties
 175
 176    /// <summary>
 177    /// Gets the number of elements contained in the dictionary.
 178    /// </summary>
 179    [JsonIgnore]
 180    [MemoryPackIgnore]
 22181    public int Count => _count;
 182
 183    [JsonIgnore]
 184    [MemoryPackIgnore]
 7185    public int Capacity => _entries.Length;
 186
 187    [JsonIgnore]
 188    [MemoryPackIgnore]
 11189    public IEqualityComparer<TKey> Comparer => _comparer;
 190
 191    [JsonIgnore]
 192    [MemoryPackIgnore]
 193    public TValue this[TKey key]
 194    {
 195        get
 4160196        {
 4160197            int index = FindEntry(key);
 4160198            SwiftThrowHelper.ThrowIfKeyInvalid(index, key);
 4158199            return _entries[index].Value;
 4158200        }
 201        set
 9567202        {
 9567203            int index = FindEntry(key);
 9567204            if (index >= 0)
 6512205                _entries[index].Value = value;
 206            else
 3055207            {
 3055208                CheckLoadThreshold();
 3055209                InsertIfNotExist(key, value);
 3055210            }
 9567211        }
 212    }
 213
 214    [JsonIgnore]
 215    [MemoryPackIgnore]
 216    object IDictionary.this[object obj]
 217    {
 218        get
 17219        {
 17220            SwiftThrowHelper.ThrowIfNull(obj, nameof(obj));
 221
 16222            if (obj is TKey key)
 15223            {
 15224                int index = FindEntry(key);
 29225                if (index >= 0) return _entries[index].Value;
 1226            }
 2227            return null;
 16228        }
 229        set
 4230        {
 4231            SwiftThrowHelper.ThrowIfNullAndNullsAreIllegal(value, default(TValue));
 232            try
 4233            {
 4234                TKey tempKey = (TKey)obj;
 235                try
 3236                {
 3237                    this[tempKey] = (TValue)value;
 2238                }
 1239                catch (InvalidCastException)
 1240                {
 1241                    throw new ArgumentException($"Value {value} does not match expected {typeof(TValue)}");
 242                }
 2243            }
 1244            catch (InvalidCastException)
 1245            {
 1246                throw new ArgumentException($"Key {obj} does not match expected {typeof(TKey)}");
 247            }
 2248        }
 249    }
 250
 251    /// <summary>
 252    /// The collection containing the keys of the dictionary.
 253    /// </summary>
 254    [JsonIgnore]
 255    [MemoryPackIgnore]
 256    private KeyCollection _keyCollection;
 257
 258    [JsonIgnore]
 259    [MemoryPackIgnore]
 10260    public ICollection<TKey> Keys => _keyCollection ??= new KeyCollection(this);
 261
 262    [JsonIgnore]
 263    [MemoryPackIgnore]
 4264    ICollection IDictionary.Keys => _keyCollection ??= new KeyCollection(this);
 265
 266    /// <summary>
 267    /// The collection containing the values of the dictionary.
 268    /// </summary>
 269    [JsonIgnore]
 270    [MemoryPackIgnore]
 271    private ValueCollection _valueCollection;
 272
 273    [JsonIgnore]
 274    [MemoryPackIgnore]
 10275    public ICollection<TValue> Values => _valueCollection ??= new ValueCollection(this);
 276
 277    [JsonIgnore]
 278    [MemoryPackIgnore]
 1279    ICollection IDictionary.Values => _valueCollection ??= new ValueCollection(this);
 280
 281    [JsonIgnore]
 282    [MemoryPackIgnore]
 1283    bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => false;
 284
 285    [JsonIgnore]
 1286    [MemoryPackIgnore] bool IDictionary.IsReadOnly => false;
 1287    bool IDictionary.IsFixedSize => false;
 288
 289    [JsonIgnore]
 290    [MemoryPackIgnore]
 1291    bool ICollection.IsSynchronized => false;
 292
 293    [JsonIgnore]
 294    [MemoryPackIgnore]
 3295    public object SyncRoot => _syncRoot ??= new object();
 296
 297    [JsonInclude]
 298    [MemoryPackInclude]
 299    public SwiftDictionaryState<TKey, TValue> State
 300    {
 301        get
 14302        {
 14303            if (_count == 0)
 2304                return new SwiftDictionaryState<TKey, TValue>(Array.Empty<KeyValuePair<TKey, TValue>>());
 305
 12306            var items = new KeyValuePair<TKey, TValue>[_count];
 12307            CopyTo(items, 0);
 308
 12309            return new SwiftDictionaryState<TKey, TValue>(items);
 14310        }
 311        internal set
 15312        {
 15313            var items = value.Items;
 15314            int count = items?.Length ?? 0;
 315
 15316            if (count == 0)
 3317            {
 3318                Initialize(DefaultCapacity);
 3319                _count = 0;
 3320                _version = 0;
 3321                return;
 322            }
 323
 12324            int size = (int)(count / _LoadFactorThreshold);
 12325            Initialize(size);
 326
 108327            foreach (var kvp in items)
 36328                InsertIfNotExist(kvp.Key, kvp.Value);
 329
 12330            _version = 0;
 15331        }
 332    }
 333
 334    #endregion
 335
 336    #region Collection Manipulation
 337
 338    /// <summary>
 339    /// Attempts to add the specified key and value to the dictionary.
 340    /// </summary>
 341    /// <param name="key">The key of the element to add.</param>
 342    /// <param name="value">The value of the element to add.</param>
 343    /// <returns>
 344    /// true if the key/value pair was added to the dictionary successfully;
 345    /// false if the key already exists.
 346    /// </returns>
 347    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 348    public virtual bool Add(TKey key, TValue value)
 116450349    {
 116450350        CheckLoadThreshold();
 116450351        return InsertIfNotExist(key, value);
 116448352    }
 353
 1354    void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) => Add(item.Key, item.Value);
 1355    void IDictionary<TKey, TValue>.Add(TKey key, TValue value) => Add(key, value);
 356    void IDictionary.Add(object key, object value)
 2357    {
 2358        SwiftThrowHelper.ThrowIfNullAndNullsAreIllegal(value, default(TValue));
 359
 360        try
 2361        {
 2362            TKey tempKey = (TKey)key;
 363            try
 1364            {
 1365                Add(tempKey, (TValue)value);
 0366            }
 0367            catch (InvalidCastException)
 0368            {
 0369                throw new ArgumentException($"Value {value} does not match expected {typeof(TValue)}");
 370            }
 0371        }
 1372        catch (InvalidCastException)
 1373        {
 1374            throw new ArgumentException($"Key {key} does not match expected {typeof(TKey)}");
 375        }
 0376    }
 377
 378    /// <summary>
 379    /// Inserts a key/value pair into the dictionary. If the key already exists and
 380    /// pair is added, or the method returns false if the key already exists.
 381    /// </summary>
 382    /// <param name="key">The key to insert or update.</param>
 383    /// <param name="value">The value to insert or update.</param>
 384    /// <returns>
 385    /// true if the key/value pair was added to the dictionary successfully;
 386    /// false if the key already exists.
 387    /// </returns>
 388    /// <exception cref="ArgumentNullException">Thrown when the key is null.</exception>
 389    internal virtual bool InsertIfNotExist(TKey key, TValue value)
 119546390    {
 119546391        SwiftThrowHelper.ThrowIfNull(key, nameof(key));
 392
 119544393        int hashCode = _comparer.GetHashCode(key) & 0x7FFFFFFF;
 119544394        int entryIndex = hashCode & _entryMask;
 395
 119544396        int step = 1;
 267525397        while (_entries[entryIndex].IsUsed)
 148023398        {
 148023399            if (_entries[entryIndex].HashCode == hashCode && _comparer.Equals(_entries[entryIndex].Key, key))
 42400                return false; // Item already exists
 401
 147981402            entryIndex = (entryIndex + step * step) & _entryMask; // Quadratic probing
 147981403            step++;
 147981404        }
 405
 134928406        if ((uint)entryIndex > (uint)_lastIndex) _lastIndex = entryIndex;
 407
 119502408        _entries[entryIndex].HashCode = hashCode;
 119502409        _entries[entryIndex].Key = key;
 119502410        _entries[entryIndex].Value = value;
 119502411        _entries[entryIndex].IsUsed = true;
 119502412        _count++;
 119502413        _version++;
 414
 119502415        if ((uint)step > (uint)_maxStepCount)
 321416        {
 321417            _maxStepCount = step;
 321418            if (_comparer is not IRandomedEqualityComparer && _maxStepCount > 100)
 1419                SwitchToRandomizedComparer();  // Attempt to recompute hash code with potential randomization for better
 321420        }
 421
 422
 119502423        return true;
 119544424    }
 425
 426    public virtual bool Remove(TKey key)
 6026427    {
 6027428        if (key == null) return false;
 429
 6025430        int hashCode = _comparer.GetHashCode(key) & 0x7FFFFFFF;
 6025431        int entryIndex = hashCode & _entryMask;
 432
 6025433        int step = 0;
 6456434        while ((uint)step <= (uint)_lastIndex)
 6455435        {
 6455436            ref Entry entry = ref _entries[entryIndex];
 437            // Stop probing if an unused entry is found (not deleted)
 6455438            if (!entry.IsUsed && entry.HashCode != -1)
 1439                return false;
 6454440            if (entry.IsUsed && entry.HashCode == hashCode && _comparer.Equals(entry.Key, key))
 6023441            {
 442                // Mark entry as deleted
 6023443                entry.IsUsed = false;
 6023444                entry.Key = default;
 6023445                entry.Value = default;
 6023446                entry.HashCode = -1;
 6023447                _count--;
 6030448                if ((uint)_count == 0) _lastIndex = 0;
 6023449                _version++;
 6023450                return true;
 451            }
 452
 453            // Move to the next entry using linear probing
 431454            step++;
 431455            entryIndex = (entryIndex + step * step) & _entryMask;
 431456        }
 1457        return false; // Item not found after full loop
 6026458    }
 459
 460    void IDictionary.Remove(object obj)
 1461    {
 1462        SwiftThrowHelper.ThrowIfNull(obj, nameof(obj));
 2463        if (obj is TKey key) Remove(key);
 1464    }
 465
 466    bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
 2467    {
 2468        int index = FindEntry(item.Key);
 2469        if (index >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[index].Value, item.Value))
 1470        {
 1471            Remove(item.Key);
 1472            return true;
 473        }
 1474        return false;
 2475    }
 476
 477    public virtual void Clear()
 18478    {
 20479        if ((uint)_count == 0) return;
 480
 170481        for (uint i = 0; i <= (uint)_lastIndex; i++)
 69482        {
 69483            _entries[i].HashCode = -1;
 69484            _entries[i].Key = default;
 69485            _entries[i].Value = default;
 69486            _entries[i].IsUsed = false;
 69487        }
 488
 16489        _count = 0;
 16490        _lastIndex = 0;
 16491        _maxStepCount = 0;
 16492        _movingFillRate = 0;
 16493        _adaptiveResizeFactor = 4;
 494
 16495        _version++;
 18496    }
 497
 498    #endregion
 499
 500    #region Capacity Management
 501
 502    /// <summary>
 503    /// Ensures that the dictionary is resized when the current load factor exceeds the predefined threshold.
 504    /// </summary>
 505    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 506    protected void CheckLoadThreshold()
 119506507    {
 119506508        if ((uint)_count >= _nextResizeCount)
 48509            Resize(_entries.Length * _adaptiveResizeFactor);
 119506510    }
 511
 512    /// <summary>
 513    /// Ensures that the dictionary can hold up to the specified number of entries, if not it resizes.
 514    /// </summary>
 515    /// <param name="capacity">The minimum capacity to ensure.</param>
 516    /// <returns>The new capacity of the dictionary.</returns>
 517    /// <exception cref="ArgumentOutOfRangeException">The capacity is less than zero.</exception>
 518    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 519    public void EnsureCapacity(int capacity)
 1520    {
 1521        capacity = SwiftHashTools.NextPowerOfTwo(capacity);  // Capacity must be a power of 2 for proper masking
 1522        if (capacity > _entries.Length)
 1523            Resize(capacity);
 1524    }
 525
 526    /// <summary>
 527    /// Resizes the internal arrays to the specified new size.
 528    /// </summary>
 529    /// <param name="newSize">The new size for the internal arrays.</param>
 530    private void Resize(int newSize)
 49531    {
 49532        Entry[] newEntries = new Entry[newSize];
 49533        int newMask = newSize - 1;
 534
 49535        int lastIndex = 0;
 116950536        for (uint i = 0; i <= (uint)_lastIndex; i++)
 58426537        {
 58426538            if (_entries[i].IsUsed) // Only rehash valid entries
 50062539            {
 50062540                ref Entry oldEntry = ref _entries[i];
 50062541                int newIndex = oldEntry.HashCode & newMask;
 542                // If current entry not available, perform Quadratic probing to find the next available entry
 50062543                int step = 1;
 54939544                while (newEntries[newIndex].IsUsed)
 4877545                {
 4877546                    newIndex = (newIndex + step * step) & newMask;
 4877547                    step++;
 4877548                }
 50062549                newEntries[newIndex] = oldEntry;
 62286550                if (newIndex > lastIndex) lastIndex = newIndex;
 50062551            }
 58426552        }
 553
 49554        _lastIndex = lastIndex;
 555
 49556        CalculateAdaptiveResizeFactors(newSize);
 557
 49558        _entries = newEntries;
 49559        _entryMask = newMask;
 560
 49561        _version++;
 49562    }
 563
 564    /// <summary>
 565    /// Sets the capacity of a <see cref="SwiftDictionary{TKey, TValue}"/> to the actual
 566    /// number of elements it contains, rounded up to a nearby next power of 2 value.
 567    /// </summary>
 568    public void TrimExcess()
 1569    {
 1570        int newSize = _count <= DefaultCapacity ? DefaultCapacity : SwiftHashTools.NextPowerOfTwo(_count);
 1571        if (newSize >= _entries.Length) return;
 572
 1573        Entry[] newEntries = new Entry[newSize];
 1574        int newMask = newSize - 1;
 575
 1576        int lastIndex = 0;
 26577        for (int i = 0; i <= (uint)_lastIndex; i++)
 12578        {
 12579            if (_entries[i].IsUsed)
 12580            {
 12581                ref Entry oldEntry = ref _entries[i];
 12582                int newIndex = oldEntry.HashCode & newMask;
 583                // If current entry not available, perform quadratic probing to find the next available entry
 12584                int step = 1;
 12585                while (newEntries[newIndex].IsUsed)
 0586                {
 0587                    newIndex = (newIndex + step * step) & newMask;
 0588                    step++;
 0589                }
 12590                newEntries[newIndex] = oldEntry;
 23591                if (newIndex > lastIndex) lastIndex = newIndex;
 12592            }
 12593        }
 594
 1595        _lastIndex = lastIndex;
 596
 1597        CalculateAdaptiveResizeFactors(newSize);
 598
 1599        _entryMask = newMask;
 1600        _entries = newEntries;
 601
 1602        _version++;
 1603    }
 604
 605    /// <summary>
 606    ///  Updates adaptive resize parameters based on the current fill rate to balance memory usage and performance.
 607    /// </summary>
 608    /// <param name="newSize"></param>
 609    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 610    private void CalculateAdaptiveResizeFactors(int newSize)
 50611    {
 612        // Calculate current fill rate and update moving average
 50613        double currentFillRate = (double)_count / newSize;
 50614        _movingFillRate = _movingFillRate == 0 ? currentFillRate : (_movingFillRate * 0.7 + currentFillRate * 0.3);
 615
 50616        if (_movingFillRate > 0.3f)
 1617            _adaptiveResizeFactor = 2; // Growth stabilizing
 49618        else if (_movingFillRate < 0.28f)
 49619            _adaptiveResizeFactor = 4; // Rapid growth
 620
 621        // Reset the resize threshold based on the new size
 50622        _nextResizeCount = (uint)(newSize * _LoadFactorThreshold);
 50623    }
 624
 625    #endregion
 626
 627    #region Utility Methods
 628
 629    /// <summary>
 630    /// Initializes the dictionary with the specified capacity.
 631    /// </summary>
 632    /// <param name="capacity">The initial number of elements that the dictionary can contain.</param>
 633    /// <param name="comparer">The comparer to use for the dictionary.</param>
 634    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 635    private void Initialize(int capacity, IEqualityComparer<TKey> comparer = null)
 221636    {
 221637        _comparer = SwiftHashTools.GetDefaultEqualityComparer(comparer);
 638
 221639        int size = capacity < DefaultCapacity ? DefaultCapacity : SwiftHashTools.NextPowerOfTwo(capacity);
 221640        _entries = new Entry[size];
 221641        _entryMask = size - 1;
 642
 221643        _nextResizeCount = (uint)(size * _LoadFactorThreshold);
 221644        _adaptiveResizeFactor = 4; // start agressive
 221645        _movingFillRate = 0.0;
 221646    }
 647
 648    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 19307649    public bool ContainsKey(TKey key) => FindEntry(key) >= 0;
 650
 651    bool IDictionary.Contains(object obj)
 4652    {
 4653        SwiftThrowHelper.ThrowIfNull(obj, nameof(obj));
 654
 7655        if (obj is TKey key) return ContainsKey(key);
 1656        return false;
 4657    }
 658
 659    bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
 2660    {
 2661        int index = FindEntry(item.Key);
 2662        if (index >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[index].Value, item.Value))
 1663            return true;
 1664        return false;
 2665    }
 666
 667    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 668    public bool TryGetValue(TKey key, out TValue value)
 6178669    {
 6178670        int index = FindEntry(key);
 6178671        if (index >= 0)
 6071672        {
 6071673            value = _entries[index].Value;
 6071674            return true;
 675        }
 107676        value = default;
 107677        return false;
 6178678    }
 679
 680    public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
 13681    {
 13682        SwiftThrowHelper.ThrowIfNull(array, nameof(array));
 13683        if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex));
 13684        if (array.Length - arrayIndex < _count) throw new ArgumentException("Insufficient space", nameof(array));
 685
 214686        for (uint i = 0; i <= (uint)_lastIndex; i++)
 94687        {
 94688            if (_entries[i].IsUsed)
 38689                array[arrayIndex++] = new KeyValuePair<TKey, TValue>(_entries[i].Key, _entries[i].Value);
 94690        }
 13691    }
 692
 1693    void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index) => CopyTo(array, 
 694
 695    void ICollection.CopyTo(Array array, int arrayIndex)
 6696    {
 6697        SwiftThrowHelper.ThrowIfNull(array, nameof(array));
 7698        if (array.Rank != 1) throw new ArgumentException("Multidimensional array not supported", nameof(array));
 6699        if (array.GetLowerBound(0) != 0) throw new ArgumentException("Non-zero lower bound", nameof(array));
 4700        if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex));
 5701        if (array.Length - arrayIndex < _count) throw new ArgumentException("Insufficient space", nameof(array));
 702
 3703        if (array is KeyValuePair<TKey, TValue>[] pairs)
 0704            ((ICollection<KeyValuePair<TKey, TValue>>)this).CopyTo(pairs, arrayIndex);
 3705        else if (array is DictionaryEntry[] dictEntryArray)
 1706        {
 8707            for (uint i = 0; i <= (uint)_lastIndex; i++)
 3708            {
 3709                if (_entries[i].IsUsed)
 2710                    dictEntryArray[arrayIndex++] = new DictionaryEntry(_entries[i].Key, _entries[i].Value);
 3711            }
 1712        }
 713        else
 2714        {
 3715            if (array is not object[] objects) throw new ArgumentException("Invalid array type", nameof(array));
 716
 717            try
 1718            {
 8719                for (uint i = 0; i <= (uint)_lastIndex; i++)
 3720                {
 3721                    if (_entries[i].IsUsed)
 2722                        objects[arrayIndex++] = new KeyValuePair<TKey, TValue>(_entries[i].Key, _entries[i].Value);
 3723                }
 1724            }
 0725            catch (ArrayTypeMismatchException)
 0726            {
 0727                throw new ArgumentException("Invalid array type", nameof(array));
 728            }
 1729        }
 2730    }
 731
 732    /// <summary>
 733    /// Sets a new comparer for the dictionary and rehashes the entries.
 734    /// </summary>
 735    /// <param name="comparer">The new comparer to use.</param>
 736    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 737    public void SetComparer(IEqualityComparer<TKey> comparer)
 4738    {
 4739        SwiftThrowHelper.ThrowIfNull(comparer, nameof(comparer));
 4740        if (ReferenceEquals(comparer, _comparer))
 0741            return;
 742
 4743        _comparer = comparer;
 4744        RehashEntries();
 4745        _maxStepCount = 0;
 4746    }
 747
 748    /// <summary>
 749    /// Switches the dictionary's comparer to a randomized comparer to mitigate the effects of high collision counts,
 750    /// and rehashes all entries using the new comparer to redistribute them across <see cref="_entries"/>.
 751    /// </summary>
 752    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 753    private void SwitchToRandomizedComparer()
 1754    {
 1755        if (SwiftHashTools.IsWellKnownEqualityComparer(_comparer))
 1756            _comparer = (IEqualityComparer<TKey>)SwiftHashTools.GetSwiftEqualityComparer(_comparer);
 0757        else return; // nothing to do here
 758
 1759        RehashEntries();
 1760        _maxStepCount = 0;
 761
 1762        _version++;
 1763    }
 764
 765    /// <summary>
 766    /// Reconstructs the internal entry structure to align with updated hash codes, ensuring efficient access and storag
 767    /// </summary>
 768    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 769    private void RehashEntries()
 5770    {
 5771        Entry[] newEntries = new Entry[_entries.Length];
 5772        int newMask = newEntries.Length - 1;
 773
 5774        int lastIndex = 0;
 612775        for (uint i = 0; i <= (uint)_lastIndex; i++)
 301776        {
 301777            if (_entries[i].IsUsed)
 109778            {
 109779                ref Entry oldEntry = ref _entries[i];
 109780                oldEntry.HashCode = _comparer.GetHashCode(oldEntry.Key) & 0x7FFFFFFF;
 109781                int newIndex = oldEntry.HashCode & newMask;
 109782                int step = 1;
 133783                while (newEntries[newIndex].IsUsed)
 24784                {
 24785                    newIndex = (newIndex + step * step) & newMask; // Quadratic probing
 24786                    step++;
 24787                }
 109788                newEntries[newIndex] = _entries[i];
 135789                if (newIndex > lastIndex) lastIndex = newIndex;
 109790            }
 301791        }
 792
 5793        _lastIndex = lastIndex;
 794
 5795        _entryMask = newMask;
 5796        _entries = newEntries;
 797
 5798        _version++;
 5799    }
 800
 801    /// <summary>
 802    /// Finds the arrayIndex of the entry with the specified key.
 803    /// </summary>
 804    /// <param name="key">The key to locate in the dictionary.</param>
 805    /// <returns>The arrayIndex of the entry if found; otherwise, -1.</returns>
 806    /// <exception cref="ArgumentNullException">The key is null.</exception>
 807    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 808    protected int FindEntry(TKey key)
 39233809    {
 39233810        if (key == null) return -1;
 811
 39233812        int hashCode = _comparer.GetHashCode(key) & 0x7FFFFFFF;
 39233813        int entryIndex = hashCode & _entryMask;
 814
 39233815        int step = 0;
 44259816        while ((uint)step <= (uint)_lastIndex)
 44250817        {
 44250818            ref Entry entry = ref _entries[entryIndex];
 819            // Stop probing if an unused entry is found (not deleted)
 44250820            if (!entry.IsUsed && entry.HashCode != -1)
 17416821                return -1;
 26834822            if (entry.IsUsed && entry.HashCode == hashCode && _comparer.Equals(entry.Key, key))
 21808823                return entryIndex; // Match found
 824
 825            // Perform quadratic probing to see if maybe the entry was shifted.
 5026826            step++;
 5026827            entryIndex = (entryIndex + step * step) & _entryMask;
 5026828        }
 9829        return -1; // Item not found, full loop completed
 39233830    }
 831
 832    #endregion
 833
 834    #region IEnumerable Implementation
 835
 31836    public SwiftDictionaryEnumerator GetEnumerator() => new SwiftDictionaryEnumerator(this);
 21837    IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() => GetEnumerator();
 1838    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
 3839    IDictionaryEnumerator IDictionary.GetEnumerator() => new SwiftDictionaryEnumerator(this, true);
 840
 841    /// <summary>
 842    /// Provides an efficient enumerator for iterating over the key-value pairs in the SwiftDictionary, enabling smooth 
 843    /// </summary>
 844    [Serializable]
 845    public struct SwiftDictionaryEnumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IEnumerator, IDictionaryEnumerato
 846    {
 847        private readonly SwiftDictionary<TKey, TValue> _dictionary;
 848        private readonly Entry[] _entries;
 849        private readonly uint _version;
 850        private readonly bool _returnEntry;
 851        private int _index;
 852        private KeyValuePair<TKey, TValue> _current;
 853
 854        internal SwiftDictionaryEnumerator(SwiftDictionary<TKey, TValue> dictionary, bool returnEntry = false)
 34855        {
 34856            _dictionary = dictionary;
 34857            _entries = dictionary._entries;
 34858            _version = dictionary._version;
 34859            _returnEntry = returnEntry;
 34860            _index = -1;
 34861            _current = default;
 34862        }
 863
 864        object IDictionaryEnumerator.Key
 865        {
 866            get
 3867            {
 3868                if (_index > (uint)_dictionary._lastIndex) throw new InvalidOperationException("Bad enumeration");
 3869                return _current.Key;
 3870            }
 871        }
 872
 873        object IDictionaryEnumerator.Value
 874        {
 875            get
 1876            {
 1877                if (_index > (uint)_dictionary._lastIndex) throw new InvalidOperationException("Bad enumeration");
 1878                return _current.Value;
 1879            }
 880        }
 881
 882        DictionaryEntry IDictionaryEnumerator.Entry
 883        {
 884            get
 2885            {
 3886                if (_index > (uint)_dictionary._lastIndex) throw new InvalidOperationException("Bad enumeration");
 1887                return new DictionaryEntry(_current.Key, _current.Value);
 1888            }
 889        }
 890
 48891        public KeyValuePair<TKey, TValue> Current => _current;
 892
 893        object IEnumerator.Current
 894        {
 895            get
 2896            {
 2897                if (_index > (uint)_dictionary._lastIndex) throw new InvalidOperationException("Bad enumeration");
 2898                return _returnEntry
 2899                    ? new DictionaryEntry(_current.Key, _current.Value)
 2900                    : new KeyValuePair<TKey, TValue>(_current.Key, _current.Value);
 2901            }
 902        }
 903
 904        public bool MoveNext()
 77905        {
 77906            if (_version != _dictionary._version)
 0907                throw new InvalidOperationException("Enumerator modified outside of enumeration!");
 908
 154909            while (++_index <= (uint)_dictionary._lastIndex)
 122910            {
 122911                if (_entries[_index].IsUsed)
 45912                {
 45913                    _current = new KeyValuePair<TKey, TValue>(_entries[_index].Key, _entries[_index].Value);
 45914                    return true;
 915                }
 77916            }
 917
 32918            _current = default;
 32919            return false;
 77920        }
 921
 922        public void Reset()
 1923        {
 1924            if (_version != _dictionary._version)
 0925                throw new InvalidOperationException("Enumerator modified outside of enumeration!");
 926
 1927            _index = -1;
 1928            _current = default;
 1929        }
 930
 931        public void Dispose()
 31932        {
 31933        }
 934    }
 935
 936    #endregion
 937
 938    #region Key & Value Collections
 939
 940    /// <summary>
 941    /// Provides a dynamic, read-only collection of all keys in the dictionary, supporting enumeration and copy operatio
 942    /// </summary>
 943    [Serializable]
 944    public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>, IEnumerable<TKey>, IE
 945    {
 946        private readonly SwiftDictionary<TKey, TValue> _dictionary;
 947        private readonly Entry[] _entries;
 948
 949        /// <summary>
 950        /// Initializes a new instance of the KeyCollection class that reflects the keys in the specified dictionary.
 951        /// </summary>
 952        /// <param name="dictionary">The dictionary whose keys are reflected in the new KeyCollection.</param>
 953        /// <exception cref="ArgumentNullException">The dictionary is null.</exception>
 13954        public KeyCollection(SwiftDictionary<TKey, TValue> dictionary)
 13955        {
 13956            _dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
 13957            _entries = dictionary._entries;
 13958        }
 959
 1960        public int Count => _dictionary._count;
 961
 1962        bool ICollection.IsSynchronized => false;
 963
 1964        object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot;
 965
 1966        bool ICollection<TKey>.IsReadOnly => true;
 967
 1968        void ICollection<TKey>.Add(TKey item) => throw new NotSupportedException();
 969
 1970        void ICollection<TKey>.Clear() => throw new NotSupportedException();
 971
 2972        bool ICollection<TKey>.Contains(TKey item) => _dictionary.ContainsKey(item);
 973
 1974        bool ICollection<TKey>.Remove(TKey item) => false;
 975
 976        public void CopyTo(TKey[] array, int arrayIndex)
 1977        {
 1978            SwiftThrowHelper.ThrowIfNull(array, nameof(array));
 1979            if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex));
 1980            if (array.Length - arrayIndex < _dictionary._count) throw new ArgumentException("Insufficient space", nameof
 981
 19982            for (int i = 0, j = arrayIndex; i < _entries.Length; i++)
 8983            {
 8984                if (_entries[i].IsUsed)
 2985                    array[j++] = _entries[i].Key;
 8986            }
 1987        }
 988
 989        void ICollection.CopyTo(Array array, int arrayIndex)
 2990        {
 2991            SwiftThrowHelper.ThrowIfNull(array, nameof(array));
 2992            if (array.Rank != 1) throw new ArgumentException("Multidimensional array not supported");
 2993            if (array.GetLowerBound(0) != 0) throw new ArgumentException("Non-zero lower bound");
 2994            if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex));
 2995            if (array.Length - arrayIndex < _dictionary._count) throw new ArgumentException("Insufficient space", nameof
 996
 2997            if (array is TKey[] keysArray)
 0998                CopyTo(keysArray, arrayIndex);
 2999            else if (array is object[] objects)
 21000            {
 1001                try
 21002                {
 241003                    for (int i = 0, j = arrayIndex; i < _entries.Length; i++)
 101004                    {
 101005                        if (_entries[i].IsUsed)
 31006                            objects[j++] = _entries[i].Key;
 91007                    }
 11008                }
 11009                catch (ArrayTypeMismatchException)
 11010                {
 11011                    throw new ArgumentException("Invalid array type", nameof(array));
 1012                }
 11013            }
 1014            else
 01015            {
 01016                throw new ArgumentException("Invalid array type", nameof(array));
 1017            }
 11018        }
 1019
 1020        /// <summary>
 1021        /// Returns an enumerator that iterates through the keys in the collection.
 1022        /// </summary>
 1023        /// <returns>An enumerator for the keys in the collection.</returns>
 91024        public KeyCollectionEnumerator GetEnumerator() => new KeyCollectionEnumerator(_dictionary);
 71025        IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() => GetEnumerator();
 21026        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
 1027
 1028        [Serializable]
 1029        public struct KeyCollectionEnumerator : IEnumerator<TKey>, IEnumerator, IDisposable
 1030        {
 1031            private readonly SwiftDictionary<TKey, TValue> _dictionary;
 1032            private readonly Entry[] _entries;
 1033            private readonly uint _version;
 1034            private int _index;
 1035            private TKey _currentKey;
 1036
 1037            internal KeyCollectionEnumerator(SwiftDictionary<TKey, TValue> dictionary)
 91038            {
 91039                _dictionary = dictionary;
 91040                _entries = dictionary._entries;
 91041                _version = dictionary._version;
 91042                _index = -1;
 91043                _currentKey = default;
 91044            }
 1045
 241046            public TKey Current => _currentKey;
 1047
 1048            object IEnumerator.Current
 1049            {
 1050                get
 11051                {
 11052                    if (_index > (uint)_dictionary._lastIndex) throw new InvalidOperationException("Bad enumeration");
 11053                    return _currentKey;
 11054                }
 1055            }
 1056
 1057            public bool MoveNext()
 251058            {
 251059                if (_version != _dictionary._version)
 11060                    throw new InvalidOperationException("Enumerator modified outside of enumeration!");
 1061
 491062                while (++_index <= (uint)_dictionary._lastIndex)
 451063                {
 451064                    if (_entries[_index].IsUsed)
 201065                    {
 201066                        _currentKey = _entries[_index].Key;
 201067                        return true;
 1068                    }
 251069                }
 1070
 41071                _currentKey = default;
 41072                return false;
 241073            }
 1074
 1075            public void Reset()
 11076            {
 11077                if (_version != _dictionary._version)
 01078                    throw new InvalidOperationException("Enumerator modified outside of enumeration!");
 1079
 11080                _index = -1;
 11081                _currentKey = default;
 11082            }
 1083
 141084            public void Dispose() { }
 1085        }
 1086    }
 1087
 1088    /// <summary>
 1089    /// Offers a dynamic, read-only collection of all values in the dictionary, supporting enumeration and copy operatio
 1090    /// </summary>
 1091    [Serializable]
 1092    public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>, IEnumerable<TVa
 1093    {
 1094        private readonly SwiftDictionary<TKey, TValue> _dictionary;
 1095        private readonly Entry[] _entries;
 1096
 1097        /// <summary>
 1098        /// Initializes a new instance of the ValueCollection class that reflects the values in the specified dictionary
 1099        /// </summary>
 1100        /// <param name="dictionary">The dictionary whose values are reflected in the new ValueCollection.</param>
 1101        /// <exception cref="ArgumentNullException">The dictionary is null.</exception>
 91102        public ValueCollection(SwiftDictionary<TKey, TValue> dictionary)
 91103        {
 91104            _dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
 91105            _entries = dictionary._entries;
 91106        }
 1107
 11108        public int Count => _dictionary._count;
 1109
 11110        bool ICollection<TValue>.IsReadOnly => true;
 1111
 11112        bool ICollection.IsSynchronized => false;
 1113
 11114        object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot;
 1115
 11116        void ICollection<TValue>.Add(TValue item) => throw new NotSupportedException();
 1117
 11118        void ICollection<TValue>.Clear() => throw new NotSupportedException();
 1119
 1120        bool ICollection<TValue>.Contains(TValue item)
 21121        {
 121122            for (uint i = 0; i <= (uint)_dictionary._lastIndex; i++)
 61123            {
 61124                if (_entries[i].IsUsed && EqualityComparer<TValue>.Default.Equals(_entries[i].Value, item))
 21125                    return true;
 41126            }
 01127            return false;
 21128        }
 1129
 11130        bool ICollection<TValue>.Remove(TValue item) => false;
 1131
 1132        public void CopyTo(TValue[] array, int arrayIndex)
 11133        {
 11134            SwiftThrowHelper.ThrowIfNull(array, nameof(array));
 11135            if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex));
 11136            if (array.Length - arrayIndex < _dictionary._count) throw new ArgumentException("Insufficient space", nameof
 1137
 1138
 91139            for (int i = 0, j = arrayIndex; i <= _dictionary._lastIndex; i++)
 31140            {
 31141                if (_dictionary._entries[i].IsUsed)
 21142                    array[j++] = _entries[i].Value;
 31143            }
 11144        }
 1145
 1146        void ICollection.CopyTo(Array array, int arrayIndex)
 21147        {
 21148            SwiftThrowHelper.ThrowIfNull(array, nameof(array));
 21149            if (array.Rank != 1) throw new ArgumentException("Multidimensional array not supported", nameof(array));
 21150            if (array.GetLowerBound(0) != 0) throw new ArgumentException("Non-zero lower bound", nameof(array));
 21151            if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex));
 21152            if (array.Length - arrayIndex < _dictionary._count) throw new ArgumentException("Insufficient space", nameof
 1153
 21154            if (array is TValue[] valuesArray)
 01155                CopyTo(valuesArray, arrayIndex);
 21156            else if (array is object[] objects)
 11157            {
 1158                try
 11159                {
 91160                    for (int i = 0, j = arrayIndex; i <= _dictionary._lastIndex; i++)
 31161                        if (_entries[i].IsUsed)
 21162                            objects[j++] = _entries[i].Value;
 11163                }
 01164                catch (ArrayTypeMismatchException)
 01165                {
 01166                    throw new ArgumentException("Invalid array type", nameof(array));
 1167                }
 11168            }
 11169            else throw new ArgumentException("Invalid array type", nameof(array));
 11170        }
 1171
 1172        /// <summary>
 1173        /// Returns an enumerator that iterates through the values in the collection.
 1174        /// </summary>
 1175        /// <returns>An enumerator for the values in the collection.</returns>
 51176        public ValueCollectionEnumerator GetEnumerator() => new ValueCollectionEnumerator(_dictionary);
 31177        IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() => GetEnumerator();
 21178        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
 1179
 1180        [Serializable]
 1181        public struct ValueCollectionEnumerator : IEnumerator<TValue>, IEnumerator, IDisposable
 1182        {
 1183            private readonly SwiftDictionary<TKey, TValue> _dictionary;
 1184            private readonly Entry[] _entries;
 1185            private readonly uint _version;
 1186            private int _index;
 1187            private TValue _currentValue;
 1188
 1189            internal ValueCollectionEnumerator(SwiftDictionary<TKey, TValue> dictionary)
 51190            {
 51191                _dictionary = dictionary;
 51192                _entries = dictionary._entries;
 51193                _version = dictionary._version;
 51194                _index = -1;
 51195                _currentValue = default;
 51196            }
 1197
 121198            public TValue Current => _currentValue;
 1199
 1200            object IEnumerator.Current
 1201            {
 1202                get
 11203                {
 11204                    if (_index > (uint)_dictionary._lastIndex) throw new InvalidOperationException("Bad enumeration");
 11205                    return _currentValue;
 11206                }
 1207            }
 1208
 1209            public bool MoveNext()
 91210            {
 91211                if (_version != _dictionary._version)
 11212                    throw new InvalidOperationException("Enumerator modified outside of enumeration!");
 1213
 131214                while (++_index <= (uint)_dictionary._lastIndex)
 131215                {
 131216                    if (_entries[_index].IsUsed)
 81217                    {
 81218                        _currentValue = _entries[_index].Value;
 81219                        return true;
 1220                    }
 51221                }
 1222
 01223                _currentValue = default;
 01224                return false;
 81225            }
 1226
 1227            public void Reset()
 11228            {
 11229                if (_version != _dictionary._version)
 01230                    throw new InvalidOperationException("Enumerator modified outside of enumeration!");
 1231
 11232                _index = -1;
 11233                _currentValue = default;
 11234            }
 1235
 61236            public void Dispose() { }
 1237        }
 1238    }
 1239
 1240    #endregion
 1241}

Methods/Properties

.ctor()
.ctor(System.Int32,System.Collections.Generic.IEqualityComparer`1<TKey>)
.ctor(System.Collections.Generic.IDictionary`2<TKey,TValue>,System.Collections.Generic.IEqualityComparer`1<TKey>)
.ctor(System.Collections.Generic.IEnumerable`1<System.Collections.Generic.KeyValuePair`2<TKey,TValue>>,System.Collections.Generic.IEqualityComparer`1<TKey>)
.ctor(SwiftCollections.SwiftDictionaryState`2<TKey,TValue>)
get_Count()
get_Capacity()
get_Comparer()
get_Item(TKey)
set_Item(TKey,TValue)
System.Collections.IDictionary.get_Item(System.Object)
System.Collections.IDictionary.set_Item(System.Object,System.Object)
get_Keys()
System.Collections.IDictionary.get_Keys()
get_Values()
System.Collections.IDictionary.get_Values()
System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.get_IsReadOnly()
System.Collections.IDictionary.get_IsReadOnly()
System.Collections.IDictionary.get_IsFixedSize()
System.Collections.ICollection.get_IsSynchronized()
get_SyncRoot()
get_State()
set_State(SwiftCollections.SwiftDictionaryState`2<TKey,TValue>)
Add(TKey,TValue)
System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(System.Collections.Generic.KeyValuePair`2<TKey,TValue>)
System.Collections.Generic.IDictionary<TKey,TValue>.Add(TKey,TValue)
System.Collections.IDictionary.Add(System.Object,System.Object)
InsertIfNotExist(TKey,TValue)
Remove(TKey)
System.Collections.IDictionary.Remove(System.Object)
System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Remove(System.Collections.Generic.KeyValuePair`2<TKey,TValue>)
Clear()
CheckLoadThreshold()
EnsureCapacity(System.Int32)
Resize(System.Int32)
TrimExcess()
CalculateAdaptiveResizeFactors(System.Int32)
Initialize(System.Int32,System.Collections.Generic.IEqualityComparer`1<TKey>)
ContainsKey(TKey)
System.Collections.IDictionary.Contains(System.Object)
System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Contains(System.Collections.Generic.KeyValuePair`2<TKey,TValue>)
TryGetValue(TKey,TValue&)
CopyTo(System.Collections.Generic.KeyValuePair`2<TKey,TValue>[],System.Int32)
System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.CopyTo(System.Collections.Generic.KeyValuePair`2<TKey,TValue>[],System.Int32)
System.Collections.ICollection.CopyTo(System.Array,System.Int32)
SetComparer(System.Collections.Generic.IEqualityComparer`1<TKey>)
SwitchToRandomizedComparer()
RehashEntries()
FindEntry(TKey)
GetEnumerator()
System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>.GetEnumerator()
System.Collections.IEnumerable.GetEnumerator()
System.Collections.IDictionary.GetEnumerator()
.ctor(SwiftCollections.SwiftDictionary`2<TKey,TValue>,System.Boolean)
System.Collections.IDictionaryEnumerator.get_Key()
System.Collections.IDictionaryEnumerator.get_Value()
System.Collections.IDictionaryEnumerator.get_Entry()
get_Current()
System.Collections.IEnumerator.get_Current()
MoveNext()
Reset()
Dispose()
.ctor(SwiftCollections.SwiftDictionary`2<TKey,TValue>)
get_Count()
System.Collections.ICollection.get_IsSynchronized()
System.Collections.ICollection.get_SyncRoot()
System.Collections.Generic.ICollection<TKey>.get_IsReadOnly()
System.Collections.Generic.ICollection<TKey>.Add(TKey)
System.Collections.Generic.ICollection<TKey>.Clear()
System.Collections.Generic.ICollection<TKey>.Contains(TKey)
System.Collections.Generic.ICollection<TKey>.Remove(TKey)
CopyTo(TKey[],System.Int32)
System.Collections.ICollection.CopyTo(System.Array,System.Int32)
GetEnumerator()
System.Collections.Generic.IEnumerable<TKey>.GetEnumerator()
System.Collections.IEnumerable.GetEnumerator()
.ctor(SwiftCollections.SwiftDictionary`2<TKey,TValue>)
get_Current()
System.Collections.IEnumerator.get_Current()
MoveNext()
Reset()
Dispose()
.ctor(SwiftCollections.SwiftDictionary`2<TKey,TValue>)
get_Count()
System.Collections.Generic.ICollection<TValue>.get_IsReadOnly()
System.Collections.ICollection.get_IsSynchronized()
System.Collections.ICollection.get_SyncRoot()
System.Collections.Generic.ICollection<TValue>.Add(TValue)
System.Collections.Generic.ICollection<TValue>.Clear()
System.Collections.Generic.ICollection<TValue>.Contains(TValue)
System.Collections.Generic.ICollection<TValue>.Remove(TValue)
CopyTo(TValue[],System.Int32)
System.Collections.ICollection.CopyTo(System.Array,System.Int32)
GetEnumerator()
System.Collections.Generic.IEnumerable<TValue>.GetEnumerator()
System.Collections.IEnumerable.GetEnumerator()
.ctor(SwiftCollections.SwiftDictionary`2<TKey,TValue>)
get_Current()
System.Collections.IEnumerator.get_Current()
MoveNext()
Reset()
Dispose()