MemoryHelper.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using Ryujinx.Memory;
  2. using System;
  3. using System.IO;
  4. using System.Runtime.CompilerServices;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. namespace Ryujinx.Cpu
  8. {
  9. public static class MemoryHelper
  10. {
  11. public static void FillWithZeros(IVirtualMemoryManager memory, ulong position, int size)
  12. {
  13. int size8 = size & ~(8 - 1);
  14. for (int offs = 0; offs < size8; offs += 8)
  15. {
  16. memory.Write<long>(position + (ulong)offs, 0);
  17. }
  18. for (int offs = size8; offs < (size - size8); offs++)
  19. {
  20. memory.Write<byte>(position + (ulong)offs, 0);
  21. }
  22. }
  23. public unsafe static T Read<T>(IVirtualMemoryManager memory, ulong position) where T : unmanaged
  24. {
  25. return MemoryMarshal.Cast<byte, T>(memory.GetSpan(position, Unsafe.SizeOf<T>()))[0];
  26. }
  27. public unsafe static ulong Write<T>(IVirtualMemoryManager memory, ulong position, T value) where T : unmanaged
  28. {
  29. ReadOnlySpan<byte> data = MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateReadOnlySpan(ref value, 1));
  30. memory.Write(position, data);
  31. return (ulong)data.Length;
  32. }
  33. public static string ReadAsciiString(IVirtualMemoryManager memory, ulong position, long maxSize = -1)
  34. {
  35. using (MemoryStream ms = new MemoryStream())
  36. {
  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.ToArray());
  47. }
  48. }
  49. }
  50. }