NetworkReaderPool.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // API consistent with Microsoft's ObjectPool<T>.
  2. using System;
  3. using System.Runtime.CompilerServices;
  4. namespace Mirror
  5. {
  6. /// <summary>Pool of NetworkReaders to avoid allocations.</summary>
  7. public static class NetworkReaderPool
  8. {
  9. // reuse Pool<T>
  10. // we still wrap it in NetworkReaderPool.Get/Recyle so we can reset the
  11. // position and array before reusing.
  12. static readonly Pool<NetworkReaderPooled> Pool = new Pool<NetworkReaderPooled>(
  13. // byte[] will be assigned in GetReader
  14. () => new NetworkReaderPooled(new byte[]{}),
  15. // initial capacity to avoid allocations in the first few frames
  16. 1000
  17. );
  18. // DEPRECATED 2022-03-10
  19. [Obsolete("GetReader() was renamed to Get()")]
  20. public static NetworkReaderPooled GetReader(byte[] bytes) => Get(bytes);
  21. /// <summary>Get the next reader in the pool. If pool is empty, creates a new Reader</summary>
  22. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  23. public static NetworkReaderPooled Get(byte[] bytes)
  24. {
  25. // grab from pool & set buffer
  26. NetworkReaderPooled reader = Pool.Get();
  27. reader.SetBuffer(bytes);
  28. return reader;
  29. }
  30. // DEPRECATED 2022-03-10
  31. [Obsolete("GetReader() was renamed to Get()")]
  32. public static NetworkReaderPooled GetReader(ArraySegment<byte> segment) => Get(segment);
  33. /// <summary>Get the next reader in the pool. If pool is empty, creates a new Reader</summary>
  34. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  35. public static NetworkReaderPooled Get(ArraySegment<byte> segment)
  36. {
  37. // grab from pool & set buffer
  38. NetworkReaderPooled reader = Pool.Get();
  39. reader.SetBuffer(segment);
  40. return reader;
  41. }
  42. // DEPRECATED 2022-03-10
  43. [Obsolete("Recycle() was renamed to Return()")]
  44. public static void Recycle(NetworkReaderPooled reader) => Return(reader);
  45. /// <summary>Returns a reader to the pool.</summary>
  46. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  47. public static void Return(NetworkReaderPooled reader)
  48. {
  49. Pool.Return(reader);
  50. }
  51. }
  52. }