Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TestHelpers.cs « tests « System.Memory « src - github.com/mono/corefx.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1341bd5c4aba5651e36b2678b637f6d21d0dc10e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// 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 Xunit;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

using static System.Buffers.Binary.BinaryPrimitives;
using System.Text;
using System.Reflection;

namespace System
{
    public static class TestHelpers
    {
        public static void Validate<T>(this Span<T> span, params T[] expected) where T : struct, IEquatable<T>
        {
            Assert.True(span.SequenceEqual(expected));
        }

        public static void ValidateReferenceType<T>(this Span<T> span, params T[] expected)
        {
            Assert.Equal(span.Length, expected.Length);
            for (int i = 0; i < expected.Length; i++)
            {
                T actual = span[i];
                Assert.Same(expected[i], actual);
            }

            T ignore;
            AssertThrows<IndexOutOfRangeException, T>(span, (_span) => ignore = _span[expected.Length]);
        }

        public static unsafe void ValidateNonNullEmpty<T>(this Span<T> span)
        {
            Assert.True(span.IsEmpty);

            // Validate that empty Span is not normalized to null
            Assert.True(Unsafe.AsPointer(ref MemoryMarshal.GetReference(span)) != null);
        }

        public delegate void AssertThrowsAction<T>(Span<T> span);

        // Cannot use standard Assert.Throws() when testing Span - Span and closures don't get along.
        public static void AssertThrows<E, T>(Span<T> span, AssertThrowsAction<T> action) where E : Exception
        {
            try
            {
                action(span);
                Assert.False(true, "Expected exception: " + typeof(E).GetType());
            }
            catch (E)
            {
            }
            catch (Exception wrongException)
            {
                Assert.False(true, "Wrong exception thrown: Expected " + typeof(E).GetType() + ": Actual: " + wrongException.GetType());
            }
        }

        // 
        // The innocent looking construct:
        //
        //    Assert.Throws<E>( () => new Span() );
        //
        // generates a hidden box of the Span as the return value of the lambda. This makes the IL illegal and unloadable on 
        // runtimes that enforce the actual Span rules (never mind that we expect never to reach the box instruction...)
        //
        // The workaround is to code it like this:
        //
        //    Assert.Throws<E>( () => new Span().DontBox() );
        // 
        // which turns the lambda return type back to "void" and eliminates the troublesome box instruction.
        //
        public static void DontBox<T>(this Span<T> span)
        {
            // This space intentionally left blank.
        }

        public static void Validate<T>(this ReadOnlySpan<T> span, params T[] expected) where T : struct, IEquatable<T>
        {
            Assert.True(span.SequenceEqual(expected));
        }

        public static void ValidateReferenceType<T>(this ReadOnlySpan<T> span, params T[] expected)
        {
            Assert.Equal(span.Length, expected.Length);
            for (int i = 0; i < expected.Length; i++)
            {
                T actual = span[i];
                Assert.Same(expected[i], actual);
            }

            T ignore;
            AssertThrows<IndexOutOfRangeException, T>(span, (_span) => ignore = _span[expected.Length]);
        }

        public static unsafe void ValidateNonNullEmpty<T>(this ReadOnlySpan<T> span)
        {
            Assert.True(span.IsEmpty);

            // Validate that empty Span is not normalized to null
            Assert.True(Unsafe.AsPointer(ref MemoryMarshal.GetReference(span)) != null);
        }

        public delegate void AssertThrowsActionReadOnly<T>(ReadOnlySpan<T> span);

        // Cannot use standard Assert.Throws() when testing Span - Span and closures don't get along.
        public static void AssertThrows<E, T>(ReadOnlySpan<T> span, AssertThrowsActionReadOnly<T> action) where E : Exception
        {
            try
            {
                action(span);
                Assert.False(true, "Expected exception: " + typeof(E).GetType());
            }
            catch (E)
            {
            }
            catch (Exception wrongException)
            {
                Assert.False(true, "Wrong exception thrown: Expected " + typeof(E).GetType() + ": Actual: " + wrongException.GetType());
            }
        }

        // 
        // The innocent looking construct:
        //
        //    Assert.Throws<E>( () => new Span() );
        //
        // generates a hidden box of the Span as the return value of the lambda. This makes the IL illegal and unloadable on 
        // runtimes that enforce the actual Span rules (never mind that we expect never to reach the box instruction...)
        //
        // The workaround is to code it like this:
        //
        //    Assert.Throws<E>( () => new Span().DontBox() );
        // 
        // which turns the lambda return type back to "void" and eliminates the troublesome box instruction.
        //
        public static void DontBox<T>(this ReadOnlySpan<T> span)
        {
            // This space intentionally left blank.
        }

        public static void Validate<T>(this Memory<T> memory, params T[] expected) where T : struct, IEquatable<T>
        {
            Assert.True(memory.Span.SequenceEqual(expected));
        }

