ByteMemoryPool.ByteMemoryPoolBuffer.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Buffers;
  3. using System.Threading;
  4. namespace Ryujinx.Common.Memory
  5. {
  6. public partial class ByteMemoryPool
  7. {
  8. /// <summary>
  9. /// Represents a <see cref="IMemoryOwner{Byte}"/> that wraps an array rented from
  10. /// <see cref="ArrayPool{Byte}.Shared"/> and exposes it as <see cref="Memory{Byte}"/>
  11. /// with a length of the requested size.
  12. /// </summary>
  13. private sealed class ByteMemoryPoolBuffer : IMemoryOwner<byte>
  14. {
  15. private byte[] _array;
  16. private readonly int _length;
  17. public ByteMemoryPoolBuffer(int length)
  18. {
  19. _array = ArrayPool<byte>.Shared.Rent(length);
  20. _length = length;
  21. }
  22. /// <summary>
  23. /// Returns a <see cref="Memory{Byte}"/> belonging to this owner.
  24. /// </summary>
  25. public Memory<byte> Memory
  26. {
  27. get
  28. {
  29. byte[] array = _array;
  30. ObjectDisposedException.ThrowIf(array is null, this);
  31. return new Memory<byte>(array, 0, _length);
  32. }
  33. }
  34. public void Dispose()
  35. {
  36. var array = Interlocked.Exchange(ref _array, null);
  37. if (array != null)
  38. {
  39. ArrayPool<byte>.Shared.Return(array);
  40. }
  41. }
  42. }
  43. }
  44. }