42 lines
		
	
	
		
			991 B
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			42 lines
		
	
	
		
			991 B
		
	
	
	
		
			C#
		
	
	
	
	
	
using System;
 | 
						|
using System.Collections.Generic;
 | 
						|
 | 
						|
namespace Engine.Core;
 | 
						|
 | 
						|
public class Pool<T> : IPool<T>
 | 
						|
{
 | 
						|
    public Event<IPool<T>, T> OnRemoved { get; } = new();
 | 
						|
    public Event<IPool<T>, T> OnReturned { get; } = new();
 | 
						|
 | 
						|
    private readonly Func<T> generator = null!;
 | 
						|
    private readonly Queue<T> queue = new();
 | 
						|
    private readonly HashSet<T> queuedHashes = [];
 | 
						|
 | 
						|
    public T Get()
 | 
						|
    {
 | 
						|
        if (!queue.TryDequeue(out T? result))
 | 
						|
            result = generator();
 | 
						|
 | 
						|
        queuedHashes.Remove(result);
 | 
						|
        OnRemoved?.Invoke(this, result);
 | 
						|
        return result;
 | 
						|
    }
 | 
						|
 | 
						|
    public void Return(T item)
 | 
						|
    {
 | 
						|
        if (queuedHashes.Contains(item))
 | 
						|
            return;
 | 
						|
 | 
						|
        queue.Enqueue(item);
 | 
						|
        queuedHashes.Add(item);
 | 
						|
        OnReturned?.Invoke(this, item);
 | 
						|
    }
 | 
						|
 | 
						|
    public Pool(Func<T> generator, int initialCapacity = 1)
 | 
						|
    {
 | 
						|
        this.generator = generator;
 | 
						|
        for (int i = 0; i < initialCapacity; i++)
 | 
						|
            queue.Enqueue(generator());
 | 
						|
    }
 | 
						|
}
 |