using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.IO;

namespace Common
{
    /// <summary>
    /// MemoryStream对象池，用于高并发场景减少GC压力
    /// </summary>
    internal static class MemoryStreamPool
    {
        private static readonly ConcurrentBag<MemoryStream> pool = new ConcurrentBag<MemoryStream>();
        private const int MaxPoolSize = 100;
        private const int MaxStreamCapacity = 10240; // 10KB，超过此大小的流不放回池中

        public static MemoryStream Rent()
        {
            MemoryStream stream = null;
            if (pool.TryTake(out stream))
            {
                stream.Position = 0;
                stream.SetLength(0);
                return stream;
            }
            return new MemoryStream();
        }

        public static void Return(MemoryStream stream)
        {
            if (stream != null && stream.Capacity <= MaxStreamCapacity && pool.Count < MaxPoolSize)
            {
                stream.Position = 0;
                stream.SetLength(0);
                pool.Add(stream);
            }
        }

    }
}
