diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs index 9ec626c1..a5663530 100644 --- a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableArrayBuilder{T}.cs @@ -3,6 +3,8 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections; +using System.Collections.Generic; using System.Collections.Immutable; using System.Runtime.CompilerServices; @@ -47,7 +49,7 @@ internal struct ImmutableArrayBuilder : IDisposable public readonly int Count { [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => this.writer!.WrittenSpan.Length; + get => this.writer!.Count; } /// @@ -95,6 +97,18 @@ internal struct ImmutableArrayBuilder : IDisposable this.writer!.Insert(index, item); } + /// + /// Gets an instance for the current builder. + /// + /// An instance for the current builder. + /// + /// The builder should not be mutated while an enumerator is in use. + /// + public readonly IEnumerable AsEnumerable() + { + return this.writer!; + } + /// public readonly ImmutableArray ToImmutable() { @@ -133,7 +147,7 @@ internal struct ImmutableArrayBuilder : IDisposable /// /// A class handling the actual buffer writing. /// - private sealed class Writer + private sealed class Writer : IList, IReadOnlyList { /// /// The underlying array. @@ -162,6 +176,9 @@ internal struct ImmutableArrayBuilder : IDisposable this.index = 0; } + /// + public int Count => this.index; + /// public ReadOnlySpan WrittenSpan { @@ -169,6 +186,19 @@ internal struct ImmutableArrayBuilder : IDisposable get => new(this.array, 0, this.index); } + /// + bool ICollection.IsReadOnly => true; + + /// + T IReadOnlyList.this[int index] => WrittenSpan[index]; + + /// + T IList.this[int index] + { + get => WrittenSpan[index]; + set => throw new NotSupportedException(); + } + /// public Span Advance(int requestedSize) { @@ -268,6 +298,54 @@ internal struct ImmutableArrayBuilder : IDisposable this.array = newArray; } + + /// + int IList.IndexOf(T item) + { + return Array.IndexOf(this.array, item, 0, this.index); + } + + /// + void IList.RemoveAt(int index) + { + throw new NotSupportedException(); + } + + /// + bool ICollection.Contains(T item) + { + return Array.IndexOf(this.array, item, 0, this.index) >= 0; + } + + /// + void ICollection.CopyTo(T[] array, int arrayIndex) + { + Array.Copy(this.array, 0, array, arrayIndex, this.index); + } + + /// + bool ICollection.Remove(T item) + { + throw new NotSupportedException(); + } + + /// + IEnumerator IEnumerable.GetEnumerator() + { + T?[] array = this.array!; + int length = this.index; + + for (int i = 0; i < length; i++) + { + yield return array[i]!; + } + } + + /// + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)this).GetEnumerator(); + } } }