        public static void ValidateReferenceType<T>(this Memory<T> memory, params T[] expected)
        {
            T[] bufferArray = memory.ToArray();
            Assert.Equal(memory.Length, expected.Length);
            for (int i = 0; i < expected.Length; i++)
            {
                T actual = bufferArray[i];
                Assert.Same(expected[i], actual);
            }
        }

        public static void Validate<T>(this ReadOnlyMemory<T> memory, params T[] expected) where T : struct, IEquatable<T>
        {
            Assert.True(memory.Span.SequenceEqual(expected));
        }

        public static void ValidateReferenceType<T>(this ReadOnlyMemory<T> memory, params T[] expected)
        {
            T[] bufferArray = memory.ToArray();
            Assert.Equal(memory.Length, expected.Length);
            for (int i = 0; i < expected.Length; i++)
            {
                T actual = bufferArray[i];
                Assert.Same(expected[i], actual);
            }
        }

        public static void Validate<T>(Span<byte> span, T value) where T : struct
        {
            T read = MemoryMarshal.Read<T>(span);
            Assert.Equal(value, read);
            span.Clear();
        }

        public static TestStructExplicit s_testExplicitStruct = new TestStructExplicit
        {
            S0 = short.MaxValue,
            I0 = int.MaxValue,
            L0 = long.MaxValue,
            US0 = ushort.MaxValue,
            UI0 = uint.MaxValue,
            UL0 = ulong.MaxValue,
            S1 = short.MinValue,
            I1 = int.MinValue,
            L1 = long.MinValue,
            US1 = ushort.MinValue,
            UI1 = uint.MinValue,
            UL1 = ulong.MinValue
        };

        public static Span<byte> GetSpanBE()
        {
            Span<byte> spanBE = new byte[Unsafe.SizeOf<TestStructExplicit>()];

            WriteInt16BigEndian(spanBE, s_testExplicitStruct.S0);
            WriteInt32BigEndian(spanBE.Slice(2), s_testExplicitStruct.I0);
            WriteInt64BigEndian(spanBE.Slice(6), s_testExplicitStruct.L0);
            WriteUInt16BigEndian(spanBE.Slice(14), s_testExplicitStruct.US0);
            WriteUInt32BigEndian(spanBE.Slice(16), s_testExplicitStruct.UI0);
            WriteUInt64BigEndian(spanBE.Slice(20), s_testExplicitStruct.UL0);
            WriteInt16BigEndian(spanBE.Slice(28), s_testExplicitStruct.S1);
            WriteInt32BigEndian(spanBE.Slice(30), s_testExplicitStruct.I1);
            WriteInt64BigEndian(spanBE.Slice(34), s_testExplicitStruct.L1);
            WriteUInt16BigEndian(spanBE.Slice(42), s_testExplicitStruct.US1);
            WriteUInt32BigEndian(spanBE.Slice(44), s_testExplicitStruct.UI1);
            WriteUInt64BigEndian(spanBE.Slice(48), s_testExplicitStruct.UL1);

            Assert.Equal(56, spanBE.Length);
            return spanBE;
        }

        public static Span<byte> GetSpanLE()
        {
            Span<byte> spanLE = new byte[Unsafe.SizeOf<TestStructExplicit>()];

            WriteInt16LittleEndian(spanLE, s_testExplicitStruct.S0);
            WriteInt32LittleEndian(spanLE.Slice(2), s_testExplicitStruct.I0);
            WriteInt64LittleEndian(spanLE.Slice(6), s_testExplicitStruct.L0);
            WriteUInt16LittleEndian(spanLE.Slice(14), s_testExplicitStruct.US0);
            WriteUInt32LittleEndian(spanLE.Slice(16), s_testExplicitStruct.UI0);
            WriteUInt64LittleEndian(spanLE.Slice(20), s_testExplicitStruct.UL0);
            WriteInt16LittleEndian(spanLE.Slice(28), s_testExplicitStruct.S1);
            WriteInt32LittleEndian(spanLE.Slice(30), s_testExplicitStruct.I1);
            WriteInt64LittleEndian(spanLE.Slice(34), s_testExplicitStruct.L1);
            WriteUInt16LittleEndian(spanLE.Slice(42), s_testExplicitStruct.US1);
            WriteUInt32LittleEndian(spanLE.Slice(44), s_testExplicitStruct.UI1);
            WriteUInt64LittleEndian(spanLE.Slice(48), s_testExplicitStruct.UL1);

            Assert.Equal(56, spanLE.Length);
            return spanLE;
        }

        public static string BuildString(int length, int seed)
        {
            Random rnd = new Random(seed);
            var builder = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                builder.Append((char)rnd.Next(65, 91));
            }
            return builder.ToString();
        }

