NetworkReaderPool.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. /// <summary>Get the next reader in the pool. If pool is empty, creates a new Reader</summary>
  19. public static NetworkReaderPooled Get(byte[] bytes)
  20. {
  21. // grab from pool & set buffer
  22. NetworkReaderPooled reader = Pool.Get();
  23. reader.SetBuffer(bytes);
  24. return reader;
  25. }
  26. /// <summary>Get the next reader in the pool. If pool is empty, creates a new Reader</summary>
  27. public static NetworkReaderPooled Get(ArraySegment<byte> segment)
  28. {
  29. // grab from pool & set buffer
  30. NetworkReaderPooled reader = Pool.Get();
  31. reader.SetBuffer(segment);
  32. return reader;
  33. }
  34. /// <summary>Returns a reader to the pool.</summary>
  35. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  36. public static void Return(NetworkReaderPooled reader)
  37. {
  38. Pool.Return(reader);
  39. }
  40. }
  41. }