diff --git a/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs b/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs new file mode 100644 index 00000000..bb52f8be --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/Extensions/SpanExtensions.cs @@ -0,0 +1,54 @@ +using System; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.NetCore.Tests.Extensions +{ + /// + /// An helper with methods to process fixed-size buffers + /// + public static class SpanExtensions + { + /// + /// Fills an input instance with random values + /// + /// The target to fill + public static void FillRandom(this Span span) + { + if (span.Length == 0) return; + + var l = span.Length; + ref var rspan = ref span.GetPinnableReference(); + + for (var i = 0; i < l; i++) + Unsafe.Add(ref rspan, i) = (float)ConcurrentRandom.Instance.NextDouble(); + } + + /// + /// The maximum threshold to validate two values as being equal + /// + private const float FloatThreshold = 0.00001f; + + /// + /// Checks whether or not the two input instances have the same content + /// + /// The first to check + /// The second to check + [Pure] + public static bool ContentEquals(this Span a, Span b) + { + if (a.Length != b.Length) return false; + if (a.Length == 0) return true; + + var l = a.Length; + ref var ra = ref a.GetPinnableReference(); + ref var rb = ref b.GetPinnableReference(); + + for (var i = 0; i < l; i++) + if (Math.Abs(Unsafe.Add(ref ra, i) - Unsafe.Add(ref rb, i)) > FloatThreshold) + return false; + + return true; + } + } +} diff --git a/tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs b/tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs new file mode 100644 index 00000000..5cbd72c0 --- /dev/null +++ b/tests/ComputeSharp.NetCore.Tests/Extensions/Types/ConcurrentRandom.cs @@ -0,0 +1,28 @@ +using System.Runtime.CompilerServices; +using System.Threading; + +namespace System +{ + /// + /// A thread-safe wrapper class + /// + public static class ConcurrentRandom + { + // Shared seed + private static int _Seed = Environment.TickCount; + + /// + /// The object that provides the instances + /// + private static readonly ThreadLocal _Instance = new ThreadLocal(() => new Random(Interlocked.Increment(ref _Seed))); + + /// + /// Gets a thread-safe instance + /// + public static Random Instance + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _Instance.Value; + } + } +} \ No newline at end of file