MemoryHelper.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. namespace Ryujinx.Cpu
  6. {
  7. public static class MemoryHelper
  8. {
  9. public static void FillWithZeros(MemoryManager memory, long position, int size)
  10. {
  11. int size8 = size & ~(8 - 1);
  12. for (int offs = 0; offs < size8; offs += 8)
  13. {
  14. memory.Write<long>((ulong)(position + offs), 0);
  15. }
  16. for (int offs = size8; offs < (size - size8); offs++)
  17. {
  18. memory.Write<byte>((ulong)(position + offs), 0);
  19. }
  20. }
  21. public unsafe static T Read<T>(MemoryManager memory, long position) where T : struct
  22. {
  23. long size = Marshal.SizeOf<T>();
  24. byte[] data = new byte[size];
  25. memory.Read((ulong)position, data);
  26. fixed (byte* ptr = data)
  27. {
  28. return Marshal.PtrToStructure<T>((IntPtr)ptr);
  29. }
  30. }
  31. public unsafe static void Write<T>(MemoryManager memory, long position, T value) where T : struct
  32. {
  33. long size = Marshal.SizeOf<T>();
  34. byte[] data = new byte[size];
  35. fixed (byte* ptr = data)
  36. {
  37. Marshal.StructureToPtr<T>(value, (IntPtr)ptr, false);
  38. }
  39. memory.Write((ulong)position, data);
  40. }
  41. public static string ReadAsciiString(MemoryManager memory, long position, long maxSize = -1)
  42. {
  43. using (MemoryStream ms = new MemoryStream())
  44. {
  45. for (long offs = 0; offs < maxSize || maxSize == -1; offs++)
  46. {
  47. byte value = memory.Read<byte>((ulong)(position + offs));
  48. if (value == 0)
  49. {
  50. break;
  51. }
  52. ms.WriteByte(value);
  53. }
  54. return Encoding.ASCII.GetString(ms.ToArray());
  55. }
  56. }
  57. }
  58. }