SpanMemoryManager.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // Copyright (c) 2019-2021 Ryujinx
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. //
  17. using System;
  18. using System.Buffers;
  19. using System.Runtime.InteropServices;
  20. namespace Ryujinx.Audio.Renderer.Utils
  21. {
  22. public sealed unsafe class SpanMemoryManager<T> : MemoryManager<T>
  23. where T : unmanaged
  24. {
  25. private readonly T* _pointer;
  26. private readonly int _length;
  27. public SpanMemoryManager(Span<T> span)
  28. {
  29. fixed (T* ptr = &MemoryMarshal.GetReference(span))
  30. {
  31. _pointer = ptr;
  32. _length = span.Length;
  33. }
  34. }
  35. public override Span<T> GetSpan() => new Span<T>(_pointer, _length);
  36. public override MemoryHandle Pin(int elementIndex = 0)
  37. {
  38. if (elementIndex < 0 || elementIndex >= _length)
  39. {
  40. throw new ArgumentOutOfRangeException(nameof(elementIndex));
  41. }
  42. return new MemoryHandle(_pointer + elementIndex);
  43. }
  44. public override void Unpin() { }
  45. protected override void Dispose(bool disposing) { }
  46. public static Memory<T> Cast<TFrom>(Memory<TFrom> memory) where TFrom : unmanaged
  47. {
  48. return new SpanMemoryManager<T>(MemoryMarshal.Cast<TFrom, T>(memory.Span)).Memory;
  49. }
  50. }
  51. }