diff --git a/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs new file mode 100644 index 00000000..f9faaaca --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Helpers/ImmutableHashSetBuilder{T}.cs @@ -0,0 +1,102 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.SourceGeneration.Helpers; + +/// +/// A helper type to build hash sets of values with pooled buffers. +/// +/// The type of items to create hash sets for. +internal struct ImmutableHashSetBuilder : IDisposable +{ + /// + /// The shared instance to share objects. + /// + private static readonly ObjectPool> SharedObjectPool = new(static () => new HashSet()); + + /// + /// The rented instance to use. + /// + private HashSet? set; + + /// + /// Creates a value with a pooled underlying data writer. + /// + /// A instance to write data to. + public static ImmutableHashSetBuilder Rent() + { + return new(SharedObjectPool.Allocate()); + } + + /// + /// Creates a new object with the specified parameters. + /// + /// The target instance to use. + private ImmutableHashSetBuilder(HashSet set) + { + this.set = set; + } + + /// + /// Gets the number of elements currently written in the current instance. + /// + public readonly int Count + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => this.set!.Count; + } + + /// + public readonly void Add(T item) + { + _ = this.set!.Add(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.set!; + } + + /// + public readonly ImmutableArray ToImmutable() + { + T[] array = this.set!.ToArray(); + + return Unsafe.As>(ref array); + } + + /// + public readonly T[] ToArray() + { + return this.set!.ToArray(); + } + + /// + public void Dispose() + { + HashSet? writer = this.set; + + this.set = null; + + if (writer is not null) + { + writer.Clear(); + + SharedObjectPool.Free(writer); + } + } +} \ No newline at end of file