| | | 1 | | using MemoryPack; |
| | | 2 | | using System; |
| | | 3 | | using System.Collections; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Linq; |
| | | 6 | | using System.Runtime.CompilerServices; |
| | | 7 | | using System.Text.Json.Serialization; |
| | | 8 | | |
| | | 9 | | namespace SwiftCollections; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Represents a dynamically sorted collection of elements. |
| | | 13 | | /// Provides efficient O(log n) operations for adding, removing, and checking for the presence of elements. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <remarks> |
| | | 16 | | /// The comparer is not serialized. After deserialization the list uses |
| | | 17 | | /// <see cref="Comparer{T}.Default"/>. |
| | | 18 | | /// |
| | | 19 | | /// If a custom comparer is required it can be reapplied using |
| | | 20 | | /// <see cref="SetComparer(IComparer{T})"/>. |
| | | 21 | | /// </remarks> |
| | | 22 | | /// <typeparam name="T">The type of elements in the collection.</typeparam> |
| | | 23 | | [Serializable] |
| | | 24 | | [JsonConverter(typeof(SwiftStateJsonConverterFactory))] |
| | | 25 | | [MemoryPackable] |
| | | 26 | | public partial class SwiftSortedList<T> : ISwiftCloneable<T>, IEnumerable<T>, IEnumerable, ICollection<T>, ICollection, |
| | | 27 | | { |
| | | 28 | | #region Constants |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// The default initial capacity of the <see cref="SwiftSortedList{T}"/> if none is specified. |
| | | 32 | | /// Used to allocate a reasonable starting size to minimize resizing operations. |
| | | 33 | | /// </summary> |
| | | 34 | | public const int DefaultCapacity = 8; |
| | | 35 | | |
| | 2 | 36 | | private static readonly T[] _emptyArray = Array.Empty<T>(); |
| | | 37 | | |
| | | 38 | | #endregion |
| | | 39 | | |
| | | 40 | | #region Fields |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Represents the internal array that stores the sorted elements. |
| | | 44 | | /// </summary> |
| | | 45 | | private T[] _innerArray; |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// The number of elements contained in the <see cref="SwiftSortedList{T}"/>. |
| | | 49 | | /// </summary> |
| | | 50 | | private int _count; |
| | | 51 | | |
| | | 52 | | /// <summary> |
| | | 53 | | /// The offset within the internal array where the logical start of the list begins. |
| | | 54 | | /// Used to efficiently manage insertions and deletions at both ends without excessive shifting. |
| | | 55 | | /// </summary> |
| | | 56 | | private int _offset; |
| | | 57 | | |
| | | 58 | | /// <summary> |
| | | 59 | | /// A version counter used to track modifications to the sorted list. |
| | | 60 | | /// Incremented on mutations to detect changes during enumeration and ensure enumerator validity. |
| | | 61 | | /// </summary> |
| | | 62 | | [NonSerialized] |
| | | 63 | | private uint _version; |
| | | 64 | | |
| | | 65 | | /// <summary> |
| | | 66 | | /// The comparer used to sort and compare elements in the collection. |
| | | 67 | | /// </summary> |
| | | 68 | | [NonSerialized] |
| | | 69 | | private IComparer<T> _comparer; |
| | | 70 | | |
| | | 71 | | /// <summary> |
| | | 72 | | /// An object that can be used to synchronize access to the SwiftList. |
| | | 73 | | /// </summary> |
| | | 74 | | [NonSerialized] |
| | | 75 | | private object _syncRoot; |
| | | 76 | | |
| | | 77 | | #endregion |
| | | 78 | | |
| | | 79 | | #region Constructors |
| | | 80 | | |
| | 153 | 81 | | public SwiftSortedList() : this(0) { } |
| | | 82 | | |
| | | 83 | | /// <summary> |
| | | 84 | | /// Initializes a new, empty instance of <see cref="SwiftSortedList{T}"/> uisng the specified <see cref="IComparer{T |
| | | 85 | | /// </summary> |
| | 9 | 86 | | public SwiftSortedList(IComparer<T> comparer) : this(0, comparer) { } |
| | | 87 | | |
| | | 88 | | /// <summary> |
| | | 89 | | /// Initializes a new, empty instance of <see cref="SwiftSortedList{T}"/> with the specified initial capacity and <s |
| | | 90 | | /// </summary> |
| | | 91 | | /// <param name="capacity">The starting initial capacity.</param> |
| | | 92 | | /// <param name="comparer">The comparer to use. If null, the default comparer is used.</param> |
| | 55 | 93 | | public SwiftSortedList(int capacity, IComparer<T> comparer = null) |
| | 55 | 94 | | { |
| | 55 | 95 | | _comparer = comparer ?? Comparer<T>.Default; |
| | | 96 | | |
| | 55 | 97 | | if (capacity == 0) |
| | 54 | 98 | | { |
| | 54 | 99 | | _innerArray = _emptyArray; |
| | 54 | 100 | | _offset = 0; |
| | 54 | 101 | | } |
| | | 102 | | else |
| | 1 | 103 | | { |
| | 1 | 104 | | capacity = capacity <= DefaultCapacity ? DefaultCapacity : SwiftHashTools.NextPowerOfTwo(capacity); |
| | 1 | 105 | | _innerArray = new T[capacity]; |
| | 1 | 106 | | _offset = capacity >> 1; // initial offset half of capacity |
| | 1 | 107 | | } |
| | 55 | 108 | | } |
| | | 109 | | |
| | | 110 | | /// <summary> |
| | | 111 | | /// Initializes a new instance of the <see cref="SwiftList{T}"/> class with elements from the specified collection. |
| | | 112 | | /// The collection must have a known count for optimized memory allocation. |
| | | 113 | | /// </summary> |
| | | 114 | | /// <exception cref="ArgumentException">Thrown if the input collection does not have a known count.</exception> |
| | 4 | 115 | | public SwiftSortedList(IEnumerable<T> items, IComparer<T> comparer = null) |
| | 4 | 116 | | { |
| | 4 | 117 | | SwiftThrowHelper.ThrowIfNull(items, nameof(items)); |
| | | 118 | | |
| | 4 | 119 | | _comparer = comparer ?? Comparer<T>.Default; |
| | | 120 | | |
| | 4 | 121 | | if (items is ICollection<T> collection) |
| | 3 | 122 | | { |
| | 3 | 123 | | int count = collection.Count; |
| | 3 | 124 | | if (count == 0) |
| | 1 | 125 | | { |
| | 1 | 126 | | _innerArray = _emptyArray; |
| | 1 | 127 | | _offset = 0; |
| | 1 | 128 | | } |
| | | 129 | | else |
| | 2 | 130 | | { |
| | 2 | 131 | | int capacity = SwiftHashTools.NextPowerOfTwo(count <= DefaultCapacity ? DefaultCapacity : count); |
| | 2 | 132 | | _innerArray = new T[capacity]; |
| | 2 | 133 | | _offset = (capacity - count) >> 1; |
| | 2 | 134 | | collection.CopyTo(_innerArray, _offset); |
| | 2 | 135 | | Array.Sort(_innerArray, _offset, count, _comparer); |
| | 2 | 136 | | _count = count; |
| | 2 | 137 | | } |
| | 3 | 138 | | } |
| | | 139 | | else |
| | 1 | 140 | | { |
| | 1 | 141 | | _innerArray = new T[DefaultCapacity]; |
| | 1 | 142 | | _offset = DefaultCapacity >> 1; |
| | 1 | 143 | | AddRange(items); // Will handle capacity increases as needed |
| | 1 | 144 | | } |
| | 4 | 145 | | } |
| | | 146 | | |
| | | 147 | | /// <summary> |
| | | 148 | | /// Initializes a new instance of the <see cref="SwiftSortedList{T}"/> class with the specified <see cref="SwiftArr |
| | | 149 | | /// </summary> |
| | | 150 | | /// <param name="state">The state containing the internal array, count, offset, and version for initialization.</pa |
| | | 151 | | [MemoryPackConstructor] |
| | 4 | 152 | | public SwiftSortedList(SwiftArrayState<T> state) |
| | 4 | 153 | | { |
| | 4 | 154 | | State = state; |
| | 4 | 155 | | } |
| | | 156 | | |
| | | 157 | | #endregion |
| | | 158 | | |
| | | 159 | | #region Properties |
| | | 160 | | |
| | | 161 | | [JsonIgnore] |
| | | 162 | | [MemoryPackIgnore] |
| | 9 | 163 | | public T[] InnerArray => _innerArray; |
| | | 164 | | |
| | | 165 | | /// <inheritdoc cref="_count"/> |
| | | 166 | | [JsonIgnore] |
| | | 167 | | [MemoryPackIgnore] |
| | 16 | 168 | | public int Count => _count; |
| | | 169 | | |
| | | 170 | | /// <inheritdoc cref="_offset"/> |
| | | 171 | | [JsonIgnore] |
| | | 172 | | [MemoryPackIgnore] |
| | 12 | 173 | | public int Offset => _offset; |
| | | 174 | | |
| | | 175 | | /// <inheritdoc cref="_version"/> |
| | | 176 | | [JsonIgnore] |
| | | 177 | | [MemoryPackIgnore] |
| | 5 | 178 | | public uint Version => _version; |
| | | 179 | | |
| | | 180 | | /// <summary> |
| | | 181 | | /// Gets the current capacity of the internal array. |
| | | 182 | | /// </summary> |
| | | 183 | | [JsonIgnore] |
| | | 184 | | [MemoryPackIgnore] |
| | 7 | 185 | | public int Capacity => _innerArray.Length; |
| | | 186 | | |
| | | 187 | | /// <inheritdoc cref="_comparer"/> |
| | | 188 | | [JsonIgnore] |
| | | 189 | | [MemoryPackIgnore] |
| | 1 | 190 | | public IComparer<T> Comparer => _comparer; |
| | | 191 | | |
| | | 192 | | [JsonIgnore] |
| | | 193 | | [MemoryPackIgnore] |
| | 1 | 194 | | bool ICollection<T>.IsReadOnly => false; |
| | | 195 | | |
| | | 196 | | [JsonIgnore] |
| | | 197 | | [MemoryPackIgnore] |
| | 1 | 198 | | public bool IsSynchronized => false; |
| | | 199 | | |
| | | 200 | | [JsonIgnore] |
| | | 201 | | [MemoryPackIgnore] |
| | 1 | 202 | | object ICollection.SyncRoot => _syncRoot ??= new object(); |
| | | 203 | | |
| | | 204 | | /// <summary> |
| | | 205 | | /// Gets the element at the specified arrayIndex. |
| | | 206 | | /// </summary> |
| | | 207 | | [JsonIgnore] |
| | | 208 | | [MemoryPackIgnore] |
| | | 209 | | public T this[int index] |
| | | 210 | | { |
| | | 211 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 212 | | get |
| | 2 | 213 | | { |
| | 3 | 214 | | if ((uint)index >= (uint)_count) throw new ArgumentOutOfRangeException(nameof(index)); |
| | 1 | 215 | | return _innerArray[GetPhysicalIndex(index)]; |
| | 1 | 216 | | } |
| | | 217 | | } |
| | | 218 | | |
| | | 219 | | [JsonInclude] |
| | | 220 | | [MemoryPackInclude] |
| | | 221 | | public SwiftArrayState<T> State |
| | | 222 | | { |
| | | 223 | | get |
| | 3 | 224 | | { |
| | 3 | 225 | | var items = new T[_count]; |
| | 3 | 226 | | Array.Copy(_innerArray, _offset, items, 0, _count); |
| | 3 | 227 | | return new SwiftArrayState<T>(items); |
| | 3 | 228 | | } |
| | | 229 | | internal set |
| | 4 | 230 | | { |
| | 4 | 231 | | int count = value.Items?.Length ?? 0; |
| | | 232 | | |
| | 4 | 233 | | if (count == 0) |
| | 1 | 234 | | { |
| | 1 | 235 | | _innerArray = _emptyArray; |
| | 1 | 236 | | _offset = 0; |
| | 1 | 237 | | _count = 0; |
| | 1 | 238 | | } |
| | | 239 | | else |
| | 3 | 240 | | { |
| | 3 | 241 | | int capacity = SwiftHashTools.NextPowerOfTwo(count <= DefaultCapacity ? DefaultCapacity : count); |
| | 3 | 242 | | _innerArray = new T[capacity]; |
| | | 243 | | |
| | 3 | 244 | | int newOffset = (capacity - count) >> 1; |
| | | 245 | | |
| | 3 | 246 | | Array.Copy(value.Items, 0, _innerArray, newOffset, count); |
| | | 247 | | |
| | 3 | 248 | | _offset = newOffset; |
| | 3 | 249 | | _count = count; |
| | 3 | 250 | | } |
| | | 251 | | |
| | 4 | 252 | | _version = 0; |
| | 4 | 253 | | _comparer = Comparer<T>.Default; |
| | 4 | 254 | | } |
| | | 255 | | } |
| | | 256 | | |
| | | 257 | | #endregion |
| | | 258 | | |
| | | 259 | | #region Collection Manipulation |
| | | 260 | | |
| | | 261 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 262 | | public void Add(T item) |
| | 80 | 263 | | { |
| | 80 | 264 | | int index = Search(item); |
| | 159 | 265 | | if (index < 0) index = ~index; |
| | 80 | 266 | | Insert(item, index); |
| | 80 | 267 | | } |
| | | 268 | | |
| | | 269 | | /// <summary> |
| | | 270 | | /// Inserts an item into the internal array at the specified arrayIndex, shifting elements as needed. |
| | | 271 | | /// </summary> |
| | | 272 | | private void Insert(T item, int index) |
| | 80 | 273 | | { |
| | 80 | 274 | | if ((uint)index > (uint)_count) throw new ArgumentOutOfRangeException(nameof(index)); |
| | 80 | 275 | | if (_offset + _count + 1 > _innerArray.Length) |
| | 28 | 276 | | Resize(_innerArray.Length * 2); |
| | | 277 | | |
| | 80 | 278 | | int physicalIndex = GetPhysicalIndex(index); |
| | | 279 | | |
| | 80 | 280 | | if (index < (uint)_count) |
| | 25 | 281 | | { |
| | 25 | 282 | | int distanceToHead = physicalIndex - _offset; |
| | 25 | 283 | | int distanceToTail = (_offset + _count - 1) - physicalIndex; |
| | | 284 | | |
| | 25 | 285 | | if (distanceToHead >= (uint)distanceToTail) |
| | 21 | 286 | | { |
| | 21 | 287 | | if ((uint)_offset == 0) |
| | 0 | 288 | | { |
| | | 289 | | // Ensure capacity for recentering |
| | 0 | 290 | | Resize(_innerArray.Length * 2); |
| | 0 | 291 | | RecenterArray(); |
| | 0 | 292 | | physicalIndex = GetPhysicalIndex(index); |
| | 0 | 293 | | } |
| | | 294 | | |
| | 21 | 295 | | _offset--; |
| | 21 | 296 | | physicalIndex--; |
| | | 297 | | // Shift elements towards the head (left) |
| | 21 | 298 | | Array.Copy(_innerArray, _offset + 1, _innerArray, _offset, distanceToHead + 1); |
| | 21 | 299 | | } |
| | | 300 | | else // Shift elements towards the tail (right) to make space |
| | 4 | 301 | | Array.Copy(_innerArray, physicalIndex, _innerArray, physicalIndex + 1, _count - index); |
| | 25 | 302 | | } |
| | | 303 | | |
| | 80 | 304 | | _innerArray[physicalIndex] = item; |
| | 80 | 305 | | _count++; |
| | | 306 | | |
| | 80 | 307 | | _version++; |
| | 80 | 308 | | } |
| | | 309 | | |
| | | 310 | | /// <summary> |
| | | 311 | | /// Adds a range of elements to the collection, ensuring they are sorted and merged efficiently. |
| | | 312 | | /// </summary> |
| | | 313 | | /// <remarks> |
| | | 314 | | /// This will compact the array for efficiency. |
| | | 315 | | /// </remarks> |
| | | 316 | | public void AddRange(IEnumerable<T> items) |
| | 23 | 317 | | { |
| | 23 | 318 | | SwiftThrowHelper.ThrowIfNull(items, nameof(items)); |
| | | 319 | | |
| | | 320 | | // Convert items to a sorted array |
| | | 321 | | T[] sortedItems; |
| | | 322 | | |
| | 23 | 323 | | if (items is ICollection<T> collection) |
| | 21 | 324 | | { |
| | 22 | 325 | | if (collection.Count == 0) return; |
| | | 326 | | |
| | 20 | 327 | | sortedItems = new T[collection.Count]; |
| | 20 | 328 | | collection.CopyTo(sortedItems, 0); |
| | 20 | 329 | | } |
| | | 330 | | else |
| | 2 | 331 | | { |
| | 2 | 332 | | sortedItems = items.ToArray(); |
| | 3 | 333 | | if (sortedItems.Length == 0) return; |
| | 1 | 334 | | } |
| | | 335 | | |
| | 21 | 336 | | Array.Sort(sortedItems, 0, sortedItems.Length, _comparer); |
| | | 337 | | |
| | 21 | 338 | | if ((uint)_count == 0) |
| | 18 | 339 | | { |
| | | 340 | | // If the list is empty, initialize with the sorted items |
| | 18 | 341 | | int initialCapacity = SwiftHashTools.NextPowerOfTwo(sortedItems.Length < DefaultCapacity ? DefaultCapacity : |
| | 18 | 342 | | int newOffset = (initialCapacity - sortedItems.Length) >> 1; |
| | 34 | 343 | | if ((uint)_innerArray.Length < initialCapacity) _innerArray = new T[initialCapacity]; |
| | 18 | 344 | | Array.Copy(sortedItems, 0, _innerArray, newOffset, sortedItems.Length); |
| | 18 | 345 | | _offset = newOffset; |
| | 18 | 346 | | _count = sortedItems.Length; |
| | 18 | 347 | | _version++; |
| | 18 | 348 | | return; |
| | | 349 | | } |
| | | 350 | | |
| | | 351 | | // Merge the sorted arrays |
| | 3 | 352 | | int newCount = _count + sortedItems.Length; |
| | 3 | 353 | | int totalRequiredCapacity = newCount + _offset; |
| | | 354 | | |
| | | 355 | | // Determine new capacity and offset |
| | 3 | 356 | | int newCapacity = SwiftHashTools.NextPowerOfTwo(totalRequiredCapacity); |
| | 3 | 357 | | int mergedOffset = (newCapacity - newCount) >> 1; |
| | | 358 | | |
| | | 359 | | // Create a new array with the new capacity |
| | 3 | 360 | | T[] newArray = new T[newCapacity]; |
| | | 361 | | |
| | | 362 | | // Merge existing items and new items into newArray |
| | 3 | 363 | | int existingIndex = 0; |
| | 3 | 364 | | int newItemsIndex = 0; |
| | 3 | 365 | | int mergedIndex = mergedOffset; |
| | | 366 | | |
| | 13 | 367 | | while (existingIndex < _count && newItemsIndex < sortedItems.Length) |
| | 10 | 368 | | { |
| | 10 | 369 | | T existingItem = _innerArray[_offset + existingIndex]; |
| | 10 | 370 | | T newItem = sortedItems[newItemsIndex]; |
| | | 371 | | |
| | 10 | 372 | | if (_comparer.Compare(existingItem, newItem) <= 0) |
| | 4 | 373 | | { |
| | 4 | 374 | | newArray[mergedIndex++] = existingItem; |
| | 4 | 375 | | existingIndex++; |
| | 4 | 376 | | } |
| | | 377 | | else |
| | 6 | 378 | | { |
| | 6 | 379 | | newArray[mergedIndex++] = newItem; |
| | 6 | 380 | | newItemsIndex++; |
| | 6 | 381 | | } |
| | 10 | 382 | | } |
| | | 383 | | |
| | | 384 | | // Copy any remaining existing items |
| | 4 | 385 | | while (existingIndex < _count) |
| | 1 | 386 | | newArray[mergedIndex++] = _innerArray[_offset + existingIndex++]; |
| | | 387 | | |
| | | 388 | | // Copy any remaining new items |
| | 7 | 389 | | while (newItemsIndex < sortedItems.Length) |
| | 4 | 390 | | newArray[mergedIndex++] = sortedItems[newItemsIndex++]; |
| | | 391 | | |
| | | 392 | | // Set the new array and update the offset |
| | 3 | 393 | | _innerArray = newArray; |
| | 3 | 394 | | _offset = mergedOffset; |
| | 3 | 395 | | _count = newCount; |
| | | 396 | | |
| | 3 | 397 | | _version++; |
| | 23 | 398 | | } |
| | | 399 | | |
| | | 400 | | /// <summary> |
| | | 401 | | /// Removes and returns the minimum element in the sorter. |
| | | 402 | | /// </summary> |
| | | 403 | | /// <returns>The minimum element.</returns> |
| | | 404 | | public T PopMin() |
| | 3 | 405 | | { |
| | 4 | 406 | | if ((uint)_count == 0) throw new IndexOutOfRangeException(); |
| | | 407 | | |
| | 2 | 408 | | int index = GetPhysicalIndex(0); |
| | 2 | 409 | | T ret = _innerArray[index]; |
| | 2 | 410 | | _innerArray[index] = default; |
| | 2 | 411 | | _count--; |
| | | 412 | | // Increment _offset as we remove from the front |
| | 2 | 413 | | _offset = _count == 0 ? _innerArray.Length >> 1 : _offset + 1; |
| | | 414 | | |
| | 2 | 415 | | _version++; |
| | | 416 | | |
| | 2 | 417 | | return ret; |
| | 2 | 418 | | } |
| | | 419 | | |
| | | 420 | | /// <summary> |
| | | 421 | | /// Removes and returns the maximum element in the sorter. |
| | | 422 | | /// </summary> |
| | | 423 | | /// <returns>The maximum element.</returns> |
| | | 424 | | public T PopMax() |
| | 3 | 425 | | { |
| | 4 | 426 | | if ((uint)_count == 0) throw new IndexOutOfRangeException(); |
| | | 427 | | |
| | 2 | 428 | | int index = GetPhysicalIndex(--_count); |
| | 2 | 429 | | T ret = _innerArray[index]; |
| | 2 | 430 | | _innerArray[index] = default; |
| | 3 | 431 | | if ((uint)_count == 0) _offset = _innerArray.Length >> 1; |
| | | 432 | | |
| | 2 | 433 | | _version++; |
| | | 434 | | |
| | 2 | 435 | | return ret; |
| | 2 | 436 | | } |
| | | 437 | | |
| | | 438 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 439 | | public bool Remove(T item) |
| | 10 | 440 | | { |
| | 11 | 441 | | if ((uint)_count == 0) return false; |
| | | 442 | | |
| | 9 | 443 | | int index = Search(item); |
| | 11 | 444 | | if (index < 0) return false; |
| | | 445 | | |
| | 7 | 446 | | RemoveAt(index); |
| | 7 | 447 | | return true; |
| | 10 | 448 | | } |
| | | 449 | | |
| | | 450 | | /// <summary> |
| | | 451 | | /// Removes the element at the specified arrayIndex from the sorted list. |
| | | 452 | | /// Shifts elements as needed to maintain the sorted order and efficient space utilization. |
| | | 453 | | /// </summary> |
| | | 454 | | /// <param name="index">The zero-based arrayIndex of the element to remove.</param> |
| | | 455 | | public void RemoveAt(int index) |
| | 10 | 456 | | { |
| | 10 | 457 | | if ((uint)index >= (uint)_count) throw new ArgumentOutOfRangeException(nameof(index)); |
| | | 458 | | |
| | 10 | 459 | | int physicalIndex = GetPhysicalIndex(index); |
| | | 460 | | |
| | 10 | 461 | | _count--; |
| | 10 | 462 | | if ((uint)index < (uint)_count) |
| | 7 | 463 | | { |
| | 7 | 464 | | int distanceToHead = physicalIndex - _offset; |
| | 7 | 465 | | int distanceToTail = (_offset + _count) - physicalIndex; |
| | | 466 | | |
| | 7 | 467 | | if (distanceToHead < distanceToTail) |
| | 6 | 468 | | { |
| | | 469 | | // Shift elements towards the tail (right) to fill the gap |
| | 6 | 470 | | Array.Copy(_innerArray, _offset, _innerArray, _offset + 1, distanceToHead); |
| | 6 | 471 | | _offset++; // Adjust offset since we've moved elements towards the tail |
| | 6 | 472 | | } |
| | | 473 | | else |
| | 1 | 474 | | { |
| | | 475 | | // Shift elements towards the head (left) to fill the gap |
| | 1 | 476 | | Array.Copy(_innerArray, physicalIndex + 1, _innerArray, physicalIndex, distanceToTail); |
| | 1 | 477 | | _innerArray[GetPhysicalIndex(_count)] = default; // Clear the last element |
| | 1 | 478 | | } |
| | 7 | 479 | | } |
| | | 480 | | else // Removing the last element; simply clear it |
| | 3 | 481 | | _innerArray[GetPhysicalIndex(_count)] = default; |
| | | 482 | | |
| | | 483 | | // Only recenter if offset is non-zero and count is less than 25% of capacity |
| | 10 | 484 | | if (_offset != 0 && (uint)_count < _innerArray.Length * 0.25) |
| | 1 | 485 | | { |
| | 1 | 486 | | if ((uint)_count == 0) |
| | 0 | 487 | | _offset = _innerArray.Length >> 1; // Reset offset to the middle when list is empty |
| | | 488 | | else |
| | 1 | 489 | | RecenterArray(); |
| | 1 | 490 | | } |
| | | 491 | | |
| | 10 | 492 | | _version++; |
| | 10 | 493 | | } |
| | | 494 | | |
| | | 495 | | public void Clear() |
| | 2 | 496 | | { |
| | 3 | 497 | | if ((uint)_count == 0) return; |
| | 1 | 498 | | Array.Clear(_innerArray, _offset, _count); |
| | 1 | 499 | | _count = 0; |
| | 1 | 500 | | _offset = _innerArray.Length == 0 ? 0 : _innerArray.Length >> 1; // Reset _offset to the middle of the array |
| | | 501 | | |
| | 1 | 502 | | _version++; |
| | 2 | 503 | | } |
| | | 504 | | |
| | | 505 | | /// <summary> |
| | | 506 | | /// Quickly clears the list by resetting the count and offset without modifying the internal array. |
| | | 507 | | /// Note: This leaves references in the internal array, which may prevent garbage collection of reference types. |
| | | 508 | | /// Use when performance is critical and you are certain that residual references are acceptable. |
| | | 509 | | /// </summary> |
| | | 510 | | public void FastClear() |
| | 2 | 511 | | { |
| | 3 | 512 | | if ((uint)_count == 0) return; |
| | 1 | 513 | | _count = 0; |
| | 1 | 514 | | _offset = _innerArray.Length == 0 ? 0 : _innerArray.Length >> 1; // Reset offset to middle |
| | | 515 | | |
| | 1 | 516 | | _version++; |
| | 2 | 517 | | } |
| | | 518 | | |
| | | 519 | | #endregion |
| | | 520 | | |
| | | 521 | | #region Capacity Management |
| | | 522 | | |
| | | 523 | | /// <summary> |
| | | 524 | | /// Ensures that the capacity of <see cref="SwiftSortedList{T}"/> is sufficient to accommodate the specified number |
| | | 525 | | /// The capacity can increase by double to balance memory allocation efficiency and space. |
| | | 526 | | /// </summary> |
| | | 527 | | public void EnsureCapacity(int capacity) |
| | 1 | 528 | | { |
| | 1 | 529 | | capacity = SwiftHashTools.NextPowerOfTwo(capacity); |
| | 1 | 530 | | if (capacity > _innerArray.Length) |
| | 1 | 531 | | Resize(capacity); |
| | 1 | 532 | | } |
| | | 533 | | |
| | | 534 | | /// <summary> |
| | | 535 | | /// Ensures that the capacity of <see cref="SwiftSortedList{T}"/> is sufficient to accommodate the specified number |
| | | 536 | | /// The capacity can increase by double to balance memory allocation efficiency and space. |
| | | 537 | | /// </summary> |
| | | 538 | | private void Resize(int newSize) |
| | 29 | 539 | | { |
| | 29 | 540 | | int newCapacity = newSize <= DefaultCapacity ? DefaultCapacity : newSize; |
| | | 541 | | |
| | 29 | 542 | | T[] newArray = new T[newCapacity]; |
| | 29 | 543 | | int newOffset = (newArray.Length - _count) >> 1; // Center the elements in the new array |
| | 29 | 544 | | if ((uint)_count > 0) |
| | 2 | 545 | | Array.Copy(_innerArray, _offset, newArray, newOffset, _count); |
| | | 546 | | |
| | 29 | 547 | | _innerArray = newArray; |
| | 29 | 548 | | _offset = newOffset; |
| | | 549 | | |
| | 29 | 550 | | _version++; |
| | 29 | 551 | | } |
| | | 552 | | |
| | | 553 | | /// <summary> |
| | | 554 | | /// Recenters the elements within the internal array to balance available space on both ends. |
| | | 555 | | /// This minimizes the need for shifting elements during future insertions and deletions. |
| | | 556 | | /// </summary> |
| | | 557 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 558 | | private void RecenterArray() |
| | 1 | 559 | | { |
| | 1 | 560 | | int newOffset = (_innerArray.Length - _count) >> 1; |
| | 1 | 561 | | Array.Copy(_innerArray, _offset, _innerArray, newOffset, _count); |
| | 1 | 562 | | _offset = newOffset; |
| | | 563 | | |
| | 1 | 564 | | _version++; |
| | 1 | 565 | | } |
| | | 566 | | |
| | | 567 | | #endregion |
| | | 568 | | |
| | | 569 | | #region Utility Methods |
| | | 570 | | |
| | | 571 | | /// <summary> |
| | | 572 | | /// Sets a new comparer for the sorted list and re-sorts the elements. |
| | | 573 | | /// </summary> |
| | | 574 | | /// <param name="comparer">The new comparer to use.</param> |
| | | 575 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 576 | | public void SetComparer(IComparer<T> comparer) |
| | 2 | 577 | | { |
| | 2 | 578 | | SwiftThrowHelper.ThrowIfNull(comparer, nameof(comparer)); |
| | 2 | 579 | | if (ReferenceEquals(comparer, _comparer)) |
| | 1 | 580 | | return; |
| | | 581 | | |
| | 1 | 582 | | _comparer = comparer; |
| | 1 | 583 | | Array.Sort(_innerArray, _offset, _count, _comparer); |
| | 1 | 584 | | _version++; |
| | 2 | 585 | | } |
| | | 586 | | |
| | | 587 | | /// <summary> |
| | | 588 | | /// Converts a logical arrayIndex within the list to the corresponding physical arrayIndex in the internal array. |
| | | 589 | | /// </summary> |
| | | 590 | | /// <param name="logicalIndex">The logical arrayIndex within the list.</param> |
| | | 591 | | /// <returns>The physical arrayIndex within the internal array.</returns> |
| | | 592 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 305 | 593 | | private int GetPhysicalIndex(int logicalIndex) => _offset + logicalIndex; |
| | | 594 | | |
| | | 595 | | /// <summary> |
| | | 596 | | /// Returns a read-only span over the populated sorted portion of the list. |
| | | 597 | | /// </summary> |
| | | 598 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 4 | 599 | | public ReadOnlySpan<T> AsReadOnlySpan() => _innerArray.AsSpan(_offset, _count); |
| | | 600 | | |
| | | 601 | | /// <summary> |
| | | 602 | | /// Returns the minimum element in the sorter without removing it. |
| | | 603 | | /// </summary> |
| | | 604 | | /// <returns>The minimum element.</returns> |
| | | 605 | | public T PeekMin() |
| | 16 | 606 | | { |
| | 17 | 607 | | if ((uint)_count == 0) throw new IndexOutOfRangeException(); |
| | 15 | 608 | | return _innerArray[GetPhysicalIndex(0)]; |
| | 15 | 609 | | } |
| | | 610 | | |
| | | 611 | | /// <summary> |
| | | 612 | | /// Returns the maximum element in the sorter without removing it. |
| | | 613 | | /// </summary> |
| | | 614 | | /// <returns>The maximum element.</returns> |
| | | 615 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 616 | | public T PeekMax() |
| | 14 | 617 | | { |
| | 15 | 618 | | if ((uint)_count == 0) throw new IndexOutOfRangeException(); |
| | 13 | 619 | | return _innerArray[GetPhysicalIndex(_count - 1)]; |
| | 13 | 620 | | } |
| | | 621 | | |
| | | 622 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 2 | 623 | | public bool Contains(T item) => Search(item) >= 0; |
| | | 624 | | |
| | | 625 | | /// <summary> |
| | | 626 | | /// Determines whether the <see cref="SwiftSortedList{T}"/> contains an element that matches the conditions defined |
| | | 627 | | /// </summary> |
| | | 628 | | /// <param name="match">The predicate that defines the conditions of the element to search for.</param> |
| | | 629 | | /// <returns><c>true</c> if the <see cref="SwiftSortedList{T}"/> contains one or more elements that match the specif |
| | | 630 | | public bool Exists(Predicate<T> match) |
| | 3 | 631 | | { |
| | 3 | 632 | | SwiftThrowHelper.ThrowIfNull(match, nameof(match)); |
| | | 633 | | |
| | 14 | 634 | | for (int i = 0; i < _count; i++) |
| | 6 | 635 | | { |
| | 6 | 636 | | if (match(_innerArray[GetPhysicalIndex(i)])) |
| | 1 | 637 | | return true; |
| | 5 | 638 | | } |
| | | 639 | | |
| | 1 | 640 | | return false; |
| | 2 | 641 | | } |
| | | 642 | | |
| | | 643 | | /// <summary> |
| | | 644 | | /// Searches for an element that matches the conditions defined by the specified predicate, and returns the first ma |
| | | 645 | | /// </summary> |
| | | 646 | | /// <param name="match">The predicate that defines the conditions of the element to search for.</param> |
| | | 647 | | /// <returns>The first element that matches the conditions defined by the specified predicate, if found; otherwise, |
| | | 648 | | public T Find(Predicate<T> match) |
| | 2 | 649 | | { |
| | 2 | 650 | | SwiftThrowHelper.ThrowIfNull(match, nameof(match)); |
| | | 651 | | |
| | 16 | 652 | | for (int i = 0; i < _count; i++) |
| | 7 | 653 | | { |
| | 7 | 654 | | T item = _innerArray[GetPhysicalIndex(i)]; |
| | 7 | 655 | | if (match(item)) |
| | 1 | 656 | | return item; |
| | 6 | 657 | | } |
| | | 658 | | |
| | 1 | 659 | | return default; |
| | 2 | 660 | | } |
| | | 661 | | |
| | | 662 | | /// <summary> |
| | | 663 | | /// Searches for the specified item in the sorted collection and returns the arrayIndex of the first occurrence. |
| | | 664 | | /// </summary> |
| | | 665 | | /// <param name="item">The item to search for.</param> |
| | | 666 | | /// <returns>The zero-based arrayIndex of the item if found; otherwise, -1.</returns> |
| | | 667 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 668 | | public int IndexOf(T item) |
| | 2 | 669 | | { |
| | 2 | 670 | | int index = Search(item); |
| | 2 | 671 | | return index >= 0 ? index : -1; |
| | 2 | 672 | | } |
| | | 673 | | |
| | | 674 | | /// <summary> |
| | | 675 | | /// Determines the insertion point for a specified item in the collection. |
| | | 676 | | /// The insertion point is the arrayIndex where the item would be inserted if it were not already present. |
| | | 677 | | /// </summary> |
| | | 678 | | /// <param name="item">The item for which to find the insertion point.</param> |
| | | 679 | | /// <returns>The insertion point as a zero-based arrayIndex.</returns> |
| | | 680 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 681 | | public int InsertionPoint(T item) |
| | 1 | 682 | | { |
| | 1 | 683 | | int index = Search(item); |
| | 1 | 684 | | return index >= 0 ? index : ~index; |
| | 1 | 685 | | } |
| | | 686 | | |
| | | 687 | | /// <summary> |
| | | 688 | | /// Searches for the specified item in the sorted collection. |
| | | 689 | | /// </summary> |
| | | 690 | | /// <param name="item">The item to search for.</param> |
| | | 691 | | /// <returns> |
| | | 692 | | /// The arrayIndex of the item if found or where the item should be inserted if not found. |
| | | 693 | | /// </returns> |
| | | 694 | | public int Search(T item) |
| | 95 | 695 | | { |
| | 95 | 696 | | int low = 0; |
| | 95 | 697 | | int high = _count - 1; |
| | 221 | 698 | | while ((uint)low <= high) |
| | 137 | 699 | | { |
| | 137 | 700 | | int mid = low + ((high - low) >> 1); |
| | 137 | 701 | | T midItem = _innerArray[GetPhysicalIndex(mid)]; |
| | 137 | 702 | | int cmp = _comparer.Compare(midItem, item); |
| | 137 | 703 | | if ((uint)cmp == 0) |
| | 11 | 704 | | return mid; // Exact match found |
| | | 705 | | |
| | 126 | 706 | | if (cmp < 0) |
| | 89 | 707 | | low = mid + 1; // Search in the right half |
| | | 708 | | else |
| | 37 | 709 | | high = mid - 1; // Search in the left half |
| | 126 | 710 | | } |
| | 84 | 711 | | return ~low; // Item not found, should be inserted at arrayIndex low |
| | 95 | 712 | | } |
| | | 713 | | |
| | | 714 | | public void CopyTo(T[] array, int arrayIndex) |
| | 2 | 715 | | { |
| | 2 | 716 | | SwiftThrowHelper.ThrowIfNull(array, nameof(array)); |
| | 2 | 717 | | if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); |
| | 3 | 718 | | if (array.Length - arrayIndex < _count) throw new ArgumentException("The target array is too small.", nameof(arr |
| | | 719 | | |
| | 1 | 720 | | Array.Copy(_innerArray, _offset, array, arrayIndex, _count); |
| | 1 | 721 | | } |
| | | 722 | | |
| | | 723 | | public void CopyTo(Array array, int arrayIndex) |
| | 2 | 724 | | { |
| | 2 | 725 | | SwiftThrowHelper.ThrowIfNull(array, nameof(array)); |
| | 2 | 726 | | if ((uint)arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); |
| | 3 | 727 | | if (array.Length - arrayIndex < _count) throw new ArgumentException("The target array is too small.", nameof(arr |
| | | 728 | | |
| | 1 | 729 | | Array.Copy(_innerArray, _offset, array, arrayIndex, _count); |
| | 1 | 730 | | } |
| | | 731 | | |
| | | 732 | | public void CloneTo(ICollection<T> output) |
| | 2 | 733 | | { |
| | 3 | 734 | | if (output == null) throw new ArgumentNullException(nameof(output)); |
| | 1 | 735 | | output.Clear(); |
| | | 736 | | |
| | 9 | 737 | | foreach (var item in this) |
| | 3 | 738 | | output.Add(item); |
| | 1 | 739 | | } |
| | | 740 | | |
| | | 741 | | #endregion |
| | | 742 | | |
| | | 743 | | #region Enumerators |
| | | 744 | | |
| | | 745 | | /// <summary> |
| | | 746 | | /// Returns an enumerator that iterates through <see cref="SwiftSortedList{T}"/>. |
| | | 747 | | /// </summary> |
| | 19 | 748 | | public SwiftSorterEnumerator GetEnumerator() => new SwiftSorterEnumerator(this); |
| | 12 | 749 | | IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator(); |
| | 2 | 750 | | IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); |
| | | 751 | | |
| | | 752 | | public struct SwiftSorterEnumerator : IEnumerator<T>, IEnumerator, IDisposable |
| | | 753 | | { |
| | | 754 | | private readonly SwiftSortedList<T> _list; |
| | | 755 | | private readonly uint _count; |
| | | 756 | | private readonly uint _version; |
| | | 757 | | private int _index; |
| | | 758 | | |
| | | 759 | | private T _current; |
| | | 760 | | |
| | | 761 | | public SwiftSorterEnumerator(SwiftSortedList<T> sortedList) |
| | 19 | 762 | | { |
| | 19 | 763 | | _list = sortedList; |
| | 19 | 764 | | _count = (uint)sortedList._count; |
| | 19 | 765 | | _version = sortedList._version; |
| | 19 | 766 | | _index = 0; |
| | 19 | 767 | | _current = default; |
| | 19 | 768 | | } |
| | | 769 | | |
| | 36 | 770 | | public T Current => _current; |
| | | 771 | | |
| | | 772 | | object IEnumerator.Current |
| | | 773 | | { |
| | | 774 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 775 | | get |
| | 2 | 776 | | { |
| | 3 | 777 | | if ((uint)_index > _count) throw new InvalidOperationException("Bad enumeration"); |
| | 1 | 778 | | return _current; |
| | 1 | 779 | | } |
| | | 780 | | |
| | | 781 | | } |
| | | 782 | | |
| | | 783 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 784 | | public bool MoveNext() |
| | 44 | 785 | | { |
| | 44 | 786 | | if (_version != _list._version) |
| | 0 | 787 | | throw new InvalidOperationException("Enumerator modified outside of enumeration!"); |
| | | 788 | | |
| | 44 | 789 | | if (_index < _count) |
| | 28 | 790 | | { |
| | 28 | 791 | | _current = _list._innerArray[_list.GetPhysicalIndex(_index)]; |
| | 28 | 792 | | _index++; |
| | 28 | 793 | | return true; |
| | | 794 | | } |
| | | 795 | | |
| | 16 | 796 | | _index = _list._count + 1; |
| | 16 | 797 | | _current = default; |
| | 16 | 798 | | return false; |
| | 44 | 799 | | } |
| | | 800 | | |
| | | 801 | | public void Reset() |
| | 2 | 802 | | { |
| | 2 | 803 | | if (_version != _list._version) |
| | 1 | 804 | | throw new InvalidOperationException("Enumerator modified outside of enumeration!"); |
| | | 805 | | |
| | 1 | 806 | | _index = 0; |
| | 1 | 807 | | _current = default; |
| | 1 | 808 | | } |
| | | 809 | | |
| | 30 | 810 | | public void Dispose() { } |
| | | 811 | | } |
| | | 812 | | |
| | | 813 | | #endregion |
| | | 814 | | } |