41 lines
		
	
	
		
			1007 B
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			41 lines
		
	
	
		
			1007 B
		
	
	
	
		
			C#
		
	
	
	
	
	
using System;
 | 
						|
using System.Collections.Generic;
 | 
						|
 | 
						|
namespace Engine.Core;
 | 
						|
 | 
						|
public class ListPool<T> : IPool<List<T>>
 | 
						|
{
 | 
						|
    public Event<IPool<List<T>>, List<T>> OnReturned { get; } = new();
 | 
						|
    public Event<IPool<List<T>>, List<T>> OnRemoved { get; } = new();
 | 
						|
 | 
						|
    private readonly Func<List<T>> generator = null!;
 | 
						|
    private readonly Queue<List<T>> queue = new();
 | 
						|
 | 
						|
    public List<T> Get()
 | 
						|
    {
 | 
						|
        if (!queue.TryDequeue(out List<T>? result))
 | 
						|
            result = generator();
 | 
						|
 | 
						|
        result.Clear();
 | 
						|
        OnRemoved?.Invoke(this, result);
 | 
						|
        return result;
 | 
						|
    }
 | 
						|
 | 
						|
    public void Return(List<T> list)
 | 
						|
    {
 | 
						|
        if (queue.Contains(list))
 | 
						|
            return;
 | 
						|
 | 
						|
        list.Clear();
 | 
						|
        queue.Enqueue(list);
 | 
						|
        OnReturned?.Invoke(this, list);
 | 
						|
    }
 | 
						|
 | 
						|
    public ListPool(int initialListCount = 1, int initialListCapacity = 32)
 | 
						|
    {
 | 
						|
        generator = () => new(initialListCapacity);
 | 
						|
        for (int i = 0; i < initialListCount; i++)
 | 
						|
            queue.Enqueue(generator());
 | 
						|
    }
 | 
						|
}
 |