1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4 
5 using Xunit;
6 
7 namespace System.SpanTests
8 {
9     public static class SpanGcReportingTests
10     {
11         /// <summary>
12         /// This is a simple sanity test to check that GC reporting for Span is not completely broken, it is not meant to be
13         /// comprehensive.
14         /// </summary>
15         [Fact]
16         [OuterLoop]
DelegateTest()17         public static void DelegateTest()
18         {
19             DelegateTest(100000, 10000);
20         }
21 
22         /// <summary>
23         /// Intended entry point for stress tests, with counts appropriate for GCStress=3. The counts in
24         /// <see cref="DelegateTest"/> are too high for running that test in a reasonable amount of time. This one runs in a
25         /// reasonable amount of time for a long-duration stress run.
26         /// </summary>
DelegateTest_Stress()27         public static void DelegateTest_Stress()
28         {
29             DelegateTest(100, 100);
30         }
31 
DelegateTest(int iterationCount, int objectCount)32         private static void DelegateTest(int iterationCount, int objectCount)
33         {
34             object[] objects = new object[objectCount];
35             Random rng = new Random();
36             var delegateTestCore =
37                 new DelegateTestCoreDelegate(DelegateTest_Core) +
38                 new DelegateTestCoreDelegate(DelegateTest_Core);
39 
40             for (int i = 0; i < iterationCount; i++)
41             {
42                 DelegateTest_CreateSomeObjects(objects, rng);
43                 delegateTestCore(new Span<int>(new int[] { 1, 2, 3 }), objects, rng);
44             }
45         }
46 
DelegateTestCoreDelegate(Span<int> span, object[] objects, Random rng)47         private delegate void DelegateTestCoreDelegate(Span<int> span, object[] objects, Random rng);
48 
DelegateTest_Core(Span<int> span, object[] objects, Random rng)49         private static void DelegateTest_Core(Span<int> span, object[] objects, Random rng)
50         {
51             ReadOnlySpan<int> initialSpan = span;
52 
53             DelegateTest_CreateSomeObjects(objects, rng);
54 
55             int sum = 0;
56             for (int i = 0; i < span.Length; ++i)
57             {
58                 sum += span[i];
59             }
60             Assert.Equal(1 + 2 + 3, sum);
61 
62             Assert.True(span == initialSpan);
63         }
64 
DelegateTest_CreateSomeObjects(object[] objects, Random rng)65         private static void DelegateTest_CreateSomeObjects(object[] objects, Random rng)
66         {
67             for (int i = 0; i < 100; ++i)
68             {
69                 objects[rng.Next(objects.Length)] = new object();
70             }
71         }
72     }
73 }
74