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