using FishNet.Managing;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace FishNet.Serializing
{
    /// 
    /// Reader which is reused to save on garbage collection and performance.
    /// 
    public sealed class PooledReader : Reader, IDisposable
    {
        internal PooledReader(byte[] bytes, NetworkManager networkManager) : base(bytes, networkManager) { }
        internal PooledReader(ArraySegment segment, NetworkManager networkManager) : base(segment, networkManager) { }
        public void Dispose() => ReaderPool.Recycle(this);
    }
    /// 
    /// Collection of PooledReader. Stores and gets PooledReader.
    /// 
    public static class ReaderPool
    {
        #region Private.
        /// 
        /// Pool of readers.
        /// 
        private static readonly Stack _pool = new Stack();
        #endregion
        /// 
        /// Get the next reader in the pool
        /// If pool is empty, creates a new Reader
        /// 
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static PooledReader GetReader(byte[] bytes, NetworkManager networkManager)
        {
            return GetReader(new ArraySegment(bytes), networkManager);
        }
        /// 
        /// Get the next reader in the pool or creates a new one if none are available.
        /// 
        public static PooledReader GetReader(ArraySegment segment, NetworkManager networkManager)
        {
            PooledReader result;
            if (_pool.Count > 0)
            {
                result = _pool.Pop();
                result.Initialize(segment, networkManager);
            }
            else
            {
                result = new PooledReader(segment, networkManager);
            }
            return result;
        }
        /// 
        /// Puts reader back into pool
        /// When pool is full, the extra reader is left for the GC
        /// 
        public static void Recycle(PooledReader reader)
        {
            _pool.Push(reader);
        }
    }
}