| | | 1 | | //======================================================================= |
| | | 2 | | // SwiftSparseSet.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 set for externally supplied non-negative integer IDs. |
| | | 22 | | /// Provides O(1) Add, Remove, Contains, and densely packed iteration. |
| | | 23 | | /// </summary> |
| | | 24 | | /// <remarks> |
| | | 25 | | /// <para> |
| | | 26 | | /// <see cref="SwiftSparseSet"/> is intended for membership workloads where the caller already owns |
| | | 27 | | /// compact integer IDs, such as entity handles, body IDs, or slot indices. |
| | | 28 | | /// </para> |
| | | 29 | | /// <para> |
| | | 30 | | /// Internally, IDs are stored in a dense array for cache-friendly iteration while a sparse lookup |
| | | 31 | | /// table maps each ID directly to its dense position. Removal uses swap-back, so iteration order is |
| | | 32 | | /// not stable. |
| | | 33 | | /// </para> |
| | | 34 | | /// <para> |
| | | 35 | | /// Memory usage scales with the highest stored ID rather than only the number of IDs. For arbitrary, |
| | | 36 | | /// huge, or widely spaced keys, prefer <see cref="SwiftHashSet{T}"/> with <c>int</c> keys. |
| | | 37 | | /// </para> |
| | | 38 | | /// </remarks> |
| | | 39 | | [Serializable] |
| | | 40 | | [JsonConverter(typeof(StateJsonConverterFactory))] |
| | | 41 | | [MemoryPackable] |
| | | 42 | | public sealed partial class SwiftSparseSet : IStateBacked<SwiftArrayState<int>>, ISwiftCloneable<int>, ISet<int>, IReadO |
| | | 43 | | { |
| | | 44 | | #region Constants |
| | | 45 | | |
| | | 46 | | /// <summary> |
| | | 47 | | /// Represents the default initial capacity for dense ID storage. |
| | | 48 | | /// </summary> |
| | | 49 | | public const int DefaultDenseCapacity = 8; |
| | | 50 | | |
| | | 51 | | /// <summary> |
| | | 52 | | /// Represents the default initial capacity for sparse ID lookup. |
| | | 53 | | /// </summary> |
| | | 54 | | public const int DefaultSparseCapacity = 8; |
| | | 55 | | |
| | | 56 | | private const int NotPresent = 0; |
| | | 57 | | |
| | | 58 | | #endregion |
| | | 59 | | |
| | | 60 | | #region Fields |
| | | 61 | | |
| | | 62 | | private int[] _sparse; // id -> denseIndex+1 |
| | | 63 | | private int[] _denseKeys; // denseIndex -> id |
| | | 64 | | private int _count; |
| | | 65 | | |
| | | 66 | | [NonSerialized] |
| | | 67 | | private uint _version; |
| | | 68 | | |
| | | 69 | | [NonSerialized] |
| | | 70 | | private object? _syncRoot; |
| | | 71 | | |
| | | 72 | | #endregion |
| | | 73 | | |
| | | 74 | | #region Constructors |
| | | 75 | | |
| | | 76 | | /// <summary> |
| | | 77 | | /// Initializes a new instance of the <see cref="SwiftSparseSet"/> class with default sparse and dense capacities. |
| | | 78 | | /// </summary> |
| | 80 | 79 | | public SwiftSparseSet() : this(DefaultSparseCapacity, DefaultDenseCapacity) { } |
| | | 80 | | |
| | | 81 | | /// <summary> |
| | | 82 | | /// Initializes a new instance of the <see cref="SwiftSparseSet"/> class with matching sparse and dense capacities. |
| | | 83 | | /// </summary> |
| | | 84 | | /// <param name="capacity">The initial sparse and dense capacity.</param> |
| | 2 | 85 | | public SwiftSparseSet(int capacity) : this(capacity, capacity) { } |
| | | 86 | | |
| | | 87 | | /// <summary> |
| | | 88 | | /// Initializes a new instance of the <see cref="SwiftSparseSet"/> class with explicit sparse and dense capacities. |
| | | 89 | | /// </summary> |
| | | 90 | | /// <param name="sparseCapacity"> |
| | | 91 | | /// Initial sparse lookup capacity. This should track the highest expected ID plus one, |
| | | 92 | | /// not just the number of stored IDs. |
| | | 93 | | /// </param> |
| | | 94 | | /// <param name="denseCapacity">Initial dense storage capacity for IDs.</param> |
| | 44 | 95 | | public SwiftSparseSet(int sparseCapacity, int denseCapacity) |
| | | 96 | | { |
| | 44 | 97 | | SwiftThrowHelper.ThrowIfNegative(sparseCapacity, nameof(sparseCapacity)); |
| | 44 | 98 | | SwiftThrowHelper.ThrowIfNegative(denseCapacity, nameof(denseCapacity)); |
| | | 99 | | |
| | 44 | 100 | | int sparseSize = sparseCapacity == 0 ? 0 : SwiftHashTools.NextPowerOfTwo(sparseCapacity); |
| | 44 | 101 | | _sparse = sparseCapacity == 0 |
| | 44 | 102 | | ? Array.Empty<int>() |
| | 44 | 103 | | : new int[sparseSize]; |
| | | 104 | | |
| | 44 | 105 | | int denseSize = denseCapacity < DefaultDenseCapacity |
| | 44 | 106 | | ? DefaultDenseCapacity |
| | 44 | 107 | | : SwiftHashTools.NextPowerOfTwo(denseCapacity); |
| | 44 | 108 | | _denseKeys = denseCapacity == 0 |
| | 44 | 109 | | ? Array.Empty<int>() |
| | 44 | 110 | | : new int[denseSize]; |
| | 44 | 111 | | } |
| | | 112 | | |
| | | 113 | | /// <summary> |
| | | 114 | | /// Initializes a new instance of the <see cref="SwiftSparseSet"/> class using the specified state. |
| | | 115 | | /// </summary> |
| | | 116 | | /// <param name="state">The state object that provides the initial IDs. Cannot be null.</param> |
| | | 117 | | [MemoryPackConstructor] |
| | 5 | 118 | | public SwiftSparseSet(SwiftArrayState<int> state) |
| | | 119 | | { |
| | 5 | 120 | | _sparse = Array.Empty<int>(); |
| | 5 | 121 | | _denseKeys = Array.Empty<int>(); |
| | | 122 | | |
| | 5 | 123 | | State = state; |
| | 3 | 124 | | } |
| | | 125 | | |
| | | 126 | | #endregion |
| | | 127 | | |
| | | 128 | | #region Properties |
| | | 129 | | |
| | | 130 | | /// <summary> |
| | | 131 | | /// Gets the number of IDs contained in the set. |
| | | 132 | | /// </summary> |
| | | 133 | | [JsonIgnore] |
| | | 134 | | [MemoryPackIgnore] |
| | 4 | 135 | | public int Count => _count; |
| | | 136 | | |
| | | 137 | | /// <summary> |
| | | 138 | | /// Capacity of the dense ID storage. |
| | | 139 | | /// </summary> |
| | | 140 | | [JsonIgnore] |
| | | 141 | | [MemoryPackIgnore] |
| | 7 | 142 | | public int DenseCapacity => _denseKeys.Length; |
| | | 143 | | |
| | | 144 | | /// <summary> |
| | | 145 | | /// Capacity of the sparse lookup table. |
| | | 146 | | /// </summary> |
| | | 147 | | [JsonIgnore] |
| | | 148 | | [MemoryPackIgnore] |
| | 7 | 149 | | public int SparseCapacity => _sparse.Length; |
| | | 150 | | |
| | | 151 | | /// <inheritdoc/> |
| | | 152 | | [JsonIgnore] |
| | | 153 | | [MemoryPackIgnore] |
| | 1 | 154 | | public bool IsReadOnly => false; |
| | | 155 | | |
| | | 156 | | /// <summary> |
| | | 157 | | /// Gets a value indicating whether access to the collection is synchronized. |
| | | 158 | | /// </summary> |
| | | 159 | | [JsonIgnore] |
| | | 160 | | [MemoryPackIgnore] |
| | 1 | 161 | | public bool IsSynchronized => false; |
| | | 162 | | |
| | | 163 | | /// <summary> |
| | | 164 | | /// Gets an object that can be used to synchronize access to the collection. |
| | | 165 | | /// </summary> |
| | | 166 | | [JsonIgnore] |
| | | 167 | | [MemoryPackIgnore] |
| | 1 | 168 | | public object SyncRoot => _syncRoot ??= new object(); |
| | | 169 | | |
| | | 170 | | /// <summary> |
| | | 171 | | /// Returns the dense ID array. Only the range [0..Count) is populated. |
| | | 172 | | /// </summary> |
| | | 173 | | [JsonIgnore] |
| | | 174 | | [MemoryPackIgnore] |
| | 4 | 175 | | public int[] DenseKeys => _denseKeys; |
| | | 176 | | |
| | | 177 | | /// <summary> |
| | | 178 | | /// Gets a span containing the current IDs in dense iteration order. |
| | | 179 | | /// </summary> |
| | | 180 | | [JsonIgnore] |
| | | 181 | | [MemoryPackIgnore] |
| | 3 | 182 | | public Span<int> Keys => _denseKeys.AsSpan(0, _count); |
| | | 183 | | |
| | | 184 | | /// <summary> |
| | | 185 | | /// Gets or sets the current state of the sparse set. |
| | | 186 | | /// </summary> |
| | | 187 | | [JsonInclude] |
| | | 188 | | [MemoryPackInclude] |
| | | 189 | | public SwiftArrayState<int> State |
| | | 190 | | { |
| | | 191 | | get |
| | | 192 | | { |
| | 2 | 193 | | var items = new int[_count]; |
| | 2 | 194 | | Array.Copy(_denseKeys, items, _count); |
| | 2 | 195 | | return new SwiftArrayState<int>(items); |
| | | 196 | | } |
| | | 197 | | internal set |
| | | 198 | | { |
| | 5 | 199 | | SwiftThrowHelper.ThrowIfNull(value.Items, nameof(value.Items)); |
| | | 200 | | |
| | 5 | 201 | | RestoreDenseKeys(value.Items); |
| | 5 | 202 | | int maxKey = ValidateDenseKeys(nameof(value.Items)); |
| | 4 | 203 | | RestoreSparseLookup(maxKey, nameof(value)); |
| | | 204 | | |
| | 3 | 205 | | _version++; |
| | 3 | 206 | | } |
| | | 207 | | } |
| | | 208 | | |
| | | 209 | | private void RestoreDenseKeys(int[] items) |
| | | 210 | | { |
| | 5 | 211 | | int count = items.Length; |
| | 5 | 212 | | _denseKeys = count == 0 |
| | 5 | 213 | | ? Array.Empty<int>() |
| | 5 | 214 | | : new int[Math.Max(DefaultDenseCapacity, SwiftHashTools.NextPowerOfTwo(count))]; |
| | | 215 | | |
| | 5 | 216 | | if (count > 0) |
| | 4 | 217 | | Array.Copy(items, _denseKeys, count); |
| | | 218 | | |
| | 5 | 219 | | _count = count; |
| | 5 | 220 | | } |
| | | 221 | | |
| | | 222 | | private int ValidateDenseKeys(string paramName) |
| | | 223 | | { |
| | 5 | 224 | | int maxKey = -1; |
| | 20 | 225 | | for (int i = 0; i < _count; i++) |
| | | 226 | | { |
| | 6 | 227 | | int key = _denseKeys[i]; |
| | 6 | 228 | | SwiftThrowHelper.ThrowIfNegative(key, paramName); |
| | 5 | 229 | | SwiftThrowHelper.ThrowIfArgumentOutOfRange(key == int.MaxValue, key, paramName, "ID is too large for direct |
| | | 230 | | |
| | 5 | 231 | | if (key > maxKey) |
| | 4 | 232 | | maxKey = key; |
| | | 233 | | } |
| | | 234 | | |
| | 4 | 235 | | return maxKey; |
| | | 236 | | } |
| | | 237 | | |
| | | 238 | | private void RestoreSparseLookup(int maxKey, string paramName) |
| | | 239 | | { |
| | 4 | 240 | | int sparseSize = maxKey < 0 |
| | 4 | 241 | | ? DefaultSparseCapacity |
| | 4 | 242 | | : Math.Max(DefaultSparseCapacity, GetRequiredSparseCapacity(maxKey)); |
| | 4 | 243 | | _sparse = new int[sparseSize]; |
| | | 244 | | |
| | 16 | 245 | | for (int i = 0; i < _count; i++) |
| | | 246 | | { |
| | 5 | 247 | | int key = _denseKeys[i]; |
| | 5 | 248 | | SwiftThrowHelper.ThrowIfArgument(_sparse[key] != NotPresent, paramName, "Duplicate ID in sparse set state.") |
| | 4 | 249 | | _sparse[key] = i + 1; |
| | | 250 | | } |
| | 3 | 251 | | } |
| | | 252 | | |
| | | 253 | | #endregion |
| | | 254 | | |
| | | 255 | | #region Core Operations |
| | | 256 | | |
| | | 257 | | /// <summary> |
| | | 258 | | /// Determines whether the set contains the specified ID. |
| | | 259 | | /// </summary> |
| | | 260 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 261 | | public bool Contains(int item) |
| | | 262 | | { |
| | 50 | 263 | | if ((uint)item >= (uint)_sparse.Length) return false; |
| | 40 | 264 | | return _sparse[item] != NotPresent; |
| | | 265 | | } |
| | | 266 | | |
| | | 267 | | /// <summary> |
| | | 268 | | /// Determines whether the set contains the specified key. Alias for <see cref="Contains(int)"/>. |
| | | 269 | | /// </summary> |
| | | 270 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 5 | 271 | | public bool ContainsKey(int key) => Contains(key); |
| | | 272 | | |
| | | 273 | | /// <summary> |
| | | 274 | | /// Adds the specified ID if it is not already present. |
| | | 275 | | /// </summary> |
| | | 276 | | /// <returns>true if the ID was added; false if it was already present.</returns> |
| | | 277 | | public bool Add(int item) |
| | | 278 | | { |
| | 90 | 279 | | EnsureSparseCapacity(GetRequiredSparseCapacity(item)); |
| | 88 | 280 | | if (_sparse[item] != NotPresent) |
| | 1 | 281 | | return false; |
| | | 282 | | |
| | 87 | 283 | | EnsureDenseCapacity(_count + 1); |
| | | 284 | | |
| | 87 | 285 | | int newIndex = _count++; |
| | 87 | 286 | | _denseKeys[newIndex] = item; |
| | 87 | 287 | | _sparse[item] = newIndex + 1; |
| | | 288 | | |
| | 87 | 289 | | _version++; |
| | 87 | 290 | | return true; |
| | | 291 | | } |
| | | 292 | | |
| | | 293 | | /// <summary> |
| | | 294 | | /// Adds the specified ID if it is not already present. |
| | | 295 | | /// </summary> |
| | 1 | 296 | | public bool TryAdd(int item) => Add(item); |
| | | 297 | | |
| | 1 | 298 | | void ICollection<int>.Add(int item) => Add(item); |
| | | 299 | | |
| | | 300 | | /// <summary> |
| | | 301 | | /// Removes the specified ID from the set. |
| | | 302 | | /// </summary> |
| | | 303 | | /// <returns>true if the ID was found and removed; otherwise, false.</returns> |
| | | 304 | | public bool Remove(int item) |
| | | 305 | | { |
| | 24 | 306 | | if ((uint)item >= (uint)_sparse.Length) return false; |
| | | 307 | | |
| | 18 | 308 | | int slot = _sparse[item]; |
| | 22 | 309 | | if (slot == NotPresent) return false; |
| | | 310 | | |
| | 14 | 311 | | int index = slot - 1; |
| | 14 | 312 | | int last = --_count; |
| | | 313 | | |
| | 14 | 314 | | _sparse[item] = NotPresent; |
| | | 315 | | |
| | 14 | 316 | | if (index != last) |
| | | 317 | | { |
| | 12 | 318 | | int movedKey = _denseKeys[last]; |
| | 12 | 319 | | _denseKeys[index] = movedKey; |
| | 12 | 320 | | _sparse[movedKey] = index + 1; |
| | | 321 | | } |
| | | 322 | | |
| | 14 | 323 | | _denseKeys[last] = default; |
| | 14 | 324 | | _version++; |
| | 14 | 325 | | return true; |
| | | 326 | | } |
| | | 327 | | |
| | | 328 | | /// <summary> |
| | | 329 | | /// Removes all IDs from the set without reducing capacity. |
| | | 330 | | /// </summary> |
| | | 331 | | public void Clear() |
| | | 332 | | { |
| | 5 | 333 | | if (_count == 0) return; |
| | | 334 | | |
| | 18 | 335 | | for (int i = 0; i < _count; i++) |
| | | 336 | | { |
| | 6 | 337 | | int key = _denseKeys[i]; |
| | 6 | 338 | | _sparse[key] = NotPresent; |
| | 6 | 339 | | _denseKeys[i] = default; |
| | | 340 | | } |
| | | 341 | | |
| | 3 | 342 | | _count = 0; |
| | 3 | 343 | | _version++; |
| | 3 | 344 | | } |
| | | 345 | | |
| | | 346 | | #endregion |
| | | 347 | | |
| | | 348 | | #region Set Operations |
| | | 349 | | |
| | | 350 | | /// <inheritdoc/> |
| | | 351 | | public void ExceptWith(IEnumerable<int> other) |
| | | 352 | | { |
| | 3 | 353 | | SwiftThrowHelper.ThrowIfNull(other, nameof(other)); |
| | | 354 | | |
| | 4 | 355 | | if (_count == 0) return; |
| | 2 | 356 | | if (ReferenceEquals(other, this)) |
| | | 357 | | { |
| | 1 | 358 | | Clear(); |
| | 1 | 359 | | return; |
| | | 360 | | } |
| | | 361 | | |
| | 6 | 362 | | foreach (int item in other) |
| | 2 | 363 | | Remove(item); |
| | 1 | 364 | | } |
| | | 365 | | |
| | | 366 | | /// <inheritdoc/> |
| | | 367 | | public void IntersectWith(IEnumerable<int> other) |
| | | 368 | | { |
| | 5 | 369 | | SwiftThrowHelper.ThrowIfNull(other, nameof(other)); |
| | | 370 | | |
| | 7 | 371 | | if (_count == 0 || ReferenceEquals(other, this)) return; |
| | | 372 | | |
| | 3 | 373 | | if (other is SwiftSparseSet sparseSet) |
| | | 374 | | { |
| | 1 | 375 | | RemoveWhereMissingFrom(sparseSet); |
| | 1 | 376 | | return; |
| | | 377 | | } |
| | | 378 | | |
| | 2 | 379 | | if (other is ISet<int> set) |
| | | 380 | | { |
| | 1 | 381 | | RemoveWhereMissingFrom(set); |
| | 1 | 382 | | return; |
| | | 383 | | } |
| | | 384 | | |
| | 1 | 385 | | RemoveWhereMissingFrom(new HashSet<int>(other)); |
| | 1 | 386 | | } |
| | | 387 | | |
| | | 388 | | /// <inheritdoc/> |
| | | 389 | | public bool IsProperSubsetOf(IEnumerable<int> other) |
| | | 390 | | { |
| | 6 | 391 | | SwiftThrowHelper.ThrowIfNull(other, nameof(other)); |
| | | 392 | | |
| | 6 | 393 | | if (other is SwiftSparseSet sparseSet) |
| | 2 | 394 | | return _count < sparseSet._count && IsSubsetOf(sparseSet); |
| | | 395 | | |
| | 4 | 396 | | if (other is ISet<int> set) |
| | 2 | 397 | | return _count < set.Count && IsSubsetOf(set); |
| | | 398 | | |
| | 2 | 399 | | var lookup = new HashSet<int>(other); |
| | 2 | 400 | | return _count < lookup.Count && IsSubsetOf(lookup); |
| | | 401 | | } |
| | | 402 | | |
| | | 403 | | /// <inheritdoc/> |
| | | 404 | | public bool IsProperSupersetOf(IEnumerable<int> other) |
| | | 405 | | { |
| | 6 | 406 | | SwiftThrowHelper.ThrowIfNull(other, nameof(other)); |
| | | 407 | | |
| | 6 | 408 | | if (other is SwiftSparseSet sparseSet) |
| | 2 | 409 | | return _count > sparseSet._count && IsSupersetOf(sparseSet); |
| | | 410 | | |
| | 4 | 411 | | if (other is ISet<int> set) |
| | 2 | 412 | | return _count > set.Count && IsSupersetOf(set); |
| | | 413 | | |
| | 2 | 414 | | var lookup = new HashSet<int>(other); |
| | 2 | 415 | | return _count > lookup.Count && IsSupersetOf(lookup); |
| | | 416 | | } |
| | | 417 | | |
| | | 418 | | /// <inheritdoc/> |
| | | 419 | | public bool IsSubsetOf(IEnumerable<int> other) |
| | | 420 | | { |
| | 10 | 421 | | SwiftThrowHelper.ThrowIfNull(other, nameof(other)); |
| | | 422 | | |
| | 12 | 423 | | if (_count == 0 || ReferenceEquals(other, this)) return true; |
| | | 424 | | |
| | 8 | 425 | | if (other is SwiftSparseSet sparseSet) |
| | 3 | 426 | | return IsSubsetOfSparseSet(sparseSet); |
| | | 427 | | |
| | 5 | 428 | | if (other is ISet<int> set) |
| | 4 | 429 | | return IsSubsetOfSet(set); |
| | | 430 | | |
| | 1 | 431 | | return IsSubsetOfSet(new HashSet<int>(other)); |
| | | 432 | | } |
| | | 433 | | |
| | | 434 | | /// <inheritdoc/> |
| | | 435 | | public bool IsSupersetOf(IEnumerable<int> other) |
| | | 436 | | { |
| | 6 | 437 | | SwiftThrowHelper.ThrowIfNull(other, nameof(other)); |
| | | 438 | | |
| | 7 | 439 | | if (ReferenceEquals(other, this)) return true; |
| | | 440 | | |
| | 29 | 441 | | foreach (int item in other) |
| | | 442 | | { |
| | 10 | 443 | | if (!Contains(item)) |
| | 1 | 444 | | return false; |
| | | 445 | | } |
| | | 446 | | |
| | 4 | 447 | | return true; |
| | 1 | 448 | | } |
| | | 449 | | |
| | | 450 | | /// <inheritdoc/> |
| | | 451 | | public bool Overlaps(IEnumerable<int> other) |
| | | 452 | | { |
| | 2 | 453 | | SwiftThrowHelper.ThrowIfNull(other, nameof(other)); |
| | | 454 | | |
| | 9 | 455 | | foreach (int item in other) |
| | | 456 | | { |
| | 3 | 457 | | if (Contains(item)) |
| | 1 | 458 | | return true; |
| | | 459 | | } |
| | | 460 | | |
| | 1 | 461 | | return false; |
| | 1 | 462 | | } |
| | | 463 | | |
| | | 464 | | /// <inheritdoc/> |
| | | 465 | | public bool SetEquals(IEnumerable<int> other) |
| | | 466 | | { |
| | 16 | 467 | | SwiftThrowHelper.ThrowIfNull(other, nameof(other)); |
| | | 468 | | |
| | 17 | 469 | | if (ReferenceEquals(other, this)) return true; |
| | | 470 | | |
| | 15 | 471 | | if (other is SwiftSparseSet sparseSet) |
| | 4 | 472 | | return SetEqualsSparseSet(sparseSet); |
| | | 473 | | |
| | 11 | 474 | | if (other is ISet<int> set) |
| | 4 | 475 | | return SetEqualsSet(set); |
| | | 476 | | |
| | 7 | 477 | | return SetEqualsSet(new HashSet<int>(other)); |
| | | 478 | | } |
| | | 479 | | |
| | | 480 | | /// <inheritdoc/> |
| | | 481 | | public void SymmetricExceptWith(IEnumerable<int> other) |
| | | 482 | | { |
| | 5 | 483 | | SwiftThrowHelper.ThrowIfNull(other, nameof(other)); |
| | | 484 | | |
| | 5 | 485 | | if (ReferenceEquals(other, this)) |
| | | 486 | | { |
| | 1 | 487 | | Clear(); |
| | 1 | 488 | | return; |
| | | 489 | | } |
| | | 490 | | |
| | 4 | 491 | | if (other is SwiftSparseSet sparseSet) |
| | | 492 | | { |
| | 1 | 493 | | SymmetricExceptWithSet(sparseSet); |
| | 1 | 494 | | return; |
| | | 495 | | } |
| | | 496 | | |
| | 3 | 497 | | if (other is ISet<int> set) |
| | | 498 | | { |
| | 1 | 499 | | SymmetricExceptWithSet(set); |
| | 1 | 500 | | return; |
| | | 501 | | } |
| | | 502 | | |
| | 2 | 503 | | SymmetricExceptWithSet(new HashSet<int>(other)); |
| | 2 | 504 | | } |
| | | 505 | | |
| | | 506 | | /// <inheritdoc/> |
| | | 507 | | public void UnionWith(IEnumerable<int> other) |
| | | 508 | | { |
| | 1 | 509 | | SwiftThrowHelper.ThrowIfNull(other, nameof(other)); |
| | | 510 | | |
| | 6 | 511 | | foreach (int item in other) |
| | 2 | 512 | | Add(item); |
| | 1 | 513 | | } |
| | | 514 | | |
| | | 515 | | private void RemoveWhereMissingFrom(SwiftSparseSet other) |
| | | 516 | | { |
| | 1 | 517 | | int index = 0; |
| | 4 | 518 | | while (index < _count) |
| | | 519 | | { |
| | 3 | 520 | | int key = _denseKeys[index]; |
| | 3 | 521 | | if (other.Contains(key)) |
| | 2 | 522 | | index++; |
| | | 523 | | else |
| | 1 | 524 | | Remove(key); |
| | | 525 | | } |
| | 1 | 526 | | } |
| | | 527 | | |
| | | 528 | | private void RemoveWhereMissingFrom(ISet<int> other) |
| | | 529 | | { |
| | 2 | 530 | | int index = 0; |
| | 9 | 531 | | while (index < _count) |
| | | 532 | | { |
| | 7 | 533 | | int key = _denseKeys[index]; |
| | 7 | 534 | | if (other.Contains(key)) |
| | 4 | 535 | | index++; |
| | | 536 | | else |
| | 3 | 537 | | Remove(key); |
| | | 538 | | } |
| | 2 | 539 | | } |
| | | 540 | | |
| | | 541 | | private bool AllKeysIn(SwiftSparseSet other) |
| | | 542 | | { |
| | 28 | 543 | | for (int i = 0; i < _count; i++) |
| | | 544 | | { |
| | 10 | 545 | | if (!other.Contains(_denseKeys[i])) |
| | 1 | 546 | | return false; |
| | | 547 | | } |
| | | 548 | | |
| | 4 | 549 | | return true; |
| | | 550 | | } |
| | | 551 | | |
| | | 552 | | private bool AllKeysIn(ISet<int> other) |
| | | 553 | | { |
| | 82 | 554 | | for (int i = 0; i < _count; i++) |
| | | 555 | | { |
| | 30 | 556 | | if (!other.Contains(_denseKeys[i])) |
| | 3 | 557 | | return false; |
| | | 558 | | } |
| | | 559 | | |
| | 11 | 560 | | return true; |
| | | 561 | | } |
| | | 562 | | |
| | | 563 | | private bool IsSubsetOfSparseSet(SwiftSparseSet other) => |
| | 3 | 564 | | _count <= other._count && AllKeysIn(other); |
| | | 565 | | |
| | | 566 | | private bool IsSubsetOfSet(ISet<int> other) => |
| | 5 | 567 | | _count <= other.Count && AllKeysIn(other); |
| | | 568 | | |
| | | 569 | | private bool SetEqualsSparseSet(SwiftSparseSet other) => |
| | 4 | 570 | | _count == other._count && AllKeysIn(other); |
| | | 571 | | |
| | | 572 | | private bool SetEqualsSet(ISet<int> other) => |
| | 11 | 573 | | _count == other.Count && AllKeysIn(other); |
| | | 574 | | |
| | | 575 | | private void SymmetricExceptWithSet(IEnumerable<int> other) |
| | | 576 | | { |
| | 26 | 577 | | foreach (int item in other) |
| | | 578 | | { |
| | 9 | 579 | | if (!Remove(item)) |
| | 4 | 580 | | Add(item); |
| | | 581 | | } |
| | 4 | 582 | | } |
| | | 583 | | |
| | | 584 | | #endregion |
| | | 585 | | |
| | | 586 | | #region Capacity Management |
| | | 587 | | |
| | | 588 | | /// <summary> |
| | | 589 | | /// Ensures that dense storage can hold at least the specified number of IDs. |
| | | 590 | | /// </summary> |
| | | 591 | | public void EnsureDenseCapacity(int capacity) |
| | | 592 | | { |
| | 175 | 593 | | if (capacity <= _denseKeys.Length) return; |
| | | 594 | | |
| | 3 | 595 | | int newCap = _denseKeys.Length == 0 ? DefaultDenseCapacity : _denseKeys.Length * 2; |
| | 5 | 596 | | if (newCap < capacity) newCap = capacity; |
| | | 597 | | |
| | 3 | 598 | | newCap = SwiftHashTools.NextPowerOfTwo(newCap); |
| | | 599 | | |
| | 3 | 600 | | var newKeys = new int[newCap]; |
| | 3 | 601 | | if (_count > 0) |
| | 1 | 602 | | Array.Copy(_denseKeys, newKeys, _count); |
| | | 603 | | |
| | 3 | 604 | | _denseKeys = newKeys; |
| | 3 | 605 | | _version++; |
| | 3 | 606 | | } |
| | | 607 | | |
| | | 608 | | /// <summary> |
| | | 609 | | /// Ensures that the sparse lookup table has at least the specified capacity. |
| | | 610 | | /// </summary> |
| | | 611 | | public void EnsureSparseCapacity(int capacity) |
| | | 612 | | { |
| | 170 | 613 | | if (capacity <= _sparse.Length) return; |
| | | 614 | | |
| | 8 | 615 | | int newCap = _sparse.Length == 0 |
| | 8 | 616 | | ? DefaultSparseCapacity |
| | 8 | 617 | | : _sparse.Length * 2; |
| | 10 | 618 | | if (newCap < capacity) newCap = capacity; |
| | | 619 | | |
| | 8 | 620 | | newCap = SwiftHashTools.NextPowerOfTwo(newCap); |
| | | 621 | | |
| | 8 | 622 | | var newSparse = new int[newCap]; |
| | 8 | 623 | | if (_sparse.Length > 0) |
| | 7 | 624 | | Array.Copy(_sparse, newSparse, _sparse.Length); |
| | | 625 | | |
| | 8 | 626 | | _sparse = newSparse; |
| | 8 | 627 | | _version++; |
| | 8 | 628 | | } |
| | | 629 | | |
| | | 630 | | /// <summary> |
| | | 631 | | /// Reduces unused dense and sparse capacity while preserving all IDs. |
| | | 632 | | /// </summary> |
| | | 633 | | public void TrimExcess() |
| | | 634 | | { |
| | 3 | 635 | | TrimDenseStorage(); |
| | 3 | 636 | | TrimSparseLookup(); |
| | 3 | 637 | | _version++; |
| | 3 | 638 | | } |
| | | 639 | | |
| | | 640 | | private void TrimDenseStorage() |
| | | 641 | | { |
| | 3 | 642 | | int newDense = Math.Max(DefaultDenseCapacity, _count); |
| | 4 | 643 | | if (newDense >= _denseKeys.Length) return; |
| | | 644 | | |
| | 2 | 645 | | var newKeys = new int[newDense]; |
| | 2 | 646 | | if (_count > 0) |
| | 1 | 647 | | Array.Copy(_denseKeys, newKeys, _count); |
| | 2 | 648 | | _denseKeys = newKeys; |
| | 2 | 649 | | } |
| | | 650 | | |
| | | 651 | | private void TrimSparseLookup() |
| | | 652 | | { |
| | 3 | 653 | | int maxKey = -1; |
| | 8 | 654 | | for (int i = 0; i < _count; i++) |
| | 2 | 655 | | if (_denseKeys[i] > maxKey) maxKey = _denseKeys[i]; |
| | | 656 | | |
| | 3 | 657 | | int newSparse = maxKey < 0 |
| | 3 | 658 | | ? DefaultSparseCapacity |
| | 3 | 659 | | : Math.Max(DefaultSparseCapacity, GetRequiredSparseCapacity(maxKey)); |
| | 4 | 660 | | if (newSparse >= _sparse.Length) return; |
| | | 661 | | |
| | 2 | 662 | | var newMap = new int[newSparse]; |
| | 6 | 663 | | for (int i = 0; i < _count; i++) |
| | 1 | 664 | | newMap[_denseKeys[i]] = i + 1; |
| | 2 | 665 | | _sparse = newMap; |
| | 2 | 666 | | } |
| | | 667 | | |
| | | 668 | | #endregion |
| | | 669 | | |
| | | 670 | | #region Copy and Enumeration |
| | | 671 | | |
| | | 672 | | /// <summary> |
| | | 673 | | /// Returns a read-only span over the populated dense ID range. |
| | | 674 | | /// </summary> |
| | 1 | 675 | | public ReadOnlySpan<int> AsReadOnlySpan() => _denseKeys.AsSpan(0, _count); |
| | | 676 | | |
| | | 677 | | /// <summary> |
| | | 678 | | /// Retrieves the backing dense ID array and current count. |
| | | 679 | | /// </summary> |
| | | 680 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 681 | | public void GetDense(out int[] keys, out int count) |
| | | 682 | | { |
| | 1 | 683 | | keys = _denseKeys; |
| | 1 | 684 | | count = _count; |
| | 1 | 685 | | } |
| | | 686 | | |
| | | 687 | | /// <summary> |
| | | 688 | | /// Replaces the destination list contents with this set's keys in dense iteration order. |
| | | 689 | | /// </summary> |
| | | 690 | | /// <remarks> |
| | | 691 | | /// The destination list is reused and only grows when its current capacity is smaller than |
| | | 692 | | /// <see cref="Count"/>. Use <see cref="CopySortedKeysTo(SwiftList{int})"/> when stable ascending |
| | | 693 | | /// key order is required. |
| | | 694 | | /// </remarks> |
| | | 695 | | /// <param name="destination">The caller-owned list that receives the keys.</param> |
| | | 696 | | public void CopyKeysTo(SwiftList<int> destination) |
| | | 697 | | { |
| | 4 | 698 | | SwiftThrowHelper.ThrowIfNull(destination, nameof(destination)); |
| | | 699 | | |
| | 4 | 700 | | destination.FastClear(); |
| | 4 | 701 | | destination.AddRange(_denseKeys.AsSpan(0, _count)); |
| | 4 | 702 | | } |
| | | 703 | | |
| | | 704 | | /// <summary> |
| | | 705 | | /// Replaces the destination list contents with this set's keys sorted in ascending order. |
| | | 706 | | /// </summary> |
| | | 707 | | /// <remarks> |
| | | 708 | | /// This method is intended for reusable hot-path scratch buffers that need deterministic key order |
| | | 709 | | /// without constructing a persistent sorted collection. |
| | | 710 | | /// </remarks> |
| | | 711 | | /// <param name="destination">The caller-owned list that receives the sorted keys.</param> |
| | | 712 | | public void CopySortedKeysTo(SwiftList<int> destination) |
| | | 713 | | { |
| | 3 | 714 | | CopyKeysTo(destination); |
| | 3 | 715 | | destination.SortInPlace(default(SwiftIntAscendingComparer)); |
| | 3 | 716 | | } |
| | | 717 | | |
| | | 718 | | /// <inheritdoc/> |
| | | 719 | | public void CopyTo(int[] array, int arrayIndex) |
| | | 720 | | { |
| | 3 | 721 | | SwiftThrowHelper.ThrowIfNull(array, nameof(array)); |
| | 3 | 722 | | SwiftThrowHelper.ThrowIfArrayIndexInvalid(arrayIndex, array.Length); |
| | 3 | 723 | | SwiftThrowHelper.ThrowIfArgument(array.Length - arrayIndex < _count, nameof(array), "The array is not large enou |
| | | 724 | | |
| | 3 | 725 | | Array.Copy(_denseKeys, 0, array, arrayIndex, _count); |
| | 3 | 726 | | } |
| | | 727 | | |
| | | 728 | | /// <inheritdoc/> |
| | | 729 | | void ICollection.CopyTo(Array array, int index) |
| | | 730 | | { |
| | 8 | 731 | | SwiftThrowHelper.ThrowIfNull(array, nameof(array)); |
| | 8 | 732 | | SwiftThrowHelper.ThrowIfArgument(array.Rank != 1, nameof(array), "Only single dimensional arrays are supported." |
| | 7 | 733 | | SwiftThrowHelper.ThrowIfArgument(array.GetLowerBound(0) != 0, nameof(array), "Non-zero lower bound arrays are no |
| | 6 | 734 | | SwiftThrowHelper.ThrowIfArrayIndexInvalid(index, array.Length, nameof(index)); |
| | 5 | 735 | | SwiftThrowHelper.ThrowIfArgument(array.Length - index < _count, nameof(array), "The array is not large enough to |
| | | 736 | | |
| | 4 | 737 | | if (array is int[] intArray) |
| | | 738 | | { |
| | 1 | 739 | | CopyTo(intArray, index); |
| | 1 | 740 | | return; |
| | | 741 | | } |
| | | 742 | | |
| | 3 | 743 | | Type elementType = array.GetType().GetElementType()!; |
| | 3 | 744 | | if (array is object[] objects && elementType.IsAssignableFrom(typeof(int))) |
| | | 745 | | { |
| | 6 | 746 | | for (int i = 0; i < _count; i++) |
| | 2 | 747 | | objects[index + i] = _denseKeys[i]; |
| | 1 | 748 | | return; |
| | | 749 | | } |
| | | 750 | | |
| | 2 | 751 | | throw new ArgumentException("Invalid array type.", nameof(array)); |
| | | 752 | | } |
| | | 753 | | |
| | | 754 | | /// <inheritdoc/> |
| | | 755 | | public void CloneTo(ICollection<int> output) |
| | | 756 | | { |
| | 1 | 757 | | SwiftThrowHelper.ThrowIfNull(output, nameof(output)); |
| | | 758 | | |
| | 1 | 759 | | output.Clear(); |
| | | 760 | | |
| | 6 | 761 | | for (int i = 0; i < _count; i++) |
| | 2 | 762 | | output.Add(_denseKeys[i]); |
| | 1 | 763 | | } |
| | | 764 | | |
| | | 765 | | /// <inheritdoc cref="IEnumerable.GetEnumerator()"/> |
| | 18 | 766 | | public SwiftSparseSetEnumerator GetEnumerator() => new(this); |
| | 15 | 767 | | IEnumerator<int> IEnumerable<int>.GetEnumerator() => GetEnumerator(); |
| | 1 | 768 | | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); |
| | | 769 | | |
| | | 770 | | /// <summary> |
| | | 771 | | /// Supports iteration over IDs in a <see cref="SwiftSparseSet"/>. |
| | | 772 | | /// </summary> |
| | | 773 | | public struct SwiftSparseSetEnumerator : IEnumerator<int> |
| | | 774 | | { |
| | | 775 | | private readonly SwiftSparseSet _set; |
| | | 776 | | private readonly int[] _keys; |
| | | 777 | | private readonly int _count; |
| | | 778 | | private readonly uint _version; |
| | | 779 | | private int _index; |
| | | 780 | | |
| | | 781 | | internal SwiftSparseSetEnumerator(SwiftSparseSet set) |
| | | 782 | | { |
| | 18 | 783 | | _set = set; |
| | 18 | 784 | | _keys = set._denseKeys; |
| | 18 | 785 | | _count = set._count; |
| | 18 | 786 | | _version = set._version; |
| | 18 | 787 | | _index = -1; |
| | 18 | 788 | | Current = default; |
| | 18 | 789 | | } |
| | | 790 | | |
| | | 791 | | /// <inheritdoc/> |
| | | 792 | | public int Current { get; private set; } |
| | 1 | 793 | | object IEnumerator.Current => Current; |
| | | 794 | | |
| | | 795 | | /// <inheritdoc/> |
| | | 796 | | public bool MoveNext() |
| | | 797 | | { |
| | 28 | 798 | | SwiftThrowHelper.ThrowIfTrue(_version != _set._version, message: "Collection was modified during enumeration |
| | | 799 | | |
| | 27 | 800 | | int next = _index + 1; |
| | 27 | 801 | | if (next >= _count) |
| | | 802 | | { |
| | 15 | 803 | | Current = default; |
| | 15 | 804 | | return false; |
| | | 805 | | } |
| | | 806 | | |
| | 12 | 807 | | _index = next; |
| | 12 | 808 | | Current = _keys[_index]; |
| | 12 | 809 | | return true; |
| | | 810 | | } |
| | | 811 | | |
| | | 812 | | /// <inheritdoc/> |
| | | 813 | | public void Reset() |
| | | 814 | | { |
| | 1 | 815 | | SwiftThrowHelper.ThrowIfTrue(_version != _set._version, message: "Collection was modified during enumeration |
| | | 816 | | |
| | 1 | 817 | | _index = -1; |
| | 1 | 818 | | Current = default; |
| | 1 | 819 | | } |
| | | 820 | | |
| | | 821 | | /// <inheritdoc/> |
| | 15 | 822 | | public void Dispose() => _index = -1; |
| | | 823 | | } |
| | | 824 | | |
| | | 825 | | #endregion |
| | | 826 | | |
| | | 827 | | #region Helpers |
| | | 828 | | |
| | | 829 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 830 | | private static int GetRequiredSparseCapacity(int key) |
| | | 831 | | { |
| | 94 | 832 | | SwiftThrowHelper.ThrowIfNegative(key, nameof(key)); |
| | 93 | 833 | | SwiftThrowHelper.ThrowIfArgumentOutOfRange(key == int.MaxValue, key, nameof(key), "ID is too large for direct sp |
| | | 834 | | |
| | 92 | 835 | | return key + 1; |
| | | 836 | | } |
| | | 837 | | |
| | | 838 | | #endregion |
| | | 839 | | } |