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
{
internal PooledReader(byte[] bytes, NetworkManager networkManager, Reader.DataSource source = Reader.DataSource.Unset) : base(bytes, networkManager, null, source) { }
internal PooledReader(ArraySegment segment, NetworkManager networkManager, Reader.DataSource source = Reader.DataSource.Unset) : base(segment, networkManager, null, source) { }
public void Store() => ReaderPool.Store(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 Retrieve(byte[] bytes, NetworkManager networkManager, Reader.DataSource source = Reader.DataSource.Unset)
{
return Retrieve(new ArraySegment(bytes), networkManager, source);
}
///
/// Get the next reader in the pool or creates a new one if none are available.
///
public static PooledReader Retrieve(ArraySegment segment, NetworkManager networkManager, Reader.DataSource source = Reader.DataSource.Unset)
{
PooledReader result;
if (_pool.Count > 0)
{
result = _pool.Pop();
result.Initialize(segment, networkManager, source);
}
else
{
result = new PooledReader(segment, networkManager, source);
}
return result;
}
///
/// Puts reader back into pool
///
public static void Store(PooledReader reader)
{
_pool.Push(reader);
}
///
/// Puts reader back into pool if not null, and nullifies source reference.
///
public static void StoreAndDefault(ref PooledReader reader)
{
if (reader != null)
{
_pool.Push(reader);
reader = null;
}
}
}
}