| | | 1 | | using MemoryPack; |
| | | 2 | | using System; |
| | | 3 | | using System.Collections; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Text.Json.Serialization; |
| | | 6 | | |
| | | 7 | | namespace SwiftCollections; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Represents a high-performance generational bucket that assigns stable handles to stored items. |
| | | 11 | | /// </summary> |
| | | 12 | | /// <remarks> |
| | | 13 | | /// <para> |
| | | 14 | | /// <see cref="SwiftGenerationalBucket{T}"/> is similar to <see cref="SwiftBucket{T}"/> but adds |
| | | 15 | | /// <b>generation tracking</b> to prevent stale references from accessing reused slots. |
| | | 16 | | /// </para> |
| | | 17 | | /// |
| | | 18 | | /// <para> |
| | | 19 | | /// When an item is added, a <see cref="Handle"/> containing both an index and generation |
| | | 20 | | /// is returned. If the item is removed and the slot reused later, the generation value |
| | | 21 | | /// changes, causing older handles to automatically become invalid. |
| | | 22 | | /// </para> |
| | | 23 | | /// |
| | | 24 | | /// <para> |
| | | 25 | | /// This pattern is widely used to safely reference objects without risking accidental access |
| | | 26 | | /// to recycled memory slots. |
| | | 27 | | /// </para> |
| | | 28 | | /// |
| | | 29 | | /// <para> |
| | | 30 | | /// Key characteristics: |
| | | 31 | | /// <list type="bullet"> |
| | | 32 | | /// <item><description>O(1) insertion and removal.</description></item> |
| | | 33 | | /// <item><description>Stable handles for the lifetime of stored items.</description></item> |
| | | 34 | | /// <item><description>Automatic invalidation of stale handles via generation counters.</description></item> |
| | | 35 | | /// <item><description>Cache-friendly contiguous storage.</description></item> |
| | | 36 | | /// </list> |
| | | 37 | | /// </para> |
| | | 38 | | /// |
| | | 39 | | /// <para> |
| | | 40 | | /// Use <see cref="SwiftBucket{T}"/> when raw indices are acceptable. |
| | | 41 | | /// Use <see cref="SwiftGenerationalBucket{T}"/> when handle safety is required. |
| | | 42 | | /// </para> |
| | | 43 | | /// </remarks> |
| | | 44 | | /// <typeparam name="T">Specifies the type of elements stored in the bucket.</typeparam> |
| | | 45 | | [Serializable] |
| | | 46 | | [JsonConverter(typeof(SwiftStateJsonConverterFactory))] |
| | | 47 | | [MemoryPackable] |
| | | 48 | | public sealed partial class SwiftGenerationalBucket<T> : ISwiftCloneable<T>, IEnumerable<T> |
| | | 49 | | { |
| | | 50 | | #region Nested Types |
| | | 51 | | |
| | | 52 | | public readonly struct Handle : IEquatable<Handle> |
| | | 53 | | { |
| | | 54 | | public readonly int Index; |
| | | 55 | | public readonly uint Generation; |
| | | 56 | | |
| | | 57 | | public Handle(int index, uint generation) |
| | 348 | 58 | | { |
| | 348 | 59 | | Index = index; |
| | 348 | 60 | | Generation = generation; |
| | 348 | 61 | | } |
| | | 62 | | |
| | | 63 | | public bool Equals(Handle other) |
| | 4 | 64 | | => Index == other.Index && Generation == other.Generation; |
| | | 65 | | |
| | | 66 | | public override bool Equals(object obj) |
| | 1 | 67 | | => obj is Handle h && Equals(h); |
| | | 68 | | |
| | | 69 | | public override int GetHashCode() |
| | 2 | 70 | | => HashCode.Combine(Index, Generation); |
| | | 71 | | |
| | | 72 | | public override string ToString() |
| | 1 | 73 | | => $"Handle({Index}:{Generation})"; |
| | | 74 | | |
| | | 75 | | public static bool operator ==(Handle left, Handle right) |
| | 2 | 76 | | { |
| | 2 | 77 | | return left.Equals(right); |
| | 2 | 78 | | } |
| | | 79 | | |
| | | 80 | | public static bool operator !=(Handle left, Handle right) |
| | 1 | 81 | | { |
| | 1 | 82 | | return !(left == right); |
| | 1 | 83 | | } |
| | | 84 | | } |
| | | 85 | | |
| | | 86 | | private struct Entry |
| | | 87 | | { |
| | | 88 | | public uint Generation; |
| | | 89 | | public bool IsUsed; |
| | | 90 | | public T Value; |
| | | 91 | | } |
| | | 92 | | |
| | | 93 | | #endregion |
| | | 94 | | |
| | | 95 | | #region Constants |
| | | 96 | | |
| | | 97 | | public const int DefaultCapacity = 8; |
| | | 98 | | |
| | | 99 | | #endregion |
| | | 100 | | |
| | | 101 | | #region Fields |
| | | 102 | | |
| | | 103 | | private Entry[] _entries; |
| | | 104 | | private SwiftIntStack _freeIndices; |
| | | 105 | | |
| | | 106 | | private int _count; |
| | | 107 | | private int _peak; |
| | | 108 | | |
| | | 109 | | private uint _version; |
| | | 110 | | |
| | | 111 | | #endregion |
| | | 112 | | |
| | | 113 | | #region Constructors |
| | | 114 | | |
| | 45 | 115 | | public SwiftGenerationalBucket() : this(DefaultCapacity) { } |
| | | 116 | | |
| | 17 | 117 | | public SwiftGenerationalBucket(int capacity) |
| | 17 | 118 | | { |
| | 17 | 119 | | capacity = capacity <= DefaultCapacity |
| | 17 | 120 | | ? DefaultCapacity |
| | 17 | 121 | | : SwiftHashTools.NextPowerOfTwo(capacity); |
| | | 122 | | |
| | 17 | 123 | | _entries = new Entry[capacity]; |
| | 17 | 124 | | _freeIndices = new SwiftIntStack(capacity); |
| | 17 | 125 | | } |
| | | 126 | | |
| | | 127 | | /// <summary> |
| | | 128 | | /// Initializes a new instance of the <see cref="SwiftGenerationalBucket{T}"/> class with the specified <see cref=" |
| | | 129 | | /// </summary> |
| | | 130 | | /// <param name="state">The state containing the internal array, count, offset, and version for initialization.</pa |
| | | 131 | | [MemoryPackConstructor] |
| | 3 | 132 | | public SwiftGenerationalBucket(SwiftGenerationalBucketState<T> state) |
| | 3 | 133 | | { |
| | 3 | 134 | | State = state; |
| | 3 | 135 | | } |
| | | 136 | | |
| | | 137 | | #endregion |
| | | 138 | | |
| | | 139 | | #region Properties |
| | | 140 | | |
| | | 141 | | [JsonIgnore] |
| | | 142 | | [MemoryPackIgnore] |
| | 9 | 143 | | public int Count => _count; |
| | | 144 | | |
| | | 145 | | [JsonIgnore] |
| | | 146 | | [MemoryPackIgnore] |
| | 1 | 147 | | public int Capacity => _entries.Length; |
| | | 148 | | |
| | | 149 | | [JsonInclude] |
| | | 150 | | [MemoryPackInclude] |
| | | 151 | | public SwiftGenerationalBucketState<T> State |
| | | 152 | | { |
| | | 153 | | get |
| | 2 | 154 | | { |
| | 2 | 155 | | int length = _entries.Length; |
| | | 156 | | |
| | 2 | 157 | | var items = new T[length]; |
| | 2 | 158 | | var allocated = new bool[length]; |
| | 2 | 159 | | var generations = new uint[length]; |
| | | 160 | | |
| | 148 | 161 | | for (int i = 0; i < length; i++) |
| | 72 | 162 | | { |
| | 72 | 163 | | generations[i] = _entries[i].Generation; |
| | | 164 | | |
| | 72 | 165 | | if (_entries[i].IsUsed) |
| | 53 | 166 | | { |
| | 53 | 167 | | items[i] = _entries[i].Value; |
| | 53 | 168 | | allocated[i] = true; |
| | 53 | 169 | | } |
| | 72 | 170 | | } |
| | | 171 | | |
| | 2 | 172 | | int[] free = new int[_freeIndices.Count]; |
| | 2 | 173 | | Array.Copy(_freeIndices.Array, free, _freeIndices.Count); |
| | | 174 | | |
| | 2 | 175 | | return new SwiftGenerationalBucketState<T>( |
| | 2 | 176 | | items, |
| | 2 | 177 | | allocated, |
| | 2 | 178 | | generations, |
| | 2 | 179 | | free, |
| | 2 | 180 | | _peak |
| | 2 | 181 | | ); |
| | 2 | 182 | | } |
| | | 183 | | internal set |
| | 3 | 184 | | { |
| | 3 | 185 | | var items = value.Items ?? Array.Empty<T>(); |
| | 3 | 186 | | var allocated = value.Allocated ?? Array.Empty<bool>(); |
| | 3 | 187 | | var generations = value.Generations ?? Array.Empty<uint>(); |
| | 3 | 188 | | var freeIndices = value.FreeIndices ?? Array.Empty<int>(); |
| | | 189 | | |
| | 3 | 190 | | int sourceLength = Math.Max(items.Length, Math.Max(allocated.Length, generations.Length)); |
| | 3 | 191 | | int capacity = sourceLength < DefaultCapacity |
| | 3 | 192 | | ? DefaultCapacity |
| | 3 | 193 | | : SwiftHashTools.NextPowerOfTwo(sourceLength); |
| | | 194 | | |
| | 3 | 195 | | _entries = new Entry[capacity]; |
| | 3 | 196 | | _freeIndices = new SwiftIntStack(Math.Max(SwiftIntStack.DefaultCapacity, freeIndices.Length)); |
| | | 197 | | |
| | 3 | 198 | | _count = 0; |
| | 3 | 199 | | int maxReferencedIndex = -1; |
| | | 200 | | |
| | 156 | 201 | | for (int i = 0; i < sourceLength; i++) |
| | 75 | 202 | | { |
| | 75 | 203 | | ref Entry entry = ref _entries[i]; |
| | | 204 | | |
| | 75 | 205 | | entry.Generation = generations.Length > i ? generations[i] : 0; |
| | 75 | 206 | | if (entry.Generation != 0) |
| | 3 | 207 | | maxReferencedIndex = i; |
| | | 208 | | |
| | 75 | 209 | | if (allocated.Length > i && allocated[i]) |
| | 55 | 210 | | { |
| | 55 | 211 | | if (items.Length > i) |
| | 55 | 212 | | entry.Value = items[i]; |
| | | 213 | | |
| | 55 | 214 | | entry.IsUsed = true; |
| | 55 | 215 | | _count++; |
| | 55 | 216 | | maxReferencedIndex = i; |
| | 55 | 217 | | } |
| | 75 | 218 | | } |
| | | 219 | | |
| | 9 | 220 | | foreach (var index in freeIndices) |
| | 0 | 221 | | { |
| | 0 | 222 | | if ((uint)index >= (uint)capacity) |
| | 0 | 223 | | throw new ArgumentException("Free index is out of range."); |
| | | 224 | | |
| | 0 | 225 | | _freeIndices.Push(index); |
| | 0 | 226 | | if (index > maxReferencedIndex) |
| | 0 | 227 | | maxReferencedIndex = index; |
| | 0 | 228 | | } |
| | | 229 | | |
| | 3 | 230 | | int peak = value.Peak; |
| | 3 | 231 | | if (peak < 0) |
| | 0 | 232 | | peak = 0; |
| | | 233 | | |
| | 3 | 234 | | _peak = Math.Max(peak, maxReferencedIndex + 1); |
| | 3 | 235 | | if (_peak > capacity) |
| | 0 | 236 | | _peak = capacity; |
| | | 237 | | |
| | 3 | 238 | | _version = 0; |
| | 3 | 239 | | } |
| | | 240 | | } |
| | | 241 | | |
| | | 242 | | #endregion |
| | | 243 | | |
| | | 244 | | #region Core Operations |
| | | 245 | | |
| | | 246 | | public Handle Add(T value) |
| | 341 | 247 | | { |
| | | 248 | | int index; |
| | | 249 | | |
| | 341 | 250 | | if (_freeIndices.Count == 0) |
| | 340 | 251 | | { |
| | 340 | 252 | | index = _peak++; |
| | | 253 | | |
| | 340 | 254 | | if ((uint)index >= (uint)_entries.Length) |
| | 16 | 255 | | Resize(_entries.Length * 2); |
| | 340 | 256 | | } |
| | | 257 | | else |
| | 1 | 258 | | { |
| | 1 | 259 | | index = _freeIndices.Pop(); |
| | 1 | 260 | | } |
| | | 261 | | |
| | 341 | 262 | | ref Entry entry = ref _entries[index]; |
| | | 263 | | |
| | 341 | 264 | | entry.Value = value; |
| | 341 | 265 | | entry.IsUsed = true; |
| | | 266 | | |
| | 341 | 267 | | _count++; |
| | 341 | 268 | | _version++; |
| | | 269 | | |
| | 341 | 270 | | return new Handle(index, entry.Generation); |
| | 341 | 271 | | } |
| | | 272 | | |
| | | 273 | | public bool TryGet(Handle handle, out T value) |
| | 208 | 274 | | { |
| | 208 | 275 | | if ((uint)handle.Index >= (uint)_entries.Length) |
| | 1 | 276 | | { |
| | 1 | 277 | | value = default; |
| | 1 | 278 | | return false; |
| | | 279 | | } |
| | | 280 | | |
| | 207 | 281 | | ref Entry entry = ref _entries[handle.Index]; |
| | | 282 | | |
| | 207 | 283 | | if (!entry.IsUsed || entry.Generation != handle.Generation) |
| | 2 | 284 | | { |
| | 2 | 285 | | value = default; |
| | 2 | 286 | | return false; |
| | | 287 | | } |
| | | 288 | | |
| | 205 | 289 | | value = entry.Value; |
| | 205 | 290 | | return true; |
| | 208 | 291 | | } |
| | | 292 | | |
| | | 293 | | public ref T GetRef(Handle handle) |
| | 1 | 294 | | { |
| | 1 | 295 | | ref Entry entry = ref _entries[handle.Index]; |
| | | 296 | | |
| | 1 | 297 | | if (!entry.IsUsed || entry.Generation != handle.Generation) |
| | 0 | 298 | | throw new InvalidOperationException("Invalid handle"); |
| | | 299 | | |
| | 1 | 300 | | return ref entry.Value; |
| | 1 | 301 | | } |
| | | 302 | | |
| | | 303 | | public bool Remove(Handle handle) |
| | 3 | 304 | | { |
| | 3 | 305 | | if ((uint)handle.Index >= (uint)_entries.Length) |
| | 1 | 306 | | return false; |
| | | 307 | | |
| | 2 | 308 | | ref Entry entry = ref _entries[handle.Index]; |
| | | 309 | | |
| | 2 | 310 | | if (!entry.IsUsed || entry.Generation != handle.Generation) |
| | 0 | 311 | | return false; |
| | | 312 | | |
| | 2 | 313 | | entry.Value = default; |
| | 2 | 314 | | entry.IsUsed = false; |
| | | 315 | | |
| | 2 | 316 | | entry.Generation++; |
| | | 317 | | |
| | 2 | 318 | | _freeIndices.Push(handle.Index); |
| | | 319 | | |
| | 2 | 320 | | _count--; |
| | 2 | 321 | | _version++; |
| | | 322 | | |
| | 2 | 323 | | return true; |
| | 3 | 324 | | } |
| | | 325 | | |
| | | 326 | | public bool IsValid(Handle handle) |
| | 1 | 327 | | { |
| | 1 | 328 | | if ((uint)handle.Index >= (uint)_entries.Length) |
| | 0 | 329 | | return false; |
| | | 330 | | |
| | 1 | 331 | | ref Entry entry = ref _entries[handle.Index]; |
| | | 332 | | |
| | 1 | 333 | | return entry.IsUsed && entry.Generation == handle.Generation; |
| | 1 | 334 | | } |
| | | 335 | | |
| | | 336 | | #endregion |
| | | 337 | | |
| | | 338 | | #region Capacity |
| | | 339 | | |
| | | 340 | | public void EnsureCapacity(int capacity) |
| | 1 | 341 | | { |
| | 1 | 342 | | capacity = SwiftHashTools.NextPowerOfTwo(capacity); |
| | 1 | 343 | | if (capacity > _entries.Length) |
| | 1 | 344 | | Resize(capacity); |
| | 1 | 345 | | } |
| | | 346 | | |
| | | 347 | | private void Resize(int newSize) |
| | 17 | 348 | | { |
| | 17 | 349 | | int newCapacity = newSize <= DefaultCapacity ? DefaultCapacity : newSize; |
| | | 350 | | |
| | 17 | 351 | | Entry[] newArray = new Entry[newCapacity]; |
| | 17 | 352 | | Array.Copy(_entries, newArray, _entries.Length); |
| | 17 | 353 | | _entries = newArray; |
| | 17 | 354 | | } |
| | | 355 | | |
| | | 356 | | #endregion |
| | | 357 | | |
| | | 358 | | #region Utility |
| | | 359 | | |
| | | 360 | | public void CloneTo(ICollection<T> output) |
| | 1 | 361 | | { |
| | 1 | 362 | | SwiftThrowHelper.ThrowIfNull(output, nameof(output)); |
| | | 363 | | |
| | 1 | 364 | | output.Clear(); |
| | | 365 | | |
| | 1 | 366 | | uint count = 0; |
| | 1 | 367 | | uint peak = (uint)_peak; |
| | | 368 | | |
| | 42 | 369 | | for (uint i = 0; i < peak && count < (uint)_count; i++) |
| | 20 | 370 | | { |
| | 20 | 371 | | if (_entries[i].IsUsed) |
| | 20 | 372 | | { |
| | 20 | 373 | | output.Add(_entries[i].Value); |
| | 20 | 374 | | count++; |
| | 20 | 375 | | } |
| | 20 | 376 | | } |
| | 1 | 377 | | } |
| | | 378 | | |
| | | 379 | | /// <summary> |
| | | 380 | | /// Determines whether the <see cref="SwiftGenerationalBucket{T}"/> contains an element that matches the conditions |
| | | 381 | | /// </summary> |
| | | 382 | | /// <param name="match">The predicate that defines the conditions of the element to search for.</param> |
| | | 383 | | /// <returns><c>true</c> if the <see cref="SwiftGenerationalBucket{T}"/> contains one or more elements that match th |
| | | 384 | | public bool Exists(Predicate<T> match) |
| | 1 | 385 | | { |
| | 1 | 386 | | SwiftThrowHelper.ThrowIfNull(match, nameof(match)); |
| | | 387 | | |
| | 1 | 388 | | uint count = 0; |
| | 1 | 389 | | uint peak = (uint)_peak; |
| | | 390 | | |
| | 4 | 391 | | for (uint i = 0; i < peak && count < (uint)_count; i++) |
| | 2 | 392 | | { |
| | 2 | 393 | | if (_entries[i].IsUsed) |
| | 2 | 394 | | { |
| | 2 | 395 | | if (match(_entries[i].Value)) |
| | 1 | 396 | | return true; |
| | | 397 | | |
| | 1 | 398 | | count++; |
| | 1 | 399 | | } |
| | 1 | 400 | | } |
| | | 401 | | |
| | 0 | 402 | | return false; |
| | 1 | 403 | | } |
| | | 404 | | |
| | | 405 | | /// <summary> |
| | | 406 | | /// Searches for an element that matches the conditions defined by the specified predicate, and returns the first ma |
| | | 407 | | /// </summary> |
| | | 408 | | /// <param name="match">The predicate that defines the conditions of the element to search for.</param> |
| | | 409 | | /// <returns>The first element that matches the conditions defined by the specified predicate, if found; otherwise, |
| | | 410 | | public T Find(Predicate<T> match) |
| | 2 | 411 | | { |
| | 2 | 412 | | SwiftThrowHelper.ThrowIfNull(match, nameof(match)); |
| | | 413 | | |
| | 2 | 414 | | uint count = 0; |
| | 2 | 415 | | uint peak = (uint)_peak; |
| | | 416 | | |
| | 10 | 417 | | for (uint i = 0; i < peak && count < (uint)_count; i++) |
| | 4 | 418 | | { |
| | 4 | 419 | | if (_entries[i].IsUsed) |
| | 4 | 420 | | { |
| | 4 | 421 | | T item = _entries[i].Value; |
| | 4 | 422 | | if (match(item)) |
| | 1 | 423 | | return item; |
| | | 424 | | |
| | 3 | 425 | | count++; |
| | 3 | 426 | | } |
| | 3 | 427 | | } |
| | | 428 | | |
| | 1 | 429 | | return default; |
| | 2 | 430 | | } |
| | | 431 | | |
| | | 432 | | #endregion |
| | | 433 | | |
| | | 434 | | #region Enumeration |
| | | 435 | | |
| | 6 | 436 | | public Enumerator GetEnumerator() => new(this); |
| | | 437 | | |
| | 1 | 438 | | IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator(); |
| | 1 | 439 | | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); |
| | | 440 | | |
| | | 441 | | public struct Enumerator : IEnumerator<T> |
| | | 442 | | { |
| | | 443 | | private readonly SwiftGenerationalBucket<T> _bucket; |
| | | 444 | | private readonly uint _version; |
| | | 445 | | private int _index; |
| | | 446 | | private T _current; |
| | | 447 | | |
| | | 448 | | internal Enumerator(SwiftGenerationalBucket<T> bucket) |
| | 6 | 449 | | { |
| | 6 | 450 | | _bucket = bucket; |
| | 6 | 451 | | _version = bucket._version; |
| | 6 | 452 | | _index = -1; |
| | 6 | 453 | | _current = default; |
| | 6 | 454 | | } |
| | | 455 | | |
| | 103 | 456 | | public readonly T Current => _current; |
| | | 457 | | |
| | 1 | 458 | | readonly object IEnumerator.Current => _current; |
| | | 459 | | |
| | | 460 | | public bool MoveNext() |
| | 110 | 461 | | { |
| | 110 | 462 | | if (_version != _bucket._version) |
| | 1 | 463 | | throw new InvalidOperationException("Collection modified"); |
| | | 464 | | |
| | 109 | 465 | | uint peak = (uint)_bucket._peak; |
| | 109 | 466 | | while (++_index < peak) |
| | 106 | 467 | | { |
| | 106 | 468 | | if (_bucket._entries[_index].IsUsed) |
| | 106 | 469 | | { |
| | 106 | 470 | | _current = _bucket._entries[_index].Value; |
| | 106 | 471 | | return true; |
| | | 472 | | } |
| | 0 | 473 | | } |
| | | 474 | | |
| | 3 | 475 | | return false; |
| | 109 | 476 | | } |
| | | 477 | | |
| | | 478 | | public void Reset() |
| | 1 | 479 | | { |
| | 1 | 480 | | _index = -1; |
| | 1 | 481 | | _current = default; |
| | 1 | 482 | | } |
| | | 483 | | |
| | 6 | 484 | | public readonly void Dispose() { } |
| | | 485 | | } |
| | | 486 | | |
| | | 487 | | #endregion |
| | | 488 | | } |