rjx-mirror/Ryujinx.Cpu/MemoryHelper.cs
jhorv 5131b71437
Reducing memory allocations (#4537)
* add RecyclableMemoryStream dependency and MemoryStreamManager

* organize BinaryReader/BinaryWriter extensions

* add StreamExtensions to reduce need for BinaryWriter

* simple replacments of MemoryStream with RecyclableMemoryStream

* add write ReadOnlySequence<byte> support to IVirtualMemoryManager

* avoid 0-length array creation

* rework IpcMessage and related types to greatly reduce memory allocation by using RecylableMemoryStream, keeping streams around longer, avoiding their creation when possible, and avoiding creation of BinaryReader and BinaryWriter when possible

* reduce LINQ-induced memory allocations with custom methods to query KPriorityQueue

* use RecyclableMemoryStream in StreamUtils, and use StreamUtils in EmbeddedResources

* add constants for nanosecond/millisecond conversions

* code formatting

* XML doc adjustments

* fix: StreamExtension.WriteByte not writing non-zero values for lengths <= 16

* XML Doc improvements. Implement StreamExtensions.WriteByte() block writes for large-enough count values.

* add copyless path for StreamExtension.Write(ReadOnlySpan<int>)

* add default implementation of IVirtualMemoryManager.Write(ulong, ReadOnlySequence<byte>); remove previous explicit implementations

* code style fixes

* remove LINQ completely from KScheduler/KPriorityQueue by implementing a custom struct-based enumerator
2023-03-17 13:14:50 +01:00

63 lines
No EOL
1.9 KiB
C#

using Microsoft.IO;
using Ryujinx.Common.Memory;
using Ryujinx.Memory;
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace Ryujinx.Cpu
{
public static class MemoryHelper
{
public static void FillWithZeros(IVirtualMemoryManager memory, ulong position, int size)
{
int size8 = size & ~(8 - 1);
for (int offs = 0; offs < size8; offs += 8)
{
memory.Write<long>(position + (ulong)offs, 0);
}
for (int offs = size8; offs < (size - size8); offs++)
{
memory.Write<byte>(position + (ulong)offs, 0);
}
}
public unsafe static T Read<T>(IVirtualMemoryManager memory, ulong position) where T : unmanaged
{
return MemoryMarshal.Cast<byte, T>(memory.GetSpan(position, Unsafe.SizeOf<T>()))[0];
}
public unsafe static ulong Write<T>(IVirtualMemoryManager memory, ulong position, T value) where T : unmanaged
{
ReadOnlySpan<byte> data = MemoryMarshal.Cast<T, byte>(MemoryMarshal.CreateReadOnlySpan(ref value, 1));
memory.Write(position, data);
return (ulong)data.Length;
}
public static string ReadAsciiString(IVirtualMemoryManager memory, ulong position, long maxSize = -1)
{
using (RecyclableMemoryStream ms = MemoryStreamManager.Shared.GetStream())
{
for (long offs = 0; offs < maxSize || maxSize == -1; offs++)
{
byte value = memory.Read<byte>(position + (ulong)offs);
if (value == 0)
{
break;
}
ms.WriteByte(value);
}
return Encoding.ASCII.GetString(ms.GetReadOnlySequence());
}
}
}
}