From 807dcb576c3f4951188074e6fbaf7b364c7dad77 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 12 Apr 2020 20:24:36 +0200 Subject: [PATCH] Added ShaderKey type --- .../Translation/Models/ShaderKey.cs | 85 +++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 src/ComputeSharp.Shaders/Translation/Models/ShaderKey.cs diff --git a/src/ComputeSharp.Shaders/Translation/Models/ShaderKey.cs b/src/ComputeSharp.Shaders/Translation/Models/ShaderKey.cs new file mode 100644 index 00000000..89c3cd1d --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/Models/ShaderKey.cs @@ -0,0 +1,85 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace ComputeSharp.Shaders.Translation.Models +{ + /// + /// A representing a key for a given shader + /// + [StructLayout(LayoutKind.Explicit)] + internal readonly struct ShaderKey : IEquatable + { + /// + /// The hashcode of the current shader type + /// + [FieldOffset(0)] + private readonly int Id; + + /// + /// The number of iterations to run on the X axis + /// + [FieldOffset(4)] + private readonly int ThreadsX; + + /// + /// The number of iterations to run on the Y axis + /// + [FieldOffset(8)] + private readonly int ThreadsY; + + /// + /// The number of iterations to run on the Z axis + /// + [FieldOffset(12)] + private readonly int ThreadsZ; + + /// + /// Creates a new instance with the specified parameters + /// + /// The hashcode of the current shader type + /// The number of iterations to run on the X axis + /// The number of iterations to run on the Y axis + /// The number of iterations to run on the Z axis + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ShaderKey(int id, int threadsX, int threadsY, int threadsZ) + { + Id = id; + ThreadsX = threadsX; + ThreadsY = threadsY; + ThreadsZ = threadsZ; + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool Equals(ShaderKey other) + { + return + Unsafe.As(ref Unsafe.AsRef(Id)) + == Unsafe.As(ref Unsafe.AsRef(other.Id)) && + Unsafe.As(ref Unsafe.AsRef(ThreadsY)) + == Unsafe.As(ref Unsafe.AsRef(other.ThreadsY)); + } + + /// + public override bool Equals(object? obj) + { + return obj is ShaderKey other && Equals(other); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override int GetHashCode() + { + ulong ul0 = Unsafe.As(ref Unsafe.AsRef(Id)); + + int hash = unchecked((int)ul0) ^ (int)(ul0 >> 32); + + ulong ul1 = Unsafe.As(ref Unsafe.AsRef(ThreadsY)); + + hash = (hash << 5) + hash + unchecked((int)ul1) ^ ((int)(ul1 >> 32)); + + return hash; + } + } +}