Array.cs 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152
  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. return BinarySearch(array, array.GetLowerBound(0), array.Length, value, null);
  339. }
  340. // Searches a section of an array for a given element using a binary search
  341. // algorithm. Elements of the array are compared to the search value using
  342. // the IComparable interface, which must be implemented by all
  343. // elements of the array and the given search value. This method assumes
  344. // that the array is already sorted according to the IComparable
  345. // interface; if this is not the case, the result will be incorrect.
  346. //
  347. // The method returns the index of the given value in the array. If the
  348. // array does not contain the given value, the method returns a negative
  349. // integer. The bitwise complement operator (~) can be applied to a
  350. // negative result to produce the index of the first element (if any) that
  351. // is larger than the given search value.
  352. //
  353. public static int BinarySearch(Array array, int index, int length, object value)
  354. {
  355. return BinarySearch(array, index, length, value, null);
  356. }
  357. // Searches an array for a given element using a binary search algorithm.
  358. // Elements of the array are compared to the search value using the given
  359. // IComparer interface. If comparer is null, elements of the
  360. // array are compared to the search value using the IComparable
  361. // interface, which in that case must be implemented by all elements of the
  362. // array and the given search value. This method assumes that the array is
  363. // already sorted; if this is not the case, the result will be incorrect.
  364. //
  365. // The method returns the index of the given value in the array. If the
  366. // array does not contain the given value, the method returns a negative
  367. // integer. The bitwise complement operator (~) can be applied to a
  368. // negative result to produce the index of the first element (if any) that
  369. // is larger than the given search value.
  370. //
  371. public static int BinarySearch(Array array, object value, IComparer comparer)
  372. {
  373. if (array == null)
  374. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  375. return BinarySearch(array, array.GetLowerBound(0), array.Length, value, comparer);
  376. }
  377. // Searches a section of an array for a given element using a binary search
  378. // algorithm. Elements of the array are compared to the search value using
  379. // the given IComparer interface. If comparer is null,
  380. // elements of the array are compared to the search value using the
  381. // IComparable interface, which in that case must be implemented by
  382. // all elements of the array and the given search value. This method
  383. // assumes that the array is already sorted; if this is not the case, the
  384. // result will be incorrect.
  385. //
  386. // The method returns the index of the given value in the array. If the
  387. // array does not contain the given value, the method returns a negative
  388. // integer. The bitwise complement operator (~) can be applied to a
  389. // negative result to produce the index of the first element (if any) that
  390. // is larger than the given search value.
  391. //
  392. public static int BinarySearch(Array array, int index, int length, object value, IComparer comparer)
  393. {
  394. if (array == null)
  395. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  396. int lb = array.GetLowerBound(0);
  397. if (index < lb)
  398. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  399. if (length < 0)
  400. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  401. if (array.Length - (index - lb) < length)
  402. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  403. if (array.Rank != 1)
  404. ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
  405. if (comparer == null) comparer = Comparer.Default;
  406. #if CORECLR
  407. if (comparer == Comparer.Default)
  408. {
  409. int retval;
  410. bool r = TrySZBinarySearch(array, index, length, value, out retval);
  411. if (r)
  412. return retval;
  413. }
  414. #endif
  415. int lo = index;
  416. int hi = index + length - 1;
  417. if (array is object[] objArray)
  418. {
  419. while (lo <= hi)
  420. {
  421. // i might overflow if lo and hi are both large positive numbers.
  422. int i = GetMedian(lo, hi);
  423. int c;
  424. try
  425. {
  426. c = comparer.Compare(objArray[i], value);
  427. }
  428. catch (Exception e)
  429. {
  430. ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
  431. return default;
  432. }
  433. if (c == 0) return i;
  434. if (c < 0)
  435. {
  436. lo = i + 1;
  437. }
  438. else
  439. {
  440. hi = i - 1;
  441. }
  442. }
  443. }
  444. else
  445. {
  446. while (lo <= hi)
  447. {
  448. int i = GetMedian(lo, hi);
  449. int c;
  450. try
  451. {
  452. c = comparer.Compare(array.GetValue(i), value);
  453. }
  454. catch (Exception e)
  455. {
  456. ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
  457. return default;
  458. }
  459. if (c == 0) return i;
  460. if (c < 0)
  461. {
  462. lo = i + 1;
  463. }
  464. else
  465. {
  466. hi = i - 1;
  467. }
  468. }
  469. }
  470. return ~lo;
  471. }
  472. public static int BinarySearch<T>(T[] array, T value)
  473. {
  474. if (array == null)
  475. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  476. return BinarySearch<T>(array, 0, array.Length, value, null);
  477. }
  478. public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T> comparer)
  479. {
  480. if (array == null)
  481. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  482. return BinarySearch<T>(array, 0, array.Length, value, comparer);
  483. }
  484. public static int BinarySearch<T>(T[] array, int index, int length, T value)
  485. {
  486. return BinarySearch<T>(array, index, length, value, null);
  487. }
  488. public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer)
  489. {
  490. if (array == null)
  491. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  492. if (index < 0)
  493. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  494. if (length < 0)
  495. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  496. if (array.Length - index < length)
  497. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  498. return ArraySortHelper<T>.Default.BinarySearch(array, index, length, value, comparer);
  499. }
  500. public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter)
  501. {
  502. if (array == null)
  503. {
  504. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  505. }
  506. if (converter == null)
  507. {
  508. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
  509. }
  510. TOutput[] newArray = new TOutput[array.Length];
  511. for (int i = 0; i < array.Length; i++)
  512. {
  513. newArray[i] = converter(array[i]);
  514. }
  515. return newArray;
  516. }
  517. // CopyTo copies a collection into an Array, starting at a particular
  518. // index into the array.
  519. //
  520. // This method is to support the ICollection interface, and calls
  521. // Array.Copy internally. If you aren't using ICollection explicitly,
  522. // call Array.Copy to avoid an extra indirection.
  523. //
  524. public void CopyTo(Array array, int index)
  525. {
  526. if (array != null && array.Rank != 1)
  527. ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
  528. // Note: Array.Copy throws a RankException and we want a consistent ArgumentException for all the IList CopyTo methods.
  529. Array.Copy(this, GetLowerBound(0), array, index, Length);
  530. }
  531. public void CopyTo(Array array, long index)
  532. {
  533. int iindex = (int)index;
  534. if (index != iindex)
  535. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
  536. this.CopyTo(array, iindex);
  537. }
  538. private static class EmptyArray<T>
  539. {
  540. internal static readonly T[] Value = new T[0];
  541. }
  542. public static T[] Empty<T>()
  543. {
  544. return EmptyArray<T>.Value;
  545. }
  546. public static bool Exists<T>(T[] array, Predicate<T> match)
  547. {
  548. return Array.FindIndex(array, match) != -1;
  549. }
  550. public static void Fill<T>(T[] array, T value)
  551. {
  552. if (array == null)
  553. {
  554. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  555. }
  556. for (int i = 0; i < array.Length; i++)
  557. {
  558. array[i] = value;
  559. }
  560. }
  561. public static void Fill<T>(T[] array, T value, int startIndex, int count)
  562. {
  563. if (array == null)
  564. {
  565. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  566. }
  567. if (startIndex < 0 || startIndex > array.Length)
  568. {
  569. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  570. }
  571. if (count < 0 || startIndex > array.Length - count)
  572. {
  573. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  574. }
  575. for (int i = startIndex; i < startIndex + count; i++)
  576. {
  577. array[i] = value;
  578. }
  579. }
  580. public static T Find<T>(T[] array, Predicate<T> match)
  581. {
  582. if (array == null)
  583. {
  584. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  585. }
  586. if (match == null)
  587. {
  588. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  589. }
  590. for (int i = 0; i < array.Length; i++)
  591. {
  592. if (match(array[i]))
  593. {
  594. return array[i];
  595. }
  596. }
  597. return default;
  598. }
  599. public static T[] FindAll<T>(T[] array, Predicate<T> match)
  600. {
  601. if (array == null)
  602. {
  603. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  604. }
  605. if (match == null)
  606. {
  607. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  608. }
  609. List<T> list = new List<T>();
  610. for (int i = 0; i < array.Length; i++)
  611. {
  612. if (match(array[i]))
  613. {
  614. list.Add(array[i]);
  615. }
  616. }
  617. return list.ToArray();
  618. }
  619. public static int FindIndex<T>(T[] array, Predicate<T> match)
  620. {
  621. if (array == null)
  622. {
  623. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  624. }
  625. return FindIndex(array, 0, array.Length, match);
  626. }
  627. public static int FindIndex<T>(T[] array, int startIndex, Predicate<T> match)
  628. {
  629. if (array == null)
  630. {
  631. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  632. }
  633. return FindIndex(array, startIndex, array.Length - startIndex, match);
  634. }
  635. public static int FindIndex<T>(T[] array, int startIndex, int count, Predicate<T> match)
  636. {
  637. if (array == null)
  638. {
  639. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  640. }
  641. if (startIndex < 0 || startIndex > array.Length)
  642. {
  643. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  644. }
  645. if (count < 0 || startIndex > array.Length - count)
  646. {
  647. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  648. }
  649. if (match == null)
  650. {
  651. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  652. }
  653. int endIndex = startIndex + count;
  654. for (int i = startIndex; i < endIndex; i++)
  655. {
  656. if (match(array[i]))
  657. 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. // Returns the index of the first occurrence of a given value in an array.
  753. // The array is searched forwards, and the elements of the array are
  754. // compared to the given value using the Object.Equals method.
  755. //
  756. public static int IndexOf(Array array, object value)
  757. {
  758. if (array == null)
  759. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  760. return IndexOf(array, value, array.GetLowerBound(0), array.Length);
  761. }
  762. // Returns the index of the first occurrence of a given value in a range of
  763. // an array. The array is searched forwards, starting at index
  764. // startIndex and ending at the last element of the array. The
  765. // elements of the array are compared to the given value using the
  766. // Object.Equals method.
  767. //
  768. public static int IndexOf(Array array, object value, int startIndex)
  769. {
  770. if (array == null)
  771. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  772. int lb = array.GetLowerBound(0);
  773. return IndexOf(array, value, startIndex, array.Length - startIndex + lb);
  774. }
  775. // Returns the index of the first occurrence of a given value in a range of
  776. // an array. The array is searched forwards, starting at index
  777. // startIndex and upto count elements. The
  778. // elements of the array are compared to the given value using the
  779. // Object.Equals method.
  780. //
  781. public static int IndexOf(Array array, object value, int startIndex, int count)
  782. {
  783. if (array == null)
  784. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  785. if (array.Rank != 1)
  786. ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
  787. int lb = array.GetLowerBound(0);
  788. if (startIndex < lb || startIndex > array.Length + lb)
  789. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  790. if (count < 0 || count > array.Length - startIndex + lb)
  791. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  792. #if CORECLR
  793. // Try calling a quick native method to handle primitive types.
  794. int retVal;
  795. bool r = TrySZIndexOf(array, startIndex, count, value, out retVal);
  796. if (r)
  797. return retVal;
  798. #endif
  799. object[] objArray = array as object[];
  800. int endIndex = startIndex + count;
  801. if (objArray != null)
  802. {
  803. if (value == null)
  804. {
  805. for (int i = startIndex; i < endIndex; i++)
  806. {
  807. if (objArray[i] == null)
  808. return i;
  809. }
  810. }
  811. else
  812. {
  813. for (int i = startIndex; i < endIndex; i++)
  814. {
  815. object obj = objArray[i];
  816. if (obj != null && obj.Equals(value))
  817. return i;
  818. }
  819. }
  820. }
  821. else
  822. {
  823. for (int i = startIndex; i < endIndex; i++)
  824. {
  825. object obj = array.GetValue(i);
  826. if (obj == null)
  827. {
  828. if (value == null)
  829. return i;
  830. }
  831. else
  832. {
  833. if (obj.Equals(value))
  834. return i;
  835. }
  836. }
  837. }
  838. // Return one less than the lower bound of the array. This way,
  839. // for arrays with a lower bound of -1 we will not return -1 when the
  840. // item was not found. And for SZArrays (the vast majority), -1 still
  841. // works for them.
  842. return lb - 1;
  843. }
  844. public static int IndexOf<T>(T[] array, T value)
  845. {
  846. if (array == null)
  847. {
  848. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  849. }
  850. return IndexOf(array, value, 0, array.Length);
  851. }
  852. public static int IndexOf<T>(T[] array, T value, int startIndex)
  853. {
  854. if (array == null)
  855. {
  856. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  857. }
  858. return IndexOf(array, value, startIndex, array.Length - startIndex);
  859. }
  860. public static int IndexOf<T>(T[] array, T value, int startIndex, int count)
  861. {
  862. if (array == null)
  863. {
  864. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  865. }
  866. if ((uint)startIndex > (uint)array.Length)
  867. {
  868. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  869. }
  870. if ((uint)count > (uint)(array.Length - startIndex))
  871. {
  872. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  873. }
  874. if (typeof(T) == typeof(byte))
  875. {
  876. int result = SpanHelpers.IndexOf(
  877. ref Unsafe.Add(ref array.GetRawSzArrayData(), startIndex),
  878. Unsafe.As<T, byte>(ref value),
  879. count);
  880. return (result >= 0 ? startIndex : 0) + result;
  881. }
  882. if (typeof(T) == typeof(char))
  883. {
  884. int result = SpanHelpers.IndexOf(
  885. ref Unsafe.Add(ref Unsafe.As<byte, char>(ref array.GetRawSzArrayData()), startIndex),
  886. Unsafe.As<T, char>(ref value),
  887. count);
  888. return (result >= 0 ? startIndex : 0) + result;
  889. }
  890. #if CORECLR
  891. return EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);
  892. #else
  893. return IndexOfImpl(array, value, startIndex, count);
  894. #endif
  895. }
  896. // Returns the index of the last occurrence of a given value in an array.
  897. // The array is searched backwards, and the elements of the array are
  898. // compared to the given value using the Object.Equals method.
  899. //
  900. public static int LastIndexOf(Array array, object value)
  901. {
  902. if (array == null)
  903. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  904. int lb = array.GetLowerBound(0);
  905. return LastIndexOf(array, value, array.Length - 1 + lb, array.Length);
  906. }
  907. // Returns the index of the last occurrence of a given value in a range of
  908. // an array. The array is searched backwards, starting at index
  909. // startIndex and ending at index 0. The elements of the array are
  910. // compared to the given value using the Object.Equals method.
  911. //
  912. public static int LastIndexOf(Array array, object value, int startIndex)
  913. {
  914. if (array == null)
  915. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  916. int lb = array.GetLowerBound(0);
  917. return LastIndexOf(array, value, startIndex, startIndex + 1 - lb);
  918. }
  919. // Returns the index of the last occurrence of a given value in a range of
  920. // an array. The array is searched backwards, starting at index
  921. // startIndex and counting uptocount elements. The elements of
  922. // the array are compared to the given value using the Object.Equals
  923. // method.
  924. //
  925. public static int LastIndexOf(Array array, object value, int startIndex, int count)
  926. {
  927. if (array == null)
  928. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  929. int lb = array.GetLowerBound(0);
  930. if (array.Length == 0)
  931. {
  932. return lb - 1;
  933. }
  934. if (startIndex < lb || startIndex >= array.Length + lb)
  935. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  936. if (count < 0)
  937. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  938. if (count > startIndex - lb + 1)
  939. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.endIndex, ExceptionResource.ArgumentOutOfRange_EndIndexStartIndex);
  940. if (array.Rank != 1)
  941. ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
  942. #if CORECLR
  943. // Try calling a quick native method to handle primitive types.
  944. int retVal;
  945. bool r = TrySZLastIndexOf(array, startIndex, count, value, out retVal);
  946. if (r)
  947. return retVal;
  948. #endif
  949. object[] objArray = array as object[];
  950. int endIndex = startIndex - count + 1;
  951. if (objArray != null)
  952. {
  953. if (value == null)
  954. {
  955. for (int i = startIndex; i >= endIndex; i--)
  956. {
  957. if (objArray[i] == null)
  958. return i;
  959. }
  960. }
  961. else
  962. {
  963. for (int i = startIndex; i >= endIndex; i--)
  964. {
  965. object obj = objArray[i];
  966. if (obj != null && obj.Equals(value))
  967. return i;
  968. }
  969. }
  970. }
  971. else
  972. {
  973. for (int i = startIndex; i >= endIndex; i--)
  974. {
  975. object obj = array.GetValue(i);
  976. if (obj == null)
  977. {
  978. if (value == null)
  979. return i;
  980. }
  981. else
  982. {
  983. if (obj.Equals(value))
  984. return i;
  985. }
  986. }
  987. }
  988. return lb - 1; // Return lb-1 for arrays with negative lower bounds.
  989. }
  990. public static int LastIndexOf<T>(T[] array, T value)
  991. {
  992. if (array == null)
  993. {
  994. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  995. }
  996. return LastIndexOf(array, value, array.Length - 1, array.Length);
  997. }
  998. public static int LastIndexOf<T>(T[] array, T value, int startIndex)
  999. {
  1000. if (array == null)
  1001. {
  1002. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1003. }
  1004. // if array is empty and startIndex is 0, we need to pass 0 as count
  1005. return LastIndexOf(array, value, startIndex, (array.Length == 0) ? 0 : (startIndex + 1));
  1006. }
  1007. public static int LastIndexOf<T>(T[] array, T value, int startIndex, int count)
  1008. {
  1009. if (array == null)
  1010. {
  1011. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1012. }
  1013. if (array.Length == 0)
  1014. {
  1015. //
  1016. // Special case for 0 length List
  1017. // accept -1 and 0 as valid startIndex for compablility reason.
  1018. //
  1019. if (startIndex != -1 && startIndex != 0)
  1020. {
  1021. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  1022. }
  1023. // only 0 is a valid value for count if array is empty
  1024. if (count != 0)
  1025. {
  1026. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  1027. }
  1028. return -1;
  1029. }
  1030. // Make sure we're not out of range
  1031. if ((uint)startIndex >= (uint)array.Length)
  1032. {
  1033. ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
  1034. }
  1035. // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
  1036. if (count < 0 || startIndex - count + 1 < 0)
  1037. {
  1038. ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
  1039. }
  1040. if (typeof(T) == typeof(byte))
  1041. {
  1042. int endIndex = startIndex - count + 1;
  1043. int result = SpanHelpers.LastIndexOf(
  1044. ref Unsafe.Add(ref array.GetRawSzArrayData(), endIndex),
  1045. Unsafe.As<T, byte>(ref value),
  1046. count);
  1047. return (result >= 0 ? endIndex : 0) + result;
  1048. }
  1049. if (typeof(T) == typeof(char))
  1050. {
  1051. int endIndex = startIndex - count + 1;
  1052. int result = SpanHelpers.LastIndexOf(
  1053. ref Unsafe.Add(ref Unsafe.As<byte, char>(ref array.GetRawSzArrayData()), endIndex),
  1054. Unsafe.As<T, char>(ref value),
  1055. count);
  1056. return (result >= 0 ? endIndex : 0) + result;
  1057. }
  1058. #if CORECLR
  1059. return EqualityComparer<T>.Default.LastIndexOf(array, value, startIndex, count);
  1060. #else
  1061. return LastIndexOfImpl(array, value, startIndex, count);
  1062. #endif
  1063. }
  1064. // Reverses all elements of the given array. Following a call to this
  1065. // method, an element previously located at index i will now be
  1066. // located at index length - i - 1, where length is the
  1067. // length of the array.
  1068. //
  1069. public static void Reverse(Array array)
  1070. {
  1071. if (array == null)
  1072. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1073. Reverse(array, array.GetLowerBound(0), array.Length);
  1074. }
  1075. // Reverses the elements in a range of an array. Following a call to this
  1076. // method, an element in the range given by index and count
  1077. // which was previously located at index i will now be located at
  1078. // index index + (index + count - i - 1).
  1079. // Reliability note: This may fail because it may have to box objects.
  1080. //
  1081. public static void Reverse(Array array, int index, int length)
  1082. {
  1083. if (array == null)
  1084. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1085. int lowerBound = array.GetLowerBound(0);
  1086. if (index < lowerBound)
  1087. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  1088. if (length < 0)
  1089. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  1090. if (array.Length - (index - lowerBound) < length)
  1091. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  1092. if (array.Rank != 1)
  1093. ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
  1094. if (length <= 1)
  1095. return;
  1096. #if CORECLR
  1097. bool r = TrySZReverse(array, index, length);
  1098. if (r)
  1099. return;
  1100. #endif
  1101. if (array is object[] objArray)
  1102. {
  1103. Array.Reverse<object>(objArray, index, length);
  1104. }
  1105. else
  1106. {
  1107. int i = index;
  1108. int j = index + length - 1;
  1109. while (i < j)
  1110. {
  1111. object temp = array.GetValue(i);
  1112. array.SetValue(array.GetValue(j), i);
  1113. array.SetValue(temp, j);
  1114. i++;
  1115. j--;
  1116. }
  1117. }
  1118. }
  1119. public static void Reverse<T>(T[] array)
  1120. {
  1121. if (array == null)
  1122. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1123. Reverse(array, 0, array.Length);
  1124. }
  1125. public static void Reverse<T>(T[] array, int index, int length)
  1126. {
  1127. if (array == null)
  1128. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1129. if (index < 0)
  1130. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  1131. if (length < 0)
  1132. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  1133. if (array.Length - index < length)
  1134. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  1135. if (length <= 1)
  1136. return;
  1137. ref T first = ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), index);
  1138. ref T last = ref Unsafe.Add(ref Unsafe.Add(ref first, length), -1);
  1139. do
  1140. {
  1141. T temp = first;
  1142. first = last;
  1143. last = temp;
  1144. first = ref Unsafe.Add(ref first, 1);
  1145. last = ref Unsafe.Add(ref last, -1);
  1146. } while (Unsafe.IsAddressLessThan(ref first, ref last));
  1147. }
  1148. // Sorts the elements of an array. The sort compares the elements to each
  1149. // other using the IComparable interface, which must be implemented
  1150. // by all elements of the array.
  1151. //
  1152. public static void Sort(Array array)
  1153. {
  1154. if (array == null)
  1155. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1156. Sort(array, null, array.GetLowerBound(0), array.Length, null);
  1157. }
  1158. // Sorts the elements of two arrays based on the keys in the first array.
  1159. // Elements in the keys array specify the sort keys for
  1160. // corresponding elements in the items array. The sort compares the
  1161. // keys to each other using the IComparable interface, which must be
  1162. // implemented by all elements of the keys array.
  1163. //
  1164. public static void Sort(Array keys, Array items)
  1165. {
  1166. if (keys == null)
  1167. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
  1168. Sort(keys, items, keys.GetLowerBound(0), keys.Length, null);
  1169. }
  1170. // Sorts the elements in a section of an array. The sort compares the
  1171. // elements to each other using the IComparable interface, which
  1172. // must be implemented by all elements in the given section of the array.
  1173. //
  1174. public static void Sort(Array array, int index, int length)
  1175. {
  1176. Sort(array, null, index, length, null);
  1177. }
  1178. // Sorts the elements in a section of two arrays based on the keys in the
  1179. // first array. Elements in the keys array specify the sort keys for
  1180. // corresponding elements in the items array. The sort compares the
  1181. // keys to each other using the IComparable interface, which must be
  1182. // implemented by all elements of the keys array.
  1183. //
  1184. public static void Sort(Array keys, Array items, int index, int length)
  1185. {
  1186. Sort(keys, items, index, length, null);
  1187. }
  1188. // Sorts the elements of an array. The sort compares the elements to each
  1189. // other using the given IComparer interface. If comparer is
  1190. // null, the elements are compared to each other using the
  1191. // IComparable interface, which in that case must be implemented by
  1192. // all elements of the array.
  1193. //
  1194. public static void Sort(Array array, IComparer comparer)
  1195. {
  1196. if (array == null)
  1197. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1198. Sort(array, null, array.GetLowerBound(0), array.Length, comparer);
  1199. }
  1200. // Sorts the elements of two arrays based on the keys in the first array.
  1201. // Elements in the keys array specify the sort keys for
  1202. // corresponding elements in the items array. The sort compares the
  1203. // keys to each other using the given IComparer interface. If
  1204. // comparer is null, the elements are compared to each other using
  1205. // the IComparable interface, which in that case must be implemented
  1206. // by all elements of the keys array.
  1207. //
  1208. public static void Sort(Array keys, Array items, IComparer comparer)
  1209. {
  1210. if (keys == null)
  1211. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
  1212. Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer);
  1213. }
  1214. // Sorts the elements in a section of an array. The sort compares the
  1215. // elements to each other using the given IComparer interface. If
  1216. // comparer is null, the elements are compared to each other using
  1217. // the IComparable interface, which in that case must be implemented
  1218. // by all elements in the given section of the array.
  1219. //
  1220. public static void Sort(Array array, int index, int length, IComparer comparer)
  1221. {
  1222. Sort(array, null, index, length, comparer);
  1223. }
  1224. // Sorts the elements in a section of two arrays based on the keys in the
  1225. // first array. Elements in the keys array specify the sort keys for
  1226. // corresponding elements in the items array. The sort compares the
  1227. // keys to each other using the given IComparer interface. If
  1228. // comparer is null, the elements are compared to each other using
  1229. // the IComparable interface, which in that case must be implemented
  1230. // by all elements of the given section of the keys array.
  1231. //
  1232. public static void Sort(Array keys, Array items, int index, int length, IComparer comparer)
  1233. {
  1234. if (keys == null)
  1235. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
  1236. if (keys.Rank != 1 || (items != null && items.Rank != 1))
  1237. ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
  1238. int keysLowerBound = keys.GetLowerBound(0);
  1239. if (items != null && keysLowerBound != items.GetLowerBound(0))
  1240. ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_LowerBoundsMustMatch);
  1241. if (index < keysLowerBound)
  1242. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  1243. if (length < 0)
  1244. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  1245. if (keys.Length - (index - keysLowerBound) < length || (items != null && (index - keysLowerBound) > items.Length - length))
  1246. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  1247. if (length > 1)
  1248. {
  1249. SortImpl(keys, items, index, length, comparer ?? Comparer.Default);
  1250. }
  1251. }
  1252. public static void Sort<T>(T[] array)
  1253. {
  1254. if (array == null)
  1255. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1256. Sort<T>(array, 0, array.Length, null);
  1257. }
  1258. public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items)
  1259. {
  1260. if (keys == null)
  1261. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
  1262. Sort<TKey, TValue>(keys, items, 0, keys.Length, null);
  1263. }
  1264. public static void Sort<T>(T[] array, int index, int length)
  1265. {
  1266. Sort<T>(array, index, length, null);
  1267. }
  1268. public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length)
  1269. {
  1270. Sort<TKey, TValue>(keys, items, index, length, null);
  1271. }
  1272. public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T> comparer)
  1273. {
  1274. if (array == null)
  1275. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1276. Sort<T>(array, 0, array.Length, comparer);
  1277. }
  1278. public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer)
  1279. {
  1280. if (keys == null)
  1281. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
  1282. Sort<TKey, TValue>(keys, items, 0, keys.Length, comparer);
  1283. }
  1284. public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer)
  1285. {
  1286. if (array == null)
  1287. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1288. if (index < 0)
  1289. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  1290. if (length < 0)
  1291. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  1292. if (array.Length - index < length)
  1293. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  1294. if (length > 1)
  1295. {
  1296. #if CORECLR
  1297. if (comparer == null || comparer == Comparer<T>.Default)
  1298. {
  1299. if (TrySZSort(array, null, index, index + length - 1))
  1300. {
  1301. return;
  1302. }
  1303. }
  1304. #endif
  1305. ArraySortHelper<T>.Default.Sort(array, index, length, comparer);
  1306. }
  1307. }
  1308. public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer)
  1309. {
  1310. if (keys == null)
  1311. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
  1312. if (index < 0)
  1313. ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
  1314. if (length < 0)
  1315. ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum();
  1316. if (keys.Length - index < length || (items != null && index > items.Length - length))
  1317. ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
  1318. if (length > 1)
  1319. {
  1320. #if CORECLR
  1321. if (comparer == null || comparer == Comparer<TKey>.Default)
  1322. {
  1323. if (TrySZSort(keys, items, index, index + length - 1))
  1324. {
  1325. return;
  1326. }
  1327. }
  1328. #endif
  1329. if (items == null)
  1330. {
  1331. Sort<TKey>(keys, index, length, comparer);
  1332. return;
  1333. }
  1334. ArraySortHelper<TKey, TValue>.Default.Sort(keys, items, index, length, comparer);
  1335. }
  1336. }
  1337. public static void Sort<T>(T[] array, Comparison<T> comparison)
  1338. {
  1339. if (array == null)
  1340. {
  1341. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1342. }
  1343. if (comparison == null)
  1344. {
  1345. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison);
  1346. }
  1347. ArraySortHelper<T>.Sort(array, 0, array.Length, comparison);
  1348. }
  1349. public static bool TrueForAll<T>(T[] array, Predicate<T> match)
  1350. {
  1351. if (array == null)
  1352. {
  1353. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
  1354. }
  1355. if (match == null)
  1356. {
  1357. ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  1358. }
  1359. for (int i = 0; i < array.Length; i++)
  1360. {
  1361. if (!match(array[i]))
  1362. {
  1363. return false;
  1364. }
  1365. }
  1366. return true;
  1367. }
  1368. #if !CORERT
  1369. // Private value type used by the Sort methods.
  1370. private readonly struct SorterObjectArray
  1371. {
  1372. private readonly object[] keys;
  1373. private readonly object[] items;
  1374. private readonly IComparer comparer;
  1375. internal SorterObjectArray(object[] keys, object[] items, IComparer comparer)
  1376. {
  1377. this.keys = keys;
  1378. this.items = items;
  1379. this.comparer = comparer;
  1380. }
  1381. internal void SwapIfGreaterWithItems(int a, int b)
  1382. {
  1383. if (a != b)
  1384. {
  1385. if (comparer.Compare(keys[a], keys[b]) > 0)
  1386. {
  1387. object temp = keys[a];
  1388. keys[a] = keys[b];
  1389. keys[b] = temp;
  1390. if (items != null)
  1391. {
  1392. object item = items[a];
  1393. items[a] = items[b];
  1394. items[b] = item;
  1395. }
  1396. }
  1397. }
  1398. }
  1399. private void Swap(int i, int j)
  1400. {
  1401. object t = keys[i];
  1402. keys[i] = keys[j];
  1403. keys[j] = t;
  1404. if (items != null)
  1405. {
  1406. object item = items[i];
  1407. items[i] = items[j];
  1408. items[j] = item;
  1409. }
  1410. }
  1411. internal void Sort(int left, int length)
  1412. {
  1413. IntrospectiveSort(left, length);
  1414. }
  1415. private void IntrospectiveSort(int left, int length)
  1416. {
  1417. if (length < 2)
  1418. return;
  1419. try
  1420. {
  1421. IntroSort(left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length));
  1422. }
  1423. catch (IndexOutOfRangeException)
  1424. {
  1425. IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
  1426. }
  1427. catch (Exception e)
  1428. {
  1429. ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
  1430. }
  1431. }
  1432. private void IntroSort(int lo, int hi, int depthLimit)
  1433. {
  1434. while (hi > lo)
  1435. {
  1436. int partitionSize = hi - lo + 1;
  1437. if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
  1438. {
  1439. if (partitionSize == 1)
  1440. {
  1441. return;
  1442. }
  1443. if (partitionSize == 2)
  1444. {
  1445. SwapIfGreaterWithItems(lo, hi);
  1446. return;
  1447. }
  1448. if (partitionSize == 3)
  1449. {
  1450. SwapIfGreaterWithItems(lo, hi - 1);
  1451. SwapIfGreaterWithItems(lo, hi);
  1452. SwapIfGreaterWithItems(hi - 1, hi);
  1453. return;
  1454. }
  1455. InsertionSort(lo, hi);
  1456. return;
  1457. }
  1458. if (depthLimit == 0)
  1459. {
  1460. Heapsort(lo, hi);
  1461. return;
  1462. }
  1463. depthLimit--;
  1464. int p = PickPivotAndPartition(lo, hi);
  1465. IntroSort(p + 1, hi, depthLimit);
  1466. hi = p - 1;
  1467. }
  1468. }
  1469. private int PickPivotAndPartition(int lo, int hi)
  1470. {
  1471. // Compute median-of-three. But also partition them, since we've done the comparison.
  1472. int mid = lo + (hi - lo) / 2;
  1473. // Sort lo, mid and hi appropriately, then pick mid as the pivot.
  1474. SwapIfGreaterWithItems(lo, mid);
  1475. SwapIfGreaterWithItems(lo, hi);
  1476. SwapIfGreaterWithItems(mid, hi);
  1477. object pivot = keys[mid];
  1478. Swap(mid, hi - 1);
  1479. 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.
  1480. while (left < right)
  1481. {
  1482. while (comparer.Compare(keys[++left], pivot) < 0) ;
  1483. while (comparer.Compare(pivot, keys[--right]) < 0) ;
  1484. if (left >= right)
  1485. break;
  1486. Swap(left, right);
  1487. }
  1488. // Put pivot in the right location.
  1489. Swap(left, (hi - 1));
  1490. return left;
  1491. }
  1492. private void Heapsort(int lo, int hi)
  1493. {
  1494. int n = hi - lo + 1;
  1495. for (int i = n / 2; i >= 1; i = i - 1)
  1496. {
  1497. DownHeap(i, n, lo);
  1498. }
  1499. for (int i = n; i > 1; i = i - 1)
  1500. {
  1501. Swap(lo, lo + i - 1);
  1502. DownHeap(1, i - 1, lo);
  1503. }
  1504. }
  1505. private void DownHeap(int i, int n, int lo)
  1506. {
  1507. object d = keys[lo + i - 1];
  1508. object dt = (items != null) ? items[lo + i - 1] : null;
  1509. int child;
  1510. while (i <= n / 2)
  1511. {
  1512. child = 2 * i;
  1513. if (child < n && comparer.Compare(keys[lo + child - 1], keys[lo + child]) < 0)
  1514. {
  1515. child++;
  1516. }
  1517. if (!(comparer.Compare(d, keys[lo + child - 1]) < 0))
  1518. break;
  1519. keys[lo + i - 1] = keys[lo + child - 1];
  1520. if (items != null)
  1521. items[lo + i - 1] = items[lo + child - 1];
  1522. i = child;
  1523. }
  1524. keys[lo + i - 1] = d;
  1525. if (items != null)
  1526. items[lo + i - 1] = dt;
  1527. }
  1528. private void InsertionSort(int lo, int hi)
  1529. {
  1530. int i, j;
  1531. object t, ti;
  1532. for (i = lo; i < hi; i++)
  1533. {
  1534. j = i;
  1535. t = keys[i + 1];
  1536. ti = (items != null) ? items[i + 1] : null;
  1537. while (j >= lo && comparer.Compare(t, keys[j]) < 0)
  1538. {
  1539. keys[j + 1] = keys[j];
  1540. if (items != null)
  1541. items[j + 1] = items[j];
  1542. j--;
  1543. }
  1544. keys[j + 1] = t;
  1545. if (items != null)
  1546. items[j + 1] = ti;
  1547. }
  1548. }
  1549. }
  1550. // Private value used by the Sort methods for instances of Array.
  1551. // This is slower than the one for Object[], since we can't use the JIT helpers
  1552. // to access the elements. We must use GetValue & SetValue.
  1553. private readonly struct SorterGenericArray
  1554. {
  1555. private readonly Array keys;
  1556. private readonly Array items;
  1557. private readonly IComparer comparer;
  1558. internal SorterGenericArray(Array keys, Array items, IComparer comparer)
  1559. {
  1560. this.keys = keys;
  1561. this.items = items;
  1562. this.comparer = comparer;
  1563. }
  1564. internal void SwapIfGreaterWithItems(int a, int b)
  1565. {
  1566. if (a != b)
  1567. {
  1568. if (comparer.Compare(keys.GetValue(a), keys.GetValue(b)) > 0)
  1569. {
  1570. object key = keys.GetValue(a);
  1571. keys.SetValue(keys.GetValue(b), a);
  1572. keys.SetValue(key, b);
  1573. if (items != null)
  1574. {
  1575. object item = items.GetValue(a);
  1576. items.SetValue(items.GetValue(b), a);
  1577. items.SetValue(item, b);
  1578. }
  1579. }
  1580. }
  1581. }
  1582. private void Swap(int i, int j)
  1583. {
  1584. object t1 = keys.GetValue(i);
  1585. keys.SetValue(keys.GetValue(j), i);
  1586. keys.SetValue(t1, j);
  1587. if (items != null)
  1588. {
  1589. object t2 = items.GetValue(i);
  1590. items.SetValue(items.GetValue(j), i);
  1591. items.SetValue(t2, j);
  1592. }
  1593. }
  1594. internal void Sort(int left, int length)
  1595. {
  1596. IntrospectiveSort(left, length);
  1597. }
  1598. private void IntrospectiveSort(int left, int length)
  1599. {
  1600. if (length < 2)
  1601. return;
  1602. try
  1603. {
  1604. IntroSort(left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length));
  1605. }
  1606. catch (IndexOutOfRangeException)
  1607. {
  1608. IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
  1609. }
  1610. catch (Exception e)
  1611. {
  1612. ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
  1613. }
  1614. }
  1615. private void IntroSort(int lo, int hi, int depthLimit)
  1616. {
  1617. while (hi > lo)
  1618. {
  1619. int partitionSize = hi - lo + 1;
  1620. if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
  1621. {
  1622. if (partitionSize == 1)
  1623. {
  1624. return;
  1625. }
  1626. if (partitionSize == 2)
  1627. {
  1628. SwapIfGreaterWithItems(lo, hi);
  1629. return;
  1630. }
  1631. if (partitionSize == 3)
  1632. {
  1633. SwapIfGreaterWithItems(lo, hi - 1);
  1634. SwapIfGreaterWithItems(lo, hi);
  1635. SwapIfGreaterWithItems(hi - 1, hi);
  1636. return;
  1637. }
  1638. InsertionSort(lo, hi);
  1639. return;
  1640. }
  1641. if (depthLimit == 0)
  1642. {
  1643. Heapsort(lo, hi);
  1644. return;
  1645. }
  1646. depthLimit--;
  1647. int p = PickPivotAndPartition(lo, hi);
  1648. IntroSort(p + 1, hi, depthLimit);
  1649. hi = p - 1;
  1650. }
  1651. }
  1652. private int PickPivotAndPartition(int lo, int hi)
  1653. {
  1654. // Compute median-of-three. But also partition them, since we've done the comparison.
  1655. int mid = lo + (hi - lo) / 2;
  1656. SwapIfGreaterWithItems(lo, mid);
  1657. SwapIfGreaterWithItems(lo, hi);
  1658. SwapIfGreaterWithItems(mid, hi);
  1659. object pivot = keys.GetValue(mid);
  1660. Swap(mid, hi - 1);
  1661. 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.
  1662. while (left < right)
  1663. {
  1664. while (comparer.Compare(keys.GetValue(++left), pivot) < 0) ;
  1665. while (comparer.Compare(pivot, keys.GetValue(--right)) < 0) ;
  1666. if (left >= right)
  1667. break;
  1668. Swap(left, right);
  1669. }
  1670. // Put pivot in the right location.
  1671. Swap(left, (hi - 1));
  1672. return left;
  1673. }
  1674. private void Heapsort(int lo, int hi)
  1675. {
  1676. int n = hi - lo + 1;
  1677. for (int i = n / 2; i >= 1; i = i - 1)
  1678. {
  1679. DownHeap(i, n, lo);
  1680. }
  1681. for (int i = n; i > 1; i = i - 1)
  1682. {
  1683. Swap(lo, lo + i - 1);
  1684. DownHeap(1, i - 1, lo);
  1685. }
  1686. }
  1687. private void DownHeap(int i, int n, int lo)
  1688. {
  1689. object d = keys.GetValue(lo + i - 1);
  1690. object dt = (items != null) ? items.GetValue(lo + i - 1) : null;
  1691. int child;
  1692. while (i <= n / 2)
  1693. {
  1694. child = 2 * i;
  1695. if (child < n && comparer.Compare(keys.GetValue(lo + child - 1), keys.GetValue(lo + child)) < 0)
  1696. {
  1697. child++;
  1698. }
  1699. if (!(comparer.Compare(d, keys.GetValue(lo + child - 1)) < 0))
  1700. break;
  1701. keys.SetValue(keys.GetValue(lo + child - 1), lo + i - 1);
  1702. if (items != null)
  1703. items.SetValue(items.GetValue(lo + child - 1), lo + i - 1);
  1704. i = child;
  1705. }
  1706. keys.SetValue(d, lo + i - 1);
  1707. if (items != null)
  1708. items.SetValue(dt, lo + i - 1);
  1709. }
  1710. private void InsertionSort(int lo, int hi)
  1711. {
  1712. int i, j;
  1713. object t, dt;
  1714. for (i = lo; i < hi; i++)
  1715. {
  1716. j = i;
  1717. t = keys.GetValue(i + 1);
  1718. dt = (items != null) ? items.GetValue(i + 1) : null;
  1719. while (j >= lo && comparer.Compare(t, keys.GetValue(j)) < 0)
  1720. {
  1721. keys.SetValue(keys.GetValue(j), j + 1);
  1722. if (items != null)
  1723. items.SetValue(items.GetValue(j), j + 1);
  1724. j--;
  1725. }
  1726. keys.SetValue(t, j + 1);
  1727. if (items != null)
  1728. items.SetValue(dt, j + 1);
  1729. }
  1730. }
  1731. }
  1732. public IEnumerator GetEnumerator()
  1733. {
  1734. int lowerBound = GetLowerBound(0);
  1735. if (Rank == 1 && lowerBound == 0)
  1736. return new SZArrayEnumerator(this);
  1737. else
  1738. return new ArrayEnumerator(this, lowerBound, Length);
  1739. }
  1740. private sealed class SZArrayEnumerator : IEnumerator, ICloneable
  1741. {
  1742. private readonly Array _array;
  1743. private int _index;
  1744. private int _endIndex; // Cache Array.Length, since it's a little slow.
  1745. internal SZArrayEnumerator(Array array)
  1746. {
  1747. Debug.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero.");
  1748. _array = array;
  1749. _index = -1;
  1750. _endIndex = array.Length;
  1751. }
  1752. public object Clone()
  1753. {
  1754. return MemberwiseClone();
  1755. }
  1756. public bool MoveNext()
  1757. {
  1758. if (_index < _endIndex)
  1759. {
  1760. _index++;
  1761. return (_index < _endIndex);
  1762. }
  1763. return false;
  1764. }
  1765. public object Current
  1766. {
  1767. get
  1768. {
  1769. if (_index < 0)
  1770. ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
  1771. if (_index >= _endIndex)
  1772. ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
  1773. return _array.GetValue(_index);
  1774. }
  1775. }
  1776. public void Reset()
  1777. {
  1778. _index = -1;
  1779. }
  1780. }
  1781. private sealed class ArrayEnumerator : IEnumerator, ICloneable
  1782. {
  1783. private Array array;
  1784. private int index;
  1785. private int endIndex;
  1786. private int startIndex; // Save for Reset.
  1787. private int[] _indices; // The current position in a multidim array
  1788. private bool _complete;
  1789. internal ArrayEnumerator(Array array, int index, int count)
  1790. {
  1791. this.array = array;
  1792. this.index = index - 1;
  1793. startIndex = index;
  1794. endIndex = index + count;
  1795. _indices = new int[array.Rank];
  1796. int checkForZero = 1; // Check for dimensions of size 0.
  1797. for (int i = 0; i < array.Rank; i++)
  1798. {
  1799. _indices[i] = array.GetLowerBound(i);
  1800. checkForZero *= array.GetLength(i);
  1801. }
  1802. // To make MoveNext simpler, decrement least significant index.
  1803. _indices[_indices.Length - 1]--;
  1804. _complete = (checkForZero == 0);
  1805. }
  1806. private void IncArray()
  1807. {
  1808. // This method advances us to the next valid array index,
  1809. // handling all the multiple dimension & bounds correctly.
  1810. // Think of it like an odometer in your car - we start with
  1811. // the last digit, increment it, and check for rollover. If
  1812. // it rolls over, we set all digits to the right and including
  1813. // the current to the appropriate lower bound. Do these overflow
  1814. // checks for each dimension, and if the most significant digit
  1815. // has rolled over it's upper bound, we're done.
  1816. //
  1817. int rank = array.Rank;
  1818. _indices[rank - 1]++;
  1819. for (int dim = rank - 1; dim >= 0; dim--)
  1820. {
  1821. if (_indices[dim] > array.GetUpperBound(dim))
  1822. {
  1823. if (dim == 0)
  1824. {
  1825. _complete = true;
  1826. break;
  1827. }
  1828. for (int j = dim; j < rank; j++)
  1829. _indices[j] = array.GetLowerBound(j);
  1830. _indices[dim - 1]++;
  1831. }
  1832. }
  1833. }
  1834. public object Clone()
  1835. {
  1836. return MemberwiseClone();
  1837. }
  1838. public bool MoveNext()
  1839. {
  1840. if (_complete)
  1841. {
  1842. index = endIndex;
  1843. return false;
  1844. }
  1845. index++;
  1846. IncArray();
  1847. return !_complete;
  1848. }
  1849. public object Current
  1850. {
  1851. get
  1852. {
  1853. if (index < startIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
  1854. if (_complete) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
  1855. return array.GetValue(_indices);
  1856. }
  1857. }
  1858. public void Reset()
  1859. {
  1860. index = startIndex - 1;
  1861. int checkForZero = 1;
  1862. for (int i = 0; i < array.Rank; i++)
  1863. {
  1864. _indices[i] = array.GetLowerBound(i);
  1865. checkForZero *= array.GetLength(i);
  1866. }
  1867. _complete = (checkForZero == 0);
  1868. // To make MoveNext simpler, decrement least significant index.
  1869. _indices[_indices.Length - 1]--;
  1870. }
  1871. }
  1872. #endif // !CORERT
  1873. }
  1874. }