< Summary

Line coverage
98%
Covered lines: 250
Uncovered lines: 3
Coverable lines: 253
Total lines: 856
Line coverage: 98.8%
Branch coverage
94%
Covered branches: 74
Total branches: 78
Branch coverage: 94.8%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
File 1: .cctor()100%11100%
File 2: .cctor()100%11100%
File 2: .ctor()100%11100%
File 2: .ctor(...)100%44100%
File 2: .ctor(...)100%44100%
File 2: .ctor(...)100%11100%
File 2: get_InnerArray()100%11100%
File 2: get_Capacity()100%11100%
File 2: get_Count()100%11100%
File 2: get_IsReadOnly()100%11100%
File 2: get_IsSynchronized()100%11100%
File 2: get_SyncRoot()100%22100%
File 2: get_IsFixedSize()100%11100%
File 2: System.Collections.IList.get_Item(...)50%22100%
File 2: System.Collections.IList.set_Item(...)100%11100%
File 2: get_Item(...)100%11100%
File 2: set_Item(...)100%11100%
File 2: get_State()100%11100%
File 2: set_State(...)100%44100%
File 2: Add(...)100%22100%
File 2: System.Collections.IList.Add(...)100%11100%
File 2: AddRange(...)83.33%6683.33%
File 2: AddRange(...)100%11100%
File 2: AddRange(...)100%44100%
File 2: Remove(...)100%22100%
File 2: System.Collections.IList.Remove(...)100%11100%
File 2: RemoveAt(...)100%22100%
File 2: RemoveAll(...)100%22100%
File 2: IndexOfFirstMatch(...)100%44100%
File 2: CompactUnmatchedItems(...)100%44100%
File 2: ClearReleasedSlots(...)100%44100%
File 2: Insert(...)75%4488.88%
File 2: System.Collections.IList.Insert(...)100%11100%
File 2: Reverse()100%11100%
File 2: Sort()100%11100%
File 2: Sort(...)100%11100%
File 2: Clear()100%22100%
File 2: FastClear()100%11100%
File 2: EnsureCapacity(...)100%22100%
File 2: Resize(...)100%44100%
File 2: TrimExcessCapacity()100%22100%
File 2: IndexOf(...)100%11100%
File 2: System.Collections.IList.IndexOf(...)100%11100%
File 2: ToArray()100%11100%
File 2: AsSpan()100%11100%
File 2: AsReadOnlySpan()100%11100%
File 2: ToString()75%44100%
File 2: Contains(...)100%11100%
File 2: Exists(...)100%44100%
File 2: Find(...)100%44100%
File 2: System.Collections.IList.Contains(...)100%11100%
File 2: Swap(...)100%11100%
File 2: CopyTo(...)100%22100%
File 2: CopyTo(...)100%11100%
File 2: CopyTo(...)100%11100%
File 2: CopyTo(...)100%11100%
File 2: CloneTo(...)100%22100%
File 2: GetEnumerator()100%11100%
File 2: System.Collections.Generic.IEnumerable<T>.GetEnumerator()100%11100%
File 2: System.Collections.IEnumerable.GetEnumerator()100%11100%
File 2: .ctor(...)100%11100%
File 2: get_Current()100%11100%
File 2: System.Collections.IEnumerator.get_Current()100%11100%
File 2: MoveNext()100%22100%
File 2: Reset()100%11100%
File 2: Dispose()100%11100%

File(s)

/_/src/SwiftCollections/obj/Release/net8.0/MemoryPack.Generator/MemoryPack.Generator.MemoryPackGenerator/SwiftCollections.SwiftList_T_.MemoryPackFormatter.g.cs

File '/_/src/SwiftCollections/obj/Release/net8.0/MemoryPack.Generator/MemoryPack.Generator.MemoryPackGenerator/SwiftCollections.SwiftList_T_.MemoryPackFormatter.g.cs' does not exist (any more).

/home/runner/work/SwiftCollections/SwiftCollections/src/SwiftCollections/Collection/SwiftList.cs

