WorkBufferAllocator.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // Copyright (c) 2019-2020 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 Ryujinx.Audio.Renderer.Utils;
  18. using Ryujinx.Common;
  19. using System;
  20. using System.Diagnostics;
  21. using System.Runtime.CompilerServices;
  22. namespace Ryujinx.Audio.Renderer.Common
  23. {
  24. public class WorkBufferAllocator
  25. {
  26. public Memory<byte> BackingMemory { get; }
  27. public ulong Offset { get; private set; }
  28. public WorkBufferAllocator(Memory<byte> backingMemory)
  29. {
  30. BackingMemory = backingMemory;
  31. }
  32. public Memory<byte> Allocate(ulong size, int align)
  33. {
  34. Debug.Assert(align != 0);
  35. if (size != 0)
  36. {
  37. ulong alignedOffset = BitUtils.AlignUp(Offset, align);
  38. if (alignedOffset + size <= (ulong)BackingMemory.Length)
  39. {
  40. Memory<byte> result = BackingMemory.Slice((int)alignedOffset, (int)size);
  41. Offset = alignedOffset + size;
  42. // Clear the memory to be sure that is does not contain any garbage.
  43. result.Span.Fill(0);
  44. return result;
  45. }
  46. }
  47. return Memory<byte>.Empty;
  48. }
  49. public Memory<T> Allocate<T>(ulong count, int align) where T: unmanaged
  50. {
  51. Memory<byte> allocatedMemory = Allocate((ulong)Unsafe.SizeOf<T>() * count, align);
  52. if (allocatedMemory.IsEmpty)
  53. {
  54. return Memory<T>.Empty;
  55. }
  56. return SpanMemoryManager<T>.Cast(allocatedMemory);
  57. }
  58. public static ulong GetTargetSize<T>(ulong currentSize, ulong count, int align) where T: unmanaged
  59. {
  60. return BitUtils.AlignUp(currentSize, align) + (ulong)Unsafe.SizeOf<T>() * count;
  61. }
  62. }
  63. }