BinaryReaderExtensions.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. namespace Ryujinx.Common
  5. {
  6. public static class BinaryReaderExtensions
  7. {
  8. public unsafe static T ReadStruct<T>(this BinaryReader reader)
  9. where T : struct
  10. {
  11. int size = Marshal.SizeOf<T>();
  12. byte[] data = reader.ReadBytes(size);
  13. fixed (byte* ptr = data)
  14. {
  15. return Marshal.PtrToStructure<T>((IntPtr)ptr);
  16. }
  17. }
  18. public unsafe static T[] ReadStructArray<T>(this BinaryReader reader, int count)
  19. where T : struct
  20. {
  21. int size = Marshal.SizeOf<T>();
  22. T[] result = new T[count];
  23. for (int i = 0; i < count; i++)
  24. {
  25. byte[] data = reader.ReadBytes(size);
  26. fixed (byte* ptr = data)
  27. {
  28. result[i] = Marshal.PtrToStructure<T>((IntPtr)ptr);
  29. }
  30. }
  31. return result;
  32. }
  33. public unsafe static void WriteStruct<T>(this BinaryWriter writer, T value)
  34. where T : struct
  35. {
  36. long size = Marshal.SizeOf<T>();
  37. byte[] data = new byte[size];
  38. fixed (byte* ptr = data)
  39. {
  40. Marshal.StructureToPtr<T>(value, (IntPtr)ptr, false);
  41. }
  42. writer.Write(data);
  43. }
  44. }
  45. }