|
| 1 | +namespace Architect.DomainModeling.Generator.Common; |
| 2 | + |
| 3 | +/// <summary> |
| 4 | +/// Wraps an <see cref="IReadOnlyList{T}"/> in a wrapper with structural equality using the collection's elements. |
| 5 | +/// </summary> |
| 6 | +/// <typeparam name="TCollection">The type of the collection to wrap.</typeparam> |
| 7 | +/// <typeparam name="TElement">The type of the collection's elements.</typeparam> |
| 8 | +internal sealed class StructuralList<TCollection, TElement>( |
| 9 | + TCollection value) |
| 10 | + : IEquatable<StructuralList<TCollection, TElement>> |
| 11 | + where TCollection : IReadOnlyList<TElement> |
| 12 | +{ |
| 13 | + public TCollection Value { get; } = value ?? throw new ArgumentNullException(nameof(value)); |
| 14 | + |
| 15 | + public override int GetHashCode() => this.Value is TCollection value && value.Count > 0 |
| 16 | + ? CombineHashCodes( |
| 17 | + value.Count, |
| 18 | + value[0]?.GetHashCode() ?? 0, |
| 19 | + value[value.Count - 1]?.GetHashCode() ?? 0) |
| 20 | + : 0; |
| 21 | + public override bool Equals(object obj) => obj is StructuralList<TCollection, TElement> other && this.Equals(other); |
| 22 | + |
| 23 | + public bool Equals(StructuralList<TCollection, TElement> other) |
| 24 | + { |
| 25 | + if (other is null) |
| 26 | + return false; |
| 27 | + |
| 28 | + var left = this.Value; |
| 29 | + var right = other.Value; |
| 30 | + |
| 31 | + if (right.Count != left.Count) |
| 32 | + return false; |
| 33 | + |
| 34 | + for (var i = 0; i < left.Count; i++) |
| 35 | + if (left[i] is not TElement leftElement ? right[i] is not null : !leftElement.Equals(right[i])) |
| 36 | + return false; |
| 37 | + |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + private static int CombineHashCodes(int count, int firstHashCode, int lastHashCode) |
| 42 | + { |
| 43 | + var countInHighBits = (ulong)count << 16; |
| 44 | + |
| 45 | + // In the upper half, combine the count with the first hash code |
| 46 | + // In the lower half, combine the count with the last hash code |
| 47 | + var combined = ((ulong)firstHashCode ^ countInHighBits) << 33; // Offset by 1 additional bit, because UInt64.GetHashCode() XORs its halves, which would cause 0 for identical first and last (e.g. single element) |
| 48 | + combined |= (ulong)lastHashCode ^ countInHighBits; |
| 49 | + |
| 50 | + return combined.GetHashCode(); |
| 51 | + } |
| 52 | + |
| 53 | + public static implicit operator TCollection(StructuralList<TCollection, TElement> instance) => instance.Value; |
| 54 | + public static implicit operator StructuralList<TCollection, TElement>(TCollection value) => new StructuralList<TCollection, TElement>(value); |
| 55 | +} |
0 commit comments