From 679d9b3d6aa4eac8d5549597fec4924566b14907 Mon Sep 17 00:00:00 2001 From: goat <16760685+goaaats@users.noreply.github.com> Date: Wed, 31 Mar 2021 03:08:15 +0200 Subject: [PATCH] refactor: new code style in SafeMemory.cs --- Dalamud/SafeMemory.cs | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/Dalamud/SafeMemory.cs b/Dalamud/SafeMemory.cs index c8a06895d..44aca3543 100644 --- a/Dalamud/SafeMemory.cs +++ b/Dalamud/SafeMemory.cs @@ -1,16 +1,14 @@ using System; -using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using System.Runtime.InteropServices; using System.Text; -using System.Threading.Tasks; + using JetBrains.Annotations; namespace Dalamud { /// - /// Class facilitating safe memory access + /// Class facilitating safe memory access. /// /// /// Attention! The performance of these methods is severely worse than regular calls. @@ -52,14 +50,16 @@ namespace Dalamud } /// - /// Read an object of the specified struct from the current process. + /// Read an object of the specified struct from the current process. /// /// The type of the struct. /// The address to read from. /// The resulting object. /// Whether or not the read succeeded. - public static bool Read(IntPtr address, out T result) where T : struct { - if (!ReadBytes(address, SizeCache.Size, out var buffer)) { + public static bool Read(IntPtr address, out T result) where T : struct + { + if (!ReadBytes(address, SizeCache.Size, out var buffer)) + { result = default; return false; } @@ -203,17 +203,17 @@ namespace Dalamud /// /// The type to inspect. /// The size of the passed type. - public static int SizeOf() where T: struct + public static int SizeOf() where T : struct { return SizeCache.Size; } - private static class SizeCache + private static class SizeCache { // ReSharper disable once StaticMemberInGenericType public static readonly int Size; - static SizeCache() + static SizeCache() { var type = typeof(T); if (type.IsEnum) @@ -236,15 +236,18 @@ namespace Dalamud private sealed class LocalMemory : IDisposable { - private IntPtr hGlobal; private readonly int size; + private IntPtr hGlobal; + public LocalMemory(int size) { this.size = size; this.hGlobal = Marshal.AllocHGlobal(this.size); } + ~LocalMemory() => this.Dispose(); + public byte[] Read() { var bytes = new byte[this.size]; @@ -253,9 +256,10 @@ namespace Dalamud } public T Read(int offset = 0) => (T)Marshal.PtrToStructure(this.hGlobal + offset, typeof(T)); + public void Write(byte[] data, int index = 0) => Marshal.Copy(data, index, this.hGlobal, this.size); + public void Write(T data, int offset = 0) => Marshal.StructureToPtr(data, this.hGlobal + offset, false); - ~LocalMemory() => Dispose(); public void Dispose() {