-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathArray.cs
2311 lines (2024 loc) · 89.3 KB
/
Array.cs
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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract partial class Array : ICloneable, IList, IStructuralComparable, IStructuralEquatable
{
// We impose limits on maximum array length in each dimension to allow efficient
// implementation of advanced range check elimination in future.
// Keep in sync with vm\gcscan.cpp and HashHelpers.MaxPrimeArrayLength.
// The constants are defined in this method: inline SIZE_T MaxArrayLength(SIZE_T componentSize) from gcscan
// We have different max sizes for arrays with elements of size 1 for backwards compatibility
internal const int MaxArrayLength = 0X7FEFFFFF;
internal const int MaxByteArrayLength = 0x7FFFFFC7;
// This is the threshold where Introspective sort switches to Insertion sort.
// Empirically, 16 seems to speed up most cases without slowing down others, at least for integers.
// Large value types may benefit from a smaller number.
internal const int IntrosortSizeThreshold = 16;
// This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area.
private protected Array() { }
public static ReadOnlyCollection<T> AsReadOnly<T>(T[] array)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
// T[] implements IList<T>.
return new ReadOnlyCollection<T>(array);
}
public static void Resize<T>([NotNull] ref T[]? array, int newSize)
{
if (newSize < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.newSize, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
T[]? larray = array;
if (larray == null)
{
array = new T[newSize];
return;
}
if (larray.Length != newSize)
{
T[] newArray = new T[newSize];
Copy(larray, 0, newArray, 0, larray.Length > newSize ? newSize : larray.Length);
array = newArray;
}
Debug.Assert(array != null);
}
public static Array CreateInstance(Type elementType, params long[] lengths)
{
if (lengths == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths);
}
if (lengths.Length == 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank);
int[] intLengths = new int[lengths.Length];
for (int i = 0; i < lengths.Length; ++i)
{
long len = lengths[i];
int ilen = (int)len;
if (len != ilen)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.len, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
intLengths[i] = ilen;
}
return Array.CreateInstance(elementType, intLengths);
}
public static void Copy(Array sourceArray, Array destinationArray, long length)
{
int ilength = (int)length;
if (length != ilength)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
Copy(sourceArray, destinationArray, ilength);
}
public static void Copy(Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length)
{
int isourceIndex = (int)sourceIndex;
int idestinationIndex = (int)destinationIndex;
int ilength = (int)length;
if (sourceIndex != isourceIndex)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceIndex, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
if (destinationIndex != idestinationIndex)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.destinationIndex, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
if (length != ilength)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
Copy(sourceArray, isourceIndex, destinationArray, idestinationIndex, ilength);
}
public object? GetValue(long index)
{
int iindex = (int)index;
if (index != iindex)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
return this.GetValue(iindex);
}
public object? GetValue(long index1, long index2)
{
int iindex1 = (int)index1;
int iindex2 = (int)index2;
if (index1 != iindex1)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
if (index2 != iindex2)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
return this.GetValue(iindex1, iindex2);
}
public object? GetValue(long index1, long index2, long index3)
{
int iindex1 = (int)index1;
int iindex2 = (int)index2;
int iindex3 = (int)index3;
if (index1 != iindex1)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
if (index2 != iindex2)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
if (index3 != iindex3)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
return this.GetValue(iindex1, iindex2, iindex3);
}
public object? GetValue(params long[] indices)
{
if (indices == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices);
if (Rank != indices.Length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices);
int[] intIndices = new int[indices.Length];
for (int i = 0; i < indices.Length; ++i)
{
long index = indices[i];
int iindex = (int)index;
if (index != iindex)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
intIndices[i] = iindex;
}
return this.GetValue(intIndices);
}
public void SetValue(object? value, long index)
{
int iindex = (int)index;
if (index != iindex)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
this.SetValue(value, iindex);
}
public void SetValue(object? value, long index1, long index2)
{
int iindex1 = (int)index1;
int iindex2 = (int)index2;
if (index1 != iindex1)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
if (index2 != iindex2)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
this.SetValue(value, iindex1, iindex2);
}
public void SetValue(object? value, long index1, long index2, long index3)
{
int iindex1 = (int)index1;
int iindex2 = (int)index2;
int iindex3 = (int)index3;
if (index1 != iindex1)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
if (index2 != iindex2)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
if (index3 != iindex3)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
this.SetValue(value, iindex1, iindex2, iindex3);
}
public void SetValue(object? value, params long[] indices)
{
if (indices == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices);
if (Rank != indices.Length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices);
int[] intIndices = new int[indices.Length];
for (int i = 0; i < indices.Length; ++i)
{
long index = indices[i];
int iindex = (int)index;
if (index != iindex)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
intIndices[i] = iindex;
}
this.SetValue(value, intIndices);
}
private static int GetMedian(int low, int hi)
{
// Note both may be negative, if we are dealing with arrays w/ negative lower bounds.
Debug.Assert(low <= hi);
Debug.Assert(hi - low >= 0, "Length overflow!");
return low + ((hi - low) >> 1);
}
public long GetLongLength(int dimension)
{
// This method should throw an IndexOufOfRangeException for compat if dimension < 0 or >= Rank
return GetLength(dimension);
}
// Number of elements in the Array.
int ICollection.Count => Length;
// Returns an object appropriate for synchronizing access to this
// Array.
public object SyncRoot => this;
// Is this Array read-only?
public bool IsReadOnly => false;
public bool IsFixedSize => true;
// Is this Array synchronized (i.e., thread-safe)? If you want a synchronized
// collection, you can use SyncRoot as an object to synchronize your
// collection with. You could also call GetSynchronized()
// to get a synchronized wrapper around the Array.
public bool IsSynchronized => false;
object? IList.this[int index]
{
get => GetValue(index);
set => SetValue(value, index);
}
int IList.Add(object? value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
return default;
}
bool IList.Contains(object? value)
{
return Array.IndexOf(this, value) >= this.GetLowerBound(0);
}
void IList.Clear()
{
Array.Clear(this, this.GetLowerBound(0), this.Length);
}
int IList.IndexOf(object? value)
{
return Array.IndexOf(this, value);
}
void IList.Insert(int index, object? value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
}
void IList.Remove(object? value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
}
void IList.RemoveAt(int index)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
}
// Make a new array which is a shallow copy of the original array.
//
public object Clone()
{
return MemberwiseClone();
}
int IStructuralComparable.CompareTo(object? other, IComparer comparer)
{
if (other == null)
{
return 1;
}
Array? o = other as Array;
if (o == null || this.Length != o.Length)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.ArgumentException_OtherNotArrayOfCorrectLength, ExceptionArgument.other);
}
int i = 0;
int c = 0;
while (i < o.Length && c == 0)
{
object? left = GetValue(i);
object? right = o.GetValue(i);
c = comparer.Compare(left, right);
i++;
}
return c;
}
bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer)
{
if (other == null)
{
return false;
}
if (object.ReferenceEquals(this, other))
{
return true;
}
if (!(other is Array o) || o.Length != this.Length)
{
return false;
}
int i = 0;
while (i < o.Length)
{
object? left = GetValue(i);
object? right = o.GetValue(i);
if (!comparer.Equals(left, right))
{
return false;
}
i++;
}
return true;
}
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
if (comparer == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer);
HashCode hashCode = default;
for (int i = (this.Length >= 8 ? this.Length - 8 : 0); i < this.Length; i++)
{
hashCode.Add(comparer.GetHashCode(GetValue(i)!));
}
return hashCode.ToHashCode();
}
// Searches an array for a given element using a binary search algorithm.
// Elements of the array are compared to the search value using the
// IComparable interface, which must be implemented by all elements
// of the array and the given search value. This method assumes that the
// array is already sorted according to the IComparable interface;
// if this is not the case, the result will be incorrect.
//
// The method returns the index of the given value in the array. If the
// array does not contain the given value, the method returns a negative
// integer. The bitwise complement operator (~) can be applied to a
// negative result to produce the index of the first element (if any) that
// is larger than the given search value.
//
public static int BinarySearch(Array array, object? value)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
return BinarySearch(array, array.GetLowerBound(0), array.Length, value, null);
}
// Searches a section of an array for a given element using a binary search
// algorithm. Elements of the array are compared to the search value using
// the IComparable interface, which must be implemented by all
// elements of the array and the given search value. This method assumes
// that the array is already sorted according to the IComparable
// interface; if this is not the case, the result will be incorrect.
//
// The method returns the index of the given value in the array. If the
// array does not contain the given value, the method returns a negative
// integer. The bitwise complement operator (~) can be applied to a
// negative result to produce the index of the first element (if any) that
// is larger than the given search value.
//
public static int BinarySearch(Array array, int index, int length, object? value)
{
return BinarySearch(array, index, length, value, null);
}
// Searches an array for a given element using a binary search algorithm.
// Elements of the array are compared to the search value using the given
// IComparer interface. If comparer is null, elements of the
// array are compared to the search value using the IComparable
// interface, which in that case must be implemented by all elements of the
// array and the given search value. This method assumes that the array is
// already sorted; if this is not the case, the result will be incorrect.
//
// The method returns the index of the given value in the array. If the
// array does not contain the given value, the method returns a negative
// integer. The bitwise complement operator (~) can be applied to a
// negative result to produce the index of the first element (if any) that
// is larger than the given search value.
//
public static int BinarySearch(Array array, object? value, IComparer? comparer)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
return BinarySearch(array, array.GetLowerBound(0), array.Length, value, comparer);
}
// Searches a section of an array for a given element using a binary search
// algorithm. Elements of the array are compared to the search value using
// the given IComparer interface. If comparer is null,
// elements of the array are compared to the search value using the
// IComparable interface, which in that case must be implemented by
// all elements of the array and the given search value. This method
// assumes that the array is already sorted; if this is not the case, the
// result will be incorrect.
//
// The method returns the index of the given value in the array. If the
// array does not contain the given value, the method returns a negative
// integer. The bitwise complement operator (~) can be applied to a
// negative result to produce the index of the first element (if any) that
// is larger than the given search value.
//
public static int BinarySearch(Array array, int index, int length, object? value, IComparer? comparer)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
int lb = array.GetLowerBound(0);
if (index < lb)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - (index - lb) < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
if (array.Rank != 1)
ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
comparer ??= Comparer.Default;
int lo = index;
int hi = index + length - 1;
if (array is object[] objArray)
{
while (lo <= hi)
{
// i might overflow if lo and hi are both large positive numbers.
int i = GetMedian(lo, hi);
int c;
try
{
c = comparer.Compare(objArray[i], value);
}
catch (Exception e)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
return default;
}
if (c == 0) return i;
if (c < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
if (comparer == Comparer.Default)
{
CorElementType et = array.GetCorElementTypeOfElementType();
if (et.IsPrimitiveType())
{
if (value == null)
return ~index;
if (array.IsValueOfElementType(value))
{
int adjustedIndex = index - lb;
int result = -1;
switch (et)
{
case CorElementType.ELEMENT_TYPE_I1:
result = GenericBinarySearch<sbyte>(array, adjustedIndex, length, value);
break;
case CorElementType.ELEMENT_TYPE_U1:
case CorElementType.ELEMENT_TYPE_BOOLEAN:
result = GenericBinarySearch<byte>(array, adjustedIndex, length, value);
break;
case CorElementType.ELEMENT_TYPE_I2:
result = GenericBinarySearch<short>(array, adjustedIndex, length, value);
break;
case CorElementType.ELEMENT_TYPE_U2:
case CorElementType.ELEMENT_TYPE_CHAR:
result = GenericBinarySearch<ushort>(array, adjustedIndex, length, value);
break;
case CorElementType.ELEMENT_TYPE_I4:
#if TARGET_32BIT
case CorElementType.ELEMENT_TYPE_I:
#endif
result = GenericBinarySearch<int>(array, adjustedIndex, length, value);
break;
case CorElementType.ELEMENT_TYPE_U4:
#if TARGET_32BIT
case CorElementType.ELEMENT_TYPE_U:
#endif
result = GenericBinarySearch<uint>(array, adjustedIndex, length, value);
break;
case CorElementType.ELEMENT_TYPE_I8:
#if TARGET_64BIT
case CorElementType.ELEMENT_TYPE_I:
#endif
result = GenericBinarySearch<long>(array, adjustedIndex, length, value);
break;
case CorElementType.ELEMENT_TYPE_U8:
#if TARGET_64BIT
case CorElementType.ELEMENT_TYPE_U:
#endif
result = GenericBinarySearch<ulong>(array, adjustedIndex, length, value);
break;
case CorElementType.ELEMENT_TYPE_R4:
result = GenericBinarySearch<float>(array, adjustedIndex, length, value);
break;
case CorElementType.ELEMENT_TYPE_R8:
result = GenericBinarySearch<double>(array, adjustedIndex, length, value);
break;
default:
Debug.Fail("All primitive types should be handled above");
break;
}
return (result >= 0) ? (index + result) : ~(index + ~result);
static int GenericBinarySearch<T>(Array array, int adjustedIndex, int length, object value) where T: struct, IComparable<T>
=> UnsafeArrayAsSpan<T>(array, adjustedIndex, length).BinarySearch(Unsafe.As<byte, T>(ref value.GetRawData()));
}
}
}
while (lo <= hi)
{
int i = GetMedian(lo, hi);
int c;
try
{
c = comparer.Compare(array.GetValue(i), value);
}
catch (Exception e)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
return default;
}
if (c == 0) return i;
if (c < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
public static int BinarySearch<T>(T[] array, T value)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
return BinarySearch<T>(array, 0, array.Length, value, null);
}
public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T>? comparer)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
return BinarySearch<T>(array, 0, array.Length, value, comparer);
}
public static int BinarySearch<T>(T[] array, int index, int length, T value)
{
return BinarySearch<T>(array, index, length, value, null);
}
public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T>? comparer)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (length < 0)
ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
if (array.Length - index < length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
return ArraySortHelper<T>.Default.BinarySearch(array, index, length, value, comparer);
}
public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (converter == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
}
TOutput[] newArray = new TOutput[array.Length];
for (int i = 0; i < array.Length; i++)
{
newArray[i] = converter(array[i]);
}
return newArray;
}
// CopyTo copies a collection into an Array, starting at a particular
// index into the array.
//
// This method is to support the ICollection interface, and calls
// Array.Copy internally. If you aren't using ICollection explicitly,
// call Array.Copy to avoid an extra indirection.
//
public void CopyTo(Array array, int index)
{
if (array != null && array.Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
// Note: Array.Copy throws a RankException and we want a consistent ArgumentException for all the IList CopyTo methods.
Array.Copy(this, GetLowerBound(0), array!, index, Length);
}
public void CopyTo(Array array, long index)
{
int iindex = (int)index;
if (index != iindex)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
this.CopyTo(array, iindex);
}
private static class EmptyArray<T>
{
#pragma warning disable CA1825 // this is the implementation of Array.Empty<T>()
internal static readonly T[] Value = new T[0];
#pragma warning restore CA1825
}
public static T[] Empty<T>()
{
return EmptyArray<T>.Value;
}
public static bool Exists<T>(T[] array, Predicate<T> match)
{
return Array.FindIndex(array, match) != -1;
}
public static void Fill<T>(T[] array, T value)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
for (int i = 0; i < array.Length; i++)
{
array[i] = value;
}
}
public static void Fill<T>(T[] array, T value, int startIndex, int count)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (startIndex < 0 || startIndex > array.Length)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if (count < 0 || startIndex > array.Length - count)
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
for (int i = startIndex; i < startIndex + count; i++)
{
array[i] = value;
}
}
[return: MaybeNull]
public static T Find<T>(T[] array, Predicate<T> match)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
for (int i = 0; i < array.Length; i++)
{
if (match(array[i]))
{
return array[i];
}
}
return default!;
}
public static T[] FindAll<T>(T[] array, Predicate<T> match)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
List<T> list = new List<T>();
for (int i = 0; i < array.Length; i++)
{
if (match(array[i]))
{
list.Add(array[i]);
}
}
return list.ToArray();
}
public static int FindIndex<T>(T[] array, Predicate<T> match)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
return FindIndex(array, 0, array.Length, match);
}
public static int FindIndex<T>(T[] array, int startIndex, Predicate<T> match)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
return FindIndex(array, startIndex, array.Length - startIndex, match);
}
public static int FindIndex<T>(T[] array, int startIndex, int count, Predicate<T> match)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (startIndex < 0 || startIndex > array.Length)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if (count < 0 || startIndex > array.Length - count)
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
int endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++)
{
if (match(array[i]))
return i;
}
return -1;
}
[return: MaybeNull]
public static T FindLast<T>(T[] array, Predicate<T> match)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
for (int i = array.Length - 1; i >= 0; i--)
{
if (match(array[i]))
{
return array[i];
}
}
return default!;
}
public static int FindLastIndex<T>(T[] array, Predicate<T> match)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
return FindLastIndex(array, array.Length - 1, array.Length, match);
}
public static int FindLastIndex<T>(T[] array, int startIndex, Predicate<T> match)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
return FindLastIndex(array, startIndex, startIndex + 1, match);
}
public static int FindLastIndex<T>(T[] array, int startIndex, int count, Predicate<T> match)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
if (array.Length == 0)
{
// Special case for 0 length List
if (startIndex != -1)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
else
{
// Make sure we're not out of range
if (startIndex < 0 || startIndex >= array.Length)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
int endIndex = startIndex - count;
for (int i = startIndex; i > endIndex; i--)
{
if (match(array[i]))
{
return i;
}
}
return -1;
}
public static void ForEach<T>(T[] array, Action<T> action)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (action == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action);
}
for (int i = 0; i < array.Length; i++)
{
action(array[i]);
}
}
// Returns the index of the first occurrence of a given value in an array.
// The array is searched forwards, and the elements of the array are
// compared to the given value using the Object.Equals method.
//
public static int IndexOf(Array array, object? value)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
return IndexOf(array, value, array.GetLowerBound(0), array.Length);
}
// Returns the index of the first occurrence of a given value in a range of
// an array. The array is searched forwards, starting at index
// startIndex and ending at the last element of the array. The
// elements of the array are compared to the given value using the
// Object.Equals method.
//
public static int IndexOf(Array array, object? value, int startIndex)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
int lb = array.GetLowerBound(0);
return IndexOf(array, value, startIndex, array.Length - startIndex + lb);
}
// Returns the index of the first occurrence of a given value in a range of
// an array. The array is searched forwards, starting at index
// startIndex and upto count elements. The
// elements of the array are compared to the given value using the
// Object.Equals method.
//
public static int IndexOf(Array array, object? value, int startIndex, int count)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (array.Rank != 1)
ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
int lb = array.GetLowerBound(0);
if (startIndex < lb || startIndex > array.Length + lb)
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
if (count < 0 || count > array.Length - startIndex + lb)
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
int endIndex = startIndex + count;
if (array is object[] objArray)
{
if (value == null)
{
for (int i = startIndex; i < endIndex; i++)