// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; using System.Threading; using CommunityToolkit.HighPerformance.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using CommunityToolkit.HighPerformance.UnitTests.Buffers.Internals; namespace CommunityToolkit.HighPerformance.UnitTests.Helpers; public partial class Test_ParallelHelper { [TestMethod] public unsafe void Test_ParallelHelper_ForEach_In() { foreach (int count in TestForCounts) { using UnmanagedSpanOwner data = CreateRandomData(count); int sum = 0; ParallelHelper.ForEach(data.Memory, new Summer(&sum)); int expected = 0; foreach (int n in data.GetSpan()) { expected += n; } Assert.AreEqual(expected, sum, $"The sum doesn't match, was {sum} instead of {expected}"); } } /// /// A type implementing to sum array elements. /// private readonly unsafe struct Summer : IInAction { private readonly int* ptr; public Summer(int* ptr) => this.ptr = ptr; /// public void Invoke(in int i) => Interlocked.Add(ref Unsafe.AsRef(this.ptr), i); } /// /// Creates a random array filled with random numbers. /// /// The number of array items to create. /// An array of random elements. private static UnmanagedSpanOwner CreateRandomData(int count) { Random? random = new(count); UnmanagedSpanOwner data = new(count); foreach (ref int n in data.GetSpan()) { n = random.Next(0, byte.MaxValue); } return data; } }