// 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.
// Ported from Roslyn, see: https://github.com/dotnet/roslyn/blob/main/src/Dependencies/PooledObjects/ObjectPool%601.cs.
using System;
using System.Runtime.CompilerServices;
using System.Threading;
#pragma warning disable RS1035
namespace ComputeSharp.SourceGeneration.Helpers;
///
///
/// Generic implementation of object pooling pattern with predefined pool size limit. The main purpose
/// is that limited number of frequently used objects can be kept in the pool for further recycling.
///
///
/// Notes:
///
/// -
/// It is not the goal to keep all returned objects. Pool is not meant for storage. If there
/// is no space in the pool, extra returned objects will be dropped.
///
/// -
/// It is implied that if object was obtained from a pool, the caller will return it back in
/// a relatively short time. Keeping checked out objects for long durations is ok, but
/// reduces usefulness of pooling. Just new up your own.
///
///
///
///
/// Not returning objects to the pool in not detrimental to the pool's work, but is a bad practice.
/// Rationale: if there is no intent for reusing the object, do not use pool - just use "new".
///
///
/// The type of objects to pool.
internal sealed class ObjectPool
where T : class
{
///
/// The factory is stored for the lifetime of the pool. We will call this only when pool needs to
/// expand. compared to "new T()", Func gives more flexibility to implementers and faster than "new T()".
///
private readonly Func factory;
///
/// The array of cached items.
///
private readonly Element[] items;
///
/// Storage for the pool objects. The first item is stored in a dedicated field
/// because we expect to be able to satisfy most requests from it.
///
private T? firstItem;
///
/// Creates a new instance with the specified parameters.
///
/// The input factory to produce items.
public ObjectPool(Func factory)
: this(factory, Environment.ProcessorCount * 2)
{
}
///
/// Creates a new instance with the specified parameters.
///
/// The input factory to produce items.
/// The pool size to use.
public ObjectPool(Func factory, int size)
{
this.factory = factory;
this.items = new Element[size - 1];
}
///
/// Produces a instance.
///
/// The returned item to use.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Allocate()
{
T? item = this.firstItem;
if (item is null || item != Interlocked.CompareExchange(ref this.firstItem, null, item))
{
item = AllocateSlow();
}
return item;
}
///
/// Returns a given instance to the pool.
///
/// The instance to return.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Free(T obj)
{
if (this.firstItem is null)
{
this.firstItem = obj;
}
else
{
FreeSlow(obj);
}
}
///
/// Allocates a new item.
///
/// The returned item to use.
[MethodImpl(MethodImplOptions.NoInlining)]
private T AllocateSlow()
{
foreach (ref Element element in this.items.AsSpan())
{
T? instance = element.Value;
if (instance is not null)
{
if (instance == Interlocked.CompareExchange(ref element.Value, null, instance))
{
return instance;
}
}
}
return this.factory();
}
///
/// Frees a given item.
///
/// The item to return to the pool.
[MethodImpl(MethodImplOptions.NoInlining)]
private void FreeSlow(T obj)
{
foreach (ref Element element in this.items.AsSpan())
{
if (element.Value is null)
{
element.Value = obj;
break;
}
}
}
///
/// A container for a produced item (using a wrapper to avoid covariance checks).
///
private struct Element
{
///
/// The value held at the current element.
///
internal T? Value;
}
}