|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.Collections; |
| 5 | + |
| 6 | +namespace ModelContextProtocol.Analyzers; |
| 7 | + |
| 8 | +/// <summary>An immutable, equatable array.</summary> |
| 9 | +/// <typeparam name="T">The type of values in the array.</typeparam> |
| 10 | +internal readonly struct EquatableArray<T> : IEnumerable<T>, IEquatable<EquatableArray<T>> |
| 11 | +{ |
| 12 | + /// <summary>The underlying <typeparamref name="T"/> array.</summary> |
| 13 | + private readonly T[]? _array; |
| 14 | + |
| 15 | + /// <param name="source">The source to enumerate and wrap.</param> |
| 16 | + public EquatableArray(IEnumerable<T> source) => _array = source.ToArray(); |
| 17 | + |
| 18 | + /// <param name="source">The source to wrap.</param> |
| 19 | + public EquatableArray(T[] array) => _array = array; |
| 20 | + |
| 21 | + /// <summary>Gets a reference to an item at a specified position within the array.</summary> |
| 22 | + /// <param name="index">The index of the item to retrieve a reference to.</param> |
| 23 | + /// <returns>A reference to an item at a specified position within the array.</returns> |
| 24 | + public ref readonly T this[int index] => ref NonNullArray[index]; |
| 25 | + |
| 26 | + /// <summary>Gets the backing array.</summary> |
| 27 | + private T[] NonNullArray => _array ?? []; |
| 28 | + |
| 29 | + /// <summary>Gets the length of the current array.</summary> |
| 30 | + public int Length => NonNullArray.Length; |
| 31 | + |
| 32 | + /// <inheritdoc/> |
| 33 | + public bool Equals(EquatableArray<T> other) => NonNullArray.SequenceEqual(other.NonNullArray); |
| 34 | + |
| 35 | + /// <inheritdoc/> |
| 36 | + public override bool Equals(object? obj) => obj is EquatableArray<T> array && Equals(array); |
| 37 | + |
| 38 | + /// <inheritdoc/> |
| 39 | + public override int GetHashCode() |
| 40 | + { |
| 41 | + int hash = 17; |
| 42 | + foreach (T item in NonNullArray) |
| 43 | + { |
| 44 | + hash = hash * 31 + (item?.GetHashCode() ?? 0); |
| 45 | + } |
| 46 | + |
| 47 | + return hash; |
| 48 | + } |
| 49 | + |
| 50 | + /// <inheritdoc/> |
| 51 | + IEnumerator<T> IEnumerable<T>.GetEnumerator() => ((IEnumerable<T>)NonNullArray).GetEnumerator(); |
| 52 | + |
| 53 | + /// <inheritdoc/> |
| 54 | + IEnumerator IEnumerable.GetEnumerator() => NonNullArray.GetEnumerator(); |
| 55 | +} |
0 commit comments