using System;
namespace Mirror
{
    /// Pooled NetworkReader, automatically returned to pool when using 'using'
    public sealed class PooledNetworkReader : NetworkReader, IDisposable
    {
        internal PooledNetworkReader(byte[] bytes) : base(bytes) {}
        internal PooledNetworkReader(ArraySegment segment) : base(segment) {}
        public void Dispose() => NetworkReaderPool.Recycle(this);
    }
    /// Pool of NetworkReaders to avoid allocations.
    public static class NetworkReaderPool
    {
        // reuse Pool
        // we still wrap it in NetworkReaderPool.Get/Recyle so we can reset the
        // position and array before reusing.
        static readonly Pool Pool = new Pool(
            // byte[] will be assigned in GetReader
            () => new PooledNetworkReader(new byte[]{}),
            // initial capacity to avoid allocations in the first few frames
            1000
        );
        /// Get the next reader in the pool. If pool is empty, creates a new Reader
        public static PooledNetworkReader GetReader(byte[] bytes)
        {
            // grab from pool & set buffer
            PooledNetworkReader reader = Pool.Take();
            reader.SetBuffer(bytes);
            return reader;
        }
        /// Get the next reader in the pool. If pool is empty, creates a new Reader
        public static PooledNetworkReader GetReader(ArraySegment segment)
        {
            // grab from pool & set buffer
            PooledNetworkReader reader = Pool.Take();
            reader.SetBuffer(segment);
            return reader;
        }
        /// Returns a reader to the pool.
        public static void Recycle(PooledNetworkReader reader)
        {
            Pool.Return(reader);
        }
    }
}