Array.cs 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145
  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. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Collections.ObjectModel;
  7. using System.Diagnostics;
  8. using System.Runtime.CompilerServices;
  9. using Internal.Runtime.CompilerServices;
  10. namespace System
  11. {
  12. [Serializable]
  13. [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
  14. public abstract partial class Array : ICloneable, IList, IStructuralComparable, IStructuralEquatable
  15. {
  16. // We impose limits on maximum array lenght in each dimension to allow efficient
  17. // implementation of advanced range check elimination in future.
  18. // Keep in sync with vm\gcscan.cpp and HashHelpers.MaxPrimeArrayLength.
  19. // The constants are defined in this method: inline SIZE_T MaxArrayLength(SIZE_T componentSize) from gcscan
  20. // We have different max sizes for arrays with elements of size 1 for backwards compatibility
  21. internal const int MaxArrayLength = 0X7FEFFFFF;
  22. internal const int MaxByteArrayLength = 0x7FFFFFC7;
  23. // This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area. I really want this to be a
  24. // "protected-and-internal" rather than "internal" but C# has no keyword for the former.
  25. internal Array() { }
  26. public static ReadOnlyCollection<T> AsReadOnly<T>(T[] array)
  27. {
  28. if (array == null)
  29. {
  30. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  31. }
  32. // T[] implements IList<T>.
  33. return new ReadOnlyCollection<T>(array);
  34. }
  35. public static void Resize<T>(ref T[] array, int newSize)
  36. {
  37. if (newSize < 0)
  38. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.newSize, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
  39. T[] larray = array;
  40. if (larray == null)
  41. {
  42. array = new T[newSize];
  43. return;
  44. }
  45. if (larray.Length != newSize)
  46. {
  47. T[] newArray = new T[newSize];
  48. Copy(larray, 0, newArray, 0, larray.Length > newSize ? newSize : larray.Length);
  49. array = newArray;
  50. }
  51. }
  52. public static Array CreateInstance(Type elementType, params long[] lengths)
  53. {
  54. if (lengths == null)
  55. {
  56. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths);
  57. }
  58. if (lengths.Length == 0)
  59. ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank);
  60. int[] intLengths = new int[lengths.Length];
  61. for (int i = 0; i < lengths.Length; ++i)
  62. {
  63. long len = lengths[i];
  64. int ilen = (int)len;
  65. if (len != ilen)
  66. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.len, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  67. intLengths[i] = ilen;
  68. }
  69. return Array.CreateInstance(elementType, intLengths);
  70. }
  71. public static void Copy(Array sourceArray, Array destinationArray, long length)
  72. {
  73. int ilength = (int)length;
  74. if (length != ilength)
  75. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  76. Copy(sourceArray, destinationArray, ilength);
  77. }
  78. public static void Copy(Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length)
  79. {
  80. int isourceIndex = (int)sourceIndex;
  81. int idestinationIndex = (int)destinationIndex;
  82. int ilength = (int)length;
  83. if (sourceIndex != isourceIndex)
  84. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceIndex, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  85. if (destinationIndex != idestinationIndex)
  86. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.destinationIndex, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  87. if (length != ilength)
  88. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  89. Copy(sourceArray, isourceIndex, destinationArray, idestinationIndex, ilength);
  90. }
  91. public object GetValue(long index)
  92. {
  93. int iindex = (int)index;
  94. if (index != iindex)
  95. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  96. return this.GetValue(iindex);
  97. }
  98. public object GetValue(long index1, long index2)
  99. {
  100. int iindex1 = (int)index1;
  101. int iindex2 = (int)index2;
  102. if (index1 != iindex1)
  103. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  104. if (index2 != iindex2)
  105. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  106. return this.GetValue(iindex1, iindex2);
  107. }
  108. public object GetValue(long index1, long index2, long index3)
  109. {
  110. int iindex1 = (int)index1;
  111. int iindex2 = (int)index2;
  112. int iindex3 = (int)index3;
  113. if (index1 != iindex1)
  114. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  115. if (index2 != iindex2)
  116. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  117. if (index3 != iindex3)
  118. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  119. return this.GetValue(iindex1, iindex2, iindex3);
  120. }
  121. public object GetValue(params long[] indices)
  122. {
  123. if (indices == null)
  124. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices);
  125. if (Rank != indices.Length)
  126. ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices);
  127. int[] intIndices = new int[indices.Length];
  128. for (int i = 0; i < indices.Length; ++i)
  129. {
  130. long index = indices[i];
  131. int iindex = (int)index;
  132. if (index != iindex)
  133. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  134. intIndices[i] = iindex;
  135. }
  136. return this.GetValue(intIndices);
  137. }
  138. public void SetValue(object value, long index)
  139. {
  140. int iindex = (int)index;
  141. if (index != iindex)
  142. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  143. this.SetValue(value, iindex);
  144. }
  145. public void SetValue(object value, long index1, long index2)
  146. {
  147. int iindex1 = (int)index1;
  148. int iindex2 = (int)index2;
  149. if (index1 != iindex1)
  150. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  151. if (index2 != iindex2)
  152. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  153. this.SetValue(value, iindex1, iindex2);
  154. }
  155. public void SetValue(object value, long index1, long index2, long index3)
  156. {
  157. int iindex1 = (int)index1;
  158. int iindex2 = (int)index2;
  159. int iindex3 = (int)index3;
  160. if (index1 != iindex1)
  161. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  162. if (index2 != iindex2)
  163. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  164. if (index3 != iindex3)
  165. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  166. this.SetValue(value, iindex1, iindex2, iindex3);
  167. }
  168. public void SetValue(object value, params long[] indices)
  169. {
  170. if (indices == null)
  171. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices);
  172. if (Rank != indices.Length)
  173. ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices);
  174. int[] intIndices = new int[indices.Length];
  175. for (int i = 0; i < indices.Length; ++i)
  176. {
  177. long index = indices[i];
  178. int iindex = (int)index;
  179. if (index != iindex)
  180. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  181. intIndices[i] = iindex;
  182. }
  183. this.SetValue(value, intIndices);
  184. }
  185. private static int GetMedian(int low, int hi)
  186. {
  187. // Note both may be negative, if we are dealing with arrays w/ negative lower bounds.
  188. Debug.Assert(low <= hi);
  189. Debug.Assert(hi - low >= 0, "Length overflow!");
  190. return low + ((hi - low) >> 1);
  191. }
  192. public long GetLongLength(int dimension)
  193. {
  194. //This method should throw an IndexOufOfRangeException for compat if dimension < 0 or >= Rank
  195. return GetLength(dimension);
  196. }
  197. // Number of elements in the Array.
  198. int ICollection.Count
  199. { get { return Length; } }
  200. // Returns an object appropriate for synchronizing access to this
  201. // Array.
  202. public object SyncRoot
  203. { get { return this; } }
  204. // Is this Array read-only?
  205. public bool IsReadOnly
  206. { get { return false; } }
  207. public bool IsFixedSize
  208. {
  209. get { return true; }
  210. }
  211. // Is this Array synchronized (i.e., thread-safe)? If you want a synchronized
  212. // collection, you can use SyncRoot as an object to synchronize your
  213. // collection with. You could also call GetSynchronized()
  214. // to get a synchronized wrapper around the Array.
  215. public bool IsSynchronized
  216. { get { return false; } }
  217. object IList.this[int index]
  218. {
  219. get { return GetValue(index); }
  220. set { SetValue(value, index); }
  221. }
  222. int IList.Add(object value)
  223. {
  224. ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
  225. return default;
  226. }
  227. bool IList.Contains(object value)
  228. {
  229. return Array.IndexOf(this, value) >= this.GetLowerBound(0);
  230. }
  231. void IList.Clear()
  232. {
  233. Array.Clear(this, this.GetLowerBound(0), this.Length);
  234. }
  235. int IList.IndexOf(object value)
  236. {
  237. return Array.IndexOf(this, value);
  238. }
  239. void IList.Insert(int index, object value)
  240. {
  241. ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
  242. }
  243. void IList.Remove(object value)
  244. {
  245. ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
  246. }
  247. void IList.RemoveAt(int index)
  248. {
  249. ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
  250. }
  251. // Make a new array which is a shallow copy of the original array.
  252. //
  253. public object Clone()
  254. {
  255. return MemberwiseClone();
  256. }
  257. int IStructuralComparable.CompareTo(object other, IComparer comparer)
  258. {
  259. if (other == null)
  260. {
  261. return 1;
  262. }
  263. Array o = other as Array;
  264. if (o == null || this.Length != o.Length)
  265. {
  266. ThrowHelper.ThrowArgumentException(ExceptionResource.ArgumentException_OtherNotArrayOfCorrectLength, ExceptionArgument.other);
  267. }
  268. int i = 0;
  269. int c = 0;
  270. while (i < o.Length && c == 0)
  271. {
  272. object left = GetValue(i);
  273. object right = o.GetValue(i);
  274. c = comparer.Compare(left, right);
  275. i++;
  276. }
  277. return c;
  278. }
  279. bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
  280. {
  281. if (other == null)
  282. {
  283. return false;
  284. }
  285. if (object.ReferenceEquals(this, other))
  286. {
  287. return true;
  288. }
  289. if (!(other is Array o) || o.Length != this.Length)
  290. {
  291. return false;
  292. }
  293. int i = 0;
  294. while (i < o.Length)
  295. {
  296. object left = GetValue(i);
  297. object right = o.GetValue(i);
  298. if (!comparer.Equals(left, right))
  299. {
  300. return false;
  301. }
  302. i++;
  303. }
  304. return true;
  305. }
  306. private static int CombineHashCodes(int h1, int h2)
  307. {
  308. return (((h1 << 5) + h1) ^ h2);
  309. }
  310. int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
  311. {
  312. if (comparer == null)
  313. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer);
  314. int ret = 0;
  315. for (int i = (this.Length >= 8 ? this.Length - 8 : 0); i < this.Length; i++)
  316. {
  317. ret = CombineHashCodes(ret, comparer.GetHashCode(GetValue(i)));
  318. }
  319. return ret;
  320. }
  321. // Searches an array for a given element using a binary search algorithm.
  322. // Elements of the array are compared to the search value using the
  323. // IComparable interface, which must be implemented by all elements
  324. // of the array and the given search value. This method assumes that the
  325. // array is already sorted according to the IComparable interface;
  326. // if this is not the case, the result will be incorrect.
  327. //
  328. // The method returns the index of the given value in the array. If the
  329. // array does not contain the given value, the method returns a negative
  330. // integer. The bitwise complement operator (~) can be applied to a
  331. // negative result to produce the index of the first element (if any) that
  332. // is larger than the given search value.
  333. //
  334. public static int BinarySearch(Array array, object value)
  335. {
  336. if (array == null)
  337. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  338. int lb = array.GetLowerBound(0);
  339. return BinarySearch(array, lb, array.Length, value, null);
  340. }
  341. // Searches a section of an array for a given element using a binary search
  342. // algorithm. Elements of the array are compared to the search value using
  343. // the IComparable interface, which must be implemented by all
  344. // elements of the array and the given search value. This method assumes
  345. // that the array is already sorted according to the IComparable
  346. // interface; if this is not the case, the result will be incorrect.
  347. //
  348. // The method returns the index of the given value in the array. If the
  349. // array does not contain the given value, the method returns a negative
  350. // integer. The bitwise complement operator (~) can be applied to a
  351. // negative result to produce the index of the first element (if any) that
  352. // is larger than the given search value.
  353. //
  354. public static int BinarySearch(Array array, int index, int length, object value)
  355. {
  356. return BinarySearch(array, index, length, value, null);
  357. }
  358. // Searches an array for a given element using a binary search algorithm.
  359. // Elements of the array are compared to the search value using the given
  360. // IComparer interface. If comparer is null, elements of the
  361. // array are compared to the search value using the IComparable
  362. // interface, which in that case must be implemented by all elements of the
  363. // array and the given search value. This method assumes that the array is
  364. // already sorted; if this is not the case, the result will be incorrect.
  365. //
  366. // The method returns the index of the given value in the array. If the
  367. // array does not contain the given value, the method returns a negative
  368. // integer. The bitwise complement operator (~) can be applied to a
  369. // negative result to produce the index of the first element (if any) that
  370. // is larger than the given search value.
  371. //
  372. public static int BinarySearch(Array array, object value, IComparer comparer)
  373. {
  374. if (array == null)
  375. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  376. return BinarySearch(array, array.GetLowerBound(0), array.Length, value, comparer);
  377. }
  378. // Searches a section of an array for a given element using a binary search
  379. // algorithm. Elements of the array are compared to the search value using
  380. // the given IComparer interface. If comparer is null,
  381. // elements of the array are compared to the search value using the
  382. // IComparable interface, which in that case must be implemented by
  383. // all elements of the array and the given search value. This method
  384. // assumes that the array is already sorted; if this is not the case, the
  385. // result will be incorrect.
  386. //
  387. // The method returns the index of the given value in the array. If the
  388. // array does not contain the given value, the method returns a negative
  389. // integer. The bitwise complement operator (~) can be applied to a
  390. // negative result to produce the index of the first element (if any) that
  391. // is larger than the given search value.
  392. //
  393. public static int BinarySearch(Array array, int index, int length, object value, IComparer comparer)
  394. {
  395. if (array == null)
  396. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  397. int lb = array.GetLowerBound(0);
  398. if (index < lb)
  399. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  400. if (length < 0)
  401. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  402. if (array.Length - (index - lb) < length)
  403. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  404. if (array.Rank != 1)
  405. ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
  406. if (comparer == null) comparer = Comparer.Default;
  407. #if CORECLR
  408. if (comparer == Comparer.Default)
  409. {
  410. int retval;
  411. bool r = TrySZBinarySearch(array, index, length, value, out retval);
  412. if (r)
  413. return retval;
  414. }
  415. #endif
  416. int lo = index;
  417. int hi = index + length - 1;
  418. if (array is object[] objArray)
  419. {
  420. while (lo <= hi)
  421. {
  422. // i might overflow if lo and hi are both large positive numbers.
  423. int i = GetMedian(lo, hi);
  424. int c;
  425. try
  426. {
  427. c = comparer.Compare(objArray[i], value);
  428. }
  429. catch (Exception e)
  430. {
  431. ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
  432. return default;
  433. }
  434. if (c == 0) return i;
  435. if (c < 0)
  436. {
  437. lo = i + 1;
  438. }
  439. else
  440. {
  441. hi = i - 1;
  442. }
  443. }
  444. }
  445. else
  446. {
  447. while (lo <= hi)
  448. {
  449. int i = GetMedian(lo, hi);
  450. int c;
  451. try
  452. {
  453. c = comparer.Compare(array.GetValue(i), value);
  454. }
  455. catch (Exception e)
  456. {
  457. ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
  458. return default;
  459. }
  460. if (c == 0) return i;
  461. if (c < 0)
  462. {
  463. lo = i + 1;
  464. }
  465. else
  466. {
  467. hi = i - 1;
  468. }
  469. }
  470. }
  471. return ~lo;
  472. }
  473. public static int BinarySearch<T>(T[] array, T value)
  474. {
  475. if (array == null)
  476. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  477. return BinarySearch<T>(array, 0, array.Length, value, null);
  478. }
  479. public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T> comparer)
  480. {
  481. if (array == null)
  482. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  483. return BinarySearch<T>(array, 0, array.Length, value, comparer);
  484. }
  485. public static int BinarySearch<T>(T[] array, int index, int length, T value)
  486. {
  487. return BinarySearch<T>(array, index, length, value, null);
  488. }
  489. public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer)
  490. {
  491. if (array == null)
  492. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  493. if (index < 0)
  494. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  495. if (length < 0)
  496. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  497. if (array.Length - index < length)
  498. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  499. return ArraySortHelper<T>.Default.BinarySearch(array, index, length, value, comparer);
  500. }
  501. public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter)
  502. {
  503. if (array == null)
  504. {
  505. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  506. }
  507. if (converter == null)
  508. {
  509. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
  510. }
  511. TOutput[] newArray = new TOutput[array.Length];
  512. for (int i = 0; i < array.Length; i++)
  513. {
  514. newArray[i] = converter(array[i]);
  515. }
  516. return newArray;
  517. }
  518. // CopyTo copies a collection into an Array, starting at a particular
  519. // index into the array.
  520. //
  521. // This method is to support the ICollection interface, and calls
  522. // Array.Copy internally. If you aren't using ICollection explicitly,
  523. // call Array.Copy to avoid an extra indirection.
  524. //
  525. public void CopyTo(Array array, int index)
  526. {
  527. if (array != null && array.Rank != 1)
  528. ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
  529. // Note: Array.Copy throws a RankException and we want a consistent ArgumentException for all the IList CopyTo methods.
  530. Array.Copy(this, GetLowerBound(0), array, index, Length);
  531. }
  532. public void CopyTo(Array array, long index)
  533. {
  534. int iindex = (int)index;
  535. if (index != iindex)
  536. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  537. this.CopyTo(array, iindex);
  538. }
  539. private static class EmptyArray<T>
  540. {
  541. internal static readonly T[] Value = new T[0];
  542. }
  543. public static T[] Empty<T>()
  544. {
  545. return EmptyArray<T>.Value;
  546. }
  547. public static bool Exists<T>(T[] array, Predicate<T> match)
  548. {
  549. return Array.FindIndex(array, match) != -1;
  550. }
  551. public static void Fill<T>(T[] array, T value)
  552. {
  553. if (array == null)
  554. {
  555. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  556. }
  557. for (int i = 0; i < array.Length; i++)
  558. {
  559. array[i] = value;
  560. }
  561. }
  562. public static void Fill<T>(T[] array, T value, int startIndex, int count)
  563. {
  564. if (array == null)
  565. {
  566. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  567. }
  568. if (startIndex < 0 || startIndex > array.Length)
  569. {
  570. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  571. }
  572. if (count < 0 || startIndex > array.Length - count)
  573. {
  574. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  575. }
  576. for (int i = startIndex; i < startIndex + count; i++)
  577. {
  578. array[i] = value;
  579. }
  580. }
  581. public static T Find<T>(T[] array, Predicate<T> match)
  582. {
  583. if (array == null)
  584. {
  585. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  586. }
  587. if (match == null)
  588. {
  589. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  590. }
  591. for (int i = 0; i < array.Length; i++)
  592. {
  593. if (match(array[i]))
  594. {
  595. return array[i];
  596. }
  597. }
  598. return default;
  599. }
  600. public static T[] FindAll<T>(T[] array, Predicate<T> match)
  601. {
  602. if (array == null)
  603. {
  604. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  605. }
  606. if (match == null)
  607. {
  608. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  609. }
  610. List<T> list = new List<T>();
  611. for (int i = 0; i < array.Length; i++)
  612. {
  613. if (match(array[i]))
  614. {
  615. list.Add(array[i]);
  616. }
  617. }
  618. return list.ToArray();
  619. }
  620. public static int FindIndex<T>(T[] array, Predicate<T> match)
  621. {
  622. if (array == null)
  623. {
  624. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  625. }
  626. return FindIndex(array, 0, array.Length, match);
  627. }
  628. public static int FindIndex<T>(T[] array, int startIndex, Predicate<T> match)
  629. {
  630. if (array == null)
  631. {
  632. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  633. }
  634. return FindIndex(array, startIndex, array.Length - startIndex, match);
  635. }
  636. public static int FindIndex<T>(T[] array, int startIndex, int count, Predicate<T> match)
  637. {
  638. if (array == null)
  639. {
  640. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  641. }
  642. if (startIndex < 0 || startIndex > array.Length)
  643. {
  644. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  645. }
  646. if (count < 0 || startIndex > array.Length - count)
  647. {
  648. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  649. }
  650. if (match == null)
  651. {
  652. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  653. }
  654. int endIndex = startIndex + count;
  655. for (int i = startIndex; i < endIndex; i++)
  656. {
  657. if (match(array[i])) return i;
  658. }
  659. return -1;
  660. }
  661. public static T FindLast<T>(T[] array, Predicate<T> match)
  662. {
  663. if (array == null)
  664. {
  665. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  666. }
  667. if (match == null)
  668. {
  669. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  670. }
  671. for (int i = array.Length - 1; i >= 0; i--)
  672. {
  673. if (match(array[i]))
  674. {
  675. return array[i];
  676. }
  677. }
  678. return default;
  679. }
  680. public static int FindLastIndex<T>(T[] array, Predicate<T> match)
  681. {
  682. if (array == null)
  683. {
  684. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  685. }
  686. return FindLastIndex(array, array.Length - 1, array.Length, match);
  687. }
  688. public static int FindLastIndex<T>(T[] array, int startIndex, Predicate<T> match)
  689. {
  690. if (array == null)
  691. {
  692. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  693. }
  694. return FindLastIndex(array, startIndex, startIndex + 1, match);
  695. }
  696. public static int FindLastIndex<T>(T[] array, int startIndex, int count, Predicate<T> match)
  697. {
  698. if (array == null)
  699. {
  700. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  701. }
  702. if (match == null)
  703. {
  704. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  705. }
  706. if (array.Length == 0)
  707. {
  708. // Special case for 0 length List
  709. if (startIndex != -1)
  710. {
  711. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  712. }
  713. }
  714. else
  715. {
  716. // Make sure we're not out of range
  717. if (startIndex < 0 || startIndex >= array.Length)
  718. {
  719. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  720. }
  721. }
  722. // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
  723. if (count < 0 || startIndex - count + 1 < 0)
  724. {
  725. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  726. }
  727. int endIndex = startIndex - count;
  728. for (int i = startIndex; i > endIndex; i--)
  729. {
  730. if (match(array[i]))
  731. {
  732. return i;
  733. }
  734. }
  735. return -1;
  736. }
  737. public static void ForEach<T>(T[] array, Action<T> action)
  738. {
  739. if (array == null)
  740. {
  741. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  742. }
  743. if (action == null)
  744. {
  745. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action);
  746. }
  747. for (int i = 0; i < array.Length; i++)
  748. {
  749. action(array[i]);
  750. }
  751. }
  752. // GetEnumerator returns an IEnumerator over this Array.
  753. //
  754. // Currently, only one dimensional arrays are supported.
  755. //
  756. public IEnumerator GetEnumerator()
  757. {
  758. int lowerBound = GetLowerBound(0);
  759. if (Rank == 1 && lowerBound == 0)
  760. return new SZArrayEnumerator(this);
  761. else
  762. return new ArrayEnumerator(this, lowerBound, Length);
  763. }
  764. // Returns the index of the first occurrence of a given value in an array.
  765. // The array is searched forwards, and the elements of the array are
  766. // compared to the given value using the Object.Equals method.
  767. //
  768. public static int IndexOf(Array array, object value)
  769. {
  770. if (array == null)
  771. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  772. return IndexOf(array, value, array.GetLowerBound(0), array.Length);
  773. }
  774. // Returns the index of the first occurrence of a given value in a range of
  775. // an array. The array is searched forwards, starting at index
  776. // startIndex and ending at the last element of the array. The
  777. // elements of the array are compared to the given value using the
  778. // Object.Equals method.
  779. //
  780. public static int IndexOf(Array array, object value, int startIndex)
  781. {
  782. if (array == null)
  783. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  784. int lb = array.GetLowerBound(0);
  785. return IndexOf(array, value, startIndex, array.Length - startIndex + lb);
  786. }
  787. // Returns the index of the first occurrence of a given value in a range of
  788. // an array. The array is searched forwards, starting at index
  789. // startIndex and upto count elements. The
  790. // elements of the array are compared to the given value using the
  791. // Object.Equals method.
  792. //
  793. public static int IndexOf(Array array, object value, int startIndex, int count)
  794. {
  795. if (array == null)
  796. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  797. if (array.Rank != 1)
  798. ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
  799. int lb = array.GetLowerBound(0);
  800. if (startIndex < lb || startIndex > array.Length + lb)
  801. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  802. if (count < 0 || count > array.Length - startIndex + lb)
  803. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  804. #if CORECLR
  805. // Try calling a quick native method to handle primitive types.
  806. int retVal;
  807. bool r = TrySZIndexOf(array, startIndex, count, value, out retVal);
  808. if (r)
  809. return retVal;
  810. #endif
  811. object[] objArray = array as object[];
  812. int endIndex = startIndex + count;
  813. if (objArray != null)
  814. {
  815. if (value == null)
  816. {
  817. for (int i = startIndex; i < endIndex; i++)
  818. {
  819. if (objArray[i] == null) return i;
  820. }
  821. }
  822. else
  823. {
  824. for (int i = startIndex; i < endIndex; i++)
  825. {
  826. object obj = objArray[i];
  827. if (obj != null && obj.Equals(value)) return i;
  828. }
  829. }
  830. }
  831. else
  832. {
  833. for (int i = startIndex; i < endIndex; i++)
  834. {
  835. object obj = array.GetValue(i);
  836. if (obj == null)
  837. {
  838. if (value == null) return i;
  839. }
  840. else
  841. {
  842. if (obj.Equals(value)) return i;
  843. }
  844. }
  845. }
  846. // Return one less than the lower bound of the array. This way,
  847. // for arrays with a lower bound of -1 we will not return -1 when the
  848. // item was not found. And for SZArrays (the vast majority), -1 still
  849. // works for them.
  850. return lb - 1;
  851. }
  852. public static int IndexOf<T>(T[] array, T value)
  853. {
  854. if (array == null)
  855. {
  856. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  857. }
  858. return IndexOf(array, value, 0, array.Length);
  859. }
  860. public static int IndexOf<T>(T[] array, T value, int startIndex)
  861. {
  862. if (array == null)
  863. {
  864. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  865. }
  866. return IndexOf(array, value, startIndex, array.Length - startIndex);
  867. }
  868. public static int IndexOf<T>(T[] array, T value, int startIndex, int count)
  869. {
  870. if (array == null)
  871. {
  872. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  873. }
  874. if ((uint)startIndex > (uint)array.Length)
  875. {
  876. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  877. }
  878. if ((uint)count > (uint)(array.Length - startIndex))
  879. {
  880. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  881. }
  882. if (typeof(T) == typeof(byte))
  883. {
  884. int result = SpanHelpers.IndexOf(
  885. ref Unsafe.Add(ref array.GetRawSzArrayData(), startIndex),
  886. Unsafe.As<T, byte>(ref value),
  887. count);
  888. return (result >= 0 ? startIndex : 0) + result;
  889. }
  890. if (typeof(T) == typeof(char))
  891. {
  892. int result = SpanHelpers.IndexOf(
  893. ref Unsafe.Add(ref Unsafe.As<byte, char>(ref array.GetRawSzArrayData()), startIndex),
  894. Unsafe.As<T, char>(ref value),
  895. count);
  896. return (result >= 0 ? startIndex : 0) + result;
  897. }
  898. #if CORECLR
  899. return EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);
  900. #else
  901. return IndexOfImpl(array, value, startIndex, count);
  902. #endif
  903. }
  904. // Returns the index of the last occurrence of a given value in an array.
  905. // The array is searched backwards, and the elements of the array are
  906. // compared to the given value using the Object.Equals method.
  907. //
  908. public static int LastIndexOf(Array array, object value)
  909. {
  910. if (array == null)
  911. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  912. int lb = array.GetLowerBound(0);
  913. return LastIndexOf(array, value, array.Length - 1 + lb, array.Length);
  914. }
  915. // Returns the index of the last occurrence of a given value in a range of
  916. // an array. The array is searched backwards, starting at index
  917. // startIndex and ending at index 0. The elements of the array are
  918. // compared to the given value using the Object.Equals method.
  919. //
  920. public static int LastIndexOf(Array array, object value, int startIndex)
  921. {
  922. if (array == null)
  923. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  924. int lb = array.GetLowerBound(0);
  925. return LastIndexOf(array, value, startIndex, startIndex + 1 - lb);
  926. }
  927. // Returns the index of the last occurrence of a given value in a range of
  928. // an array. The array is searched backwards, starting at index
  929. // startIndex and counting uptocount elements. The elements of
  930. // the array are compared to the given value using the Object.Equals
  931. // method.
  932. //
  933. public static int LastIndexOf(Array array, object value, int startIndex, int count)
  934. {
  935. if (array == null)
  936. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  937. int lb = array.GetLowerBound(0);
  938. if (array.Length == 0)
  939. {
  940. return lb - 1;
  941. }
  942. if (startIndex < lb || startIndex >= array.Length + lb)
  943. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  944. if (count < 0)
  945. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  946. if (count > startIndex - lb + 1)
  947. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.endIndex, ExceptionResource.ArgumentOutOfRange_EndIndexStartIndex);
  948. if (array.Rank != 1)
  949. ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
  950. #if CORECLR
  951. // Try calling a quick native method to handle primitive types.
  952. int retVal;
  953. bool r = TrySZLastIndexOf(array, startIndex, count, value, out retVal);
  954. if (r)
  955. return retVal;
  956. #endif
  957. object[] objArray = array as object[];
  958. int endIndex = startIndex - count + 1;
  959. if (objArray != null)
  960. {
  961. if (value == null)
  962. {
  963. for (int i = startIndex; i >= endIndex; i--)
  964. {
  965. if (objArray[i] == null) return i;
  966. }
  967. }
  968. else
  969. {
  970. for (int i = startIndex; i >= endIndex; i--)
  971. {
  972. object obj = objArray[i];
  973. if (obj != null && obj.Equals(value)) return i;
  974. }
  975. }
  976. }
  977. else
  978. {
  979. for (int i = startIndex; i >= endIndex; i--)
  980. {
  981. object obj = array.GetValue(i);
  982. if (obj == null)
  983. {
  984. if (value == null) return i;
  985. }
  986. else
  987. {
  988. if (obj.Equals(value)) return i;
  989. }
  990. }
  991. }
  992. return lb - 1; // Return lb-1 for arrays with negative lower bounds.
  993. }
  994. public static int LastIndexOf<T>(T[] array, T value)
  995. {
  996. if (array == null)
  997. {
  998. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  999. }
  1000. return LastIndexOf(array, value, array.Length - 1, array.Length);
  1001. }
  1002. public static int LastIndexOf<T>(T[] array, T value, int startIndex)
  1003. {
  1004. if (array == null)
  1005. {
  1006. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1007. }
  1008. // if array is empty and startIndex is 0, we need to pass 0 as count
  1009. return LastIndexOf(array, value, startIndex, (array.Length == 0) ? 0 : (startIndex + 1));
  1010. }
  1011. public static int LastIndexOf<T>(T[] array, T value, int startIndex, int count)
  1012. {
  1013. if (array == null)
  1014. {
  1015. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1016. }
  1017. if (array.Length == 0)
  1018. {
  1019. //
  1020. // Special case for 0 length List
  1021. // accept -1 and 0 as valid startIndex for compablility reason.
  1022. //
  1023. if (startIndex != -1 && startIndex != 0)
  1024. {
  1025. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  1026. }
  1027. // only 0 is a valid value for count if array is empty
  1028. if (count != 0)
  1029. {
  1030. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  1031. }
  1032. return -1;
  1033. }
  1034. // Make sure we're not out of range
  1035. if ((uint)startIndex >= (uint)array.Length)
  1036. {
  1037. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  1038. }
  1039. // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
  1040. if (count < 0 || startIndex - count + 1 < 0)
  1041. {
  1042. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  1043. }
  1044. if (typeof(T) == typeof(byte))
  1045. {
  1046. int endIndex = startIndex - count + 1;
  1047. int result = SpanHelpers.LastIndexOf(
  1048. ref Unsafe.Add(ref array.GetRawSzArrayData(), endIndex),
  1049. Unsafe.As<T, byte>(ref value),
  1050. count);
  1051. return (result >= 0 ? endIndex : 0) + result;
  1052. }
  1053. if (typeof(T) == typeof(char))
  1054. {
  1055. int endIndex = startIndex - count + 1;
  1056. int result = SpanHelpers.LastIndexOf(
  1057. ref Unsafe.Add(ref Unsafe.As<byte, char>(ref array.GetRawSzArrayData()), endIndex),
  1058. Unsafe.As<T, char>(ref value),
  1059. count);
  1060. return (result >= 0 ? endIndex : 0) + result;
  1061. }
  1062. #if CORECLR
  1063. return EqualityComparer<T>.Default.LastIndexOf(array, value, startIndex, count);
  1064. #else
  1065. return LastIndexOfImpl(array, value, startIndex, count);
  1066. #endif
  1067. }
  1068. // Reverses all elements of the given array. Following a call to this
  1069. // method, an element previously located at index i will now be
  1070. // located at index length - i - 1, where length is the
  1071. // length of the array.
  1072. //
  1073. public static void Reverse(Array array)
  1074. {
  1075. if (array == null)
  1076. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1077. Reverse(array, array.GetLowerBound(0), array.Length);
  1078. }
  1079. // Reverses the elements in a range of an array. Following a call to this
  1080. // method, an element in the range given by index and count
  1081. // which was previously located at index i will now be located at
  1082. // index index + (index + count - i - 1).
  1083. // Reliability note: This may fail because it may have to box objects.
  1084. //
  1085. public static void Reverse(Array array, int index, int length)
  1086. {
  1087. if (array == null)
  1088. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1089. int lowerBound = array.GetLowerBound(0);
  1090. if (index < lowerBound)
  1091. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  1092. if (length < 0)
  1093. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  1094. if (array.Length - (index - lowerBound) < length)
  1095. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  1096. if (array.Rank != 1)
  1097. ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
  1098. if (length <= 1)
  1099. return;
  1100. #if CORECLR
  1101. bool r = TrySZReverse(array, index, length);
  1102. if (r)
  1103. return;
  1104. #endif
  1105. if (array is object[] objArray)
  1106. {
  1107. Array.Reverse<object>(objArray, index, length);
  1108. }
  1109. else
  1110. {
  1111. int i = index;
  1112. int j = index + length - 1;
  1113. while (i < j)
  1114. {
  1115. object temp = array.GetValue(i);
  1116. array.SetValue(array.GetValue(j), i);
  1117. array.SetValue(temp, j);
  1118. i++;
  1119. j--;
  1120. }
  1121. }
  1122. }
  1123. public static void Reverse<T>(T[] array)
  1124. {
  1125. if (array == null)
  1126. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1127. Reverse(array, 0, array.Length);
  1128. }
  1129. public static void Reverse<T>(T[] array, int index, int length)
  1130. {
  1131. if (array == null)
  1132. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1133. if (index < 0)
  1134. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  1135. if (length < 0)
  1136. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  1137. if (array.Length - index < length)
  1138. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  1139. if (length <= 1)
  1140. return;
  1141. ref T first = ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), index);
  1142. ref T last = ref Unsafe.Add(ref Unsafe.Add(ref first, length), -1);
  1143. do
  1144. {
  1145. T temp = first;
  1146. first = last;
  1147. last = temp;
  1148. first = ref Unsafe.Add(ref first, 1);
  1149. last = ref Unsafe.Add(ref last, -1);
  1150. } while (Unsafe.IsAddressLessThan(ref first, ref last));
  1151. }
  1152. // Sorts the elements of an array. The sort compares the elements to each
  1153. // other using the IComparable interface, which must be implemented
  1154. // by all elements of the array.
  1155. //
  1156. public static void Sort(Array array)
  1157. {
  1158. if (array == null)
  1159. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1160. Sort(array, null, array.GetLowerBound(0), array.Length, null);
  1161. }
  1162. // Sorts the elements of two arrays based on the keys in the first array.
  1163. // Elements in the keys array specify the sort keys for
  1164. // corresponding elements in the items array. The sort compares the
  1165. // keys to each other using the IComparable interface, which must be
  1166. // implemented by all elements of the keys array.
  1167. //
  1168. public static void Sort(Array keys, Array items)
  1169. {
  1170. if (keys == null)
  1171. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
  1172. Sort(keys, items, keys.GetLowerBound(0), keys.Length, null);
  1173. }
  1174. // Sorts the elements in a section of an array. The sort compares the
  1175. // elements to each other using the IComparable interface, which
  1176. // must be implemented by all elements in the given section of the array.
  1177. //
  1178. public static void Sort(Array array, int index, int length)
  1179. {
  1180. Sort(array, null, index, length, null);
  1181. }
  1182. // Sorts the elements in a section of two arrays based on the keys in the
  1183. // first array. Elements in the keys array specify the sort keys for
  1184. // corresponding elements in the items array. The sort compares the
  1185. // keys to each other using the IComparable interface, which must be
  1186. // implemented by all elements of the keys array.
  1187. //
  1188. public static void Sort(Array keys, Array items, int index, int length)
  1189. {
  1190. Sort(keys, items, index, length, null);
  1191. }
  1192. // Sorts the elements of an array. The sort compares the elements to each
  1193. // other using the given IComparer interface. If comparer is
  1194. // null, the elements are compared to each other using the
  1195. // IComparable interface, which in that case must be implemented by
  1196. // all elements of the array.
  1197. //
  1198. public static void Sort(Array array, IComparer comparer)
  1199. {
  1200. if (array == null)
  1201. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1202. Sort(array, null, array.GetLowerBound(0), array.Length, comparer);
  1203. }
  1204. // Sorts the elements of two arrays based on the keys in the first array.
  1205. // Elements in the keys array specify the sort keys for
  1206. // corresponding elements in the items array. The sort compares the
  1207. // keys to each other using the given IComparer interface. If
  1208. // comparer is null, the elements are compared to each other using
  1209. // the IComparable interface, which in that case must be implemented
  1210. // by all elements of the keys array.
  1211. //
  1212. public static void Sort(Array keys, Array items, IComparer comparer)
  1213. {
  1214. if (keys == null)
  1215. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
  1216. Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer);
  1217. }
  1218. // Sorts the elements in a section of an array. The sort compares the
  1219. // elements to each other using the given IComparer interface. If
  1220. // comparer is null, the elements are compared to each other using
  1221. // the IComparable interface, which in that case must be implemented
  1222. // by all elements in the given section of the array.
  1223. //
  1224. public static void Sort(Array array, int index, int length, IComparer comparer)
  1225. {
  1226. Sort(array, null, index, length, comparer);
  1227. }
  1228. // Sorts the elements in a section of two arrays based on the keys in the
  1229. // first array. Elements in the keys array specify the sort keys for
  1230. // corresponding elements in the items array. The sort compares the
  1231. // keys to each other using the given IComparer interface. If
  1232. // comparer is null, the elements are compared to each other using
  1233. // the IComparable interface, which in that case must be implemented
  1234. // by all elements of the given section of the keys array.
  1235. //
  1236. public static void Sort(Array keys, Array items, int index, int length, IComparer comparer)
  1237. {
  1238. if (keys == null)
  1239. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
  1240. if (keys.Rank != 1 || (items != null && items.Rank != 1))
  1241. ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
  1242. int keysLowerBound = keys.GetLowerBound(0);
  1243. if (items != null && keysLowerBound != items.GetLowerBound(0))
  1244. ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_LowerBoundsMustMatch);
  1245. if (index < keysLowerBound)
  1246. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  1247. if (length < 0)
  1248. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  1249. if (keys.Length - (index - keysLowerBound) < length || (items != null && (index - keysLowerBound) > items.Length - length))
  1250. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  1251. if (length > 1)
  1252. {
  1253. SortImpl(keys, items, index, length, comparer ?? Comparer.Default);
  1254. }
  1255. }
  1256. public static void Sort<T>(T[] array)
  1257. {
  1258. if (array == null)
  1259. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1260. Sort<T>(array, 0, array.Length, null);
  1261. }
  1262. public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items)
  1263. {
  1264. if (keys == null)
  1265. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
  1266. Sort<TKey, TValue>(keys, items, 0, keys.Length, null);
  1267. }
  1268. public static void Sort<T>(T[] array, int index, int length)
  1269. {
  1270. Sort<T>(array, index, length, null);
  1271. }
  1272. public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length)
  1273. {
  1274. Sort<TKey, TValue>(keys, items, index, length, null);
  1275. }
  1276. public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T> comparer)
  1277. {
  1278. if (array == null)
  1279. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1280. Sort<T>(array, 0, array.Length, comparer);
  1281. }
  1282. public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer)
  1283. {
  1284. if (keys == null)
  1285. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
  1286. Sort<TKey, TValue>(keys, items, 0, keys.Length, comparer);
  1287. }
  1288. public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer)
  1289. {
  1290. if (array == null)
  1291. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1292. if (index < 0)
  1293. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  1294. if (length < 0)
  1295. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  1296. if (array.Length - index < length)
  1297. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  1298. if (length > 1)
  1299. {
  1300. #if CORECLR
  1301. if (comparer == null || comparer == Comparer<T>.Default)
  1302. {
  1303. if (TrySZSort(array, null, index, index + length - 1))
  1304. {
  1305. return;
  1306. }
  1307. }
  1308. #endif
  1309. ArraySortHelper<T>.Default.Sort(array, index, length, comparer);
  1310. }
  1311. }
  1312. public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer)
  1313. {
  1314. if (keys == null)
  1315. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
  1316. if (index < 0)
  1317. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  1318. if (length < 0)
  1319. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  1320. if (keys.Length - index < length || (items != null && index > items.Length - length))
  1321. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  1322. if (length > 1)
  1323. {
  1324. #if CORECLR
  1325. if (comparer == null || comparer == Comparer<TKey>.Default)
  1326. {
  1327. if (TrySZSort(keys, items, index, index + length - 1))
  1328. {
  1329. return;
  1330. }
  1331. }
  1332. #endif
  1333. if (items == null)
  1334. {
  1335. Sort<TKey>(keys, index, length, comparer);
  1336. return;
  1337. }
  1338. ArraySortHelper<TKey, TValue>.Default.Sort(keys, items, index, length, comparer);
  1339. }
  1340. }
  1341. public static void Sort<T>(T[] array, Comparison<T> comparison)
  1342. {
  1343. if (array == null)
  1344. {
  1345. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1346. }
  1347. if (comparison == null)
  1348. {
  1349. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison);
  1350. }
  1351. ArraySortHelper<T>.Sort(array, 0, array.Length, comparison);
  1352. }
  1353. public static bool TrueForAll<T>(T[] array, Predicate<T> match)
  1354. {
  1355. if (array == null)
  1356. {
  1357. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1358. }
  1359. if (match == null)
  1360. {
  1361. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  1362. }
  1363. for (int i = 0; i < array.Length; i++)
  1364. {
  1365. if (!match(array[i]))
  1366. {
  1367. return false;
  1368. }
  1369. }
  1370. return true;
  1371. }
  1372. // Private value type used by the Sort methods.
  1373. private readonly struct SorterObjectArray
  1374. {
  1375. private readonly object[] keys;
  1376. private readonly object[] items;
  1377. private readonly IComparer comparer;
  1378. internal SorterObjectArray(object[] keys, object[] items, IComparer comparer)
  1379. {
  1380. this.keys = keys;
  1381. this.items = items;
  1382. this.comparer = comparer;
  1383. }
  1384. internal void SwapIfGreaterWithItems(int a, int b)
  1385. {
  1386. if (a != b)
  1387. {
  1388. if (comparer.Compare(keys[a], keys[b]) > 0)
  1389. {
  1390. object temp = keys[a];
  1391. keys[a] = keys[b];
  1392. keys[b] = temp;
  1393. if (items != null)
  1394. {
  1395. object item = items[a];
  1396. items[a] = items[b];
  1397. items[b] = item;
  1398. }
  1399. }
  1400. }
  1401. }
  1402. private void Swap(int i, int j)
  1403. {
  1404. object t = keys[i];
  1405. keys[i] = keys[j];
  1406. keys[j] = t;
  1407. if (items != null)
  1408. {
  1409. object item = items[i];
  1410. items[i] = items[j];
  1411. items[j] = item;
  1412. }
  1413. }
  1414. internal void Sort(int left, int length)
  1415. {
  1416. IntrospectiveSort(left, length);
  1417. }
  1418. private void IntrospectiveSort(int left, int length)
  1419. {
  1420. if (length < 2)
  1421. return;
  1422. try
  1423. {
  1424. IntroSort(left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length));
  1425. }
  1426. catch (IndexOutOfRangeException)
  1427. {
  1428. IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
  1429. }
  1430. catch (Exception e)
  1431. {
  1432. ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
  1433. }
  1434. }
  1435. private void IntroSort(int lo, int hi, int depthLimit)
  1436. {
  1437. while (hi > lo)
  1438. {
  1439. int partitionSize = hi - lo + 1;
  1440. if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
  1441. {
  1442. if (partitionSize == 1)
  1443. {
  1444. return;
  1445. }
  1446. if (partitionSize == 2)
  1447. {
  1448. SwapIfGreaterWithItems(lo, hi);
  1449. return;
  1450. }
  1451. if (partitionSize == 3)
  1452. {
  1453. SwapIfGreaterWithItems(lo, hi - 1);
  1454. SwapIfGreaterWithItems(lo, hi);
  1455. SwapIfGreaterWithItems(hi - 1, hi);
  1456. return;
  1457. }
  1458. InsertionSort(lo, hi);
  1459. return;
  1460. }
  1461. if (depthLimit == 0)
  1462. {
  1463. Heapsort(lo, hi);
  1464. return;
  1465. }
  1466. depthLimit--;
  1467. int p = PickPivotAndPartition(lo, hi);
  1468. IntroSort(p + 1, hi, depthLimit);
  1469. hi = p - 1;
  1470. }
  1471. }
  1472. private int PickPivotAndPartition(int lo, int hi)
  1473. {
  1474. // Compute median-of-three. But also partition them, since we've done the comparison.
  1475. int mid = lo + (hi - lo) / 2;
  1476. // Sort lo, mid and hi appropriately, then pick mid as the pivot.
  1477. SwapIfGreaterWithItems(lo, mid);
  1478. SwapIfGreaterWithItems(lo, hi);
  1479. SwapIfGreaterWithItems(mid, hi);
  1480. object pivot = keys[mid];
  1481. Swap(mid, hi - 1);
  1482. int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
  1483. while (left < right)
  1484. {
  1485. while (comparer.Compare(keys[++left], pivot) < 0) ;
  1486. while (comparer.Compare(pivot, keys[--right]) < 0) ;
  1487. if (left >= right)
  1488. break;
  1489. Swap(left, right);
  1490. }
  1491. // Put pivot in the right location.
  1492. Swap(left, (hi - 1));
  1493. return left;
  1494. }
  1495. private void Heapsort(int lo, int hi)
  1496. {
  1497. int n = hi - lo + 1;
  1498. for (int i = n / 2; i >= 1; i = i - 1)
  1499. {
  1500. DownHeap(i, n, lo);
  1501. }
  1502. for (int i = n; i > 1; i = i - 1)
  1503. {
  1504. Swap(lo, lo + i - 1);
  1505. DownHeap(1, i - 1, lo);
  1506. }
  1507. }
  1508. private void DownHeap(int i, int n, int lo)
  1509. {
  1510. object d = keys[lo + i - 1];
  1511. object dt = (items != null) ? items[lo + i - 1] : null;
  1512. int child;
  1513. while (i <= n / 2)
  1514. {
  1515. child = 2 * i;
  1516. if (child < n && comparer.Compare(keys[lo + child - 1], keys[lo + child]) < 0)
  1517. {
  1518. child++;
  1519. }
  1520. if (!(comparer.Compare(d, keys[lo + child - 1]) < 0))
  1521. break;
  1522. keys[lo + i - 1] = keys[lo + child - 1];
  1523. if (items != null)
  1524. items[lo + i - 1] = items[lo + child - 1];
  1525. i = child;
  1526. }
  1527. keys[lo + i - 1] = d;
  1528. if (items != null)
  1529. items[lo + i - 1] = dt;
  1530. }
  1531. private void InsertionSort(int lo, int hi)
  1532. {
  1533. int i, j;
  1534. object t, ti;
  1535. for (i = lo; i < hi; i++)
  1536. {
  1537. j = i;
  1538. t = keys[i + 1];
  1539. ti = (items != null) ? items[i + 1] : null;
  1540. while (j >= lo && comparer.Compare(t, keys[j]) < 0)
  1541. {
  1542. keys[j + 1] = keys[j];
  1543. if (items != null)
  1544. items[j + 1] = items[j];
  1545. j--;
  1546. }
  1547. keys[j + 1] = t;
  1548. if (items != null)
  1549. items[j + 1] = ti;
  1550. }
  1551. }
  1552. }
  1553. // Private value used by the Sort methods for instances of Array.
  1554. // This is slower than the one for Object[], since we can't use the JIT helpers
  1555. // to access the elements. We must use GetValue & SetValue.
  1556. private readonly struct SorterGenericArray
  1557. {
  1558. private readonly Array keys;
  1559. private readonly Array items;
  1560. private readonly IComparer comparer;
  1561. internal SorterGenericArray(Array keys, Array items, IComparer comparer)
  1562. {
  1563. this.keys = keys;
  1564. this.items = items;
  1565. this.comparer = comparer;
  1566. }
  1567. internal void SwapIfGreaterWithItems(int a, int b)
  1568. {
  1569. if (a != b)
  1570. {
  1571. if (comparer.Compare(keys.GetValue(a), keys.GetValue(b)) > 0)
  1572. {
  1573. object key = keys.GetValue(a);
  1574. keys.SetValue(keys.GetValue(b), a);
  1575. keys.SetValue(key, b);
  1576. if (items != null)
  1577. {
  1578. object item = items.GetValue(a);
  1579. items.SetValue(items.GetValue(b), a);
  1580. items.SetValue(item, b);
  1581. }
  1582. }
  1583. }
  1584. }
  1585. private void Swap(int i, int j)
  1586. {
  1587. object t1 = keys.GetValue(i);
  1588. keys.SetValue(keys.GetValue(j), i);
  1589. keys.SetValue(t1, j);
  1590. if (items != null)
  1591. {
  1592. object t2 = items.GetValue(i);
  1593. items.SetValue(items.GetValue(j), i);
  1594. items.SetValue(t2, j);
  1595. }
  1596. }
  1597. internal void Sort(int left, int length)
  1598. {
  1599. IntrospectiveSort(left, length);
  1600. }
  1601. private void IntrospectiveSort(int left, int length)
  1602. {
  1603. if (length < 2)
  1604. return;
  1605. try
  1606. {
  1607. IntroSort(left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length));
  1608. }
  1609. catch (IndexOutOfRangeException)
  1610. {
  1611. IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
  1612. }
  1613. catch (Exception e)
  1614. {
  1615. ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
  1616. }
  1617. }
  1618. private void IntroSort(int lo, int hi, int depthLimit)
  1619. {
  1620. while (hi > lo)
  1621. {
  1622. int partitionSize = hi - lo + 1;
  1623. if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
  1624. {
  1625. if (partitionSize == 1)
  1626. {
  1627. return;
  1628. }
  1629. if (partitionSize == 2)
  1630. {
  1631. SwapIfGreaterWithItems(lo, hi);
  1632. return;
  1633. }
  1634. if (partitionSize == 3)
  1635. {
  1636. SwapIfGreaterWithItems(lo, hi - 1);
  1637. SwapIfGreaterWithItems(lo, hi);
  1638. SwapIfGreaterWithItems(hi - 1, hi);
  1639. return;
  1640. }
  1641. InsertionSort(lo, hi);
  1642. return;
  1643. }
  1644. if (depthLimit == 0)
  1645. {
  1646. Heapsort(lo, hi);
  1647. return;
  1648. }
  1649. depthLimit--;
  1650. int p = PickPivotAndPartition(lo, hi);
  1651. IntroSort(p + 1, hi, depthLimit);
  1652. hi = p - 1;
  1653. }
  1654. }
  1655. private int PickPivotAndPartition(int lo, int hi)
  1656. {
  1657. // Compute median-of-three. But also partition them, since we've done the comparison.
  1658. int mid = lo + (hi - lo) / 2;
  1659. SwapIfGreaterWithItems(lo, mid);
  1660. SwapIfGreaterWithItems(lo, hi);
  1661. SwapIfGreaterWithItems(mid, hi);
  1662. object pivot = keys.GetValue(mid);
  1663. Swap(mid, hi - 1);
  1664. int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
  1665. while (left < right)
  1666. {
  1667. while (comparer.Compare(keys.GetValue(++left), pivot) < 0) ;
  1668. while (comparer.Compare(pivot, keys.GetValue(--right)) < 0) ;
  1669. if (left >= right)
  1670. break;
  1671. Swap(left, right);
  1672. }
  1673. // Put pivot in the right location.
  1674. Swap(left, (hi - 1));
  1675. return left;
  1676. }
  1677. private void Heapsort(int lo, int hi)
  1678. {
  1679. int n = hi - lo + 1;
  1680. for (int i = n / 2; i >= 1; i = i - 1)
  1681. {
  1682. DownHeap(i, n, lo);
  1683. }
  1684. for (int i = n; i > 1; i = i - 1)
  1685. {
  1686. Swap(lo, lo + i - 1);
  1687. DownHeap(1, i - 1, lo);
  1688. }
  1689. }
  1690. private void DownHeap(int i, int n, int lo)
  1691. {
  1692. object d = keys.GetValue(lo + i - 1);
  1693. object dt = (items != null) ? items.GetValue(lo + i - 1) : null;
  1694. int child;
  1695. while (i <= n / 2)
  1696. {
  1697. child = 2 * i;
  1698. if (child < n && comparer.Compare(keys.GetValue(lo + child - 1), keys.GetValue(lo + child)) < 0)
  1699. {
  1700. child++;
  1701. }
  1702. if (!(comparer.Compare(d, keys.GetValue(lo + child - 1)) < 0))
  1703. break;
  1704. keys.SetValue(keys.GetValue(lo + child - 1), lo + i - 1);
  1705. if (items != null)
  1706. items.SetValue(items.GetValue(lo + child - 1), lo + i - 1);
  1707. i = child;
  1708. }
  1709. keys.SetValue(d, lo + i - 1);
  1710. if (items != null)
  1711. items.SetValue(dt, lo + i - 1);
  1712. }
  1713. private void InsertionSort(int lo, int hi)
  1714. {
  1715. int i, j;
  1716. object t, dt;
  1717. for (i = lo; i < hi; i++)
  1718. {
  1719. j = i;
  1720. t = keys.GetValue(i + 1);
  1721. dt = (items != null) ? items.GetValue(i + 1) : null;
  1722. while (j >= lo && comparer.Compare(t, keys.GetValue(j)) < 0)
  1723. {
  1724. keys.SetValue(keys.GetValue(j), j + 1);
  1725. if (items != null)
  1726. items.SetValue(items.GetValue(j), j + 1);
  1727. j--;
  1728. }
  1729. keys.SetValue(t, j + 1);
  1730. if (items != null)
  1731. items.SetValue(dt, j + 1);
  1732. }
  1733. }
  1734. }
  1735. private sealed class SZArrayEnumerator : IEnumerator, ICloneable
  1736. {
  1737. private readonly Array _array;
  1738. private int _index;
  1739. private int _endIndex; // Cache Array.Length, since it's a little slow.
  1740. internal SZArrayEnumerator(Array array)
  1741. {
  1742. Debug.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero.");
  1743. _array = array;
  1744. _index = -1;
  1745. _endIndex = array.Length;
  1746. }
  1747. public object Clone()
  1748. {
  1749. return MemberwiseClone();
  1750. }
  1751. public bool MoveNext()
  1752. {
  1753. if (_index < _endIndex)
  1754. {
  1755. _index++;
  1756. return (_index < _endIndex);
  1757. }
  1758. return false;
  1759. }
  1760. public object Current
  1761. {
  1762. get
  1763. {
  1764. if (_index < 0) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
  1765. if (_index >= _endIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
  1766. return _array.GetValue(_index);
  1767. }
  1768. }
  1769. public void Reset()
  1770. {
  1771. _index = -1;
  1772. }
  1773. }
  1774. private sealed class ArrayEnumerator : IEnumerator, ICloneable
  1775. {
  1776. private Array array;
  1777. private int index;
  1778. private int endIndex;
  1779. private int startIndex; // Save for Reset.
  1780. private int[] _indices; // The current position in a multidim array
  1781. private bool _complete;
  1782. internal ArrayEnumerator(Array array, int index, int count)
  1783. {
  1784. this.array = array;
  1785. this.index = index - 1;
  1786. startIndex = index;
  1787. endIndex = index + count;
  1788. _indices = new int[array.Rank];
  1789. int checkForZero = 1; // Check for dimensions of size 0.
  1790. for (int i = 0; i < array.Rank; i++)
  1791. {
  1792. _indices[i] = array.GetLowerBound(i);
  1793. checkForZero *= array.GetLength(i);
  1794. }
  1795. // To make MoveNext simpler, decrement least significant index.
  1796. _indices[_indices.Length - 1]--;
  1797. _complete = (checkForZero == 0);
  1798. }
  1799. private void IncArray()
  1800. {
  1801. // This method advances us to the next valid array index,
  1802. // handling all the multiple dimension & bounds correctly.
  1803. // Think of it like an odometer in your car - we start with
  1804. // the last digit, increment it, and check for rollover. If
  1805. // it rolls over, we set all digits to the right and including
  1806. // the current to the appropriate lower bound. Do these overflow
  1807. // checks for each dimension, and if the most significant digit
  1808. // has rolled over it's upper bound, we're done.
  1809. //
  1810. int rank = array.Rank;
  1811. _indices[rank - 1]++;
  1812. for (int dim = rank - 1; dim >= 0; dim--)
  1813. {
  1814. if (_indices[dim] > array.GetUpperBound(dim))
  1815. {
  1816. if (dim == 0)
  1817. {
  1818. _complete = true;
  1819. break;
  1820. }
  1821. for (int j = dim; j < rank; j++)
  1822. _indices[j] = array.GetLowerBound(j);
  1823. _indices[dim - 1]++;
  1824. }
  1825. }
  1826. }
  1827. public object Clone()
  1828. {
  1829. return MemberwiseClone();
  1830. }
  1831. public bool MoveNext()
  1832. {
  1833. if (_complete)
  1834. {
  1835. index = endIndex;
  1836. return false;
  1837. }
  1838. index++;
  1839. IncArray();
  1840. return !_complete;
  1841. }
  1842. public object Current
  1843. {
  1844. get
  1845. {
  1846. if (index < startIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
  1847. if (_complete) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
  1848. return array.GetValue(_indices);
  1849. }
  1850. }
  1851. public void Reset()
  1852. {
  1853. index = startIndex - 1;
  1854. int checkForZero = 1;
  1855. for (int i = 0; i < array.Rank; i++)
  1856. {
  1857. _indices[i] = array.GetLowerBound(i);
  1858. checkForZero *= array.GetLength(i);
  1859. }
  1860. _complete = (checkForZero == 0);
  1861. // To make MoveNext simpler, decrement least significant index.
  1862. _indices[_indices.Length - 1]--;
  1863. }
  1864. }
  1865. }
  1866. }