        [StructLayout(LayoutKind.Explicit)]
        public struct TestStructExplicit
        {
            [FieldOffset(0)]
            public short S0;
            [FieldOffset(2)]
            public int I0;
            [FieldOffset(6)]
            public long L0;
            [FieldOffset(14)]
            public ushort US0;
            [FieldOffset(16)]
            public uint UI0;
            [FieldOffset(20)]
            public ulong UL0;
            [FieldOffset(28)]
            public short S1;
            [FieldOffset(30)]
            public int I1;
            [FieldOffset(34)]
            public long L1;
            [FieldOffset(42)]
            public ushort US1;
            [FieldOffset(44)]
            public uint UI1;
            [FieldOffset(48)]
            public ulong UL1;
        }

        [StructLayout(LayoutKind.Sequential)]
        public sealed class TestClass
        {
            private double _d;
            public char C0;
            public char C1;
            public char C2;
            public char C3;
            public char C4;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct TestValueTypeWithReference
        {
            public int I;
            public string S;
        }

#pragma warning disable 0649 //Field 'SpanTests.InnerStruct.J' is never assigned to, and will always have its default value 0
        internal struct StructWithReferences
        {
            public int I;
            public InnerStruct Inner;
        }

        internal struct InnerStruct
        {
            public int J;
            public object O;
        }
#pragma warning restore 0649 //Field 'SpanTests.InnerStruct.J' is never assigned to, and will always have its default value 0

        public enum TestEnum
        {
            e0,
            e1,
            e2,
            e3,
            e4,
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public static void DoNotIgnore<T>(T value, int consumed)
        {
        }

        //
        // { text, start, length } triplets. A "-1" in start or length means "test the overload that doesn't have that parameter."
        //
        public static IEnumerable<object[]> StringSliceTestData
        {
            get
            {
                foreach (string text in new string[] { string.Empty, "012" })
                {
                    yield return new object[] { text, -1, -1 };
                    for (int start = 0; start <= text.Length; start++)
                    {
                        yield return new object[] { text, start, -1 };

                        for (int length = 0; length <= text.Length - start; length++)
                        {
                            yield return new object[] { text, start, length };
                        }
                    }
                }
            }
        }

        public static IEnumerable<object[]> StringSlice2ArgTestOutOfRangeData
        {
            get
            {
                foreach (string text in new string[] { string.Empty, "012" })
                {
                    yield return new object[] { text, -1 };
                    yield return new object[] { text, int.MinValue };

                    yield return new object[] { text, text.Length + 1 };
                    yield return new object[] { text, int.MaxValue };
                }
            }
        }

        public static IEnumerable<object[]> StringSlice3ArgTestOutOfRangeData
        {
            get
            {
                foreach (string text in new string[] { string.Empty, "012" })
                {
                    yield return new object[] { text, -1, 0 };
                    yield return new object[] { text, int.MinValue, 0 };

                    yield return new object[] { text, text.Length + 1, 0 };
                    yield return new object[] { text, int.MaxValue, 0 };

                    yield return new object[] { text, 0, -1 };
                    yield return new object[] { text, 0, int.MinValue };

                    yield return new object[] { text, 0, text.Length + 1 };
                    yield return new object[] { text, 0, int.MaxValue };

                    yield return new object[] { text, 1, text.Length };
                    yield return new object[] { text, 1, int.MaxValue };

                    yield return new object[] { text, text.Length - 1, 2 };
                    yield return new object[] { text, text.Length - 1, int.MaxValue };

                    yield return new object[] { text, text.Length, 1 };
                    yield return new object[] { text, text.Length, int.MaxValue };
                }
            }
        }

        // @todo: https://github.com/dotnet/corefx/issues/26894 - these emulate MemoryExtension apis that we removed. Clean up the callsites and remove this class.
        public static ReadOnlySpan<T> AsReadOnlySpan<T>(this Span<T> span) => span;
        public static ReadOnlySpan<T> AsReadOnlySpan<T>(this T[] array) => new ReadOnlySpan<T>(array);
        public static ReadOnlySpan<T> AsReadOnlySpan<T>(this ArraySegment<T> segment) => new ReadOnlySpan<T>(segment.Array, segment.Offset, segment.Count);
        public static ReadOnlyMemory<T> AsReadOnlyMemory<T>(this Memory<T> memory) => memory;

        /// <summary>Creates a <see cref="Memory{T}"/> with the specified values in its backing field.</summary>
        public static Memory<T> DangerousCreateMemory<T>(object obj, int offset, int length)
        {
            Memory<T> mem = default;
            object boxedMemory = mem;

            typeof(Memory<T>).GetField("_object", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(boxedMemory, obj);
            typeof(Memory<T>).GetField("_index", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(boxedMemory, offset);
            typeof(Memory<T>).GetField("_length", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(boxedMemory, length);

            return (Memory<T>)boxedMemory;
        }

        /// <summary>Creates a <see cref="ReadOnlyMemory{T}"/> with the specified values in its backing field.</summary>
        public static ReadOnlyMemory<T> DangerousCreateReadOnlyMemory<T>(object obj, int offset, int length) =>
            DangerousCreateMemory<T>(obj, offset, length).AsReadOnlyMemory();
    }
}