From 40735c713a01c01069cbe816822cbb47fe072bfc Mon Sep 17 00:00:00 2001 From: Syntriax Date: Mon, 9 Jun 2025 17:51:06 +0300 Subject: [PATCH] feat: added basic pool helper --- Engine.Core/Helpers/Pool.cs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Engine.Core/Helpers/Pool.cs diff --git a/Engine.Core/Helpers/Pool.cs b/Engine.Core/Helpers/Pool.cs new file mode 100644 index 0000000..b9f5c99 --- /dev/null +++ b/Engine.Core/Helpers/Pool.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; + +namespace Syntriax.Engine.Core; + +public class Pool +{ + private readonly Func factory; + private readonly Queue queue = new(); + + public T Get() + { + if (queue.TryDequeue(out T? result)) + return result; + + return factory(); + } + + public void Return(T item) + { + if (queue.Contains(item)) + return; + + queue.Enqueue(item); + } + + public Pool(Func factory, int initialCapacity = 1) + { + this.factory = factory; + for (int i = 0; i < initialCapacity; i++) + queue.Enqueue(factory()); + } +}