< Summary

Information
Class: SwiftCollections.Dimensions.SwiftArray2D<T>
Assembly: SwiftCollections
File(s): /home/runner/work/SwiftCollections/SwiftCollections/src/SwiftCollections/Dimension/SwiftArray2D.cs
Line coverage
98%
Covered lines: 129
Uncovered lines: 2
Coverable lines: 131
Total lines: 416
Line coverage: 98.4%
Branch coverage
96%
Covered branches: 64
Total branches: 66
Branch coverage: 96.9%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor()100%11100%
.ctor(...)100%11100%
.ctor(...)100%11100%
.ctor(...)100%44100%
.ctor(...)100%11100%
get_Width()100%11100%
get_Height()100%11100%
get_InnerArray()100%11100%
get_Size()100%11100%
get_Length()100%11100%
get_Item(...)100%11100%
set_Item(...)100%11100%
get_State()100%11100%
set_State(...)100%11100%
AddRange(...)100%44100%
Fill(...)100%22100%
Shift(...)100%22100%
ShiftWrapped(...)100%44100%
ShiftClamped(...)100%44100%
Clear()100%11100%
Resize(...)100%88100%
Initialize(...)100%11100%
NormalizeShift(...)75%4475%
WrapForwardIndex(...)100%22100%
GetShiftRange(...)83.33%6685.71%
ValidateIndex(...)100%88100%
IsValidIndex(...)100%66100%
GetIndex(...)100%11100%
ToArray()100%44100%
Clone()100%44100%
GetEnumerator()100%44100%
System.Collections.IEnumerable.GetEnumerator()100%11100%

File(s)

/home/runner/work/SwiftCollections/SwiftCollections/src/SwiftCollections/Dimension/SwiftArray2D.cs

