using System.Collections.Concurrent;
using System.Text;

namespace EonaCat.LogStack.EonaCatLogStackCore
{
    // This file is part of the EonaCat project(s) which is released under the Apache License.
    // See the LICENSE file or go to https://EonaCat.com/License for full license details.

    internal static class StringBuilderPool
    {
        private static readonly ConcurrentBag<StringBuilder> Pool = new ConcurrentBag<StringBuilder>();
        private const int InitialCapacity = 4096;
        private const int MaxCapacity = 131072; // 128 KB – discard oversized builders

        public static StringBuilder Rent()
        {
            StringBuilder sb;
            if (Pool.TryTake(out sb))
            {
                sb.Clear();
                return sb;
            }
            return new StringBuilder(InitialCapacity);
        }

        public static void Return(StringBuilder sb)
        {
            if (sb.Capacity <= MaxCapacity)
            {
                sb.Clear();
                Pool.Add(sb);
            }
        }
    }
}