// 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 new object. /// public ImmutableHashSetBuilder() { this.set = SharedObjectPool.Allocate(); } /// /// 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); } } }