using System;
using System.Text;

namespace XGame.Framework.Utils
{
    public static class StringBuilderUtils
    {
        private const int CAPACITY_LIMIT = 360;
        [ThreadStatic]
        private static StringBuilder CachedInstance;
        private const int DefaultCapacity = 16;
        public static StringBuilder Acquire(int capacity = DefaultCapacity)
        {
            if (capacity <= CAPACITY_LIMIT)
            {
                StringBuilder sb = CachedInstance;
                if (sb != null)
                {
                    // Avoid stringbuilder block fragmentation by getting a new StringBuilder
                    // when the requested size is larger than the current capacity
                    if (capacity <= sb.Capacity)
                    {
                        CachedInstance = null;
                        sb.Clear();
                        return sb;
                    }
                }
            }
            return new StringBuilder(capacity);
        }

        public static void Release(StringBuilder sb)
        {
            if (sb.Capacity <= CAPACITY_LIMIT)
            {
                CachedInstance = sb;
            }
        }

        public static string GetStringAndRelease(StringBuilder sb)
        {
            string result = sb.ToString();
            Release(sb);
            return result;
        }
    }

}
