diff options
author | Mary-nyan <mary@mary.zone> | 2022-11-24 15:26:29 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-11-24 15:26:29 +0100 |
commit | f4e879a1e6ad810aa38c1c020467a2589441871b (patch) | |
tree | 274c6ee1f55129f01bbd28a6dcd92ce3f84237fb /Ryujinx.Common/Extensions/BinaryReaderExtensions.cs | |
parent | a1ddaa2736b188de928564af56aa787a25831ff7 (diff) |
Reduce usage of Marshal.PtrToStructure and Marshal.StructureToPtr (#3805)1.1.381
* common: Make BinaryReaderExtensions Read & Write take unamanged types
This allows us to not rely on Marshal.PtrToStructure and Marshal.StructureToPtr for those.
* common: Make MemoryHelper Read & Write takes unamanged types
* Update Marshal.SizeOf => Unsafe.SizeOf when appropriate and start moving software applet to unmanaged types
Diffstat (limited to 'Ryujinx.Common/Extensions/BinaryReaderExtensions.cs')
-rw-r--r-- | Ryujinx.Common/Extensions/BinaryReaderExtensions.cs | 43 |
1 files changed, 5 insertions, 38 deletions
diff --git a/Ryujinx.Common/Extensions/BinaryReaderExtensions.cs b/Ryujinx.Common/Extensions/BinaryReaderExtensions.cs index 2c24678d..ea404d2a 100644 --- a/Ryujinx.Common/Extensions/BinaryReaderExtensions.cs +++ b/Ryujinx.Common/Extensions/BinaryReaderExtensions.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Ryujinx.Common @@ -7,49 +8,15 @@ namespace Ryujinx.Common public static class BinaryReaderExtensions { public unsafe static T ReadStruct<T>(this BinaryReader reader) - where T : struct + where T : unmanaged { - int size = Marshal.SizeOf<T>(); - - byte[] data = reader.ReadBytes(size); - - fixed (byte* ptr = data) - { - return Marshal.PtrToStructure<T>((IntPtr)ptr); - } - } - - public unsafe static T[] ReadStructArray<T>(this BinaryReader reader, int count) - where T : struct - { - int size = Marshal.SizeOf<T>(); - - T[] result = new T[count]; - - for (int i = 0; i < count; i++) - { - byte[] data = reader.ReadBytes(size); - - fixed (byte* ptr = data) - { - result[i] = Marshal.PtrToStructure<T>((IntPtr)ptr); - } - } - - return result; + return MemoryMarshal.Cast<byte, T>(reader.ReadBytes(Unsafe.SizeOf<T>()))[0]; } public unsafe static void WriteStruct<T>(this BinaryWriter writer, T value) - where T : struct + where T : unmanaged { - long size = Marshal.SizeOf<T>(); - - byte[] data = new byte[size]; - - fixed (byte* ptr = data) - { - Marshal.StructureToPtr<T>(value, (IntPtr)ptr, false); - } + ReadOnlySpan<byte> data = MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateReadOnlySpan(ref value, 1)); writer.Write(data); } |