MemoryHelper.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. namespace ARMeilleure.Memory
  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.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>(MemoryManager memory, long position) where T : struct
  22. {
  23. long size = Marshal.SizeOf<T>();
  24. byte[] data = memory.ReadBytes(position, size);
  25. fixed (byte* ptr = data)
  26. {
  27. return Marshal.PtrToStructure<T>((IntPtr)ptr);
  28. }
  29. }
  30. public unsafe static void Write<T>(MemoryManager memory, long position, T value) where T : struct
  31. {
  32. long size = Marshal.SizeOf<T>();
  33. byte[] data = new byte[size];
  34. fixed (byte* ptr = data)
  35. {
  36. Marshal.StructureToPtr<T>(value, (IntPtr)ptr, false);
  37. }
  38. memory.WriteBytes(position, data);
  39. }
  40. public static string ReadAsciiString(MemoryManager memory, long position, long maxSize = -1)
  41. {
  42. using (MemoryStream ms = new MemoryStream())
  43. {
  44. for (long offs = 0; offs < maxSize || maxSize == -1; offs++)
  45. {
  46. byte value = (byte)memory.ReadByte(position + offs);
  47. if (value == 0)
  48. {
  49. break;
  50. }
  51. ms.WriteByte(value);
  52. }
  53. return Encoding.ASCII.GetString(ms.ToArray());
  54. }
  55. }
  56. }
  57. }