#LineLine coverage
 1using Chronicler;
 2using MemoryPack;
 3using System;
 4using System.Collections;
 5using System.Collections.Generic;
 6using System.Text.Json.Serialization;
 7
 8namespace SwiftCollections.Dimensions;
 9
 10/// <summary>
 11/// Represents a flattened 2D array with dynamic resizing and efficient access.
 12/// </summary>
 13/// <typeparam name="T">The type of elements in the array.</typeparam>
 14[Serializable]
 15[JsonConverter(typeof(StateJsonConverterFactory))]
 16[MemoryPackable]
 17public partial class SwiftArray2D<T> : IStateBacked<Array2DState<T>>, IEnumerable<T>, IEnumerable
 18{
 19    #region Fields
 20
 21    private T[] _innerArray;
 22
 23    private int _width;
 24
 25    private int _height;
 26
 27    #endregion
 28
 29    #region Constructors
 30
 31    /// <summary>
 32    /// Initializes a new instance of the <see cref="SwiftArray2D{T}"/> class.
 33    /// </summary>
 234    public SwiftArray2D() : this(0, 0) { }
 35
 36    /// <summary>
 37    /// Initializes a new instance of the <see cref="SwiftArray2D{T}"/> class with specified dimensions.
 38    /// </summary>
 3439    public SwiftArray2D(int width, int height)
 40    {
 3441        Initialize(width, height);
 42
 43        // Ensure that the inner array is not null after initialization
 3444        SwiftThrowHelper.ThrowIfNull(_innerArray, nameof(_innerArray));
 3445    }
 46
 47    /// <summary>
 48    /// Initializes a new instance of the <see cref="SwiftArray2D{T}"/> class with specified dimensions and default valu
 49    /// </summary>
 1250    public SwiftArray2D(int width, int height, T defaultValue) : this(width, height)
 51    {
 1252        Fill(defaultValue);
 1253    }
 54
 55    /// <summary>
 56    /// Initializes a new instance of the SwiftArray2D class by copying the contents of the specified two-dimensional ar
 57    /// </summary>
 58    /// <remarks>
 59    /// The dimensions of the new SwiftArray2D instance match those of the source array.
 60    /// Changes to the source array after construction do not affect the SwiftArray2D instance.
 61    /// </remarks>
 62    /// <param name="source">The two-dimensional array whose elements are copied to the new SwiftArray2D instance. Canno
 263    public SwiftArray2D(T[,] source)
 64    {
 265        int width = source.GetLength(0);
 266        int height = source.GetLength(1);
 67
 268        Initialize(width, height);
 69
 270        SwiftThrowHelper.ThrowIfNull(_innerArray, nameof(_innerArray));
 71
 1272        for (int x = 0; x < width; x++)
 2473            for (int y = 0; y < height; y++)
 874                this[x, y] = source[x, y];
 275    }
 76
 77    /// <summary>
 78    /// Initializes a new instance of the SwiftArray2D class with the specified array state.
 79    /// </summary>
 80    /// <param name="state">The state object that encapsulates the underlying data and configuration for the two-dimensi
 81    [MemoryPackConstructor]
 782    public SwiftArray2D(Array2DState<T> state)
 83    {
 784        State = state;
 85
 786        SwiftThrowHelper.ThrowIfNull(_innerArray, nameof(_innerArray));
 787    }
 88
 89    #endregion
 90
 91    #region Properties
 92
 93    /// <summary>
 94    /// Gets the width of the 2D array.
 95    /// </summary>
 96    [JsonIgnore]
 97    [MemoryPackIgnore]
 7398    public int Width => _width;
 99
 100    /// <summary>
 101    /// Gets the height of the 2D array.
 102    /// </summary>
 103    [JsonIgnore]
 104    [MemoryPackIgnore]
 88105    public int Height => _height;
 106
 107    /// <summary>
 108    /// Gets the underlying flattened array for direct access.
 109    /// </summary>
 110    [JsonIgnore]
 111    [MemoryPackIgnore]
 113112    public T[] InnerArray => _innerArray;
 113
 114    /// <summary>
 115    /// Total size of the array
 116    /// </summary>
 117    [JsonIgnore]
 118    [MemoryPackIgnore]
 1119    public int Size => _width * _height;
 120
 121    /// <inheritdoc cref="Array.Length" />
 122    [JsonIgnore]
 123    [MemoryPackIgnore]
 7124    public int Length => _innerArray.Length;
 125
 126    /// <summary>
 127    /// Gets or sets the element at the specified position in the 2D array.
 128    /// </summary>
 129    /// <param name="x">The zero-based X coordinate.</param>
 130    /// <param name="y">The zero-based Y coordinate.</param>
 131    [JsonIgnore]
 132    [MemoryPackIgnore]
 133    public T this[int x, int y]
 134    {
 135        get
 136        {
 1000188137            ValidateIndex(x, y);
 1000186138            return _innerArray[GetIndex(x, y)];
 139        }
 140        set
 141        {
 1000085142            ValidateIndex(x, y);
 1000085143            _innerArray[GetIndex(x, y)] = value;
 1000085144        }
 145    }
 146
 147    /// <summary>
 148    /// Gets or sets the current state of the two-dimensional array, including its dimensions and data.
 149    /// </summary>
 150    /// <remarks>
 151    /// The returned state is a snapshot and is independent of future changes to the array.
 152    /// Setting this property replaces the entire contents and dimensions of the array with those from the provided stat
 153    /// This property is intended for serialization and deserialization scenarios.
 154    /// </remarks>
 155    [JsonInclude]
 156    [MemoryPackInclude]
 157    public Array2DState<T> State
 158    {
 159        get
 160        {
 7161            var data = new T[_innerArray.Length];
 7162            Array.Copy(_innerArray, data, data.Length);
 163
 7164            return new Array2DState<T>(
 7165                _width,
 7166                _height,
 7167                data
 7168            );
 169        }
 170
 171        internal set
 172        {
 7173            SwiftThrowHelper.ThrowIfNull(value.Data, nameof(value.Data));
 174
 7175            _width = value.Width;
 7176            _height = value.Height;
 177
 7178            int capacity = value.Data.Length;
 179
 7180            _innerArray = new T[capacity];
 7181            Array.Copy(value.Data, _innerArray, capacity);
 7182        }
 183    }
 184
 185    #endregion
 186
 187    #region Collection Management
 188
 189    /// <summary>
 190    /// Adds the provides source into the current 2D Array.
 191    /// </summary>
 192    /// <remarks>
 193    /// Will overwrite current values.
 194    /// </remarks>
 195    /// <param name="source"></param>
 196    public void AddRange(T[,] source)
 197    {
 1198        Resize(source.GetLength(0), source.GetLength(1));
 6199        for (int i = 0; i < Width; i++)
 200        {
 12201            for (int j = 0; j < Height; j++)
 4202                this[i, j] = source[i, j];
 203        }
 1204    }
 205
 206    /// <summary>
 207    /// Fills the array with the specified value.
 208    /// </summary>
 209    public void Fill(T value)
 210    {
 4000304211        for (int i = 0; i < _innerArray.Length; i++)
 2000137212            _innerArray[i] = value;
 15213    }
 214
 215    /// <summary>
 216    /// Shifts the elements in the array by the specified X and Y offsets.
 217    /// </summary>
 218    /// <param name="xShift">The offset to apply along the X-axis.</param>
 219    /// <param name="yShift">The offset to apply along the Y-axis.</param>
 220    /// <param name="wrap">
 221    /// Specifies whether to wrap elements that exceed the array's boundaries.
 222    /// If <c>true</c>, values wrap around to the other side of the array.
 223    /// If <c>false</c>, values that exceed boundaries are discarded.
 224    /// </param>
 225    public void Shift(int xShift, int yShift, bool wrap = true)
 226    {
 6227        T[] newArray = new T[_innerArray.Length];
 228
 6229        if (wrap)
 4230            ShiftWrapped(newArray, xShift, yShift);
 231        else
 2232            ShiftClamped(newArray, xShift, yShift);
 233
 6234        _innerArray = newArray;
 6235    }
 236
 237    private void ShiftWrapped(T[] newArray, int xShift, int yShift)
 238    {
 4239        int normalizedXShift = NormalizeShift(xShift, _width);
 4240        int normalizedYShift = NormalizeShift(yShift, _height);
 241
 36242        for (int x = 0; x < _width; x++)
 243        {
 14244            int newX = WrapForwardIndex(x, normalizedXShift, _width);
 14245            int sourceBase = x * _height;
 14246            int targetBase = newX * _height;
 247
 138248            for (int y = 0; y < _height; y++)
 249            {
 55250                int newY = WrapForwardIndex(y, normalizedYShift, _height);
 55251                newArray[targetBase + newY] = _innerArray[sourceBase + y];
 252            }
 253        }
 4254    }
 255
 256    private void ShiftClamped(T[] newArray, int xShift, int yShift)
 257    {
 2258        GetShiftRange(_width, xShift, out int xStart, out int xEnd);
 2259        GetShiftRange(_height, yShift, out int yStart, out int yEnd);
 260
 8261        for (int x = xStart; x < xEnd; x++)
 262        {
 2263            int newX = x + xShift;
 2264            int sourceBase = x * _height;
 2265            int targetBase = newX * _height;
 266
 12267            for (int y = yStart; y < yEnd; y++)
 268            {
 4269                int newY = y + yShift;
 4270                newArray[targetBase + newY] = _innerArray[sourceBase + y];
 271            }
 272        }
 2273    }
 274
 275    /// <summary>
 276    /// Clears all elements in the array.
 277    /// </summary>
 1278    public void Clear() => Array.Clear(_innerArray, 0, _innerArray.Length);
 279
 280    #endregion
 281
 282    #region Capacity Management
 283
 284    /// <summary>
 285    /// Resizes the 2D array to new dimensions, preserving existing values within the new bounds.
 286    /// </summary>
 287    public void Resize(int newWidth, int newHeight)
 288    {
 4289        SwiftThrowHelper.ThrowIfNegative(newWidth, nameof(newWidth));
 4290        SwiftThrowHelper.ThrowIfNegative(newHeight, nameof(newHeight));
 291
 4292        if (newWidth == _width && newHeight == _height)
 1293            return;
 294
 3295        T[] newArray = new T[newWidth * newHeight];
 3296        int minWidth = Math.Min(_width, newWidth);
 3297        int minHeight = Math.Min(_height, newHeight);
 298
 16299        for (int x = 0; x < minWidth; x++)
 28300            for (int y = 0; y < minHeight; y++)
 9301                newArray[x * newHeight + y] = this[x, y];
 302
 3303        _innerArray = newArray;
 3304        _width = newWidth;
 3305        _height = newHeight;
 3306    }
 307
 308    #endregion
 309
 310    #region Utility Methods
 311
 312    private void Initialize(int width, int height)
 313    {
 36314        _width = Math.Max(0, width);
 36315        _height = Math.Max(0, height);
 36316        _innerArray = new T[_width * _height];
 36317    }
 318
 319    private static int NormalizeShift(int shift, int length)
 320    {
 8321        if (length == 0)
 0322            return 0;
 323
 8324        int normalized = shift % length;
 8325        return normalized < 0 ? normalized + length : normalized;
 326    }
 327
 328    private static int WrapForwardIndex(int index, int normalizedShift, int length)
 329    {
 69330        int shifted = index + normalizedShift;
 69331        return shifted >= length ? shifted - length : shifted;
 332    }
 333
 334    private static void GetShiftRange(int length, int shift, out int start, out int end)
 335    {
 4336        long startValue = shift < 0 ? -(long)shift : 0L;
 4337        long endValue = shift > 0 ? (long)length - shift : length;
 338
 4339        start = (int)Math.Min(startValue, length);
 4340        end = (int)Math.Max(0L, Math.Min(endValue, length));
 4341        if (end < start)
 0342            end = start;
 4343    }
 344
 345    /// <summary>
 346    /// Validates the specified index coordinates.
 347    /// </summary>
 348    public virtual void ValidateIndex(int x, int y)
 349    {
 2000273350        if (x < 0 || x >= _width || y < 0 || y >= _height)
 2351            throw new IndexOutOfRangeException($"Invalid index: ({x}, {y})");
 2000271352    }
 353
 354    /// <summary>
 355    /// Checks if the specified index is valid in the current array dimensions.
 356    /// </summary>
 43357    public virtual bool IsValidIndex(int x, int y) => x >= 0 && x < Width && y >= 0 && y < Height;
 358
 359    /// <summary>
 360    /// Converts 2D coordinates to a flattened index.
 361    /// </summary>
 2000271362    public virtual int GetIndex(int x, int y) => x * _height + y;
 363
 364    /// <summary>
 365    /// Converts the flattened array back to a 2D array representation.
 366    /// </summary>
 367    public T[,] ToArray()
 368    {
 2369        T[,] result = new T[_width, _height];
 12370        for (int x = 0; x < _width; x++)
 24371            for (int y = 0; y < _height; y++)
 8372                result[x, y] = this[x, y];
 2373        return result;
 374    }
 375
 376    /// <summary>
 377    /// Clones a 2D array into a new instance of Array2D.
 378    /// </summary>
 379    public SwiftArray2D<T> Clone()
 380    {
 1381        var array2D = new SwiftArray2D<T>(Width, Height);
 6382        for (int x = 0; x < Width; x++)
 383        {
 12384            for (int y = 0; y < Height; y++)
 4385                array2D[x, y] = this[x, y];
 386        }
 1387        return array2D;
 388    }
 389
 390    #endregion
 391
 392    #region IEnumerator Implementation
 393
 394    /// <summary>
 395    /// Returns an enumerator that iterates through all elements in the 2D array.
 396    /// </summary>
 397    /// <returns>An enumerator for the 2D array.</returns>
 398    public IEnumerator<T> GetEnumerator()
 399    {
 62400        for (int x = 0; x < _width; x++)
 401        {
 180402            for (int y = 0; y < _height; y++)
 403            {
 67404                yield return this[x, y];
 405            }
 406        }
 8407    }
 408
 409    /// <summary>
 410    /// Returns an enumerator that iterates through all elements in the 2D array (non-generic).
 411    /// </summary>
 412    /// <returns>An enumerator for the 2D array.</returns>
 1413    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
 414
 415    #endregion
 416}