diff --git a/src/ComputeSharp.D2D1.UI/Extensions/ID2D1EffectExtensions.cs b/src/ComputeSharp.D2D1.UI/Extensions/ID2D1EffectExtensions.cs index 86133bab..090d6c56 100644 --- a/src/ComputeSharp.D2D1.UI/Extensions/ID2D1EffectExtensions.cs +++ b/src/ComputeSharp.D2D1.UI/Extensions/ID2D1EffectExtensions.cs @@ -52,9 +52,7 @@ internal static unsafe class ID2D1EffectExtensions dataSize: (uint)constantBufferSize).Assert(); } - Unsafe.SkipInit(out T shader); - - shader = shader.CreateFromConstantBuffer(buffer.AsSpan(0, constantBufferSize)); + T shader = D2D1PixelShader.CreateFromConstantBuffer(buffer); ArrayPool.Shared.Return(buffer); diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs index 53e0b7a1..8642d8ed 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs @@ -461,4 +461,47 @@ public static class D2D1PixelShader Unsafe.AsRef(in shader).LoadConstantBuffer(in shader, ref dataLoader); } + + /// + /// Creates a new value from constant buffer data. + /// + /// The type of D2D1 pixel shader value to create. + /// The input with the constant buffer data. + /// The resulting instance. + /// Thrown if is not large enough to contain the constant buffer. + public static T CreateFromConstantBuffer(ReadOnlySpan span) + where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor + { + if (!TryCreateFromConstantBuffer(span, out T shader)) + { + default(ArgumentException).Throw(nameof(span)); + } + + return shader; + + } + + /// + /// Tries to create a value from constant buffer data. + /// + /// The type of D2D1 pixel shader value to create. + /// The input with the constant buffer data. + /// The resulting value, if successful. + /// Whether or not the value was retrieved successfully. + public static bool TryCreateFromConstantBuffer(ReadOnlySpan span, out T shader) + where T : unmanaged, ID2D1PixelShader, ID2D1PixelShaderDescriptor + { + Unsafe.SkipInit(out shader); + + if (span.Length >= shader.ConstantBufferSize) + { + shader = shader.CreateFromConstantBuffer(span); + + return true; + } + + shader = default; + + return false; + } } \ No newline at end of file