-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathPolyfills.cs
More file actions
971 lines (772 loc) · 38.7 KB
/
Polyfills.cs
File metadata and controls
971 lines (772 loc) · 38.7 KB
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// This file provides polyfills for types that are not available on older target frameworks (netstandard2.0, .NET Framework).
#pragma warning disable SA1201 // Elements should appear in the correct order
#pragma warning disable SA1403 // File may only contain a single namespace
#pragma warning disable SA1502 // Element should not be on a single line
#pragma warning disable SA1649 // File name should match first type name
#pragma warning disable SA1405 // Debug.Assert should provide message text
#pragma warning disable SA1407 // Arithmetic expressions should declare precedence
#pragma warning disable SA1513 // Closing brace should be followed by blank line
#pragma warning disable SA1516 // Elements should be separated by blank line
#pragma warning disable CA1305 // Specify IFormatProvider
#pragma warning disable IDE0007 // Use 'var' instead of explicit type
#pragma warning disable IDE0046 // If statement can be simplified
#pragma warning disable IDE0065 // Misplaced using directive
#pragma warning disable IDE0280 // Use 'nameof'
#pragma warning disable SA1512 // Single-line comments should not be followed by blank line
// On TFMs where IsExternalInit is provided by the BCL, add a TypeForwardedTo so that
// assemblies compiled against the netstandard2.0 version (which had the polyfill type)
// can resolve the type at runtime on net5+.
// See https://github.com/SimonCropp/Polyfill/issues/290
#if NET5_0_OR_GREATER
#pragma warning disable RS0016 // Symbol is not part of the declared public API - compiler support type forwarding
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsExternalInit))]
#pragma warning restore RS0016
#else
namespace System.Runtime.CompilerServices
{
internal static class IsExternalInit;
[global::System.AttributeUsage(global::System.AttributeTargets.Module | global::System.AttributeTargets.Class | global::System.AttributeTargets.Struct | global::System.AttributeTargets.Constructor | global::System.AttributeTargets.Method | global::System.AttributeTargets.Property | global::System.AttributeTargets.Event | global::System.AttributeTargets.Interface, Inherited = false)]
internal sealed class RequiredMemberAttribute : Attribute { }
[global::System.AttributeUsage(global::System.AttributeTargets.All, AllowMultiple = true, Inherited = false)]
internal sealed class CompilerFeatureRequiredAttribute : Attribute
{
public CompilerFeatureRequiredAttribute(string featureName) => FeatureName = featureName;
public string FeatureName { get; }
public bool IsOptional { get; init; }
}
}
namespace System.Diagnostics.CodeAnalysis
{
[global::System.AttributeUsage(global::System.AttributeTargets.Method, Inherited = false)]
internal sealed class DoesNotReturnAttribute : Attribute { }
[global::System.AttributeUsage(global::System.AttributeTargets.Parameter, Inherited = false)]
internal sealed class DoesNotReturnIfAttribute : Attribute
{
public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;
public bool ParameterValue { get; }
}
[global::System.AttributeUsage(global::System.AttributeTargets.Method | global::System.AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
internal sealed class MemberNotNullAttribute : Attribute
{
public MemberNotNullAttribute(string member) => Members = [member];
public MemberNotNullAttribute(params string[] members) => Members = members;
public string[] Members { get; }
}
[global::System.AttributeUsage(global::System.AttributeTargets.Method | global::System.AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
internal sealed class MemberNotNullWhenAttribute : Attribute
{
public MemberNotNullWhenAttribute(bool returnValue, string member)
{
ReturnValue = returnValue;
Members = [member];
}
public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
{
ReturnValue = returnValue;
Members = members;
}
public bool ReturnValue { get; }
public string[] Members { get; }
}
[global::System.AttributeUsage(global::System.AttributeTargets.Property | global::System.AttributeTargets.Parameter | global::System.AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
internal sealed class NotNullIfNotNullAttribute : Attribute
{
public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName;
public string ParameterName { get; }
}
[global::System.AttributeUsage(global::System.AttributeTargets.Parameter, Inherited = false)]
internal sealed class NotNullWhenAttribute : Attribute
{
public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;
public bool ReturnValue { get; }
}
[global::System.AttributeUsage(global::System.AttributeTargets.Property | global::System.AttributeTargets.Field | global::System.AttributeTargets.Parameter | global::System.AttributeTargets.ReturnValue, Inherited = false)]
internal sealed class NotNullAttribute : Attribute { }
[global::System.AttributeUsage(global::System.AttributeTargets.Property | global::System.AttributeTargets.Field | global::System.AttributeTargets.Parameter, Inherited = false)]
internal sealed class AllowNullAttribute : Attribute { }
[global::System.AttributeUsage(global::System.AttributeTargets.Property | global::System.AttributeTargets.Field | global::System.AttributeTargets.Parameter, Inherited = false)]
internal sealed class DisallowNullAttribute : Attribute { }
[global::System.AttributeUsage(global::System.AttributeTargets.Property | global::System.AttributeTargets.Field | global::System.AttributeTargets.Parameter | global::System.AttributeTargets.ReturnValue, Inherited = false)]
internal sealed class MaybeNullAttribute : Attribute { }
[global::System.AttributeUsage(global::System.AttributeTargets.Parameter | global::System.AttributeTargets.Property | global::System.AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
internal sealed class StringSyntaxAttribute : Attribute
{
public const string Regex = nameof(Regex);
public const string Uri = nameof(Uri);
public const string Xml = nameof(Xml);
public StringSyntaxAttribute(string syntax, params object?[] arguments)
{
Syntax = syntax;
Arguments = arguments;
}
public string Syntax { get; }
public object?[] Arguments { get; }
}
[global::System.AttributeUsage(global::System.AttributeTargets.Field | global::System.AttributeTargets.ReturnValue | global::System.AttributeTargets.GenericParameter | global::System.AttributeTargets.Parameter | global::System.AttributeTargets.Property | global::System.AttributeTargets.Method | global::System.AttributeTargets.Class | global::System.AttributeTargets.Interface | global::System.AttributeTargets.Struct, Inherited = false)]
internal sealed class DynamicallyAccessedMembersAttribute : Attribute
{
public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) => MemberTypes = memberTypes;
public DynamicallyAccessedMemberTypes MemberTypes { get; }
}
[global::System.Flags]
internal enum DynamicallyAccessedMemberTypes
{
None = 0,
PublicParameterlessConstructor = 0x0001,
PublicConstructors = 0x0003,
NonPublicConstructors = 0x0004,
PublicMethods = 0x0008,
NonPublicMethods = 0x0010,
PublicFields = 0x0020,
NonPublicFields = 0x0040,
PublicNestedTypes = 0x0080,
NonPublicNestedTypes = 0x0100,
PublicProperties = 0x0200,
NonPublicProperties = 0x0400,
PublicEvents = 0x0800,
NonPublicEvents = 0x1000,
Interfaces = 0x2000,
All = ~None,
}
[global::System.AttributeUsage(global::System.AttributeTargets.Method | global::System.AttributeTargets.Constructor | global::System.AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
internal sealed class UnconditionalSuppressMessageAttribute : Attribute
{
public UnconditionalSuppressMessageAttribute(string category, string checkId)
{
Category = category;
CheckId = checkId;
}
public string Category { get; }
public string CheckId { get; }
public string? Scope { get; set; }
public string? Target { get; set; }
public string? MessageId { get; set; }
public string? Justification { get; set; }
}
}
namespace System.Runtime.Versioning
{
[global::System.AttributeUsage(global::System.AttributeTargets.Assembly | global::System.AttributeTargets.Module | global::System.AttributeTargets.Class | global::System.AttributeTargets.Struct | global::System.AttributeTargets.Enum | global::System.AttributeTargets.Constructor | global::System.AttributeTargets.Method | global::System.AttributeTargets.Property | global::System.AttributeTargets.Field | global::System.AttributeTargets.Event | global::System.AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
internal sealed class SupportedOSPlatformAttribute : Attribute
{
public SupportedOSPlatformAttribute(string platformName) => PlatformName = platformName;
public string PlatformName { get; }
}
[global::System.AttributeUsage(global::System.AttributeTargets.Method | global::System.AttributeTargets.Property | global::System.AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
internal sealed class SupportedOSPlatformGuardAttribute : Attribute
{
public SupportedOSPlatformGuardAttribute(string platformName) => PlatformName = platformName;
public string PlatformName { get; }
}
[global::System.AttributeUsage(global::System.AttributeTargets.Assembly | global::System.AttributeTargets.Module | global::System.AttributeTargets.Class | global::System.AttributeTargets.Struct | global::System.AttributeTargets.Enum | global::System.AttributeTargets.Constructor | global::System.AttributeTargets.Method | global::System.AttributeTargets.Property | global::System.AttributeTargets.Field | global::System.AttributeTargets.Event | global::System.AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
internal sealed class UnsupportedOSPlatformAttribute : Attribute
{
public UnsupportedOSPlatformAttribute(string platformName) => PlatformName = platformName;
public string PlatformName { get; }
}
[global::System.AttributeUsage(global::System.AttributeTargets.Method | global::System.AttributeTargets.Property | global::System.AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
internal sealed class UnsupportedOSPlatformGuardAttribute : Attribute
{
public UnsupportedOSPlatformGuardAttribute(string platformName) => PlatformName = platformName;
public string PlatformName { get; }
}
}
#endif
#if !NET6_0_OR_GREATER
namespace System.Runtime.CompilerServices
{
[global::System.AttributeUsage(global::System.AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
internal sealed class CallerArgumentExpressionAttribute : Attribute
{
public CallerArgumentExpressionAttribute(string parameterName) => ParameterName = parameterName;
public string ParameterName { get; }
}
[global::System.AttributeUsage(global::System.AttributeTargets.Class | global::System.AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
internal sealed class InterpolatedStringHandlerAttribute : Attribute { }
[global::System.AttributeUsage(global::System.AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute
{
public InterpolatedStringHandlerArgumentAttribute(string argument) => Arguments = [argument];
public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) => Arguments = arguments;
public string[] Arguments { get; }
}
}
namespace System.Diagnostics
{
[global::System.AttributeUsage(global::System.AttributeTargets.Class | global::System.AttributeTargets.Method | global::System.AttributeTargets.Constructor | global::System.AttributeTargets.Struct, Inherited = false)]
internal sealed class StackTraceHiddenAttribute : Attribute { }
}
namespace System.Runtime.CompilerServices
{
[global::System.AttributeUsage(global::System.AttributeTargets.Method, Inherited = false)]
internal sealed class ModuleInitializerAttribute : Attribute { }
}
#endif
#if !NET8_0_OR_GREATER
namespace System.Diagnostics.CodeAnalysis
{
[global::System.AttributeUsage(global::System.AttributeTargets.Assembly | global::System.AttributeTargets.Module | global::System.AttributeTargets.Class | global::System.AttributeTargets.Struct | global::System.AttributeTargets.Enum | global::System.AttributeTargets.Constructor | global::System.AttributeTargets.Method | global::System.AttributeTargets.Property | global::System.AttributeTargets.Field | global::System.AttributeTargets.Event | global::System.AttributeTargets.Interface | global::System.AttributeTargets.Delegate, Inherited = false)]
internal sealed class ExperimentalAttribute : Attribute
{
public ExperimentalAttribute(string diagnosticId) => DiagnosticId = diagnosticId;
public string DiagnosticId { get; }
public string? UrlFormat { get; set; }
}
}
#endif
#if !NET9_0_OR_GREATER
namespace System.Runtime.CompilerServices
{
[global::System.AttributeUsage(global::System.AttributeTargets.Parameter, Inherited = false, AllowMultiple = false)]
internal sealed class ParamCollectionAttribute : Attribute { }
}
#endif
#if !NET9_0_OR_GREATER
namespace System.Threading
{
#pragma warning disable CS9216 // A value of type 'Lock' converted to a different type will use likely unintended monitor-based locking
internal sealed class Lock
{
public void Enter() => Monitor.Enter(this);
public void Exit() => Monitor.Exit(this);
public Scope EnterScope()
{
Monitor.Enter(this);
return new Scope(this);
}
public ref struct Scope
{
private Lock? _lock;
internal Scope(Lock @lock) => _lock = @lock;
public void Dispose()
{
Lock? lockObj = _lock;
if (lockObj is not null)
{
_lock = null;
lockObj.Exit();
}
}
}
}
}
#endif
#if !NET5_0_OR_GREATER
namespace System
{
internal readonly struct Index : IEquatable<Index>
{
private readonly int _value;
public Index(int value, bool fromEnd = false)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), "Index must not be negative.");
}
_value = fromEnd ? ~value : value;
}
private Index(int value) => _value = value;
public static Index Start => new(0);
public static Index End => new(~0);
public int Value => _value < 0 ? ~_value : _value;
public bool IsFromEnd => _value < 0;
public static Index FromStart(int value) => value >= 0 ? new Index(value) : throw new ArgumentOutOfRangeException(nameof(value), "Index must not be negative.");
public static Index FromEnd(int value) => value >= 0 ? new Index(~value) : throw new ArgumentOutOfRangeException(nameof(value), "Index must not be negative.");
public static implicit operator Index(int value) => FromStart(value);
public int GetOffset(int length)
{
int offset = _value;
if (IsFromEnd)
{
offset += length + 1;
}
return offset;
}
public override bool Equals(object? value) => value is Index index && _value == index._value;
public bool Equals(Index other) => _value == other._value;
public override int GetHashCode() => _value;
public override string ToString() => IsFromEnd ? $"^{(uint)Value}" : ((uint)Value).ToString();
}
internal readonly struct Range : IEquatable<Range>
{
public Index Start { get; }
public Index End { get; }
public Range(Index start, Index end)
{
Start = start;
End = end;
}
public static Range StartAt(Index start) => new(start, Index.End);
public static Range EndAt(Index end) => new(Index.Start, end);
public static Range All => new(Index.Start, Index.End);
public override bool Equals(object? value) => value is Range r && r.Start.Equals(Start) && r.End.Equals(End);
public bool Equals(Range other) => other.Start.Equals(Start) && other.End.Equals(End);
public override int GetHashCode() => Start.GetHashCode() * 31 + End.GetHashCode();
public override string ToString() => $"{Start}..{End}";
public void GetOffsetAndLength(int length, out int offset, out int len)
{
int start = Start.GetOffset(length);
int end = End.GetOffset(length);
if ((uint)end > (uint)length || (uint)start > (uint)end)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
offset = start;
len = end - start;
}
}
}
namespace System.Runtime.CompilerServices
{
internal static class RuntimeHelpers
{
/// <summary>Slices the specified array using the specified range.</summary>
/// <typeparam name="T">The type of the array elements.</typeparam>
public static T[] GetSubArray<T>(T[] array, Range range)
{
range.GetOffsetAndLength(array.Length, out int offset, out int length);
T[] dest = new T[length];
Array.Copy(array, offset, dest, 0, length);
return dest;
}
}
}
#endif
namespace Microsoft.CodeAnalysis
{
[global::System.AttributeUsage(global::System.AttributeTargets.All, AllowMultiple = false, Inherited = false)]
internal sealed partial class EmbeddedAttribute : global::System.Attribute { }
}
#pragma warning disable CS8603 // Possible null reference return
#pragma warning disable CS8777 // Parameter must have a non-null value when exiting
#pragma warning disable RS0030 // Banned API - Ensure is the guard implementation itself
internal static class Ensure
{
[return: global::System.Diagnostics.CodeAnalysis.NotNull]
public static T NotNull<T>([global::System.Diagnostics.CodeAnalysis.NotNull] T? argument, [global::System.Runtime.CompilerServices.CallerArgumentExpression("argument")] string? paramName = null)
{
if (argument is null)
{
throw new global::System.ArgumentNullException(paramName);
}
return argument;
}
public static string NotNullOrEmpty([global::System.Diagnostics.CodeAnalysis.NotNull] string? argument, [global::System.Runtime.CompilerServices.CallerArgumentExpression("argument")] string? paramName = null)
{
if (argument is null)
{
throw new global::System.ArgumentNullException(paramName);
}
if (argument.Length == 0)
{
throw new global::System.ArgumentException("Value cannot be null or empty.", paramName);
}
return argument;
}
public static void NotNullOrEmpty<T>([global::System.Diagnostics.CodeAnalysis.NotNull] global::System.Collections.Generic.IEnumerable<T>? argument, [global::System.Runtime.CompilerServices.CallerArgumentExpression("argument")] string? paramName = null)
{
if (argument is null)
{
throw new global::System.ArgumentNullException(paramName);
}
if (argument is global::System.Collections.Generic.ICollection<T> collection)
{
if (collection.Count == 0)
{
throw new global::System.ArgumentException("Value cannot be empty.", paramName);
}
return;
}
using global::System.Collections.Generic.IEnumerator<T> enumerator = argument.GetEnumerator();
if (!enumerator.MoveNext())
{
throw new global::System.ArgumentException("Value cannot be empty.", paramName);
}
}
public static string NotNullOrWhiteSpace([global::System.Diagnostics.CodeAnalysis.NotNull] string? argument, [global::System.Runtime.CompilerServices.CallerArgumentExpression("argument")] string? paramName = null)
{
if (argument is null)
{
throw new global::System.ArgumentNullException(paramName);
}
if (argument.Trim().Length == 0)
{
throw new global::System.ArgumentException("Value cannot be null or whitespace.", paramName);
}
return argument;
}
}
// Backward-compatible stubs for Polyfills.Guard and Polyfills.Ensure types.
// The old Polyfill NuGet package generated these types into the Microsoft.Testing.Platform assembly;
// old extension packages (compiled against the previous platform version with InternalsVisibleTo)
// may reference these types at runtime. Providing them here prevents TypeLoadExceptions.
#if IS_CORE_MTP
namespace Polyfills
{
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
internal static class Guard
{
[return: global::System.Diagnostics.CodeAnalysis.NotNull]
public static T NotNull<T>([global::System.Diagnostics.CodeAnalysis.NotNull] T? argument, [global::System.Runtime.CompilerServices.CallerArgumentExpression("argument")] string? name = null)
where T : class
{
if (argument is null)
{
throw new global::System.ArgumentNullException(name);
}
return argument;
}
[return: global::System.Diagnostics.CodeAnalysis.NotNull]
public static string NotNull([global::System.Diagnostics.CodeAnalysis.NotNull] string? argument, [global::System.Runtime.CompilerServices.CallerArgumentExpression("argument")] string? name = null)
{
if (argument is null)
{
throw new global::System.ArgumentNullException(name);
}
return argument;
}
public static string NotNullOrEmpty([global::System.Diagnostics.CodeAnalysis.NotNull] string? value, [global::System.Runtime.CompilerServices.CallerArgumentExpression("value")] string? name = null)
=> Ensure.NotNullOrEmpty(value, name);
public static T NotNullOrEmpty<T>([global::System.Diagnostics.CodeAnalysis.NotNull] T? value, [global::System.Runtime.CompilerServices.CallerArgumentExpression("value")] string? name = null)
where T : global::System.Collections.IEnumerable
=> Ensure.NotNullOrEmpty(value, name);
public static string NotNullOrWhiteSpace([global::System.Diagnostics.CodeAnalysis.NotNull] string? value, [global::System.Runtime.CompilerServices.CallerArgumentExpression("value")] string? name = null)
=> Ensure.NotNullOrWhiteSpace(value, name);
public static void FileExists(string path, [global::System.Runtime.CompilerServices.CallerArgumentExpression("path")] string? name = null)
=> Ensure.FileExists(path, name);
public static void DirectoryExists(string path, [global::System.Runtime.CompilerServices.CallerArgumentExpression("path")] string? name = null)
=> Ensure.DirectoryExists(path, name);
}
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
internal static class Ensure
{
[return: global::System.Diagnostics.CodeAnalysis.NotNull]
public static T NotNull<T>([global::System.Diagnostics.CodeAnalysis.NotNull] T? argument, [global::System.Runtime.CompilerServices.CallerArgumentExpression("argument")] string? name = null)
where T : class
{
if (argument is null)
{
throw new global::System.ArgumentNullException(name);
}
return argument;
}
[return: global::System.Diagnostics.CodeAnalysis.NotNull]
public static string NotNull([global::System.Diagnostics.CodeAnalysis.NotNull] string? argument, [global::System.Runtime.CompilerServices.CallerArgumentExpression("argument")] string? name = null)
{
if (argument is null)
{
throw new global::System.ArgumentNullException(name);
}
return argument;
}
public static string NotNullOrEmpty([global::System.Diagnostics.CodeAnalysis.NotNull] string? value, [global::System.Runtime.CompilerServices.CallerArgumentExpression("value")] string? name = null)
{
if (string.IsNullOrEmpty(value))
{
throw new global::System.ArgumentException("Must not be null or empty.", name);
}
return value;
}
[return: global::System.Diagnostics.CodeAnalysis.NotNull]
public static T NotNullOrEmpty<T>([global::System.Diagnostics.CodeAnalysis.NotNull] T? value, [global::System.Runtime.CompilerServices.CallerArgumentExpression("value")] string? name = null)
where T : global::System.Collections.IEnumerable
{
if (value is null)
{
throw new global::System.ArgumentNullException(name);
}
global::System.Collections.IEnumerator enumerator = value.GetEnumerator();
try
{
if (!enumerator.MoveNext())
{
throw new global::System.ArgumentException("Must not be empty.", name);
}
}
finally
{
(enumerator as global::System.IDisposable)?.Dispose();
}
return value;
}
public static string NotNullOrWhiteSpace([global::System.Diagnostics.CodeAnalysis.NotNull] string? value, [global::System.Runtime.CompilerServices.CallerArgumentExpression("value")] string? name = null)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new global::System.ArgumentException("Must not be null or whitespace.", name);
}
return value;
}
public static void FileExists(string path, [global::System.Runtime.CompilerServices.CallerArgumentExpression("path")] string? name = null)
{
if (!global::System.IO.File.Exists(path))
{
throw new global::System.ArgumentException($"File not found. Path: {path}", name);
}
}
public static void DirectoryExists(string path, [global::System.Runtime.CompilerServices.CallerArgumentExpression("path")] string? name = null)
{
if (!global::System.IO.Directory.Exists(path))
{
throw new global::System.ArgumentException($"Directory not found. Path: {path}", name);
}
}
}
// Polyfills.Polyfill stub: The old Polyfill NuGet package generated this type into every assembly.
// Old extensions (compiled with InternalsVisibleTo to the platform) may reference methods on
// this type from the platform assembly. We need to provide it for backward compatibility.
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
internal static class Polyfill
{
#if NETCOREAPP
public static bool Contains<T>(global::System.ReadOnlySpan<T> span, T value, global::System.Collections.Generic.IEqualityComparer<T>? comparer = null)
{
comparer ??= global::System.Collections.Generic.EqualityComparer<T>.Default;
foreach (T item in span)
{
if (comparer.Equals(item, value))
{
return true;
}
}
return false;
}
#endif
}
}
#endif
// All extension method polyfills are guarded with IS_CORE_MTP to avoid ambiguity when
// projects reference Microsoft.Testing.Platform with InternalsVisibleTo. Projects that
// do not reference Platform and need these extensions should provide their own copies.
#if IS_CORE_MTP
#if !NET8_0_OR_GREATER
internal static class CancellationTokenSourceExtensions
{
public static global::System.Threading.Tasks.Task CancelAsync(this global::System.Threading.CancellationTokenSource cancellationTokenSource)
{
cancellationTokenSource.Cancel();
return global::System.Threading.Tasks.Task.CompletedTask;
}
}
#endif // !NET8_0_OR_GREATER
#if !NET5_0_OR_GREATER
internal static class PolyfillStringExtensions
{
public static bool Contains(this string s, char c) => s.IndexOf(c) >= 0;
public static bool StartsWith(this string s, char c) => s.Length > 0 && s[0] == c;
public static bool EndsWith(this string s, char c) => s.Length > 0 && s[s.Length - 1] == c;
public static string[] Split(this string s, char separator, global::System.StringSplitOptions options = global::System.StringSplitOptions.None) =>
s.Split([separator], options);
public static string[] Split(this string s, char separator, int count, global::System.StringSplitOptions options = global::System.StringSplitOptions.None) =>
s.Split([separator], count, options);
public static string Replace(this string s, string oldValue, string? newValue, global::System.StringComparison comparisonType)
{
if (comparisonType == global::System.StringComparison.Ordinal)
{
return s.Replace(oldValue, newValue);
}
var sb = new global::System.Text.StringBuilder();
int previousIndex = 0;
int index = s.IndexOf(oldValue, comparisonType);
while (index != -1)
{
sb.Append(s, previousIndex, index - previousIndex);
sb.Append(newValue);
index += oldValue.Length;
previousIndex = index;
index = s.IndexOf(oldValue, index, comparisonType);
}
sb.Append(s, previousIndex, s.Length - previousIndex);
return sb.ToString();
}
public static bool Contains(this string s, string value, global::System.StringComparison comparisonType) =>
s.IndexOf(value, comparisonType) >= 0;
public static int GetHashCode(this string s, global::System.StringComparison comparisonType) =>
comparisonType switch
{
global::System.StringComparison.Ordinal => global::System.StringComparer.Ordinal.GetHashCode(s),
global::System.StringComparison.OrdinalIgnoreCase => global::System.StringComparer.OrdinalIgnoreCase.GetHashCode(s),
_ => global::System.StringComparer.OrdinalIgnoreCase.GetHashCode(s),
};
}
internal static class PolyfillEnumExtensions
{
public static TEnum Parse<TEnum>(string value)
where TEnum : struct =>
(TEnum)global::System.Enum.Parse(typeof(TEnum), value);
public static TEnum Parse<TEnum>(string value, bool ignoreCase)
where TEnum : struct =>
(TEnum)global::System.Enum.Parse(typeof(TEnum), value, ignoreCase);
}
// Note: Deconstruct for KeyValuePair is intentionally NOT provided here because it causes
// ambiguity errors when projects reference each other with InternalsVisibleTo and both
// compile this file. It is provided in Microsoft.Testing.Platform project's own source.
internal static class PolyfillDictionaryExtensions
{
public static bool TryAdd<TKey, TValue>(this global::System.Collections.Generic.Dictionary<TKey, TValue> dictionary, TKey key, TValue value)
where TKey : notnull
{
if (!dictionary.ContainsKey(key))
{
dictionary.Add(key, value);
return true;
}
return false;
}
}
internal static class PolyfillStringBuilderExtensions
{
public static global::System.Text.StringBuilder AppendJoin(this global::System.Text.StringBuilder sb, string separator, global::System.Collections.Generic.IEnumerable<string> values)
{
bool first = true;
foreach (string value in values)
{
if (!first)
{
sb.Append(separator);
}
sb.Append(value);
first = false;
}
return sb;
}
public static global::System.Text.StringBuilder AppendJoin<T>(this global::System.Text.StringBuilder sb, string separator, global::System.Collections.Generic.IEnumerable<T> values)
{
bool first = true;
foreach (T value in values)
{
if (!first)
{
sb.Append(separator);
}
sb.Append(value);
first = false;
}
return sb;
}
public static global::System.Text.StringBuilder AppendJoin(this global::System.Text.StringBuilder sb, char separator, global::System.Collections.Generic.IEnumerable<string> values) =>
sb.AppendJoin(separator.ToString(), values);
}
internal static class PolyfillTaskExtensions
{
public static async global::System.Threading.Tasks.Task WaitAsync(this global::System.Threading.Tasks.Task task, global::System.Threading.CancellationToken cancellationToken)
{
var tcs = new global::System.Threading.Tasks.TaskCompletionSource<bool>(global::System.Threading.Tasks.TaskCreationOptions.RunContinuationsAsynchronously);
using (cancellationToken.Register(s => ((global::System.Threading.Tasks.TaskCompletionSource<bool>)s!).TrySetCanceled(cancellationToken), tcs))
{
if (task != await global::System.Threading.Tasks.Task.WhenAny(task, tcs.Task).ConfigureAwait(false))
{
throw new global::System.OperationCanceledException(cancellationToken);
}
}
await task.ConfigureAwait(false);
}
public static async global::System.Threading.Tasks.Task WaitAsync(this global::System.Threading.Tasks.Task task, global::System.TimeSpan timeout, global::System.Threading.CancellationToken cancellationToken = default)
{
using var cts = global::System.Threading.CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(timeout);
try
{
await task.WaitAsync(cts.Token).ConfigureAwait(false);
}
catch (global::System.OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
throw new global::System.TimeoutException();
}
}
public static async global::System.Threading.Tasks.Task<T> WaitAsync<T>(this global::System.Threading.Tasks.Task<T> task, global::System.Threading.CancellationToken cancellationToken)
{
var tcs = new global::System.Threading.Tasks.TaskCompletionSource<bool>(global::System.Threading.Tasks.TaskCreationOptions.RunContinuationsAsynchronously);
using (cancellationToken.Register(s => ((global::System.Threading.Tasks.TaskCompletionSource<bool>)s!).TrySetCanceled(cancellationToken), tcs))
{
if (task != await global::System.Threading.Tasks.Task.WhenAny(task, tcs.Task).ConfigureAwait(false))
{
throw new global::System.OperationCanceledException(cancellationToken);
}
}
return await task.ConfigureAwait(false);
}
}
internal static class PolyfillProcessExtensions
{
public static global::System.Threading.Tasks.Task WaitForExitAsync(this global::System.Diagnostics.Process process, global::System.Threading.CancellationToken cancellationToken = default)
{
if (process.HasExited)
{
return global::System.Threading.Tasks.Task.CompletedTask;
}
var tcs = new global::System.Threading.Tasks.TaskCompletionSource<bool>(global::System.Threading.Tasks.TaskCreationOptions.RunContinuationsAsynchronously);
process.EnableRaisingEvents = true;
global::System.EventHandler handler = (_, _) => tcs.TrySetResult(true);
process.Exited += handler;
global::System.Threading.CancellationTokenRegistration cancellationRegistration = default;
if (cancellationToken.CanBeCanceled)
{
cancellationRegistration = cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken));
}
if (process.HasExited)
{
process.Exited -= handler;
cancellationRegistration.Dispose();
return global::System.Threading.Tasks.Task.CompletedTask;
}
return tcs.Task.ContinueWith(
_ =>
{
process.Exited -= handler;
cancellationRegistration.Dispose();
},
global::System.Threading.CancellationToken.None,
global::System.Threading.Tasks.TaskContinuationOptions.ExecuteSynchronously,
global::System.Threading.Tasks.TaskScheduler.Default);
}
public static void Kill(this global::System.Diagnostics.Process process, bool entireProcessTree) =>
// entireProcessTree not supported on netstandard2.0 - just kill the process
process.Kill();
}
#endif // !NET5_0_OR_GREATER
#endif // IS_CORE_MTP
#if !NET5_0_OR_GREATER
internal static class OperatingSystem
{
public static bool IsBrowser() => false;
public static bool IsWasi() => false;
public static bool IsAndroid() => false;
public static bool IsIOS() => false;
public static bool IsTvOS() => false;
#if NETFRAMEWORK
public static bool IsWindows() => global::System.Environment.OSVersion.Platform == global::System.PlatformID.Win32NT;
public static bool IsLinux() => false;
public static bool IsMacOS() => false;
#else
public static bool IsWindows() => global::System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(global::System.Runtime.InteropServices.OSPlatform.Windows);
public static bool IsLinux() => global::System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(global::System.Runtime.InteropServices.OSPlatform.Linux);
public static bool IsMacOS() => global::System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(global::System.Runtime.InteropServices.OSPlatform.OSX);
#endif
}
#endif
#if !NET7_0_OR_GREATER
namespace System.Diagnostics
{
internal sealed class UnreachableException : Exception
{
public UnreachableException()
: base("The program executed an instruction that was thought to be unreachable.")
{
}
public UnreachableException(string? message)
: base(message)
{
}
public UnreachableException(string? message, Exception? innerException)
: base(message, innerException)
{
}
}
}
#endif