| | | 1 | | //======================================================================= |
| | | 2 | | // SwiftSparseMap.cs |
| | | 3 | | //======================================================================= |
| | | 4 | | // MIT License, Copyright (c) 2024–present David Oravsky (mrdav30) |
| | | 5 | | // See LICENSE file in the project root for full license information. |
| | | 6 | | //======================================================================= |
| | | 7 | | |
| | | 8 | | using Chronicler; |
| | | 9 | | using MemoryPack; |
| | | 10 | | using SwiftCollections.Diagnostics; |
| | | 11 | | using SwiftCollections.Utility; |
| | | 12 | | using System; |
| | | 13 | | using System.Collections; |
| | | 14 | | using System.Collections.Generic; |
| | | 15 | | using System.Runtime.CompilerServices; |
| | | 16 | | using System.Text.Json.Serialization; |
| | | 17 | | |
| | | 18 | | namespace SwiftCollections; |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Represents a high-performance sparse map that stores values indexed by externally supplied integer keys. |
| | | 22 | | /// Provides O(1) Add, Remove, Contains, and lookup operations while maintaining densely packed storage |
| | | 23 | | /// for cache-friendly iteration. |
| | | 24 | | /// </summary> |
| | | 25 | | /// <remarks> |
| | | 26 | | /// Unlike <see cref="SwiftBucket{T}"/>, which internally assigns and manages item indices, |
| | | 27 | | /// <see cref="SwiftSparseMap{T}"/> is externally keyed. The caller supplies the integer key |
| | | 28 | | /// (for example, an entity ID or handle) used to index the value. |
| | | 29 | | /// |
| | | 30 | | /// Internally, the container maintains: |
| | | 31 | | /// <list type="bullet"> |
| | | 32 | | /// <item> |
| | | 33 | | /// <description>A sparse lookup table mapping keys to dense indices.</description> |
| | | 34 | | /// </item> |
| | | 35 | | /// <item> |
| | | 36 | | /// <description>A dense array of keys.</description> |
| | | 37 | | /// </item> |
| | | 38 | | /// <item> |
| | | 39 | | /// <description>A dense array of values.</description> |
| | | 40 | | /// </item> |
| | | 41 | | /// </list> |
| | | 42 | | /// |
| | | 43 | | /// Removal uses a swap-back strategy to keep dense storage contiguous. As a result, |
| | | 44 | | /// iteration order is not guaranteed to remain stable. |
| | | 45 | | /// |
| | | 46 | | /// Keys are used as direct indices into the sparse lookup table, so memory usage scales |
| | | 47 | | /// with the highest stored key rather than the number of stored values. This container is |
| | | 48 | | /// intended for compact, non-negative IDs such as entity handles or slot indices. It is |
| | | 49 | | /// not a good fit for arbitrary hashes or widely spaced keys; for those workloads prefer |
| | | 50 | | /// <c>SwiftDictionary<TKey, TValue></c>. |
| | | 51 | | /// </remarks> |
| | | 52 | | /// <typeparam name="T">Value type stored by key.</typeparam> |
| | | 53 | | [Serializable] |
| | | 54 | | [JsonConverter(typeof(StateJsonConverterFactory))] |
| | | 55 | | [MemoryPackable] |
| | | 56 | | public sealed partial class SwiftSparseMap<T> : IStateBacked<SwiftSparseMapState<T>>, ISwiftCloneable<T>, IEnumerable<Ke |
| | | 57 | | { |
| | | 58 | | #region Constants |
| | | 59 | | |
| | | 60 | | /// <summary> |
| | | 61 | | /// Represents the default initial capacity for dense collections. |
| | | 62 | | /// </summary> |
| | | 63 | | public const int DefaultDenseCapacity = 8; |
| | | 64 | | |
| | | 65 | | /// <summary> |
| | | 66 | | /// Represents the default initial capacity for sparse collections. |
| | | 67 | | /// </summary> |
| | | 68 | | public const int DefaultSparseCapacity = 8; |
| | | 69 | | |
| | | 70 | | /// <summary> |
| | | 71 | | /// Represents the value used to indicate that a key is not present in the sparse array. |
| | | 72 | | /// </summary> |
| | | 73 | | /// <remarks> |
| | | 74 | | /// A value of 0 signifies that the key is absent. |
| | | 75 | | /// When a key is present, the stored value is the dense index plus one. |
| | | 76 | | /// </remarks> |
| | | 77 | | private const int NotPresent = 0; |
| | | 78 | | |
| | | 79 | | #endregion |
| | | 80 | | |
| | | 81 | | #region Fields |
| | | 82 | | |
| | | 83 | | private int[] _sparse; // key -> denseIndex+1 |
| | | 84 | | private int[] _denseKeys; // denseIndex -> key |
| | | 85 | | private T[] _denseValues; // denseIndex -> value |
| | | 86 | | private int _count; |
| | | 87 | | |
| | | 88 | | [NonSerialized] |
| | | 89 | | private uint _version; |
| | | 90 | | |
| | | 91 | | [NonSerialized] |
| | | 92 | | private object? _syncRoot; |
| | | 93 | | |
| | | 94 | | #endregion |
| | | 95 | | |
| | | 96 | | #region Constructors |
| | | 97 | | |
| | | 98 | | /// <summary> |
| | | 99 | | /// Initializes a new instance of the SwiftSparseMap class with default sparse and dense capacities. |
| | | 100 | | /// </summary> |
| | 78 | 101 | | public SwiftSparseMap() : this(DefaultSparseCapacity, DefaultDenseCapacity) { } |
| | | 102 | | |
| | | 103 | | /// <summary> |
| | | 104 | | /// Initializes a new sparse map with the specified sparse and dense capacities. |
| | | 105 | | /// </summary> |
| | | 106 | | /// <param name="sparseCapacity"> |
| | | 107 | | /// Initial sparse lookup capacity. This should track the highest expected key plus one, |
| | | 108 | | /// not the number of stored values. |
| | | 109 | | /// </param> |
| | | 110 | | /// <param name="denseCapacity">Initial dense storage capacity for values.</param> |
| | 42 | 111 | | public SwiftSparseMap(int sparseCapacity, int denseCapacity) |
| | | 112 | | { |
| | 42 | 113 | | SwiftThrowHelper.ThrowIfNegative(sparseCapacity, nameof(sparseCapacity)); |
| | 42 | 114 | | SwiftThrowHelper.ThrowIfNegative(denseCapacity, nameof(denseCapacity)); |
| | | 115 | | |
| | 42 | 116 | | int sparseSize = sparseCapacity == 0 ? 0 : SwiftHashTools.NextPowerOfTwo(sparseCapacity); |
| | 42 | 117 | | _sparse = sparseCapacity == 0 |
| | 42 | 118 | | ? Array.Empty<int>() |
| | 42 | 119 | | : new int[sparseSize]; |
| | 42 | 120 | | int denseSize = denseCapacity < DefaultDenseCapacity |
| | 42 | 121 | | ? DefaultDenseCapacity |
| | 42 | 122 | | : SwiftHashTools.NextPowerOfTwo(denseCapacity); |
| | 42 | 123 | | _denseKeys = denseCapacity == 0 |
| | 42 | 124 | | ? Array.Empty<int>() |
| | 42 | 125 | | : new int[denseSize]; |
| | 42 | 126 | | _denseValues = _denseKeys.Length == 0 ? Array.Empty<T>() : new T[_denseKeys.Length]; |
| | | 127 | | |
| | 42 | 128 | | _count = 0; |
| | 42 | 129 | | } |
| | | 130 | | |
| | | 131 | | /// <summary> |
| | | 132 | | /// Initializes a new instance of the SwiftSparseMap class using the specified state. |
| | | 133 | | /// </summary> |
| | | 134 | | /// <param name="state">The state object that provides the initial configuration and data for the map. Cannot be nul |
| | | 135 | | [MemoryPackConstructor] |
| | 7 | 136 | | public SwiftSparseMap(SwiftSparseMapState<T> state) |
| | | 137 | | { |
| | 7 | 138 | | _sparse = Array.Empty<int>(); |
| | 7 | 139 | | _denseKeys = Array.Empty<int>(); |
| | 7 | 140 | | _denseValues = Array.Empty<T>(); |
| | | 141 | | |
| | 7 | 142 | | State = state; |
| | 5 | 143 | | } |
| | | 144 | | |
| | | 145 | | #endregion |
| | | 146 | | |
| | | 147 | | #region Properties |
| | | 148 | | |
| | | 149 | | /// <summary> |
| | | 150 | | /// Gets the number of elements contained in the collection. |
| | | 151 | | /// </summary> |
| | | 152 | | [JsonIgnore] |
| | | 153 | | [MemoryPackIgnore] |
| | 16 | 154 | | public int Count => _count; |
| | | 155 | | |
| | | 156 | | /// <summary> |
| | | 157 | | /// Capacity of the dense arrays (Keys/Values storage). |
| | | 158 | | /// </summary> |
| | | 159 | | [JsonIgnore] |
| | | 160 | | [MemoryPackIgnore] |
| | 5 | 161 | | public int DenseCapacity => _denseKeys.Length; |
| | | 162 | | |
| | | 163 | | /// <summary> |
| | | 164 | | /// Capacity of the sparse array (max key+1 that can be mapped without resizing). |
| | | 165 | | /// Memory usage grows with this capacity. |
| | | 166 | | /// </summary> |
| | | 167 | | [JsonIgnore] |
| | | 168 | | [MemoryPackIgnore] |
| | 6 | 169 | | public int SparseCapacity => _sparse.Length; |
| | | 170 | | |
| | | 171 | | /// <summary> |
| | | 172 | | /// Gets a value indicating whether access to the collection is synchronized (thread safe). |
| | | 173 | | /// </summary> |
| | | 174 | | [JsonIgnore] |
| | | 175 | | [MemoryPackIgnore] |
| | 1 | 176 | | public bool IsSynchronized => false; |
| | | 177 | | |
| | | 178 | | /// <summary> |
| | | 179 | | /// Gets an object that can be used to synchronize access to the collection. |
| | | 180 | | /// </summary> |
| | | 181 | | /// <remarks> |
| | | 182 | | /// Use this object to lock the collection during multithreaded operations to ensure thread safety. |
| | | 183 | | /// The returned object is unique to this collection instance. |
| | | 184 | | /// </remarks> |
| | | 185 | | [JsonIgnore] |
| | | 186 | | [MemoryPackIgnore] |
| | 1 | 187 | | public object SyncRoot => _syncRoot ??= new object(); |
| | | 188 | | |
| | | 189 | | /// <summary> |
| | | 190 | | /// Returns the dense keys array (valid range: [0..Count)). |
| | | 191 | | /// </summary> |
| | | 192 | | [JsonIgnore] |
| | | 193 | | [MemoryPackIgnore] |
| | 6 | 194 | | public int[] DenseKeys => _denseKeys; |
| | | 195 | | |
| | | 196 | | /// <summary> |
| | | 197 | | /// Gets a span containing the keys currently stored in the collection. |
| | | 198 | | /// </summary> |
| | | 199 | | /// <remarks> |
| | | 200 | | /// The returned span provides a view of the underlying key data and reflects the current state of the collection. |
| | | 201 | | /// Modifying the span will affect the collection's contents. |
| | | 202 | | /// The span is only valid as long as the underlying collection is not modified. |
| | | 203 | | /// </remarks> |
| | | 204 | | [JsonIgnore] |
| | | 205 | | [MemoryPackIgnore] |
| | 1 | 206 | | public Span<int> Keys => _denseKeys.AsSpan(0, _count); |
| | | 207 | | |
| | | 208 | | /// <summary> |
| | | 209 | | /// Returns the dense values array (valid range: [0..Count)). |
| | | 210 | | /// </summary> |
| | | 211 | | [JsonIgnore] |
| | | 212 | | [MemoryPackIgnore] |
| | 5 | 213 | | public T[] DenseValues => _denseValues; |
| | | 214 | | |
| | | 215 | | /// <summary> |
| | | 216 | | /// Gets a span containing the current values in the collection. |
| | | 217 | | /// </summary> |
| | | 218 | | /// <remarks> |
| | | 219 | | /// The returned span reflects the live contents of the collection up to the current count. |
| | | 220 | | /// Modifying the span will update the underlying collection data. |
| | | 221 | | /// The span length is equal to the number of elements currently stored. |
| | | 222 | | /// </remarks> |
| | | 223 | | [JsonIgnore] |
| | | 224 | | [MemoryPackIgnore] |
| | 1 | 225 | | public Span<T> Values => _denseValues.AsSpan(0, _count); |
| | | 226 | | |
| | | 227 | | /// <summary> |
| | | 228 | | /// Gets/sets the value for a key. Setting: |
| | | 229 | | /// - overwrites if present |
| | | 230 | | /// - inserts if not present |
| | | 231 | | /// </summary> |
| | | 232 | | [JsonIgnore] |
| | | 233 | | [MemoryPackIgnore] |
| | | 234 | | public T this[int key] |
| | | 235 | | { |
| | | 236 | | get |
| | | 237 | | { |
| | 22 | 238 | | int denseIndex = GetDenseIndexOrThrow(key); |
| | 19 | 239 | | return _denseValues[denseIndex]; |
| | | 240 | | } |
| | | 241 | | set |
| | | 242 | | { |
| | 58 | 243 | | EnsureSparseCapacity(GetRequiredSparseCapacity(key)); |
| | | 244 | | |
| | 56 | 245 | | int slot = _sparse[key]; |
| | 56 | 246 | | if (slot != NotPresent) |
| | | 247 | | { |
| | | 248 | | // present -> overwrite |
| | 1 | 249 | | int denseIndex = slot - 1; |
| | 1 | 250 | | _denseValues[denseIndex] = value; |
| | 1 | 251 | | _version++; |
| | 1 | 252 | | return; |
| | | 253 | | } |
| | | 254 | | |
| | | 255 | | // not present -> insert |
| | 55 | 256 | | EnsureDenseCapacity(_count + 1); |
| | | 257 | | |
| | 55 | 258 | | int newIndex = _count++; |
| | 55 | 259 | | _denseKeys[newIndex] = key; |
| | 55 | 260 | | _denseValues[newIndex] = value; |
| | 55 | 261 | | _sparse[key] = newIndex + 1; |
| | | 262 | | |
| | 55 | 263 | | _version++; |
| | 55 | 264 | | } |
| | | 265 | | } |
| | | 266 | | |
| | | 267 | | /// <summary> |
| | | 268 | | /// Gets or sets the current state of the sparse map, including the used dense keys and values. |
| | | 269 | | /// </summary> |
| | | 270 | | /// <remarks> |
| | | 271 | | /// The state includes only the active elements in the map. |
| | | 272 | | /// Setting this property replaces the current contents with the provided state. |
| | | 273 | | /// The setter is intended for internal use, such as serialization or deserialization scenarios. |
| | | 274 | | /// </remarks> |
| | | 275 | | [JsonInclude] |
| | | 276 | | [MemoryPackInclude] |
| | | 277 | | public SwiftSparseMapState<T> State |
| | | 278 | | { |
| | | 279 | | get |
| | | 280 | | { |
| | | 281 | | // Serialize only the used portions of dense arrays |
| | 4 | 282 | | var denseKeys = new int[_count]; |
| | 4 | 283 | | Array.Copy(_denseKeys, denseKeys, _count); |
| | | 284 | | |
| | 4 | 285 | | var denseValues = new T[_count]; |
| | 4 | 286 | | Array.Copy(_denseValues, denseValues, _count); |
| | | 287 | | |
| | 4 | 288 | | return new SwiftSparseMapState<T>(denseKeys, denseValues); |
| | | 289 | | } |
| | | 290 | | internal set |
| | | 291 | | { |
| | 7 | 292 | | SwiftThrowHelper.ThrowIfNull(value.DenseKeys); |
| | 7 | 293 | | SwiftThrowHelper.ThrowIfNull(value.DenseValues); |
| | | 294 | | |
| | 7 | 295 | | int n = value.DenseKeys.Length; |
| | | 296 | | |
| | 7 | 297 | | SwiftThrowHelper.ThrowIfArgument(n != value.DenseValues.Length, nameof(value), "DenseKeys and DenseValues le |
| | | 298 | | |
| | | 299 | | // Allocate dense storage |
| | 6 | 300 | | _denseKeys = n == 0 ? Array.Empty<int>() : new int[Math.Max(DefaultDenseCapacity, n)]; |
| | 6 | 301 | | _denseValues = n == 0 ? Array.Empty<T>() : new T[_denseKeys.Length]; |
| | | 302 | | |
| | 6 | 303 | | if (n > 0) |
| | | 304 | | { |
| | 5 | 305 | | Array.Copy(value.DenseKeys, _denseKeys, n); |
| | 5 | 306 | | Array.Copy(value.DenseValues, _denseValues, n); |
| | | 307 | | } |
| | | 308 | | |
| | 6 | 309 | | _count = n; |
| | | 310 | | |
| | | 311 | | // Compute maxKey from dense keys |
| | 6 | 312 | | int maxKey = -1; |
| | 30 | 313 | | for (int i = 0; i < n; i++) |
| | | 314 | | { |
| | 9 | 315 | | int key = _denseKeys[i]; |
| | 9 | 316 | | SwiftThrowHelper.ThrowIfArgument(key < 0, nameof(value), "Key cannot be negative."); |
| | | 317 | | |
| | 9 | 318 | | if (key > maxKey) |
| | 8 | 319 | | maxKey = key; |
| | | 320 | | } |
| | | 321 | | |
| | | 322 | | // Allocate sparse map |
| | 6 | 323 | | int sparseSize = maxKey < 0 |
| | 6 | 324 | | ? DefaultSparseCapacity |
| | 6 | 325 | | : Math.Max(DefaultSparseCapacity, GetRequiredSparseCapacity(maxKey)); |
| | 6 | 326 | | _sparse = new int[sparseSize]; |
| | | 327 | | |
| | | 328 | | // Rebuild sparse lookup |
| | 28 | 329 | | for (int i = 0; i < n; i++) |
| | | 330 | | { |
| | 9 | 331 | | int key = _denseKeys[i]; |
| | | 332 | | |
| | 9 | 333 | | SwiftThrowHelper.ThrowIfArgument(_sparse[key] != NotPresent, nameof(value), "Duplicate key in DenseKeys. |
| | | 334 | | |
| | 8 | 335 | | _sparse[key] = i + 1; |
| | | 336 | | } |
| | | 337 | | |
| | 5 | 338 | | _version++; |
| | 5 | 339 | | } |
| | | 340 | | } |
| | | 341 | | |
| | | 342 | | #endregion |
| | | 343 | | |
| | | 344 | | #region Core Operations |
| | | 345 | | |
| | | 346 | | /// <summary> |
| | | 347 | | /// Determines whether the collection contains the specified key. |
| | | 348 | | /// </summary> |
| | | 349 | | /// <param name="key">The key to locate in the collection.</param> |
| | | 350 | | /// <returns>true if the collection contains an element with the specified key; otherwise, false.</returns> |
| | | 351 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 352 | | public bool ContainsKey(int key) |
| | | 353 | | { |
| | 12 | 354 | | if ((uint)key >= (uint)_sparse.Length) return false; |
| | 10 | 355 | | return _sparse[key] != NotPresent; |
| | | 356 | | } |
| | | 357 | | |
| | | 358 | | /// <summary> |
| | | 359 | | /// Adds a key/value only if the key is not present. |
| | | 360 | | /// Returns false if already present. |
| | | 361 | | /// </summary> |
| | | 362 | | public bool TryAdd(int key, T value) |
| | | 363 | | { |
| | 2 | 364 | | EnsureSparseCapacity(GetRequiredSparseCapacity(key)); |
| | 2 | 365 | | if (_sparse[key] != NotPresent) |
| | 1 | 366 | | return false; |
| | | 367 | | |
| | 1 | 368 | | EnsureDenseCapacity(_count + 1); |
| | | 369 | | |
| | 1 | 370 | | int newIndex = _count++; |
| | 1 | 371 | | _denseKeys[newIndex] = key; |
| | 1 | 372 | | _denseValues[newIndex] = value; |
| | 1 | 373 | | _sparse[key] = newIndex + 1; |
| | | 374 | | |
| | 1 | 375 | | _version++; |
| | 1 | 376 | | return true; |
| | | 377 | | } |
| | | 378 | | |
| | | 379 | | /// <summary> |
| | | 380 | | /// Adds or overwrites (same behavior as indexer set). |
| | | 381 | | /// </summary> |
| | 57 | 382 | | public void Add(int key, T value) => this[key] = value; |
| | | 383 | | |
| | | 384 | | /// <summary> |
| | | 385 | | /// Attempts to retrieve the value associated with the specified key. |
| | | 386 | | /// </summary> |
| | | 387 | | /// <param name="key">The key whose associated value is to be retrieved.</param> |
| | | 388 | | /// <param name="value"> |
| | | 389 | | /// When this method returns, contains the value associated with the specified key, if the key is found; |
| | | 390 | | /// otherwise, the default value for the type parameter <typeparamref name="T"/>. |
| | | 391 | | /// This parameter is passed uninitialized. |
| | | 392 | | /// </param> |
| | | 393 | | /// <returns>true if the key was found and its value was retrieved; otherwise, false.</returns> |
| | | 394 | | public bool TryGetValue(int key, out T value) |
| | | 395 | | { |
| | 3 | 396 | | if ((uint)key < (uint)_sparse.Length) |
| | | 397 | | { |
| | 2 | 398 | | int slot = _sparse[key]; |
| | 2 | 399 | | if (slot != NotPresent) |
| | | 400 | | { |
| | 1 | 401 | | value = _denseValues[slot - 1]; |
| | 1 | 402 | | return true; |
| | | 403 | | } |
| | | 404 | | } |
| | | 405 | | |
| | 2 | 406 | | value = default!; |
| | 2 | 407 | | return false; |
| | | 408 | | } |
| | | 409 | | |
| | | 410 | | /// <summary> |
| | | 411 | | /// Removes the element with the specified key from the collection, if it exists. |
| | | 412 | | /// </summary> |
| | | 413 | | /// <param name="key">The key of the element to remove. Must be a non-negative integer within the valid range of key |
| | | 414 | | /// <returns>true if the element is successfully found and removed; otherwise, false.</returns> |
| | | 415 | | public bool Remove(int key) |
| | | 416 | | { |
| | 8 | 417 | | if ((uint)key >= (uint)_sparse.Length) return false; |
| | | 418 | | |
| | 6 | 419 | | int slot = _sparse[key]; |
| | 7 | 420 | | if (slot == NotPresent) return false; |
| | | 421 | | |
| | 5 | 422 | | int index = slot - 1; |
| | 5 | 423 | | int last = --_count; |
| | | 424 | | |
| | 5 | 425 | | _sparse[key] = NotPresent; |
| | | 426 | | |
| | 5 | 427 | | if (index != last) |
| | | 428 | | { |
| | 3 | 429 | | int movedKey = _denseKeys[last]; |
| | | 430 | | |
| | 3 | 431 | | _denseKeys[index] = movedKey; |
| | 3 | 432 | | _denseValues[index] = _denseValues[last]; |
| | | 433 | | |
| | 3 | 434 | | _sparse[movedKey] = index + 1; |
| | | 435 | | } |
| | | 436 | | |
| | 5 | 437 | | _denseKeys[last] = default; |
| | 5 | 438 | | _denseValues[last] = default!; |
| | | 439 | | |
| | 5 | 440 | | _version++; |
| | 5 | 441 | | return true; |
| | | 442 | | } |
| | | 443 | | |
| | | 444 | | /// <summary> |
| | | 445 | | /// Removes all keys and values from the collection. |
| | | 446 | | /// </summary> |
| | | 447 | | /// <remarks> |
| | | 448 | | /// After calling this method, the collection will be empty and its Count property will be zero. |
| | | 449 | | /// This method does not reduce the capacity of the underlying storage. |
| | | 450 | | /// </remarks> |
| | | 451 | | public void Clear() |
| | | 452 | | { |
| | 7 | 453 | | if (_count == 0) return; |
| | | 454 | | |
| | | 455 | | // reset sparse for keys that were present |
| | 14 | 456 | | for (int i = 0; i < _count; i++) |
| | | 457 | | { |
| | 4 | 458 | | int key = _denseKeys[i]; |
| | 4 | 459 | | if ((uint)key < (uint)_sparse.Length) |
| | 4 | 460 | | _sparse[key] = NotPresent; |
| | | 461 | | } |
| | | 462 | | |
| | 3 | 463 | | Array.Clear(_denseKeys, 0, _count); |
| | 3 | 464 | | Array.Clear(_denseValues, 0, _count); |
| | | 465 | | |
| | 3 | 466 | | _count = 0; |
| | 3 | 467 | | _version++; |
| | 3 | 468 | | } |
| | | 469 | | |
| | | 470 | | #endregion |
| | | 471 | | |
| | | 472 | | #region Capacity Management |
| | | 473 | | |
| | | 474 | | /// <summary> |
| | | 475 | | /// Ensures that the internal dense storage has at least the specified capacity, expanding it if necessary. |
| | | 476 | | /// </summary> |
| | | 477 | | /// <remarks> |
| | | 478 | | /// If the current capacity is less than the specified value, the internal storage is resized to accommodate at leas |
| | | 479 | | /// Existing elements are preserved. |
| | | 480 | | /// The capacity is increased to the next power of two greater than or equal to the requested capacity for performan |
| | | 481 | | /// </remarks> |
| | | 482 | | /// <param name="capacity">The minimum number of elements that the dense storage must be able to hold. Must be non-n |
| | | 483 | | public void EnsureDenseCapacity(int capacity) |
| | | 484 | | { |
| | 115 | 485 | | if (capacity <= _denseKeys.Length) return; |
| | | 486 | | |
| | 3 | 487 | | int newCap = _denseKeys.Length == 0 ? DefaultDenseCapacity : _denseKeys.Length * 2; |
| | 5 | 488 | | if (newCap < capacity) newCap = capacity; |
| | | 489 | | |
| | 3 | 490 | | newCap = SwiftHashTools.NextPowerOfTwo(newCap); |
| | | 491 | | |
| | 3 | 492 | | var newKeys = new int[newCap]; |
| | 3 | 493 | | var newVals = new T[newCap]; |
| | | 494 | | |
| | 3 | 495 | | if (_count > 0) |
| | | 496 | | { |
| | 1 | 497 | | Array.Copy(_denseKeys, newKeys, _count); |
| | 1 | 498 | | Array.Copy(_denseValues, newVals, _count); |
| | | 499 | | } |
| | | 500 | | |
| | 3 | 501 | | _denseKeys = newKeys; |
| | 3 | 502 | | _denseValues = newVals; |
| | | 503 | | |
| | 3 | 504 | | _version++; |
| | 3 | 505 | | } |
| | | 506 | | |
| | | 507 | | /// <summary> |
| | | 508 | | /// Ensures that the internal sparse array has a capacity at least as large as the specified value. |
| | | 509 | | /// </summary> |
| | | 510 | | /// <remarks> |
| | | 511 | | /// If the current capacity is less than the specified value, the internal storage is resized to accommodate at leas |
| | | 512 | | /// Existing elements are preserved. |
| | | 513 | | /// The capacity is increased to the next power of two greater than or equal to the requested capacity for performan |
| | | 514 | | /// </remarks> |
| | | 515 | | /// <param name="capacity">The minimum required capacity for the internal sparse array. Must be non-negative.</param |
| | | 516 | | public void EnsureSparseCapacity(int capacity) |
| | | 517 | | { |
| | 111 | 518 | | if (capacity <= _sparse.Length) return; |
| | | 519 | | |
| | 9 | 520 | | int newCap = _sparse.Length == 0 |
| | 9 | 521 | | ? DefaultSparseCapacity |
| | 9 | 522 | | : _sparse.Length * 2; |
| | 12 | 523 | | if (newCap < capacity) newCap = capacity; |
| | | 524 | | |
| | 9 | 525 | | newCap = SwiftHashTools.NextPowerOfTwo(newCap); |
| | | 526 | | |
| | 9 | 527 | | var newSparse = new int[newCap]; |
| | 9 | 528 | | if (_sparse.Length > 0) |
| | 8 | 529 | | Array.Copy(_sparse, newSparse, _sparse.Length); |
| | | 530 | | |
| | 9 | 531 | | _sparse = newSparse; |
| | 9 | 532 | | _version++; |
| | 9 | 533 | | } |
| | | 534 | | |
| | | 535 | | /// <summary> |
| | | 536 | | /// Reduces the memory usage of the collection by resizing internal storage to fit the current number of elements as |
| | | 537 | | /// </summary> |
| | | 538 | | /// <remarks> |
| | | 539 | | /// Call this method to minimize the collection's memory footprint after removing a significant number of elements. |
| | | 540 | | /// This operation may improve memory efficiency but can be an expensive operation if the collection is large. |
| | | 541 | | /// The method does not affect the logical contents of the collection. |
| | | 542 | | /// </remarks> |
| | | 543 | | public void TrimExcess() |
| | | 544 | | { |
| | | 545 | | // Dense: shrink to Count (with a minimum) |
| | 2 | 546 | | int newDense = Math.Max(DefaultDenseCapacity, _count); |
| | 2 | 547 | | if (newDense < _denseKeys.Length) |
| | | 548 | | { |
| | 2 | 549 | | var newKeys = new int[newDense]; |
| | 2 | 550 | | var newVals = new T[newDense]; |
| | 2 | 551 | | if (_count > 0) |
| | | 552 | | { |
| | 1 | 553 | | Array.Copy(_denseKeys, newKeys, _count); |
| | 1 | 554 | | Array.Copy(_denseValues, newVals, _count); |
| | | 555 | | } |
| | 2 | 556 | | _denseKeys = newKeys; |
| | 2 | 557 | | _denseValues = newVals; |
| | | 558 | | } |
| | | 559 | | |
| | | 560 | | // Sparse: shrink to (maxKey+1) based on dense keys |
| | 2 | 561 | | int maxKey = -1; |
| | 6 | 562 | | for (int i = 0; i < _count; i++) |
| | 2 | 563 | | if (_denseKeys[i] > maxKey) maxKey = _denseKeys[i]; |
| | | 564 | | |
| | 2 | 565 | | int newSparse = maxKey < 0 |
| | 2 | 566 | | ? DefaultSparseCapacity |
| | 2 | 567 | | : Math.Max(DefaultSparseCapacity, GetRequiredSparseCapacity(maxKey)); |
| | 2 | 568 | | if (newSparse < _sparse.Length) |
| | | 569 | | { |
| | 2 | 570 | | var newMap = new int[newSparse]; |
| | | 571 | | // rebuild from dense |
| | 6 | 572 | | for (int i = 0; i < _count; i++) |
| | 1 | 573 | | newMap[_denseKeys[i]] = i + 1; |
| | 2 | 574 | | _sparse = newMap; |
| | | 575 | | } |
| | | 576 | | |
| | 2 | 577 | | _version++; |
| | 2 | 578 | | } |
| | | 579 | | |
| | | 580 | | #endregion |
| | | 581 | | |
| | | 582 | | #region Enumeration |
| | | 583 | | |
| | | 584 | | /// <inheritdoc cref="IEnumerable.GetEnumerator()"/> |
| | 10 | 585 | | public SwiftSparseMapEnumerator GetEnumerator() => new(this); |
| | 7 | 586 | | IEnumerator<KeyValuePair<int, T>> IEnumerable<KeyValuePair<int, T>>.GetEnumerator() => GetEnumerator(); |
| | 1 | 587 | | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); |
| | | 588 | | |
| | | 589 | | /// <summary> |
| | | 590 | | /// Supports iteration over the key/value pairs in a <see cref="SwiftSparseMap{T}"/> collection. |
| | | 591 | | /// </summary> |
| | | 592 | | /// <remarks> |
| | | 593 | | /// The enumerator provides a forward-only, read-only traversal of the collection. |
| | | 594 | | /// It is invalidated if the underlying collection is modified during enumeration, and any such modification will ca |
| | | 595 | | /// subsequent operations to throw an InvalidOperationException. |
| | | 596 | | /// </remarks> |
| | | 597 | | public struct SwiftSparseMapEnumerator : IEnumerator<KeyValuePair<int, T>> |
| | | 598 | | { |
| | | 599 | | private readonly SwiftSparseMap<T> _map; |
| | | 600 | | private readonly int[] _keys; |
| | | 601 | | private readonly T[] _values; |
| | | 602 | | private readonly int _count; |
| | | 603 | | private readonly uint _version; |
| | | 604 | | private int _index; |
| | | 605 | | |
| | | 606 | | internal SwiftSparseMapEnumerator(SwiftSparseMap<T> map) |
| | | 607 | | { |
| | 10 | 608 | | _map = map; |
| | 10 | 609 | | _keys = map._denseKeys; |
| | 10 | 610 | | _values = map._denseValues; |
| | 10 | 611 | | _count = map._count; |
| | 10 | 612 | | _version = map._version; |
| | 10 | 613 | | _index = -1; |
| | 10 | 614 | | Current = default; |
| | 10 | 615 | | } |
| | | 616 | | |
| | | 617 | | /// <inheritdoc/> |
| | | 618 | | public KeyValuePair<int, T> Current { get; private set; } |
| | 1 | 619 | | object IEnumerator.Current => Current; |
| | | 620 | | |
| | | 621 | | /// <inheritdoc/> |
| | | 622 | | public bool MoveNext() |
| | | 623 | | { |
| | 14 | 624 | | SwiftThrowHelper.ThrowIfTrue(_version != _map._version, message: "Collection was modified during enumeration |
| | | 625 | | |
| | 13 | 626 | | int next = _index + 1; |
| | 13 | 627 | | if (next >= _count) |
| | | 628 | | { |
| | 7 | 629 | | Current = default; |
| | 7 | 630 | | return false; |
| | | 631 | | } |
| | | 632 | | |
| | 6 | 633 | | _index = next; |
| | 6 | 634 | | Current = new KeyValuePair<int, T>(_keys[_index], _values[_index]); |
| | 6 | 635 | | return true; |
| | | 636 | | } |
| | | 637 | | |
| | | 638 | | /// <inheritdoc/> |
| | | 639 | | public void Reset() |
| | | 640 | | { |
| | 1 | 641 | | SwiftThrowHelper.ThrowIfTrue(_version != _map._version, message: "Collection was modified during enumeration |
| | | 642 | | |
| | 1 | 643 | | _index = -1; |
| | 1 | 644 | | Current = default; |
| | 1 | 645 | | } |
| | | 646 | | |
| | | 647 | | /// <inheritdoc/> |
| | 7 | 648 | | public void Dispose() => _index = -1; |
| | | 649 | | } |
| | | 650 | | |
| | | 651 | | #endregion |
| | | 652 | | |
| | | 653 | | #region Helpers |
| | | 654 | | |
| | | 655 | | /// <summary> |
| | | 656 | | /// Retrieves the dense representation of the collection as parallel arrays of keys and values, along with the numbe |
| | | 657 | | /// </summary> |
| | | 658 | | /// <remarks> |
| | | 659 | | /// The arrays returned may be larger than the actual number of elements. |
| | | 660 | | /// Only the first <paramref name="count"/> entries in each array are valid and should be used. |
| | | 661 | | /// </remarks> |
| | | 662 | | /// <param name="keys"> |
| | | 663 | | /// When this method returns, contains an array of keys representing the dense mapping. |
| | | 664 | | /// The array length is at least as large as the number of elements returned in <paramref name="count"/>. |
| | | 665 | | /// </param> |
| | | 666 | | /// <param name="values"> |
| | | 667 | | /// When this method returns, contains an array of values corresponding to the keys in <paramref name="keys"/>. |
| | | 668 | | /// The array length is at least as large as the number of elements returned in <paramref name="count"/>. |
| | | 669 | | /// </param> |
| | | 670 | | /// <param name="count">When this method returns, contains the number of valid key-value pairs in the dense arrays.< |
| | | 671 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 672 | | public void GetDense(out int[] keys, out T[] values, out int count) |
| | | 673 | | { |
| | 1 | 674 | | keys = _denseKeys; |
| | 1 | 675 | | values = _denseValues; |
| | 1 | 676 | | count = _count; |
| | 1 | 677 | | } |
| | | 678 | | |
| | | 679 | | /// <summary> |
| | | 680 | | /// Replaces the destination list contents with this map's keys in dense iteration order. |
| | | 681 | | /// </summary> |
| | | 682 | | /// <remarks> |
| | | 683 | | /// The destination list is reused and only grows when its current capacity is smaller than |
| | | 684 | | /// <see cref="Count"/>. Use <see cref="CopySortedKeysTo(SwiftList{int})"/> when stable ascending |
| | | 685 | | /// key order is required. |
| | | 686 | | /// </remarks> |
| | | 687 | | /// <param name="destination">The caller-owned list that receives the keys.</param> |
| | | 688 | | public void CopyKeysTo(SwiftList<int> destination) |
| | | 689 | | { |
| | 6 | 690 | | SwiftThrowHelper.ThrowIfNull(destination, nameof(destination)); |
| | | 691 | | |
| | 6 | 692 | | destination.FastClear(); |
| | 6 | 693 | | destination.AddRange(_denseKeys.AsSpan(0, _count)); |
| | 6 | 694 | | } |
| | | 695 | | |
| | | 696 | | /// <summary> |
| | | 697 | | /// Replaces the destination list contents with this map's keys sorted in ascending order. |
| | | 698 | | /// </summary> |
| | | 699 | | /// <remarks> |
| | | 700 | | /// This method is intended for reusable hot-path scratch buffers that need deterministic key order |
| | | 701 | | /// without constructing a persistent sorted collection. |
| | | 702 | | /// </remarks> |
| | | 703 | | /// <param name="destination">The caller-owned list that receives the sorted keys.</param> |
| | | 704 | | public void CopySortedKeysTo(SwiftList<int> destination) |
| | | 705 | | { |
| | 4 | 706 | | CopyKeysTo(destination); |
| | 4 | 707 | | destination.SortInPlace(default(SwiftIntAscendingComparer)); |
| | 4 | 708 | | } |
| | | 709 | | |
| | | 710 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 711 | | private static int GetRequiredSparseCapacity(int key) |
| | | 712 | | { |
| | 66 | 713 | | SwiftThrowHelper.ThrowIfNegative(key, nameof(key)); |
| | 65 | 714 | | SwiftThrowHelper.ThrowIfArgumentOutOfRange(key == int.MaxValue, key, nameof(key), "Key is too large for direct s |
| | | 715 | | |
| | 64 | 716 | | return key + 1; |
| | | 717 | | } |
| | | 718 | | |
| | | 719 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 720 | | private int GetDenseIndexOrThrow(int key) |
| | | 721 | | { |
| | 22 | 722 | | SwiftThrowHelper.ThrowIfKeyNotFound((uint)key >= (uint)_sparse.Length, key); |
| | | 723 | | |
| | 20 | 724 | | int slot = _sparse[key]; |
| | | 725 | | |
| | 20 | 726 | | SwiftThrowHelper.ThrowIfKeyNotFound(slot == NotPresent, key); |
| | | 727 | | |
| | 19 | 728 | | return slot - 1; |
| | | 729 | | } |
| | | 730 | | |
| | | 731 | | /// <inheritdoc/> |
| | | 732 | | public void CloneTo(ICollection<T> output) |
| | | 733 | | { |
| | 1 | 734 | | SwiftThrowHelper.ThrowIfNull(output, nameof(output)); |
| | | 735 | | |
| | 1 | 736 | | output.Clear(); |
| | | 737 | | |
| | 6 | 738 | | for (int i = 0; i < _count; i++) |
| | 2 | 739 | | output.Add(_denseValues[i]); |
| | 1 | 740 | | } |
| | | 741 | | |
| | | 742 | | #endregion |
| | | 743 | | } |