AMemoryHelper.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. namespace ChocolArm64.Memory
  6. {
  7. public static class AMemoryHelper
  8. {
  9. public static void FillWithZeros(AMemory Memory, long Position, int Size)
  10. {
  11. int Size8 = Size & ~(8 - 1);
  12. for (int Offs = 0; Offs < Size8; Offs += 8)
  13. {
  14. Memory.WriteInt64(Position + Offs, 0);
  15. }
  16. for (int Offs = Size8; Offs < (Size - Size8); Offs++)
  17. {
  18. Memory.WriteByte(Position + Offs, 0);
  19. }
  20. }
  21. public unsafe static T Read<T>(AMemory Memory, long Position) where T : struct
  22. {
  23. long Size = Marshal.SizeOf<T>();
  24. Memory.EnsureRangeIsValid(Position, Size);
  25. IntPtr Ptr = (IntPtr)Memory.Translate(Position);
  26. return Marshal.PtrToStructure<T>(Ptr);
  27. }
  28. public unsafe static void Write<T>(AMemory Memory, long Position, T Value) where T : struct
  29. {
  30. long Size = Marshal.SizeOf<T>();
  31. Memory.EnsureRangeIsValid(Position, Size);
  32. IntPtr Ptr = (IntPtr)Memory.TranslateWrite(Position);
  33. Marshal.StructureToPtr<T>(Value, Ptr, false);
  34. }
  35. public static string ReadAsciiString(AMemory Memory, long Position, long MaxSize = -1)
  36. {
  37. using (MemoryStream MS = new MemoryStream())
  38. {
  39. for (long Offs = 0; Offs < MaxSize || MaxSize == -1; Offs++)
  40. {
  41. byte Value = (byte)Memory.ReadByte(Position + Offs);
  42. if (Value == 0)
  43. {
  44. break;
  45. }
  46. MS.WriteByte(Value);
  47. }
  48. return Encoding.ASCII.GetString(MS.ToArray());
  49. }
  50. }
  51. }
  52. }