MemoryHelper.cs
1 using Microsoft.IO; 2 using Ryujinx.Common.Memory; 3 using Ryujinx.Memory; 4 using System; 5 using System.Runtime.CompilerServices; 6 using System.Runtime.InteropServices; 7 using System.Text; 8 9 namespace Ryujinx.Cpu 10 { 11 public static class MemoryHelper 12 { 13 public static void FillWithZeros(IVirtualMemoryManager memory, ulong position, int size) 14 { 15 int size8 = size & ~(8 - 1); 16 17 for (int offs = 0; offs < size8; offs += 8) 18 { 19 memory.Write<long>(position + (ulong)offs, 0); 20 } 21 22 for (int offs = size8; offs < (size - size8); offs++) 23 { 24 memory.Write<byte>(position + (ulong)offs, 0); 25 } 26 } 27 28 public static T Read<T>(IVirtualMemoryManager memory, ulong position) where T : unmanaged 29 { 30 return MemoryMarshal.Cast<byte, T>(memory.GetSpan(position, Unsafe.SizeOf<T>()))[0]; 31 } 32 33 public static ulong Write<T>(IVirtualMemoryManager memory, ulong position, T value) where T : unmanaged 34 { 35 ReadOnlySpan<byte> data = MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateReadOnlySpan(ref value, 1)); 36 37 memory.Write(position, data); 38 39 return (ulong)data.Length; 40 } 41 42 public static string ReadAsciiString(IVirtualMemoryManager memory, ulong position, long maxSize = -1) 43 { 44 using RecyclableMemoryStream ms = MemoryStreamManager.Shared.GetStream(); 45 46 for (long offs = 0; offs < maxSize || maxSize == -1; offs++) 47 { 48 byte value = memory.Read<byte>(position + (ulong)offs); 49 50 if (value == 0) 51 { 52 break; 53 } 54 55 ms.WriteByte(value); 56 } 57 58 return Encoding.ASCII.GetString(ms.GetReadOnlySequence()); 59 } 60 } 61 }