From bcb327db8efcba4e644b92b8794e713f70d325d6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 20 Jun 2023 17:06:43 +0200 Subject: [PATCH] Add ImmutableArrayBuilder.AsEnumerable() --- .../Helpers/ImmutableArrayBuilder{T}.cs | 61 ++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/src/CommunityToolkit.Mvvm.SourceGenerators/Helpers/ImmutableArrayBuilder{T}.cs b/src/CommunityToolkit.Mvvm.SourceGenerators/Helpers/ImmutableArrayBuilder{T}.cs index ee775972..228512b3 100644 --- a/src/CommunityToolkit.Mvvm.SourceGenerators/Helpers/ImmutableArrayBuilder{T}.cs +++ b/src/CommunityToolkit.Mvvm.SourceGenerators/Helpers/ImmutableArrayBuilder{T}.cs @@ -7,6 +7,8 @@ using System; using System.Buffers; +using System.Collections; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; @@ -88,6 +90,18 @@ public readonly T[] ToArray() return this.writer!.WrittenSpan.ToArray(); } + /// + /// 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 override readonly string ToString() { @@ -107,7 +121,7 @@ public void Dispose() /// /// A class handling the actual buffer writing. /// - private sealed class Writer : IDisposable + private sealed class Writer : ICollection, IDisposable { /// /// The underlying array. @@ -142,6 +156,9 @@ public ReadOnlySpan WrittenSpan get => new(this.array!, 0, this.index); } + /// + bool ICollection.IsReadOnly => true; + /// public void Add(T value) { @@ -173,6 +190,48 @@ public void Dispose() } } + /// + void ICollection.Clear() + { + throw new NotSupportedException(); + } + + /// + bool ICollection.Contains(T item) + { + throw new NotSupportedException(); + } + + /// + void ICollection.CopyTo(T[] array, int arrayIndex) + { + Array.Copy(this.array!, 0, array, arrayIndex, this.index); + } + + /// + 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(); + } + + /// + bool ICollection.Remove(T item) + { + throw new NotSupportedException(); + } + /// /// Ensures that has enough free space to contain a given number of new items. ///