| | | 1 | | using MemoryPack; |
| | | 2 | | using System; |
| | | 3 | | using System.Collections; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Runtime.CompilerServices; |
| | | 6 | | using System.Text.Json.Serialization; |
| | | 7 | | |
| | | 8 | | namespace 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] |
| | | 30 | | public 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> |
| | 255 | 129 | | public SwiftDictionary() : this(DefaultCapacity, null) { } |
| | | 130 | | |
| | | 131 | | /// <inheritdoc cref="SwiftDictionary()"/> |
| | 204 | 132 | | public SwiftDictionary(int capacity, IEqualityComparer<TKey> comparer = null) |
| | 204 | 133 | | { |
| | 204 | 134 | | Initialize(capacity, comparer); |
| | 204 | 135 | | } |
| | | 136 | | |
| | | 137 | | /// <inheritdoc cref="SwiftDictionary()"/> |
| | 2 | 138 | | public SwiftDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer = null) |
| | 2 | 139 | | { |
| | 2 | 140 | | SwiftThrowHelper.ThrowIfNull(dictionary, nameof(dictionary)); |
| | | 141 | | |
| | 1 | 142 | | Initialize(dictionary.Count, comparer); |
| | | 143 | | |
| | 7 | 144 | | foreach (KeyValuePair<TKey, TValue> kvp in dictionary) |
| | 2 | 145 | | InsertIfNotExist(kvp.Key, kvp.Value); |
| | 1 | 146 | | } |
| | | 147 | | |
| | | 148 | | /// <inheritdoc cref="SwiftDictionary()"/> |
| | 2 | 149 | | public SwiftDictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer = null) |
| | 2 | 150 | | { |
| | 2 | 151 | | SwiftThrowHelper.ThrowIfNull(collection, nameof(collection)); |
| | | 152 | | |
| | 1 | 153 | | int count = (collection as ICollection<TKey>)?.Count ?? DefaultCapacity; |
| | | 154 | | // Dynamic padding based on collision estimation |
| | 1 | 155 | | int size = (int)(count / _LoadFactorThreshold); |
| | 1 | 156 | | Initialize(size, comparer); |
| | | 157 | | |
| | 7 | 158 | | foreach (KeyValuePair<TKey, TValue> kvp in collection) |
| | 2 | 159 | | InsertIfNotExist(kvp.Key, kvp.Value); |
| | 1 | 160 | | } |
| | | 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] |
| | 10 | 167 | | public SwiftDictionary(SwiftDictionaryState<TKey, TValue> state) |
| | 10 | 168 | | { |
| | 10 | 169 | | State = state; |
| | 10 | 170 | | } |
| | | 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] |
| | 22 | 181 | | public int Count => _count; |
| | | 182 | | |
| | | 183 | | [JsonIgnore] |
| | | 184 | | [MemoryPackIgnore] |
| | 7 | 185 | | public int Capacity => _entries.Length; |
| | | 186 | | |
| | | 187 | | [JsonIgnore] |
| | | 188 | | [MemoryPackIgnore] |
| | 11 | 189 | | public IEqualityComparer<TKey> Comparer => _comparer; |
| | | 190 | | |
| | | 191 | | [JsonIgnore] |
| | | 192 | | [MemoryPackIgnore] |
| | | 193 | | public TValue this[TKey key] |
| | | 194 | | { |
| | | 195 | | get |
| | 4160 | 196 | | { |
| | 4160 | 197 | | int index = FindEntry(key); |
| | 4160 | 198 | | SwiftThrowHelper.ThrowIfKeyInvalid(index, key); |
| | 4158 | 199 | | return _entries[index].Value; |
| | 4158 | 200 | | } |
| | | 201 | | set |
| | 9567 | 202 | | { |
| | 9567 | 203 | | int index = FindEntry(key); |
| | 9567 | 204 | | if (index >= 0) |
| | 6512 | 205 | | _entries[index].Value = value; |
| | | 206 | | else |
| | 3055 | 207 | | { |
| | 3055 | 208 | | CheckLoadThreshold(); |
| | 3055 | 209 | | InsertIfNotExist(key, value); |
| | 3055 | 210 | | } |
| | 9567 | 211 | | } |
| | | 212 | | } |
| | | 213 | | |
| | | 214 | | [JsonIgnore] |
| | | 215 | | [MemoryPackIgnore] |
| | | 216 | | object IDictionary.this[object obj] |
| | | 217 | | { |
| | | 218 | | get |
| | 17 | 219 | | { |
| | 17 | 220 | | SwiftThrowHelper.ThrowIfNull(obj, nameof(obj)); |
| | | 221 | | |
| | 16 | 222 | | if (obj is TKey key) |
| | 15 | 223 | | { |
| | 15 | 224 | | int index = FindEntry(key); |
| | 29 | 225 | | if (index >= 0) return _entries[index].Value; |
| | 1 | 226 | | } |
| | 2 | 227 | | return null; |
| | 16 | 228 | | } |
| | | 229 | | set |
| | 4 | 230 | | { |
| | 4 | 231 | | SwiftThrowHelper.ThrowIfNullAndNullsAreIllegal(value, default(TValue)); |
| | | 232 | | try |
| | 4 | 233 | | { |
| | 4 | 234 | | TKey tempKey = (TKey)obj; |
| | | 235 | | try |
| | 3 | 236 | | { |
| | 3 | 237 | | this[tempKey] = (TValue)value; |
| | 2 | 238 | | } |
| | 1 | 239 | | catch (InvalidCastException) |
| | 1 | 240 | | { |
| | 1 | 241 | | throw new ArgumentException($"Value {value} does not match expected {typeof(TValue)}"); |
| | | 242 | | } |
| | 2 | 243 | | } |
| | 1 | 244 | | catch (InvalidCastException) |
| | 1 | 245 | | { |
| | 1 | 246 | | throw new ArgumentException($"Key {obj} does not match expected {typeof(TKey)}"); |
| | | 247 | | } |
| | 2 | 248 | | } |
| | | 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] |
| | 10 | 260 | | public ICollection<TKey> Keys => _keyCollection ??= new KeyCollection(this); |
| | | 261 | | |
| | | 262 | | [JsonIgnore] |
| | | 263 | | [MemoryPackIgnore] |
| | 4 | 264 | | 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] |
| | 10 | 275 | | public ICollection<TValue> Values => _valueCollection ??= new ValueCollection(this); |
| | | 276 | | |
| | | 277 | | [JsonIgnore] |
| | | 278 | | [MemoryPackIgnore] |
| | 1 | 279 | | ICollection IDictionary.Values => _valueCollection ??= new ValueCollection(this); |
| | | 280 | | |
| | | 281 | | [JsonIgnore] |
| | | 282 | | [MemoryPackIgnore] |
| | 1 | 283 | | bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => false; |
| | | 284 | | |
| | | 285 | | [JsonIgnore] |
| | 1 | 286 | | [MemoryPackIgnore] bool IDictionary.IsReadOnly => false; |
| | 1 | 287 | | bool IDictionary.IsFixedSize => false; |
| | | 288 | | |
| | | 289 | | [JsonIgnore] |
| | | 290 | | [MemoryPackIgnore] |
| | 1 | 291 | | bool ICollection.IsSynchronized => false; |
| | | 292 | | |
| | | 293 | | [JsonIgnore] |
| | | 294 | | [MemoryPackIgnore] |
| | 3 | 295 | | public object SyncRoot => _syncRoot ??= new object(); |
| | | 296 | | |
| | | 297 | | [JsonInclude] |
| | | 298 | | [MemoryPackInclude] |
| | | 299 | | public SwiftDictionaryState<TKey, TValue> State |
| | | 300 | | { |
| | | 301 | | get |
| | 14 | 302 | | { |
| | 14 | 303 | | if (_count == 0) |
| | 2 | 304 | | return new SwiftDictionaryState<TKey, TValue>(Array.Empty<KeyValuePair<TKey, TValue>>()); |
| | | 305 | | |
| | 12 | 306 | | var items = new KeyValuePair<TKey, TValue>[_count]; |
| | 12 | 307 | | CopyTo(items, 0); |
| | | 308 | | |
| | 12 | 309 | | return new SwiftDictionaryState<TKey, TValue>(items); |
| | 14 | 310 | | } |
| | | 311 | | internal set |
| | 15 | 312 | | { |
| | 15 | 313 | | var items = value.Items; |
| | 15 | 314 | | int count = items?.Length ?? 0; |
| | | 315 | | |
| | 15 | 316 | | if (count == 0) |
| | 3 | 317 | | { |
| | 3 | 318 | | Initialize(DefaultCapacity); |
| | 3 | 319 | | _count = 0; |
| | 3 | 320 | | _version = 0; |
| | 3 | 321 | | return; |
| | | 322 | | } |
| | | 323 | | |
| | 12 | 324 | | int size = (int)(count / _LoadFactorThreshold); |
| | 12 | 325 | | Initialize(size); |
| | | 326 | | |
| | 108 | 327 | | foreach (var kvp in items) |
| | 36 | 328 | | InsertIfNotExist(kvp.Key, kvp.Value); |
| | | 329 | | |
| | 12 | 330 | | _version = 0; |
| | 15 | 331 | | } |
| | | 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) |
| | 116450 | 349 | | { |
| | 116450 | 350 | | CheckLoadThreshold(); |
| | 116450 | 351 | | return InsertIfNotExist(key, value); |
| | 116448 | 352 | | } |
| | | 353 | | |
| | 1 | 354 | | void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) => Add(item.Key, item.Value); |
| | 1 | 355 | | void IDictionary<TKey, TValue>.Add(TKey key, TValue value) => Add(key, value); |
| | | 356 | | void IDictionary.Add(object key, object value) |
| | 2 | 357 | | { |
| | 2 | 358 | | SwiftThrowHelper.ThrowIfNullAndNullsAreIllegal(value, default(TValue)); |
| | | 359 | | |
| | | 360 | | try |
| | 2 | 361 | | { |
| | 2 | 362 | | TKey tempKey = (TKey)key; |
| | | 363 | | try |
| | 1 | 364 | | { |
| | 1 | 365 | | Add(tempKey, (TValue)value); |
| | 0 | 366 | | } |
| | 0 | 367 | | catch (InvalidCastException) |
| | 0 | 368 | | { |
| | 0 | 369 | | throw new ArgumentException($"Value {value} does not match expected {typeof(TValue)}"); |
| | | 370 | | } |
| | 0 | 371 | | } |
| | 1 | 372 | | catch (InvalidCastException) |
| | 1 | 373 | | { |
| | 1 | 374 | | throw new ArgumentException($"Key {key} does not match expected {typeof(TKey)}"); |
| | | 375 | | } |
| | 0 | 376 | | } |
| | | 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) |
| | 119546 | 390 | | { |
| | 119546 | 391 | | SwiftThrowHelper.ThrowIfNull(key, nameof(key)); |
| | | 392 | | |
| | 119544 | 393 | | int hashCode = _comparer.GetHashCode(key) & 0x7FFFFFFF; |
| | 119544 | 394 | | int entryIndex = hashCode & _entryMask; |
| | | 395 | | |
| | 119544 | 396 | | int step = 1; |
| | 267525 | 397 | | while (_entries[entryIndex].IsUsed) |
| | 148023 | 398 | | { |
| | 148023 | 399 | | if (_entries[entryIndex].HashCode == hashCode && _comparer.Equals(_entries[entryIndex].Key, key)) |
| | 42 | 400 | | return false; // Item already exists |
| | | 401 | | |
| | 147981 | 402 | | entryIndex = (entryIndex + step * step) & _entryMask; // Quadratic probing |
| | 147981 | 403 | | step++; |
| | 147981 | 404 | | } |
| | | 405 | | |
| | 134928 | 406 | | if ((uint)entryIndex > (uint)_lastIndex) _lastIndex = entryIndex; |
| | | 407 | | |
| | 119502 | 408 | | _entries[entryIndex].HashCode = hashCode; |
| | 119502 | 409 | | _entries[entryIndex].Key = key; |
| | 119502 | 410 | | _entries[entryIndex].Value = value; |
| | 119502 | 411 | | _entries[entryIndex].IsUsed = true; |
| | 119502 | 412 | | _count++; |
| | 119502 | 413 | | _version++; |
| | | 414 | | |
| | 119502 | 415 | | if ((uint)step > (uint)_maxStepCount) |
| | 321 | 416 | | { |
| | 321 | 417 | | _maxStepCount = step; |
| | 321 | 418 | | if (_comparer is not IRandomedEqualityComparer && _maxStepCount > 100) |
| | 1 | 419 | | SwitchToRandomizedComparer(); // Attempt to recompute hash code with potential randomization for better |
| | 321 | 420 | | } |
| | | 421 | | |
| | | 422 | | |
| | 119502 | 423 | | return true; |
| | 119544 | 424 | | } |
| | | 425 | | |
| | | 426 | | public virtual bool Remove(TKey key) |
| | 6026 | 427 | | { |
| | 6027 | 428 | | if (key == null) return false; |
| | | 429 | | |
| | 6025 | 430 | | int hashCode = _comparer.GetHashCode(key) & 0x7FFFFFFF; |
| | 6025 | 431 | | int entryIndex = hashCode & _entryMask; |
| | | 432 | | |
| | 6025 | 433 | | int step = 0; |
| | 6456 | 434 | | while ((uint)step <= (uint)_lastIndex) |
| | 6455 | 435 | | { |
| | 6455 | 436 | | ref Entry entry = ref _entries[entryIndex]; |
| | | 437 | | // Stop probing if an unused entry is found (not deleted) |
| | 6455 | 438 | | if (!entry.IsUsed && entry.HashCode != -1) |
| | 1 | 439 | | return false; |
| | 6454 | 440 | | if (entry.IsUsed && entry.HashCode == hashCode && _comparer.Equals(entry.Key, key)) |
| | 6023 | 441 | | { |
| | | 442 | | // Mark entry as deleted |
| | 6023 | 443 | | entry.IsUsed = false; |
| | 6023 | 444 | | entry.Key = default; |
| | 6023 | 445 | | entry.Value = default; |
| | 6023 | 446 | | entry.HashCode = -1; |
| | 6023 | 447 | | _count--; |
| | 6030 | 448 | | if ((uint)_count == 0) _lastIndex = 0; |
| | 6023 | 449 | | _version++; |
| | 6023 | 450 | | return true; |
| | | 451 | | } |
| | | 452 | | |
| | | 453 | | // Move to the next entry using linear probing |
| | 431 | 454 | | step++; |
| | 431 | 455 | | entryIndex = (entryIndex + step * step) & _entryMask; |
| | 431 | 456 | | } |
| | 1 | 457 | | return false; // Item not found after full loop |
| | 6026 | 458 | | } |
| | | 459 | | |
| | | 460 | | void IDictionary.Remove(object obj) |
| | 1 | 461 | | { |
| | 1 | 462 | | SwiftThrowHelper.ThrowIfNull(obj, nameof(obj)); |
| | 2 | 463 | | if (obj is TKey key) Remove(key); |
| | 1 | 464 | | } |
| | | 465 | | |
| | | 466 | | bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) |
| | 2 | 467 | | { |
| | 2 | 468 | | int index = FindEntry(item.Key); |
| | 2 | 469 | | if (index >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[index].Value, item.Value)) |
| | 1 | 470 | | { |
| | 1 | 471 | | Remove(item.Key); |
| | 1 | 472 | | return true; |
| | | 473 | | } |
| | 1 | 474 | | return false; |
| | 2 | 475 | | } |
| | | 476 | | |
| | | 477 | | public virtual void Clear() |
| | 18 | 478 | | { |
| | 20 | 479 | | if ((uint)_count == 0) return; |
| | | 480 | | |
| | 170 | 481 | | for (uint i = 0; i <= (uint)_lastIndex; i++) |
| | 69 | 482 | | { |
| | 69 | 483 | | _entries[i].HashCode = -1; |
| | 69 | 484 | | _entries[i].Key = default; |
| | 69 | 485 | | _entries[i].Value = default; |
| | 69 | 486 | | _entries[i].IsUsed = false; |
| | 69 | 487 | | } |
| | | 488 | | |
| | 16 | 489 | | _count = 0; |
| | 16 | 490 | | _lastIndex = 0; |
| | 16 | 491 | | _maxStepCount = 0; |
| | 16 | 492 | | _movingFillRate = 0; |
| | 16 | 493 | | _adaptiveResizeFactor = 4; |
| | | 494 | | |
| | 16 | 495 | | _version++; |
| | 18 | 496 | | } |
| | | 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() |
| | 119506 | 507 | | { |
| | 119506 | 508 | | if ((uint)_count >= _nextResizeCount) |
| | 48 | 509 | | Resize(_entries.Length * _adaptiveResizeFactor); |
| | 119506 | 510 | | } |
| | | 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) |
| | 1 | 520 | | { |
| | 1 | 521 | | capacity = SwiftHashTools.NextPowerOfTwo(capacity); // Capacity must be a power of 2 for proper masking |
| | 1 | 522 | | if (capacity > _entries.Length) |
| | 1 | 523 | | Resize(capacity); |
| | 1 | 524 | | } |
| | | 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) |
| | 49 | 531 | | { |
| | 49 | 532 | | Entry[] newEntries = new Entry[newSize]; |
| | 49 | 533 | | int newMask = newSize - 1; |
| | | 534 | | |
| | 49 | 535 | | int lastIndex = 0; |
| | 116950 | 536 | | for (uint i = 0; i <= (uint)_lastIndex; i++) |
| | 58426 | 537 | | { |
| | 58426 | 538 | | if (_entries[i].IsUsed) // Only rehash valid entries |
| | 50062 | 539 | | { |
| | 50062 | 540 | | ref Entry oldEntry = ref _entries[i]; |
| | 50062 | 541 | | int newIndex = oldEntry.HashCode & newMask; |
| | | 542 | | // If current entry not available, perform Quadratic probing to find the next available entry |
| | 50062 | 543 | | int step = 1; |
| | 54939 | 544 | | while (newEntries[newIndex].IsUsed) |
| | 4877 | 545 | | { |
| | 4877 | 546 | | newIndex = (newIndex + step * step) & newMask; |
| | 4877 | 547 | | step++; |
| | 4877 | 548 | | } |
| | 50062 | 549 | | newEntries[newIndex] = oldEntry; |
| | 62286 | 550 | | if (newIndex > lastIndex) lastIndex = newIndex; |
| | 50062 | 551 | | } |
| | 58426 | 552 | | } |
| | | 553 | | |
| | 49 | 554 | | _lastIndex = lastIndex; |
| | | 555 | | |
| | 49 | 556 | | CalculateAdaptiveResizeFactors(newSize); |
| | | 557 | | |
| | 49 | 558 | | _entries = newEntries; |
| | 49 | 559 | | _entryMask = newMask; |
| | | 560 | | |
| | 49 | 561 | | _version++; |
| | 49 | 562 | | } |
| | | 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() |
| | 1 | 569 | | { |
| | 1 | 570 | | int newSize = _count <= DefaultCapacity ? DefaultCapacity : SwiftHashTools.NextPowerOfTwo(_count); |
| | 1 | 571 | | if (newSize >= _entries.Length) return; |
| | | 572 | | |
| | 1 | 573 | | Entry[] newEntries = new Entry[newSize]; |
| | 1 | 574 | | int newMask = newSize - 1; |
| | | 575 | | |
| | 1 | 576 | | int lastIndex = 0; |
| | 26 | 577 | | for (int i = 0; i <= (uint)_lastIndex; i++) |
| | 12 | 578 | | { |
| | 12 | 579 | | if (_entries[i].IsUsed) |
| | 12 | 580 | | { |
| | 12 | 581 | | ref Entry oldEntry = ref _entries[i]; |
| | 12 | 582 | | int newIndex = oldEntry.HashCode & newMask; |
| | | 583 | | // If current entry not available, perform quadratic probing to find the next available entry |
| | 12 | 584 | | int step = 1; |
| | 12 | 585 | | while (newEntries[newIndex].IsUsed) |
| | 0 | 586 | | { |
| | 0 | 587 | | newIndex = (newIndex + step * step) & newMask; |
| | 0 | 588 | | step++; |
| | 0 | 589 | | } |
| | 12 | 590 | | newEntries[newIndex] = oldEntry; |
| | 23 | 591 | | if (newIndex > lastIndex) lastIndex = newIndex; |
| | 12 | 592 | | } |
| | 12 | 593 | | } |
| | | 594 | | |
| | 1 | 595 | | _lastIndex = lastIndex; |
| | | 596 | | |
| | 1 | 597 | | CalculateAdaptiveResizeFactors(newSize); |
| | | 598 | | |
| | 1 | 599 | | _entryMask = newMask; |
| | 1 | 600 | | _entries = newEntries; |
| | | 601 | | |
| | 1 | 602 | | _version++; |
| | 1 | 603 | | } |
| | | 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) |
| | 50 | 611 | | { |
| | | 612 | | // Calculate current fill rate and update moving average |
| | 50 | 613 | | double currentFillRate = (double)_count / newSize; |
| | 50 | 614 | | _movingFillRate = _movingFillRate == 0 ? currentFillRate : (_movingFillRate * 0.7 + currentFillRate * 0.3); |
| | | 615 | | |
| | 50 | 616 | | if (_movingFillRate > 0.3f) |
| | 1 | 617 | | _adaptiveResizeFactor = 2; // Growth stabilizing |
| | 49 | 618 | | else if (_movingFillRate < 0.28f) |
| | 49 | 619 | | _adaptiveResizeFactor = 4; // Rapid growth |
| | | 620 | | |
| | | 621 | | // Reset the resize threshold based on the new size |
| | 50 | 622 | | _nextResizeCount = (uint)(newSize * _LoadFactorThreshold); |
| | 50 | 623 | | } |
| | | 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) |
| | 221 | 636 | | { |
| | 221 | 637 | | _comparer = SwiftHashTools.GetDefaultEqualityComparer(comparer); |
| | | 638 | | |
| | 221 | 639 | | int size = capacity < DefaultCapacity ? DefaultCapacity : SwiftHashTools.NextPowerOfTwo(capacity); |
| | 221 | 640 | | _entries = new Entry[size]; |
| | 221 | 641 | | _entryMask = size - 1; |
| | | 642 | | |
| | 221 | 643 | | _nextResizeCount = (uint)(size * _LoadFactorThreshold); |
| | 221 | 644 | | _adaptiveResizeFactor = 4; // start agressive |
| | 221 | 645 | | _movingFillRate = 0.0; |
| | 221 | 646 | | } |
| | | 647 | | |
| | | 648 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 19307 | 649 | | public bool ContainsKey(TKey key) => FindEntry(key) >= 0; |
| | | 650 | | |
| | | 651 | | bool IDictionary.Contains(object obj) |
| | 4 | 652 | | { |
| | 4 | 653 | | SwiftThrowHelper.ThrowIfNull(obj, nameof(obj)); |
| | | 654 | | |
| | 7 | 655 | | if (obj is TKey key) return ContainsKey(key); |
| | 1 | 656 | | return false; |
| | 4 | 657 | | } |
| | | 658 | | |
| | | 659 | | bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) |
| | 2 | 660 | | { |
| | 2 | 661 | | int index = FindEntry(item.Key); |
| | 2 | 662 | | if (index >= 0 && EqualityComparer<TValue>.Default.Equals(_entries[index].Value, item.Value)) |
| | 1 | 663 | | return true; |
| | 1 | 664 | | return false; |
| | 2 | 665 | | } |
| | | 666 | | |
| | | 667 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 668 | | public bool TryGetValue(TKey key, out TValue value) |
| | 6178 | 669 | | { |
| | 6178 | 670 | | int index = FindEntry(key); |
| | 6178 | 671 | | if (index >= 0) |
| | 6071 | 672 | | { |
| | 6071 | 673 | | value = _entries[index].Value; |
| | 6071 | 674 | | return true; |
| | | 675 | | } |
| | 107 | 676 | | value = default; |
| | 107 | 677 | | return false; |
| | 6178 | 678 | | } |
| | | 679 | | |
| | | 680 | | public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) |
| | 13 | 681 | | { |
| | 13 | 682 | | SwiftThrowHelper.ThrowIfNull(array, nameof(array)); |
| | 13 | 683 | | if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); |
| | 13 | 684 | | if (array.Length - arrayIndex < _count) throw new ArgumentException("Insufficient space", nameof(array)); |
| | | 685 | | |
| | 214 | 686 | | for (uint i = 0; i <= (uint)_lastIndex; i++) |
| | 94 | 687 | | { |
| | 94 | 688 | | if (_entries[i].IsUsed) |
| | 38 | 689 | | array[arrayIndex++] = new KeyValuePair<TKey, TValue>(_entries[i].Key, _entries[i].Value); |
| | 94 | 690 | | } |
| | 13 | 691 | | } |
| | | 692 | | |
| | 1 | 693 | | void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index) => CopyTo(array, |
| | | 694 | | |
| | | 695 | | void ICollection.CopyTo(Array array, int arrayIndex) |
| | 6 | 696 | | { |
| | 6 | 697 | | SwiftThrowHelper.ThrowIfNull(array, nameof(array)); |
| | 7 | 698 | | if (array.Rank != 1) throw new ArgumentException("Multidimensional array not supported", nameof(array)); |
| | 6 | 699 | | if (array.GetLowerBound(0) != 0) throw new ArgumentException("Non-zero lower bound", nameof(array)); |
| | 4 | 700 | | if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); |
| | 5 | 701 | | if (array.Length - arrayIndex < _count) throw new ArgumentException("Insufficient space", nameof(array)); |
| | | 702 | | |
| | 3 | 703 | | if (array is KeyValuePair<TKey, TValue>[] pairs) |
| | 0 | 704 | | ((ICollection<KeyValuePair<TKey, TValue>>)this).CopyTo(pairs, arrayIndex); |
| | 3 | 705 | | else if (array is DictionaryEntry[] dictEntryArray) |
| | 1 | 706 | | { |
| | 8 | 707 | | for (uint i = 0; i <= (uint)_lastIndex; i++) |
| | 3 | 708 | | { |
| | 3 | 709 | | if (_entries[i].IsUsed) |
| | 2 | 710 | | dictEntryArray[arrayIndex++] = new DictionaryEntry(_entries[i].Key, _entries[i].Value); |
| | 3 | 711 | | } |
| | 1 | 712 | | } |
| | | 713 | | else |
| | 2 | 714 | | { |
| | 3 | 715 | | if (array is not object[] objects) throw new ArgumentException("Invalid array type", nameof(array)); |
| | | 716 | | |
| | | 717 | | try |
| | 1 | 718 | | { |
| | 8 | 719 | | for (uint i = 0; i <= (uint)_lastIndex; i++) |
| | 3 | 720 | | { |
| | 3 | 721 | | if (_entries[i].IsUsed) |
| | 2 | 722 | | objects[arrayIndex++] = new KeyValuePair<TKey, TValue>(_entries[i].Key, _entries[i].Value); |
| | 3 | 723 | | } |
| | 1 | 724 | | } |
| | 0 | 725 | | catch (ArrayTypeMismatchException) |
| | 0 | 726 | | { |
| | 0 | 727 | | throw new ArgumentException("Invalid array type", nameof(array)); |
| | | 728 | | } |
| | 1 | 729 | | } |
| | 2 | 730 | | } |
| | | 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) |
| | 4 | 738 | | { |
| | 4 | 739 | | SwiftThrowHelper.ThrowIfNull(comparer, nameof(comparer)); |
| | 4 | 740 | | if (ReferenceEquals(comparer, _comparer)) |
| | 0 | 741 | | return; |
| | | 742 | | |
| | 4 | 743 | | _comparer = comparer; |
| | 4 | 744 | | RehashEntries(); |
| | 4 | 745 | | _maxStepCount = 0; |
| | 4 | 746 | | } |
| | | 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() |
| | 1 | 754 | | { |
| | 1 | 755 | | if (SwiftHashTools.IsWellKnownEqualityComparer(_comparer)) |
| | 1 | 756 | | _comparer = (IEqualityComparer<TKey>)SwiftHashTools.GetSwiftEqualityComparer(_comparer); |
| | 0 | 757 | | else return; // nothing to do here |
| | | 758 | | |
| | 1 | 759 | | RehashEntries(); |
| | 1 | 760 | | _maxStepCount = 0; |
| | | 761 | | |
| | 1 | 762 | | _version++; |
| | 1 | 763 | | } |
| | | 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() |
| | 5 | 770 | | { |
| | 5 | 771 | | Entry[] newEntries = new Entry[_entries.Length]; |
| | 5 | 772 | | int newMask = newEntries.Length - 1; |
| | | 773 | | |
| | 5 | 774 | | int lastIndex = 0; |
| | 612 | 775 | | for (uint i = 0; i <= (uint)_lastIndex; i++) |
| | 301 | 776 | | { |
| | 301 | 777 | | if (_entries[i].IsUsed) |
| | 109 | 778 | | { |
| | 109 | 779 | | ref Entry oldEntry = ref _entries[i]; |
| | 109 | 780 | | oldEntry.HashCode = _comparer.GetHashCode(oldEntry.Key) & 0x7FFFFFFF; |
| | 109 | 781 | | int newIndex = oldEntry.HashCode & newMask; |
| | 109 | 782 | | int step = 1; |
| | 133 | 783 | | while (newEntries[newIndex].IsUsed) |
| | 24 | 784 | | { |
| | 24 | 785 | | newIndex = (newIndex + step * step) & newMask; // Quadratic probing |
| | 24 | 786 | | step++; |
| | 24 | 787 | | } |
| | 109 | 788 | | newEntries[newIndex] = _entries[i]; |
| | 135 | 789 | | if (newIndex > lastIndex) lastIndex = newIndex; |
| | 109 | 790 | | } |
| | 301 | 791 | | } |
| | | 792 | | |
| | 5 | 793 | | _lastIndex = lastIndex; |
| | | 794 | | |
| | 5 | 795 | | _entryMask = newMask; |
| | 5 | 796 | | _entries = newEntries; |
| | | 797 | | |
| | 5 | 798 | | _version++; |
| | 5 | 799 | | } |
| | | 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) |
| | 39233 | 809 | | { |
| | 39233 | 810 | | if (key == null) return -1; |
| | | 811 | | |
| | 39233 | 812 | | int hashCode = _comparer.GetHashCode(key) & 0x7FFFFFFF; |
| | 39233 | 813 | | int entryIndex = hashCode & _entryMask; |
| | | 814 | | |
| | 39233 | 815 | | int step = 0; |
| | 44259 | 816 | | while ((uint)step <= (uint)_lastIndex) |
| | 44250 | 817 | | { |
| | 44250 | 818 | | ref Entry entry = ref _entries[entryIndex]; |
| | | 819 | | // Stop probing if an unused entry is found (not deleted) |
| | 44250 | 820 | | if (!entry.IsUsed && entry.HashCode != -1) |
| | 17416 | 821 | | return -1; |
| | 26834 | 822 | | if (entry.IsUsed && entry.HashCode == hashCode && _comparer.Equals(entry.Key, key)) |
| | 21808 | 823 | | return entryIndex; // Match found |
| | | 824 | | |
| | | 825 | | // Perform quadratic probing to see if maybe the entry was shifted. |
| | 5026 | 826 | | step++; |
| | 5026 | 827 | | entryIndex = (entryIndex + step * step) & _entryMask; |
| | 5026 | 828 | | } |
| | 9 | 829 | | return -1; // Item not found, full loop completed |
| | 39233 | 830 | | } |
| | | 831 | | |
| | | 832 | | #endregion |
| | | 833 | | |
| | | 834 | | #region IEnumerable Implementation |
| | | 835 | | |
| | 31 | 836 | | public SwiftDictionaryEnumerator GetEnumerator() => new SwiftDictionaryEnumerator(this); |
| | 21 | 837 | | IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() => GetEnumerator(); |
| | 1 | 838 | | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); |
| | 3 | 839 | | 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) |
| | 34 | 855 | | { |
| | 34 | 856 | | _dictionary = dictionary; |
| | 34 | 857 | | _entries = dictionary._entries; |
| | 34 | 858 | | _version = dictionary._version; |
| | 34 | 859 | | _returnEntry = returnEntry; |
| | 34 | 860 | | _index = -1; |
| | 34 | 861 | | _current = default; |
| | 34 | 862 | | } |
| | | 863 | | |
| | | 864 | | object IDictionaryEnumerator.Key |
| | | 865 | | { |
| | | 866 | | get |
| | 3 | 867 | | { |
| | 3 | 868 | | if (_index > (uint)_dictionary._lastIndex) throw new InvalidOperationException("Bad enumeration"); |
| | 3 | 869 | | return _current.Key; |
| | 3 | 870 | | } |
| | | 871 | | } |
| | | 872 | | |
| | | 873 | | object IDictionaryEnumerator.Value |
| | | 874 | | { |
| | | 875 | | get |
| | 1 | 876 | | { |
| | 1 | 877 | | if (_index > (uint)_dictionary._lastIndex) throw new InvalidOperationException("Bad enumeration"); |
| | 1 | 878 | | return _current.Value; |
| | 1 | 879 | | } |
| | | 880 | | } |
| | | 881 | | |
| | | 882 | | DictionaryEntry IDictionaryEnumerator.Entry |
| | | 883 | | { |
| | | 884 | | get |
| | 2 | 885 | | { |
| | 3 | 886 | | if (_index > (uint)_dictionary._lastIndex) throw new InvalidOperationException("Bad enumeration"); |
| | 1 | 887 | | return new DictionaryEntry(_current.Key, _current.Value); |
| | 1 | 888 | | } |
| | | 889 | | } |
| | | 890 | | |
| | 48 | 891 | | public KeyValuePair<TKey, TValue> Current => _current; |
| | | 892 | | |
| | | 893 | | object IEnumerator.Current |
| | | 894 | | { |
| | | 895 | | get |
| | 2 | 896 | | { |
| | 2 | 897 | | if (_index > (uint)_dictionary._lastIndex) throw new InvalidOperationException("Bad enumeration"); |
| | 2 | 898 | | return _returnEntry |
| | 2 | 899 | | ? new DictionaryEntry(_current.Key, _current.Value) |
| | 2 | 900 | | : new KeyValuePair<TKey, TValue>(_current.Key, _current.Value); |
| | 2 | 901 | | } |
| | | 902 | | } |
| | | 903 | | |
| | | 904 | | public bool MoveNext() |
| | 77 | 905 | | { |
| | 77 | 906 | | if (_version != _dictionary._version) |
| | 0 | 907 | | throw new InvalidOperationException("Enumerator modified outside of enumeration!"); |
| | | 908 | | |
| | 154 | 909 | | while (++_index <= (uint)_dictionary._lastIndex) |
| | 122 | 910 | | { |
| | 122 | 911 | | if (_entries[_index].IsUsed) |
| | 45 | 912 | | { |
| | 45 | 913 | | _current = new KeyValuePair<TKey, TValue>(_entries[_index].Key, _entries[_index].Value); |
| | 45 | 914 | | return true; |
| | | 915 | | } |
| | 77 | 916 | | } |
| | | 917 | | |
| | 32 | 918 | | _current = default; |
| | 32 | 919 | | return false; |
| | 77 | 920 | | } |
| | | 921 | | |
| | | 922 | | public void Reset() |
| | 1 | 923 | | { |
| | 1 | 924 | | if (_version != _dictionary._version) |
| | 0 | 925 | | throw new InvalidOperationException("Enumerator modified outside of enumeration!"); |
| | | 926 | | |
| | 1 | 927 | | _index = -1; |
| | 1 | 928 | | _current = default; |
| | 1 | 929 | | } |
| | | 930 | | |
| | | 931 | | public void Dispose() |
| | 31 | 932 | | { |
| | 31 | 933 | | } |
| | | 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> |
| | 13 | 954 | | public KeyCollection(SwiftDictionary<TKey, TValue> dictionary) |
| | 13 | 955 | | { |
| | 13 | 956 | | _dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary)); |
| | 13 | 957 | | _entries = dictionary._entries; |
| | 13 | 958 | | } |
| | | 959 | | |
| | 1 | 960 | | public int Count => _dictionary._count; |
| | | 961 | | |
| | 1 | 962 | | bool ICollection.IsSynchronized => false; |
| | | 963 | | |
| | 1 | 964 | | object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; |
| | | 965 | | |
| | 1 | 966 | | bool ICollection<TKey>.IsReadOnly => true; |
| | | 967 | | |
| | 1 | 968 | | void ICollection<TKey>.Add(TKey item) => throw new NotSupportedException(); |
| | | 969 | | |
| | 1 | 970 | | void ICollection<TKey>.Clear() => throw new NotSupportedException(); |
| | | 971 | | |
| | 2 | 972 | | bool ICollection<TKey>.Contains(TKey item) => _dictionary.ContainsKey(item); |
| | | 973 | | |
| | 1 | 974 | | bool ICollection<TKey>.Remove(TKey item) => false; |
| | | 975 | | |
| | | 976 | | public void CopyTo(TKey[] array, int arrayIndex) |
| | 1 | 977 | | { |
| | 1 | 978 | | SwiftThrowHelper.ThrowIfNull(array, nameof(array)); |
| | 1 | 979 | | if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); |
| | 1 | 980 | | if (array.Length - arrayIndex < _dictionary._count) throw new ArgumentException("Insufficient space", nameof |
| | | 981 | | |
| | 19 | 982 | | for (int i = 0, j = arrayIndex; i < _entries.Length; i++) |
| | 8 | 983 | | { |
| | 8 | 984 | | if (_entries[i].IsUsed) |
| | 2 | 985 | | array[j++] = _entries[i].Key; |
| | 8 | 986 | | } |
| | 1 | 987 | | } |
| | | 988 | | |
| | | 989 | | void ICollection.CopyTo(Array array, int arrayIndex) |
| | 2 | 990 | | { |
| | 2 | 991 | | SwiftThrowHelper.ThrowIfNull(array, nameof(array)); |
| | 2 | 992 | | if (array.Rank != 1) throw new ArgumentException("Multidimensional array not supported"); |
| | 2 | 993 | | if (array.GetLowerBound(0) != 0) throw new ArgumentException("Non-zero lower bound"); |
| | 2 | 994 | | if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); |
| | 2 | 995 | | if (array.Length - arrayIndex < _dictionary._count) throw new ArgumentException("Insufficient space", nameof |
| | | 996 | | |
| | 2 | 997 | | if (array is TKey[] keysArray) |
| | 0 | 998 | | CopyTo(keysArray, arrayIndex); |
| | 2 | 999 | | else if (array is object[] objects) |
| | 2 | 1000 | | { |
| | | 1001 | | try |
| | 2 | 1002 | | { |
| | 24 | 1003 | | for (int i = 0, j = arrayIndex; i < _entries.Length; i++) |
| | 10 | 1004 | | { |
| | 10 | 1005 | | if (_entries[i].IsUsed) |
| | 3 | 1006 | | objects[j++] = _entries[i].Key; |
| | 9 | 1007 | | } |
| | 1 | 1008 | | } |
| | 1 | 1009 | | catch (ArrayTypeMismatchException) |
| | 1 | 1010 | | { |
| | 1 | 1011 | | throw new ArgumentException("Invalid array type", nameof(array)); |
| | | 1012 | | } |
| | 1 | 1013 | | } |
| | | 1014 | | else |
| | 0 | 1015 | | { |
| | 0 | 1016 | | throw new ArgumentException("Invalid array type", nameof(array)); |
| | | 1017 | | } |
| | 1 | 1018 | | } |
| | | 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> |
| | 9 | 1024 | | public KeyCollectionEnumerator GetEnumerator() => new KeyCollectionEnumerator(_dictionary); |
| | 7 | 1025 | | IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() => GetEnumerator(); |
| | 2 | 1026 | | 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) |
| | 9 | 1038 | | { |
| | 9 | 1039 | | _dictionary = dictionary; |
| | 9 | 1040 | | _entries = dictionary._entries; |
| | 9 | 1041 | | _version = dictionary._version; |
| | 9 | 1042 | | _index = -1; |
| | 9 | 1043 | | _currentKey = default; |
| | 9 | 1044 | | } |
| | | 1045 | | |
| | 24 | 1046 | | public TKey Current => _currentKey; |
| | | 1047 | | |
| | | 1048 | | object IEnumerator.Current |
| | | 1049 | | { |
| | | 1050 | | get |
| | 1 | 1051 | | { |
| | 1 | 1052 | | if (_index > (uint)_dictionary._lastIndex) throw new InvalidOperationException("Bad enumeration"); |
| | 1 | 1053 | | return _currentKey; |
| | 1 | 1054 | | } |
| | | 1055 | | } |
| | | 1056 | | |
| | | 1057 | | public bool MoveNext() |
| | 25 | 1058 | | { |
| | 25 | 1059 | | if (_version != _dictionary._version) |
| | 1 | 1060 | | throw new InvalidOperationException("Enumerator modified outside of enumeration!"); |
| | | 1061 | | |
| | 49 | 1062 | | while (++_index <= (uint)_dictionary._lastIndex) |
| | 45 | 1063 | | { |
| | 45 | 1064 | | if (_entries[_index].IsUsed) |
| | 20 | 1065 | | { |
| | 20 | 1066 | | _currentKey = _entries[_index].Key; |
| | 20 | 1067 | | return true; |
| | | 1068 | | } |
| | 25 | 1069 | | } |
| | | 1070 | | |
| | 4 | 1071 | | _currentKey = default; |
| | 4 | 1072 | | return false; |
| | 24 | 1073 | | } |
| | | 1074 | | |
| | | 1075 | | public void Reset() |
| | 1 | 1076 | | { |
| | 1 | 1077 | | if (_version != _dictionary._version) |
| | 0 | 1078 | | throw new InvalidOperationException("Enumerator modified outside of enumeration!"); |
| | | 1079 | | |
| | 1 | 1080 | | _index = -1; |
| | 1 | 1081 | | _currentKey = default; |
| | 1 | 1082 | | } |
| | | 1083 | | |
| | 14 | 1084 | | 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> |
| | 9 | 1102 | | public ValueCollection(SwiftDictionary<TKey, TValue> dictionary) |
| | 9 | 1103 | | { |
| | 9 | 1104 | | _dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary)); |
| | 9 | 1105 | | _entries = dictionary._entries; |
| | 9 | 1106 | | } |
| | | 1107 | | |
| | 1 | 1108 | | public int Count => _dictionary._count; |
| | | 1109 | | |
| | 1 | 1110 | | bool ICollection<TValue>.IsReadOnly => true; |
| | | 1111 | | |
| | 1 | 1112 | | bool ICollection.IsSynchronized => false; |
| | | 1113 | | |
| | 1 | 1114 | | object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; |
| | | 1115 | | |
| | 1 | 1116 | | void ICollection<TValue>.Add(TValue item) => throw new NotSupportedException(); |
| | | 1117 | | |
| | 1 | 1118 | | void ICollection<TValue>.Clear() => throw new NotSupportedException(); |
| | | 1119 | | |
| | | 1120 | | bool ICollection<TValue>.Contains(TValue item) |
| | 2 | 1121 | | { |
| | 12 | 1122 | | for (uint i = 0; i <= (uint)_dictionary._lastIndex; i++) |
| | 6 | 1123 | | { |
| | 6 | 1124 | | if (_entries[i].IsUsed && EqualityComparer<TValue>.Default.Equals(_entries[i].Value, item)) |
| | 2 | 1125 | | return true; |
| | 4 | 1126 | | } |
| | 0 | 1127 | | return false; |
| | 2 | 1128 | | } |
| | | 1129 | | |
| | 1 | 1130 | | bool ICollection<TValue>.Remove(TValue item) => false; |
| | | 1131 | | |
| | | 1132 | | public void CopyTo(TValue[] array, int arrayIndex) |
| | 1 | 1133 | | { |
| | 1 | 1134 | | SwiftThrowHelper.ThrowIfNull(array, nameof(array)); |
| | 1 | 1135 | | if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); |
| | 1 | 1136 | | if (array.Length - arrayIndex < _dictionary._count) throw new ArgumentException("Insufficient space", nameof |
| | | 1137 | | |
| | | 1138 | | |
| | 9 | 1139 | | for (int i = 0, j = arrayIndex; i <= _dictionary._lastIndex; i++) |
| | 3 | 1140 | | { |
| | 3 | 1141 | | if (_dictionary._entries[i].IsUsed) |
| | 2 | 1142 | | array[j++] = _entries[i].Value; |
| | 3 | 1143 | | } |
| | 1 | 1144 | | } |
| | | 1145 | | |
| | | 1146 | | void ICollection.CopyTo(Array array, int arrayIndex) |
| | 2 | 1147 | | { |
| | 2 | 1148 | | SwiftThrowHelper.ThrowIfNull(array, nameof(array)); |
| | 2 | 1149 | | if (array.Rank != 1) throw new ArgumentException("Multidimensional array not supported", nameof(array)); |
| | 2 | 1150 | | if (array.GetLowerBound(0) != 0) throw new ArgumentException("Non-zero lower bound", nameof(array)); |
| | 2 | 1151 | | if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); |
| | 2 | 1152 | | if (array.Length - arrayIndex < _dictionary._count) throw new ArgumentException("Insufficient space", nameof |
| | | 1153 | | |
| | 2 | 1154 | | if (array is TValue[] valuesArray) |
| | 0 | 1155 | | CopyTo(valuesArray, arrayIndex); |
| | 2 | 1156 | | else if (array is object[] objects) |
| | 1 | 1157 | | { |
| | | 1158 | | try |
| | 1 | 1159 | | { |
| | 9 | 1160 | | for (int i = 0, j = arrayIndex; i <= _dictionary._lastIndex; i++) |
| | 3 | 1161 | | if (_entries[i].IsUsed) |
| | 2 | 1162 | | objects[j++] = _entries[i].Value; |
| | 1 | 1163 | | } |
| | 0 | 1164 | | catch (ArrayTypeMismatchException) |
| | 0 | 1165 | | { |
| | 0 | 1166 | | throw new ArgumentException("Invalid array type", nameof(array)); |
| | | 1167 | | } |
| | 1 | 1168 | | } |
| | 1 | 1169 | | else throw new ArgumentException("Invalid array type", nameof(array)); |
| | 1 | 1170 | | } |
| | | 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> |
| | 5 | 1176 | | public ValueCollectionEnumerator GetEnumerator() => new ValueCollectionEnumerator(_dictionary); |
| | 3 | 1177 | | IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() => GetEnumerator(); |
| | 2 | 1178 | | 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) |
| | 5 | 1190 | | { |
| | 5 | 1191 | | _dictionary = dictionary; |
| | 5 | 1192 | | _entries = dictionary._entries; |
| | 5 | 1193 | | _version = dictionary._version; |
| | 5 | 1194 | | _index = -1; |
| | 5 | 1195 | | _currentValue = default; |
| | 5 | 1196 | | } |
| | | 1197 | | |
| | 12 | 1198 | | public TValue Current => _currentValue; |
| | | 1199 | | |
| | | 1200 | | object IEnumerator.Current |
| | | 1201 | | { |
| | | 1202 | | get |
| | 1 | 1203 | | { |
| | 1 | 1204 | | if (_index > (uint)_dictionary._lastIndex) throw new InvalidOperationException("Bad enumeration"); |
| | 1 | 1205 | | return _currentValue; |
| | 1 | 1206 | | } |
| | | 1207 | | } |
| | | 1208 | | |
| | | 1209 | | public bool MoveNext() |
| | 9 | 1210 | | { |
| | 9 | 1211 | | if (_version != _dictionary._version) |
| | 1 | 1212 | | throw new InvalidOperationException("Enumerator modified outside of enumeration!"); |
| | | 1213 | | |
| | 13 | 1214 | | while (++_index <= (uint)_dictionary._lastIndex) |
| | 13 | 1215 | | { |
| | 13 | 1216 | | if (_entries[_index].IsUsed) |
| | 8 | 1217 | | { |
| | 8 | 1218 | | _currentValue = _entries[_index].Value; |
| | 8 | 1219 | | return true; |
| | | 1220 | | } |
| | 5 | 1221 | | } |
| | | 1222 | | |
| | 0 | 1223 | | _currentValue = default; |
| | 0 | 1224 | | return false; |
| | 8 | 1225 | | } |
| | | 1226 | | |
| | | 1227 | | public void Reset() |
| | 1 | 1228 | | { |
| | 1 | 1229 | | if (_version != _dictionary._version) |
| | 0 | 1230 | | throw new InvalidOperationException("Enumerator modified outside of enumeration!"); |
| | | 1231 | | |
| | 1 | 1232 | | _index = -1; |
| | 1 | 1233 | | _currentValue = default; |
| | 1 | 1234 | | } |
| | | 1235 | | |
| | 6 | 1236 | | public void Dispose() { } |
| | | 1237 | | } |
| | | 1238 | | } |
| | | 1239 | | |
| | | 1240 | | #endregion |
| | | 1241 | | } |