using FishNet.Managing;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace FishNet.Serializing
{
///
/// Writer which is reused to save on garbage collection and performance.
///
public sealed class PooledWriter : Writer, IDisposable
{
public void Dispose() => WriterPool.Recycle(this);
}
///
/// Collection of PooledWriter. Stores and gets PooledWriter.
///
public static class WriterPool
{
#region Private.
///
/// Pool of writers.
///
private static readonly Stack _pool = new Stack();
#endregion
///
/// Get the next writer in the pool.
/// If pool is empty, creates a new Reader
///
public static PooledWriter GetWriter(NetworkManager networkManager)
{
PooledWriter result = (_pool.Count > 0) ? _pool.Pop() : new PooledWriter();
result.Reset(networkManager);
return result;
}
///
/// Get the next writer in the pool.
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static PooledWriter GetWriter()
{
return GetWriter(null);
}
///
/// Puts writer back into pool
/// When pool is full, the extra writer is left for the GC
///
public static void Recycle(PooledWriter writer)
{
_pool.Push(writer);
}
}
}