From a23b438b5d92b3dc92c2231e6af76f72b1c75564 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 12 Sep 2023 16:29:12 +0200 Subject: [PATCH] Remove string allocation in ID3DIncludeForD2DHelpers.Open --- .../Translation/D3DCompiler.ID3DInclude.cs | 10 +++++++-- .../Runtime/InteropServices/MemoryMarshal.cs | 21 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.ID3DInclude.cs b/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.ID3DInclude.cs index c4c48c11..9f4065fb 100644 --- a/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.ID3DInclude.cs +++ b/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.ID3DInclude.cs @@ -1,8 +1,12 @@ +using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; -#if !NET6_0_OR_GREATER +#if NET6_0_OR_GREATER +using MemoryMarshal2 = System.Runtime.InteropServices.MemoryMarshal; +#else +using MemoryMarshal2 = ComputeSharp.NetStandard.MemoryMarshal; using RuntimeHelpers = ComputeSharp.NetStandard.RuntimeHelpers; #endif @@ -82,7 +86,9 @@ partial class D3DCompiler [UnmanagedCallersOnly] public static int Open(ID3DIncludeForD2DHelpers* @this, D3D_INCLUDE_TYPE IncludeType, sbyte* pFileName, void* pParentData, void** ppData, uint* pBytes) { - if (new string(pFileName) == "d2d1effecthelpers.hlsli") + ReadOnlySpan fileName = MemoryMarshal2.CreateReadOnlySpanFromNullTerminated((byte*)pFileName); + + if (fileName.SequenceEqual("d2d1effecthelpers.hlsli"u8)) { *ppData = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(D2D1EffectHelpers.TextUtf8)); *pBytes = (uint)D2D1EffectHelpers.TextUtf8.Length; diff --git a/src/ComputeSharp.NetStandard/System/Runtime/InteropServices/MemoryMarshal.cs b/src/ComputeSharp.NetStandard/System/Runtime/InteropServices/MemoryMarshal.cs index a3ff9bcd..143ecf6c 100644 --- a/src/ComputeSharp.NetStandard/System/Runtime/InteropServices/MemoryMarshal.cs +++ b/src/ComputeSharp.NetStandard/System/Runtime/InteropServices/MemoryMarshal.cs @@ -18,4 +18,25 @@ internal static class MemoryMarshal { return ref global::System.Runtime.InteropServices.MemoryMarshal.GetReference(array.AsSpan()); } + + /// + /// Creates a new read-only span for a -terminated UTF-8 string. + /// + /// The pointer to the -terminated string of bytes. + /// A read-only span representing the specified -terminated string, or an empty span if the pointer is . + /// The returned span does not include the terminator, nor does it validate the well-formedness of the UTF-8 data. + /// The string is longer than . + public static unsafe ReadOnlySpan CreateReadOnlySpanFromNullTerminated(byte* value) + { + for (int i = 0; i < int.MaxValue; i++) + { + // Stop when the null-terminator has been found + if (value[i] == 0) + { + return new(value, i); + } + } + + throw new ArgumentException("The string must be null-terminated."); + } } \ No newline at end of file