NetworkReaderPool.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. namespace Mirror
  3. {
  4. /// <summary>Pooled NetworkReader, automatically returned to pool when using 'using'</summary>
  5. public sealed class PooledNetworkReader : NetworkReader, IDisposable
  6. {
  7. internal PooledNetworkReader(byte[] bytes) : base(bytes) {}
  8. internal PooledNetworkReader(ArraySegment<byte> segment) : base(segment) {}
  9. public void Dispose() => NetworkReaderPool.Recycle(this);
  10. }
  11. /// <summary>Pool of NetworkReaders to avoid allocations.</summary>
  12. public static class NetworkReaderPool
  13. {
  14. // reuse Pool<T>
  15. // we still wrap it in NetworkReaderPool.Get/Recyle so we can reset the
  16. // position and array before reusing.
  17. static readonly Pool<PooledNetworkReader> Pool = new Pool<PooledNetworkReader>(
  18. // byte[] will be assigned in GetReader
  19. () => new PooledNetworkReader(new byte[]{}),
  20. // initial capacity to avoid allocations in the first few frames
  21. 1000
  22. );
  23. /// <summary>Get the next reader in the pool. If pool is empty, creates a new Reader</summary>
  24. public static PooledNetworkReader GetReader(byte[] bytes)
  25. {
  26. // grab from pool & set buffer
  27. PooledNetworkReader reader = Pool.Take();
  28. reader.SetBuffer(bytes);
  29. return reader;
  30. }
  31. /// <summary>Get the next reader in the pool. If pool is empty, creates a new Reader</summary>
  32. public static PooledNetworkReader GetReader(ArraySegment<byte> segment)
  33. {
  34. // grab from pool & set buffer
  35. PooledNetworkReader reader = Pool.Take();
  36. reader.SetBuffer(segment);
  37. return reader;
  38. }
  39. /// <summary>Returns a reader to the pool.</summary>
  40. public static void Recycle(PooledNetworkReader reader)
  41. {
  42. Pool.Return(reader);
  43. }
  44. }
  45. }