// 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.Immutable; namespace ComputeSharp.SourceGeneration.Helpers; /// /// A helper type to build instances with pooled buffers. /// /// The type of items to create arrays for. internal ref struct ImmutableArrayBuilder { /// /// The shared instance to share objects. /// private static readonly ObjectPool.Builder> sharedObjectPool = new(ImmutableArray.CreateBuilder); /// /// The owner instance. /// private readonly ObjectPool.Builder> objectPool; /// /// The rented instance to use. /// private ImmutableArray.Builder? builder; /// /// Rents a new pooled instance through a new value. /// /// A to interact with the underlying instance. public static ImmutableArrayBuilder Rent() { return new(sharedObjectPool, sharedObjectPool.Allocate()); } /// /// Creates a new object with the specified parameters. /// /// /// private ImmutableArrayBuilder(ObjectPool.Builder> objectPool, ImmutableArray.Builder builder) { this.objectPool = objectPool; this.builder = builder; } /// public readonly int Count { get => this.builder!.Count; } /// public readonly void Add(T item) { this.builder!.Add(item); } /// public readonly ImmutableArray ToImmutable() { return this.builder!.ToImmutable(); } /// public readonly T[] ToArray() { return this.builder!.ToArray(); } /// public void Dispose() { ImmutableArray.Builder? builder = this.builder; this.builder = null; if (builder is not null) { builder.Clear(); this.objectPool.Free(builder); } } }