#LineLine coverage
 1using Chronicler;
 2using MemoryPack;
 3using System;
 4using System.Collections;
 5using System.Collections.Generic;
 6using System.Runtime.CompilerServices;
 7using System.Text.Json.Serialization;
 8
 9namespace SwiftCollections;
 10
 11/// <summary>
 12/// <c>SwiftList&lt;T&gt;</c> is a high-performance, memory-efficient dynamic list designed to outperform
 13/// traditional generic lists in speed-critical applications.
 14/// <para>
 15/// By utilizing custom growth and
 16/// shrink strategies, SwiftList optimizes memory allocation and minimizes resizing overhead,
 17/// all while maintaining compact storage. With aggressive inlining and optimized algorithms,
 18/// SwiftList delivers faster iteration, insertion, and overall memory management compared to
 19/// standard List. It is ideal for scenarios where predictable performance and minimal
 20/// memory allocations are essential.
 21/// </para>
 22/// <para>
 23/// This implementation is optimized for performance and does not perform versioning checks.
 24/// Modifying the list during enumeration may result in undefined behavior.
 25/// </para>
 26/// </summary>
 27/// <typeparam name="T">Specifies the type of elements in the list.</typeparam>
 28[Serializable]
 29[JsonConverter(typeof(StateJsonConverterFactory))]
 30[MemoryPackable]
 31public partial class SwiftList<T> : IStateBacked<SwiftArrayState<T>>, ISwiftCloneable<T>, IEnumerable<T>, IEnumerable, I
 32{
 33    #region Constants
 34
 35    /// <summary>
 36    /// The default initial capacity of the <see cref="SwiftList{T}"/> if none is specified.
 37    /// Used to allocate a reasonable starting size to minimize resizing operations.
 38    /// </summary>
 39    public const int DefaultCapacity = 8;
 40
 241    private static readonly T[] _emptyArray = Array.Empty<T>();
 242    private static readonly bool _clearReleasedSlots = RuntimeHelpers.IsReferenceOrContainsReferences<T>();
 43
 44    #endregion
 45
 46    #region Fields
 47
 48    /// <summary>
 49    /// The internal array that stores elements of the SwiftList. Resized as needed to
 50    /// accommodate additional elements. Not directly exposed outside the list.
 51    /// </summary>
 52    protected T[] _innerArray;
 53
 54    /// <summary>
 55    /// The current number of elements in the SwiftList. Represents the total count of
 56    /// valid elements stored in the list, also indicating the arrayIndex of the next insertion point.
 57    /// </summary>
 58    protected int _count;
 59
 60    /// <summary>
 61    /// The version of the SwiftList, used to track modifications.
 62    /// </summary>
 63    [NonSerialized]
 64    protected uint _version;
 65
 66    /// <summary>
 67    /// An object that can be used to synchronize access to the SwiftList.
 68    /// </summary>
 69    [NonSerialized]
 70    private object? _syncRoot;
 71
 72    #endregion
 73
 74    #region Constructors
 75
 76    /// <summary>
 77    /// Initializes a new instance of the SwiftList class that is empty and has the default initial capacity.
 78    /// </summary>
 51079    public SwiftList() : this(0) { }
 80
 81    /// <summary>
 82    /// Initializes a new, empty instance of <see cref="SwiftList{T}"/> with the specified initial capacity.
 83    /// </summary>
 48484    public SwiftList(int capacity)
 85    {
 48486        if (capacity == 0)
 25587            _innerArray = _emptyArray;
 88        else
 89        {
 22990            capacity = SwiftHashTools.NextPowerOfTwo(capacity <= DefaultCapacity ? DefaultCapacity : capacity);
 22991            _innerArray = new T[capacity];
 92        }
 22993    }
 94
 95    /// <summary>
 96    /// Initializes a new instance of the <see cref="SwiftList{T}"/> class with elements from the specified collection.
 97    /// The collection must have a known count for optimized memory allocation.
 98    /// </summary>
 99    /// <exception cref="ArgumentException">Thrown if the input collection does not have a known count.</exception>
 13100    public SwiftList(IEnumerable<T> items)
 101    {
 13102        SwiftThrowHelper.ThrowIfNull(items, nameof(items));
 103
 13104        if (items is ICollection<T> collection)
 105        {
 10106            int count = collection.Count;
 10107            if (count == 0)
 1108                _innerArray = _emptyArray;
 109            else
 110            {
 9111                _innerArray = new T[count];
 9112                collection.CopyTo(_innerArray, 0);
 9113                _count = count;
 114            }
 115        }
 116        else
 117        {
 3118            _innerArray = new T[DefaultCapacity];
 3119            AddRange(items); // Will handle capacity increases as needed
 120        }
 3121    }
 122
 123    ///  <summary>
 124    ///  Initializes a new instance of the <see cref="SwiftList{T}"/> class with the specified <see cref="SwiftArrayStat
 125    ///  </summary>
 126    ///  <param name="state">The state containing the internal array, count, offset, and version for initialization.</pa
 127    [MemoryPackConstructor]
 10128    public SwiftList(SwiftArrayState<T> state)
 129    {
 10130        State = state;
 131
 132        // Validate that the internal array is not null after deserialization
 10133        SwiftThrowHelper.ThrowIfNull(_innerArray, nameof(_innerArray));
 10134    }
 135
 136    #endregion
 137
 138    #region Properties
 139
 140    /// <summary>
 141    /// Gets the underlying array that stores the elements of the collection.
 142    /// </summary>
 143    [JsonIgnore]
 144    [MemoryPackIgnore]
 8145    public T[] InnerArray => _innerArray;
 146
 147    /// <summary>
 148    /// Gets the total number of elements the SwiftList can hold without resizing.
 149    /// Reflects the current allocated size of the internal array.
 150    /// </summary>
 151    [JsonIgnore]
 152    [MemoryPackIgnore]
 14153    public int Capacity => _innerArray.Length;
 154
 155    /// <inheritdoc cref="_count"/>
 156    [JsonIgnore]
 157    [MemoryPackIgnore]
 837158    public int Count => _count;
 159
 160    /// <inheritdoc/>
 161    [JsonIgnore]
 162    [MemoryPackIgnore]
 1163    public bool IsReadOnly => false;
 164
 165    /// <inheritdoc/>
 166    [JsonIgnore]
 167    [MemoryPackIgnore]
 1168    public bool IsSynchronized => false;
 169
 170    /// <inheritdoc/>
 171    [JsonIgnore]
 172    [MemoryPackIgnore]
 1173    public object SyncRoot => _syncRoot ??= new object();
 174
 175    /// <inheritdoc/>
 176    [JsonIgnore]
 177    [MemoryPackIgnore]
 1178    public bool IsFixedSize => false;
 179
 180    [JsonIgnore]
 181    [MemoryPackIgnore]
 182    object? IList.this[int index]
 183    {
 1184        get => this[index] ?? default!;
 185        set
 186        {
 187            try
 188            {
 2189                this[index] = (T)value!;
 1190            }
 1191            catch
 192            {
 1193                throw new NotSupportedException($"Unsupported value type for {value}");
 194            }
 1195        }
 196    }
 197
 198    /// <summary>
 199    /// Gets the element at the specified arrayIndex.
 200    /// </summary>
 201    [JsonIgnore]
 202    [MemoryPackIgnore]
 203    public T this[int index]
 204    {
 205        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 206        get
 207        {
 2500208            SwiftThrowHelper.ThrowIfListIndexInvalid(index, _count, message: "Index is out of range.");
 2496209            return _innerArray[index];
 210        }
 211        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 212        set
 213        {
 1514214            SwiftThrowHelper.ThrowIfListIndexInvalid(index, _count, message: "Index is out of range.");
 1514215            _innerArray[index] = value;
 1514216        }
 217    }
 218
 219    /// <summary>
 220    /// Gets or sets the current state of the array, including its items and count.
 221    /// </summary>
 222    /// <remarks>
 223    /// Setting this property replaces the entire contents of the array with the items from the specified state.
 224    /// The previous contents are discarded.
 225    /// The version is reset when the state is set.
 226    /// </remarks>
 227    [JsonInclude]
 228    [MemoryPackInclude]
 229    public SwiftArrayState<T> State
 230    {
 231        get
 232        {
 9233            var items = new T[_count];
 9234            Array.Copy(_innerArray, 0, items, 0, _count);
 9235            return new SwiftArrayState<T>(items);
 236        }
 237        internal set
 238        {
 10239            SwiftThrowHelper.ThrowIfNull(value.Items, nameof(value.Items));
 240
 10241            int count = value.Items.Length;
 242
 10243            if (count == 0)
 244            {
 1245                _innerArray = _emptyArray;
 1246                _count = 0;
 247            }
 248            else
 249            {
 9250                _innerArray = new T[count <= DefaultCapacity ? DefaultCapacity : count];
 9251                Array.Copy(value.Items, 0, _innerArray, 0, count);
 9252                _count = count;
 253            }
 254
 10255            _version = 0;
 10256        }
 257    }
 258
 259    #endregion
 260
 261    #region Collection Manipulation
 262
 263    /// <summary>
 264    /// Adds an object to the end of the SwiftList.
 265    /// </summary>
 266    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 267    public virtual void Add(T item)
 268    {
 111795269        if ((uint)_count == (uint)_innerArray.Length)
 182270            Resize(_innerArray.Length * 2);
 111795271        _innerArray[_count++] = item;
 111795272        _version++;
 111795273    }
 274
 275    int IList.Add(object? value)
 276    {
 277        try
 278        {
 2279            Add((T)value!);
 1280        }
 1281        catch (InvalidCastException)
 282        {
 1283            throw new NotSupportedException($"Wrong value type for {value}");
 284        }
 285
 1286        return _count - 1;
 287    }
 288
 289    /// <summary>
 290    /// Adds the elements of the specified collection to the end of the SwiftList.
 291    /// </summary>
 292    public virtual void AddRange(IEnumerable<T> items)
 293    {
 7294        SwiftThrowHelper.ThrowIfNull(items, nameof(items));
 295
 7296        if (items is ICollection<T> collection)
 297        {
 298            // Ensure capacity to fit all new items
 3299            if (_count + collection.Count > _innerArray.Length)
 300            {
 0301                int newCapacity = SwiftHashTools.NextPowerOfTwo(_count + collection.Count);
 0302                Resize(newCapacity);
 303            }
 304
 305            // Copy new items directly into the internal array
 3306            collection.CopyTo(_innerArray, _count);
 3307            _count += collection.Count;
 3308            _version++;
 309
 3310            return;
 311        }
 312
 313        // Fallback for non-ICollection, adding each item individually
 38314        foreach (T item in items)
 15315            Add(item);
 4316    }
 317
 318    /// <summary>
 319    /// Adds the elements of the specified array to the end of the SwiftList.
 320    /// </summary>
 321    /// <param name="items">The array whose elements should be appended.</param>
 322    public virtual void AddRange(T[] items)
 323    {
 1324        SwiftThrowHelper.ThrowIfNull(items, nameof(items));
 1325        AddRange(items.AsSpan());
 1326    }
 327
 328    /// <summary>
 329    /// Adds the elements of the specified span to the end of the SwiftList.
 330    /// </summary>
 331    /// <param name="items">The span whose elements should be appended.</param>
 332    public virtual void AddRange(ReadOnlySpan<T> items)
 333    {
 3334        if (items.Length == 0)
 1335            return;
 336
 2337        if (_count + items.Length > _innerArray.Length)
 338        {
 1339            int newCapacity = SwiftHashTools.NextPowerOfTwo(_count + items.Length);
 1340            Resize(newCapacity);
 341        }
 342
 2343        items.CopyTo(_innerArray.AsSpan(_count, items.Length));
 2344        _count += items.Length;
 2345        _version++;
 2346    }
 347
 348    /// <summary>
 349    /// Removes the first occurrence of a specific object from the SwiftList.
 350    /// </summary>
 351    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 352    public virtual bool Remove(T item)
 353    {
 3354        int index = IndexOf(item);
 4355        if (index < 0) return false; // Item not found return false;
 2356        RemoveAt(index);
 2357        return true;
 358    }
 359
 360    void IList.Remove(object? value)
 361    {
 362        try
 363        {
 2364            Remove((T)value!);
 1365        }
 1366        catch (InvalidCastException)
 367        {
 1368            throw new NotSupportedException($"Wrong value type for {value}");
 369        }
 1370    }
 371
 372    /// <summary>
 373    /// Removes the element at the specified arrayIndex of the SwiftList.
 374    /// </summary>
 375    public virtual void RemoveAt(int index)
 376    {
 604377        SwiftThrowHelper.ThrowIfListIndexInvalid(index, _count, message: "Index is out of range.");
 603378        Array.Copy(_innerArray, index + 1, _innerArray, index, _count - index - 1);
 603379        _count--;
 603380        if (_clearReleasedSlots)
 2381            _innerArray[_count] = default!;
 603382        _version++;
 603383    }
 384
 385    /// <summary>
 386    /// Removes all the elements that match the conditions defined by the specified predicate.
 387    /// </summary>
 388    public virtual int RemoveAll(Predicate<T> match)
 389    {
 11390        SwiftThrowHelper.ThrowIfNull(match, nameof(match));
 391
 10392        int firstMatchIndex = IndexOfFirstMatch(match);
 10393        if (firstMatchIndex >= _count)
 3394            return 0;
 395
 7396        int newCount = CompactUnmatchedItems(firstMatchIndex, match);
 7397        int removedCount = _count - newCount;
 7398        ClearReleasedSlots(newCount, removedCount);
 7399        _count = newCount;
 7400        _version++;
 401
 7402        return removedCount;
 403    }
 404
 405    private int IndexOfFirstMatch(Predicate<T> match)
 406    {
 10407        int index = 0;
 25408        while (index < _count && !match(_innerArray[index]))
 15409            index++;
 410
 10411        return index;
 412    }
 413
 414    private int CompactUnmatchedItems(int writeIndex, Predicate<T> match)
 415    {
 200042416        for (int readIndex = writeIndex + 1; readIndex < _count; readIndex++)
 417        {
 100014418            if (!match(_innerArray[readIndex]))
 50006419                _innerArray[writeIndex++] = _innerArray[readIndex];
 420        }
 421
 7422        return writeIndex;
 423    }
 424
 425    private void ClearReleasedSlots(int startIndex, int count)
 426    {
 7427        if (_clearReleasedSlots && count > 0)
 2428            Array.Clear(_innerArray, startIndex, count);
 7429    }
 430
 431    /// <summary>
 432    /// Inserts an element into the SwiftList at the specified arrayIndex.
 433    /// </summary>
 434    public virtual void Insert(int index, T item)
 435    {
 7436        SwiftThrowHelper.ThrowIfArrayIndexInvalid(index, _count, message: "Index is out of range.");
 6437        if ((uint)_count == (uint)_innerArray.Length)
 0438            Resize(_innerArray.Length * 2);
 6439        if ((uint)index < (uint)_count)
 4440            Array.Copy(_innerArray, index, _innerArray, index + 1, _count - index);
 6441        _innerArray[index] = item;
 6442        _count++;
 6443        _version++;
 6444    }
 445
 446    void IList.Insert(int index, object? value)
 447    {
 448        try
 449        {
 2450            Insert(index, (T)value!);
 1451        }
 1452        catch (InvalidCastException)
 453        {
 1454            throw new NotSupportedException($"Wrong value type for {value}");
 455        }
 1456    }
 457
 458    /// <summary>
 459    /// Reverses the order of the elements in the entire <see cref="SwiftList{T}"/>.
 460    /// </summary>
 461    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 462    public void Reverse()
 463    {
 1464        Array.Reverse(_innerArray, 0, _count);
 1465        _version++;
 1466    }
 467
 468    /// <summary>
 469    /// Sorts the elements in the <see cref="SwiftList{T}"/> using the <see cref="IComparable"/> interface implementatio
 470    /// </summary>
 471    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 472    public void Sort()
 473    {
 1474        Array.Sort(_innerArray, 0, _count, Comparer<T>.Default);
 1475        _version++;
 1476    }
 477
 478    /// <summary>
 479    /// Sorts the elements in the entire <see cref="SwiftList{T}"/> using the specified comparer.
 480    /// </summary>
 481    /// <param name="comparer">The comparer to use for comparing elements.</param>
 482    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 483    public void Sort(IComparer<T> comparer)
 484    {
 2485        Array.Sort(_innerArray, 0, _count, comparer);
 2486        _version++;
 2487    }
 488
 489    /// <summary>
 490    /// Removes all elements from the <see cref="SwiftList{T}"/>, resetting its count to zero.
 491    /// </summary>
 492    public virtual void Clear()
 493    {
 9494        if (_clearReleasedSlots)
 1495            Array.Clear(_innerArray, 0, _count);
 9496        _count = 0;
 9497        _version++;
 9498    }
 499
 500    /// <summary>
 501    /// Clears the <see cref="SwiftList{T}"/> without releasing the reference to the stored elements.
 502    /// Use FastClear() when you want to quickly reset the list without reallocating memory.
 503    /// </summary>
 504    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 505    public void FastClear()
 506    {
 1507        _count = 0;
 1508        _version++;
 1509    }
 510
 511    #endregion
 512
 513    #region Capacity Management
 514
 515    /// <summary>
 516    /// Ensures that the capacity of <see cref="SwiftList{T}"/> is sufficient to accommodate the specified number of ele
 517    /// The capacity can increase by double to balance memory allocation efficiency and space.
 518    /// </summary>
 519    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 520    public void EnsureCapacity(int capacity)
 521    {
 2522        capacity = SwiftHashTools.NextPowerOfTwo(capacity);
 2523        if (capacity > _innerArray.Length)
 1524            Resize(capacity);
 2525    }
 526
 527    /// <summary>
 528    /// Resizes the internal array to accommodate the specified number of elements.
 529    /// </summary>
 530    /// <remarks>
 531    /// If the specified size is less than or equal to the default capacity, the internal array is
 532    /// set to the default capacity.
 533    /// Existing elements are preserved up to the current count.
 534    /// </remarks>
 535    /// <param name="newSize">The desired new size of the internal array. Must be greater than or equal to zero.</param>
 536    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 537    protected void Resize(int newSize)
 538    {
 185539        int newCapacity = newSize <= DefaultCapacity ? DefaultCapacity : newSize;
 540
 185541        T[] newArray = new T[newCapacity];
 185542        if (_count > 0)
 42543            Array.Copy(_innerArray, 0, newArray, 0, _count);
 185544        _innerArray = newArray;
 185545        _version++;
 185546    }
 547
 548    /// <summary>
 549    /// Reduces the capacity of the SwiftList if the element count falls below 50% of the current capacity.
 550    /// Ensures efficient memory usage by resizing the internal array to match the current count when necessary.
 551    /// </summary>
 552    public void TrimExcessCapacity()
 553    {
 2554        int newCapacity = _count < DefaultCapacity ? DefaultCapacity : SwiftHashTools.NextPowerOfTwo(_count);
 2555        Array.Resize(ref _innerArray, newCapacity);
 2556        _version++;
 2557    }
 558
 559    #endregion
 560
 561    #region Utility Methods
 562
 563    /// <summary>
 564    /// Searches for the specified object and returns the zero-based arrayIndex of the first occurrence within the Swift
 565    /// </summary>
 566    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 513567    public int IndexOf(T item) => Array.IndexOf(_innerArray, item, 0, _count);
 568
 569    int IList.IndexOf(object? value)
 570    {
 571        int index;
 572        try
 573        {
 2574            index = Array.IndexOf(_innerArray, (T)value!, 0, _count);
 1575        }
 1576        catch
 577        {
 1578            throw new NotSupportedException($"Unsupported value type for {value}");
 579        }
 1580        return index;
 581    }
 582
 583    /// <summary>
 584    /// Copies the elements of the SwiftList to a new array.
 585    /// </summary>
 586    public T[] ToArray()
 587    {
 27588        T[] result = new T[_count];
 27589        Array.Copy(_innerArray, result, _count);
 27590        return result;
 591    }
 592
 593    /// <summary>
 594    /// Returns a mutable span over the populated portion of the list.
 595    /// </summary>
 596    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2597    public Span<T> AsSpan() => _innerArray.AsSpan(0, _count);
 598
 599    /// <summary>
 600    /// Returns a read-only span over the populated portion of the list.
 601    /// </summary>
 602    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1603    public ReadOnlySpan<T> AsReadOnlySpan() => _innerArray.AsSpan(0, _count);
 604
 605    /// <summary>
 606    /// Returns a string that represents the current collection.
 607    /// </summary>
 608    /// <remarks>
 609    /// This method provides a human-readable representation of the collection's contents,
 610    /// which can be useful for debugging or logging purposes.
 611    /// </remarks>
 612    /// <returns>A comma-separated list of the collection's elements, or the default string representation if the collec
 613    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2614    public override string ToString() => _count == 0
 2615        ? base.ToString() ?? string.Empty
 2616        : string.Join(", ", this);
 617
 618    /// <summary>
 619    /// Determines whether an element is in the SwiftList.
 620    /// </summary>
 621    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 3622    public bool Contains(T item) => IndexOf(item) != -1;
 623
 624    /// <summary>
 625    /// Determines whether the <see cref="SwiftList{T}"/> contains an element that matches the conditions defined by the
 626    /// </summary>
 627    /// <param name="match">The predicate that defines the conditions of the element to search for.</param>
 628    /// <returns><c>true</c> if the <see cref="SwiftList{T}"/> contains one or more elements that match the specified pr
 629    public bool Exists(Predicate<T> match)
 630    {
 3631        SwiftThrowHelper.ThrowIfNull(match, nameof(match));
 632
 14633        for (int i = 0; i < _count; i++)
 634        {
 6635            if (match(_innerArray[i]))
 1636                return true;
 637        }
 638
 1639        return false;
 640    }
 641
 642    /// <summary>
 643    /// Searches for an element that matches the conditions defined by the specified predicate, and returns the first oc
 644    /// </summary>
 645    /// <param name="match">The predicate that defines the conditions of the element to search for.</param>
 646    /// <returns>The first element that matches the conditions defined by the specified predicate, if found; otherwise, 
 647    public T Find(Predicate<T> match)
 648    {
 4649        SwiftThrowHelper.ThrowIfNull(match, nameof(match));
 650
 20651        for (int i = 0; i < _count; i++)
 652        {
 8653            if (match(_innerArray[i]))
 1654                return _innerArray[i];
 655        }
 656
 2657        return default!;
 658    }
 659
 660    bool IList.Contains(object? value)
 661    {
 662        int index;
 663        try
 664        {
 2665            index = IndexOf((T)value!);
 1666        }
 1667        catch
 668        {
 1669            throw new NotSupportedException($"Unsupported value type for {value}");
 670        }
 1671        return index != -1;
 672    }
 673
 674    /// <summary>
 675    /// Swaps the values of two elements in the SwiftList.
 676    /// This method exchanges the values referenced by two variables.
 677    /// </summary>
 678    /// <param name="indexA">The first element to swap.</param>
 679    /// <param name="indexB">The second element to swap.</param>
 680    [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1681    public void Swap(int indexA, int indexB) => (_innerArray[indexB], _innerArray[indexA]) = (_innerArray[indexA], _inne
 682
 683    /// <summary>
 684    /// Copies the elements of the SwiftList to the specified target SwiftList.
 685    /// The target list will resize if it lacks sufficient capacity,
 686    /// but retains any existing elements beyond the copied range.
 687    /// </summary>
 688    public void CopyTo(SwiftList<T> target)
 689    {
 2690        if (_count + 1 > target._innerArray.Length)
 1691            target.Resize(target._innerArray.Length * 2);
 2692        Array.Copy(_innerArray, 0, target._innerArray, 0, _count);
 2693        target._count = _count;
 2694        target._version++;
 2695    }
 696
 697    /// <inheritdoc/>
 698    public void CopyTo(T[] array, int arrayIndex)
 699    {
 4700        SwiftThrowHelper.ThrowIfNull(array, nameof(array));
 4701        SwiftThrowHelper.ThrowIfArrayIndexInvalid(arrayIndex, array.Length, message: "Array index is out of range.");
 4702        SwiftThrowHelper.ThrowIfArgument(array.Length - arrayIndex < _count, nameof(array), "Destination array is not lo
 703
 2704        Array.Copy(_innerArray, 0, array, arrayIndex, _count);
 2705    }
 706
 707    /// <summary>
 708    /// Copies the populated elements of the SwiftList into the specified destination span.
 709    /// </summary>
 710    /// <param name="destination">The destination span.</param>
 711    public void CopyTo(Span<T> destination)
 712    {
 2713        SwiftThrowHelper.ThrowIfArgument(destination.Length < _count, nameof(destination), "Destination span is not long
 714
 1715        AsSpan().CopyTo(destination);
 1716    }
 717
 718    /// <inheritdoc/>
 719    public void CopyTo(Array array, int arrayIndex)
 720    {
 3721        SwiftThrowHelper.ThrowIfNull(array, nameof(array));
 3722        SwiftThrowHelper.ThrowIfArgument(array.Rank != 1, nameof(array), "Array must be single dimensional.");
 2723        SwiftThrowHelper.ThrowIfArgument(array.GetLowerBound(0) != 0, nameof(array), "Array must have zero-based indexin
 1724        SwiftThrowHelper.ThrowIfArrayIndexInvalid(arrayIndex, array.Length, message: "Array index is out of range.");
 1725        SwiftThrowHelper.ThrowIfArgument(array.Length - arrayIndex < _count, nameof(array), "Destination array is not lo
 726
 1727        Array.Copy(_innerArray, 0, array, arrayIndex, _count);
 1728    }
 729
 730    /// <inheritdoc/>
 731    public void CloneTo(ICollection<T> output)
 732    {
 1733        output.Clear();
 8734        foreach (var item in this)
 3735            output.Add(item);
 1736    }
 737
 738    #endregion
 739
 740    #region Enumerators
 741
 742    /// <summary>
 743    /// Returns an enumerator that iterates through the <see cref="SwiftList{T}"/>.
 744    /// </summary>
 26745    public SwiftListEnumerator GetEnumerator() => new(this);
 21746    IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
 2747    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
 748
 749    /// <summary>
 750    /// Enumerates the elements of a <see cref="SwiftList{T}"/> collection.
 751    /// </summary>
 752    /// <remarks>
 753    /// The enumerator provides read-only, forward-only iteration over the collection.
 754    /// The enumerator is invalidated if the collection is modified after the enumerator is created.
 755    /// In such cases, calling MoveNext or Reset will throw an InvalidOperationException.
 756    /// </remarks>
 757    public struct SwiftListEnumerator : IEnumerator<T>, IEnumerator, IDisposable
 758    {
 759        private readonly SwiftList<T> _list;
 760        private readonly T[] _array;
 761        private readonly uint _count;
 762        private readonly uint _version;
 763        private uint _index;
 764
 765        private T _current;
 766
 767        internal SwiftListEnumerator(SwiftList<T> list)
 768        {
 26769            _list = list;
 26770            _array = list._innerArray;
 26771            _count = (uint)list._count;
 26772            _version = list._version;
 26773            _index = 0;
 26774            _current = default!;
 26775        }
 776
 777        /// <inheritdoc/>
 436778        public T Current => _current;
 779
 780        object IEnumerator.Current
 781        {
 782            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 783            get
 784            {
 3785                SwiftThrowHelper.ThrowIfTrue(_index >= _count, message: "Enumeration has either not started or has alrea
 2786                return _current!;
 787            }
 788        }
 789
 790        /// <inheritdoc/>
 791        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 792        public bool MoveNext()
 793        {
 249794            SwiftThrowHelper.ThrowIfTrue(_version != _list._version, message: "Collection was modified during enumeratio
 795
 270796            if (_index >= _count) return false;
 226797            _current = _array[_index++];
 226798            return true;
 799        }
 800
 801        /// <inheritdoc/>
 802        public void Reset()
 803        {
 2804            SwiftThrowHelper.ThrowIfTrue(_version != _list._version, message: "Collection was modified during enumeratio
 805
 1806            _index = 0;
 1807            _current = default!;
 1808        }
 809
 810        /// <inheritdoc/>
 22811        public void Dispose() => _index = 0;
 812    }
 813
 814    #endregion
 815}

Methods/Properties

.cctor()
.cctor()
.ctor()
.ctor(System.Int32)
.ctor(System.Collections.Generic.IEnumerable`1<T>)
.ctor(SwiftCollections.SwiftArrayState`1<T>)
get_InnerArray()
get_Capacity()
get_Count()
get_IsReadOnly()
get_IsSynchronized()
get_SyncRoot()
get_IsFixedSize()
System.Collections.IList.get_Item(System.Int32)
System.Collections.IList.set_Item(System.Int32,System.Object)
get_Item(System.Int32)
set_Item(System.Int32,T)
get_State()
set_State(SwiftCollections.SwiftArrayState`1<T>)
Add(T)
System.Collections.IList.Add(System.Object)
AddRange(System.Collections.Generic.IEnumerable`1<T>)
AddRange(T[])
AddRange(System.ReadOnlySpan`1<T>)
Remove(T)
System.Collections.IList.Remove(System.Object)
RemoveAt(System.Int32)
RemoveAll(System.Predicate`1<T>)
IndexOfFirstMatch(System.Predicate`1<T>)
CompactUnmatchedItems(System.Int32,System.Predicate`1<T>)
ClearReleasedSlots(System.Int32,System.Int32)
Insert(System.Int32,T)
System.Collections.IList.Insert(System.Int32,System.Object)
Reverse()
Sort()
Sort(System.Collections.Generic.IComparer`1<T>)
Clear()
FastClear()
EnsureCapacity(System.Int32)
Resize(System.Int32)
TrimExcessCapacity()
IndexOf(T)
System.Collections.IList.IndexOf(System.Object)
ToArray()
AsSpan()
AsReadOnlySpan()
ToString()
Contains(T)
Exists(System.Predicate`1<T>)
Find(System.Predicate`1<T>)
System.Collections.IList.Contains(System.Object)
Swap(System.Int32,System.Int32)
CopyTo(SwiftCollections.SwiftList`1<T>)
CopyTo(T[],System.Int32)
CopyTo(System.Span`1<T>)
CopyTo(System.Array,System.Int32)
CloneTo(System.Collections.Generic.ICollection`1<T>)
GetEnumerator()
System.Collections.Generic.IEnumerable<T>.GetEnumerator()
System.Collections.IEnumerable.GetEnumerator()
.ctor(SwiftCollections.SwiftList`1<T>)
get_Current()
System.Collections.IEnumerator.get_Current()
MoveNext()
Reset()
Dispose()