MemoryHelper.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using Microsoft.IO;
  2. using Ryujinx.Common.Memory;
  3. using Ryujinx.Memory;
  4. using System;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. namespace Ryujinx.Cpu
  9. {
  10. public static class MemoryHelper
  11. {
  12. public static void FillWithZeros(IVirtualMemoryManager memory, ulong position, int size)
  13. {
  14. int size8 = size & ~(8 - 1);
  15. for (int offs = 0; offs < size8; offs += 8)
  16. {
  17. memory.Write<long>(position + (ulong)offs, 0);
  18. }
  19. for (int offs = size8; offs < (size - size8); offs++)
  20. {
  21. memory.Write<byte>(position + (ulong)offs, 0);
  22. }
  23. }
  24. public static T Read<T>(IVirtualMemoryManager memory, ulong position) where T : unmanaged
  25. {
  26. return MemoryMarshal.Cast<byte, T>(memory.GetSpan(position, Unsafe.SizeOf<T>()))[0];
  27. }
  28. public static ulong Write<T>(IVirtualMemoryManager memory, ulong position, T value) where T : unmanaged
  29. {
  30. ReadOnlySpan<byte> data = MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateReadOnlySpan(ref value, 1));
  31. memory.Write(position, data);
  32. return (ulong)data.Length;
  33. }
  34. public static string ReadAsciiString(IVirtualMemoryManager memory, ulong position, long maxSize = -1)
  35. {
  36. using RecyclableMemoryStream ms = MemoryStreamManager.Shared.GetStream();
  37. for (long offs = 0; offs < maxSize || maxSize == -1; offs++)
  38. {
  39. byte value = memory.Read<byte>(position + (ulong)offs);
  40. if (value == 0)
  41. {
  42. break;
  43. }
  44. ms.WriteByte(value);
  45. }
  46. return Encoding.ASCII.GetString(ms.GetReadOnlySequence());
  47. }
  48. }
  49. }