MemoryHelper.cs 1.9 KB

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