5 // Joe Shaw (joe@ximian.com)
6 // Martin Baulig (martin@gnome.org)
7 // Dietmar Maurer (dietmar@ximian.com)
8 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
9 // Jeffrey Stedfast (fejj@novell.com)
10 // Marek Safar (marek.safar@gmail.com)
12 // (C) 2001-2003 Ximian, Inc. http://www.ximian.com
13 // Copyright (C) 2004-2011 Novell, Inc (http://www.novell.com)
14 // Copyright (C) 2011 Xamarin Inc (http://www.xamarin.com)
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Collections;
37 using System.Runtime.CompilerServices;
38 using System.Runtime.InteropServices;
40 using System.Collections.Generic;
41 using System.Collections.ObjectModel;
42 using System.Runtime.ConstrainedExecution;
43 using System.Reflection.Emit;
49 // FIXME: We are doing way to many double/triple exception checks for the overloaded functions"
50 public abstract class Array : ICloneable, ICollection, IList, IEnumerable
51 #if NET_4_0 || MOONLIGHT || MOBILE
52 , IStructuralComparable, IStructuralEquatable
61 * These methods are used to implement the implicit generic interfaces
62 * implemented by arrays in NET 2.0.
63 * Only make those methods generic which really need it, to avoid
64 * creating useless instantiations.
66 internal int InternalArray__ICollection_get_Count ()
71 internal bool InternalArray__ICollection_get_IsReadOnly ()
76 internal IEnumerator<T> InternalArray__IEnumerable_GetEnumerator<T> ()
78 return new InternalEnumerator<T> (this);
81 internal void InternalArray__ICollection_Clear ()
83 throw new NotSupportedException ("Collection is read-only");
86 internal void InternalArray__ICollection_Add<T> (T item)
88 throw new NotSupportedException ("Collection is of a fixed size");
91 internal bool InternalArray__ICollection_Remove<T> (T item)
93 throw new NotSupportedException ("Collection is of a fixed size");
96 internal bool InternalArray__ICollection_Contains<T> (T item)
99 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
101 int length = this.Length;
102 for (int i = 0; i < length; i++) {
104 GetGenericValueImpl (i, out value);
112 if (item.Equals (value))
119 internal void InternalArray__ICollection_CopyTo<T> (T[] array, int index)
122 throw new ArgumentNullException ("array");
124 // The order of these exception checks may look strange,
125 // but that's how the microsoft runtime does it.
127 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
128 if (index + this.GetLength (0) > array.GetLowerBound (0) + array.GetLength (0))
129 throw new ArgumentException ("Destination array was not long " +
130 "enough. Check destIndex and length, and the array's " +
133 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
135 throw new ArgumentOutOfRangeException (
136 "index", Locale.GetText ("Value has to be >= 0."));
138 Copy (this, this.GetLowerBound (0), array, index, this.GetLength (0));
141 internal void InternalArray__Insert<T> (int index, T item)
143 throw new NotSupportedException ("Collection is of a fixed size");
146 internal void InternalArray__RemoveAt (int index)
148 throw new NotSupportedException ("Collection is of a fixed size");
151 internal int InternalArray__IndexOf<T> (T item)
154 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
156 int length = this.Length;
157 for (int i = 0; i < length; i++) {
159 GetGenericValueImpl (i, out value);
162 return i + this.GetLowerBound (0);
166 if (value.Equals (item))
167 // array index may not be zero-based.
169 return i + this.GetLowerBound (0);
173 // lower bound may be MinValue
174 return this.GetLowerBound (0) - 1;
178 internal T InternalArray__get_Item<T> (int index)
180 if (unchecked ((uint) index) >= unchecked ((uint) Length))
181 throw new ArgumentOutOfRangeException ("index");
184 GetGenericValueImpl (index, out value);
188 internal void InternalArray__set_Item<T> (int index, T item)
190 if (unchecked ((uint) index) >= unchecked ((uint) Length))
191 throw new ArgumentOutOfRangeException ("index");
193 object[] oarray = this as object [];
194 if (oarray != null) {
195 oarray [index] = (object)item;
198 SetGenericValueImpl (index, ref item);
201 // CAUTION! No bounds checking!
202 [MethodImplAttribute (MethodImplOptions.InternalCall)]
203 internal extern void GetGenericValueImpl<T> (int pos, out T value);
205 // CAUTION! No bounds checking!
206 [MethodImplAttribute (MethodImplOptions.InternalCall)]
207 internal extern void SetGenericValueImpl<T> (int pos, ref T value);
209 internal struct InternalEnumerator<T> : IEnumerator<T>
211 const int NOT_STARTED = -2;
213 // this MUST be -1, because we depend on it in move next.
214 // we just decr the size, so, 0 - 1 == FINISHED
215 const int FINISHED = -1;
220 internal InternalEnumerator (Array array)
226 public void Dispose ()
231 public bool MoveNext ()
233 if (idx == NOT_STARTED)
236 return idx != FINISHED && -- idx != FINISHED;
241 if (idx == NOT_STARTED)
242 throw new InvalidOperationException ("Enumeration has not started. Call MoveNext");
244 throw new InvalidOperationException ("Enumeration already finished");
246 return array.InternalArray__get_Item<T> (array.Length - 1 - idx);
250 void IEnumerator.Reset ()
255 object IEnumerator.Current {
264 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
266 int length = this.GetLength (0);
268 for (int i = 1; i < this.Rank; i++) {
269 length *= this.GetLength (i);
276 public long LongLength {
277 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
278 get { return Length; }
282 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
284 return this.GetRank ();
289 object IList.this [int index] {
291 if (unchecked ((uint) index) >= unchecked ((uint) Length))
292 throw new IndexOutOfRangeException ("index");
294 throw new ArgumentException (Locale.GetText ("Only single dimension arrays are supported."));
295 return GetValueImpl (index);
298 if (unchecked ((uint) index) >= unchecked ((uint) Length))
299 throw new IndexOutOfRangeException ("index");
301 throw new ArgumentException (Locale.GetText ("Only single dimension arrays are supported."));
302 SetValueImpl (value, index);
306 int IList.Add (object value)
308 throw new NotSupportedException ();
313 Array.Clear (this, this.GetLowerBound (0), this.Length);
316 bool IList.Contains (object value)
319 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
321 int length = this.Length;
322 for (int i = 0; i < length; i++) {
323 if (Object.Equals (this.GetValueImpl (i), value))
329 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
330 int IList.IndexOf (object value)
333 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
335 int length = this.Length;
336 for (int i = 0; i < length; i++) {
337 if (Object.Equals (this.GetValueImpl (i), value))
338 // array index may not be zero-based.
340 return i + this.GetLowerBound (0);
344 // lower bound may be MinValue
345 return this.GetLowerBound (0) - 1;
349 void IList.Insert (int index, object value)
351 throw new NotSupportedException ();
354 void IList.Remove (object value)
356 throw new NotSupportedException ();
359 void IList.RemoveAt (int index)
361 throw new NotSupportedException ();
364 // InternalCall Methods
365 [MethodImplAttribute (MethodImplOptions.InternalCall)]
366 extern int GetRank ();
368 [MethodImplAttribute (MethodImplOptions.InternalCall)]
369 public extern int GetLength (int dimension);
372 public long GetLongLength (int dimension)
374 return GetLength (dimension);
377 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
378 [MethodImplAttribute (MethodImplOptions.InternalCall)]
379 public extern int GetLowerBound (int dimension);
381 [MethodImplAttribute (MethodImplOptions.InternalCall)]
382 public extern object GetValue (params int[] indices);
384 [MethodImplAttribute (MethodImplOptions.InternalCall)]
385 public extern void SetValue (object value, params int[] indices);
387 // CAUTION! No bounds checking!
388 [MethodImplAttribute (MethodImplOptions.InternalCall)]
389 internal extern object GetValueImpl (int pos);
391 // CAUTION! No bounds checking!
392 [MethodImplAttribute (MethodImplOptions.InternalCall)]
393 internal extern void SetValueImpl (object value, int pos);
395 [MethodImplAttribute (MethodImplOptions.InternalCall)]
396 internal extern static bool FastCopy (Array source, int source_idx, Array dest, int dest_idx, int length);
398 [MethodImplAttribute (MethodImplOptions.InternalCall)]
399 internal extern static Array CreateInstanceImpl (Type elementType, int[] lengths, int[] bounds);
402 int ICollection.Count {
408 public bool IsSynchronized {
414 public object SyncRoot {
420 public bool IsFixedSize {
426 public bool IsReadOnly {
432 public IEnumerator GetEnumerator ()
434 return new SimpleEnumerator (this);
437 #if NET_4_0 || MOONLIGHT || MOBILE
438 int IStructuralComparable.CompareTo (object other, IComparer comparer)
443 Array arr = other as Array;
445 throw new ArgumentException ("Not an array", "other");
447 int len = GetLength (0);
448 if (len != arr.GetLength (0))
449 throw new ArgumentException ("Not of the same length", "other");
452 throw new ArgumentException ("Array must be single dimensional");
455 throw new ArgumentException ("Array must be single dimensional", "other");
457 for (int i = 0; i < len; ++i) {
458 object a = GetValue (i);
459 object b = arr.GetValue (i);
460 int r = comparer.Compare (a, b);
467 bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer)
469 Array o = other as Array;
470 if (o == null || o.Length != Length)
473 if (Object.ReferenceEquals (other, this))
476 for (int i = 0; i < Length; i++) {
477 object this_item = this.GetValue (i);
478 object other_item = o.GetValue (i);
479 if (!comparer.Equals (this_item, other_item))
486 int IStructuralEquatable.GetHashCode (IEqualityComparer comparer)
488 if (comparer == null)
489 throw new ArgumentNullException ("comparer");
492 for (int i = 0; i < Length; i++)
493 hash = ((hash << 7) + hash) ^ comparer.GetHashCode (GetValueImpl (i));
498 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
499 public int GetUpperBound (int dimension)
501 return GetLowerBound (dimension) + GetLength (dimension) - 1;
504 public object GetValue (int index)
507 throw new ArgumentException (Locale.GetText ("Array was not a one-dimensional array."));
508 if (index < GetLowerBound (0) || index > GetUpperBound (0))
509 throw new IndexOutOfRangeException (Locale.GetText (
510 "Index has to be between upper and lower bound of the array."));
512 return GetValueImpl (index - GetLowerBound (0));
515 public object GetValue (int index1, int index2)
517 int[] ind = {index1, index2};
518 return GetValue (ind);
521 public object GetValue (int index1, int index2, int index3)
523 int[] ind = {index1, index2, index3};
524 return GetValue (ind);
528 public object GetValue (long index)
530 if (index < 0 || index > Int32.MaxValue)
531 throw new ArgumentOutOfRangeException ("index", Locale.GetText (
532 "Value must be >= 0 and <= Int32.MaxValue."));
534 return GetValue ((int) index);
538 public object GetValue (long index1, long index2)
540 if (index1 < 0 || index1 > Int32.MaxValue)
541 throw new ArgumentOutOfRangeException ("index1", Locale.GetText (
542 "Value must be >= 0 and <= Int32.MaxValue."));
544 if (index2 < 0 || index2 > Int32.MaxValue)
545 throw new ArgumentOutOfRangeException ("index2", Locale.GetText (
546 "Value must be >= 0 and <= Int32.MaxValue."));
548 return GetValue ((int) index1, (int) index2);
552 public object GetValue (long index1, long index2, long index3)
554 if (index1 < 0 || index1 > Int32.MaxValue)
555 throw new ArgumentOutOfRangeException ("index1", Locale.GetText (
556 "Value must be >= 0 and <= Int32.MaxValue."));
558 if (index2 < 0 || index2 > Int32.MaxValue)
559 throw new ArgumentOutOfRangeException ("index2", Locale.GetText (
560 "Value must be >= 0 and <= Int32.MaxValue."));
562 if (index3 < 0 || index3 > Int32.MaxValue)
563 throw new ArgumentOutOfRangeException ("index3", Locale.GetText (
564 "Value must be >= 0 and <= Int32.MaxValue."));
566 return GetValue ((int) index1, (int) index2, (int) index3);
570 public void SetValue (object value, long index)
572 if (index < 0 || index > Int32.MaxValue)
573 throw new ArgumentOutOfRangeException ("index", Locale.GetText (
574 "Value must be >= 0 and <= Int32.MaxValue."));
576 SetValue (value, (int) index);
580 public void SetValue (object value, long index1, long index2)
582 if (index1 < 0 || index1 > Int32.MaxValue)
583 throw new ArgumentOutOfRangeException ("index1", Locale.GetText (
584 "Value must be >= 0 and <= Int32.MaxValue."));
586 if (index2 < 0 || index2 > Int32.MaxValue)
587 throw new ArgumentOutOfRangeException ("index2", Locale.GetText (
588 "Value must be >= 0 and <= Int32.MaxValue."));
590 int[] ind = {(int) index1, (int) index2};
591 SetValue (value, ind);
595 public void SetValue (object value, long index1, long index2, long index3)
597 if (index1 < 0 || index1 > Int32.MaxValue)
598 throw new ArgumentOutOfRangeException ("index1", Locale.GetText (
599 "Value must be >= 0 and <= Int32.MaxValue."));
601 if (index2 < 0 || index2 > Int32.MaxValue)
602 throw new ArgumentOutOfRangeException ("index2", Locale.GetText (
603 "Value must be >= 0 and <= Int32.MaxValue."));
605 if (index3 < 0 || index3 > Int32.MaxValue)
606 throw new ArgumentOutOfRangeException ("index3", Locale.GetText (
607 "Value must be >= 0 and <= Int32.MaxValue."));
609 int[] ind = {(int) index1, (int) index2, (int) index3};
610 SetValue (value, ind);
613 public void SetValue (object value, int index)
616 throw new ArgumentException (Locale.GetText ("Array was not a one-dimensional array."));
617 if (index < GetLowerBound (0) || index > GetUpperBound (0))
618 throw new IndexOutOfRangeException (Locale.GetText (
619 "Index has to be >= lower bound and <= upper bound of the array."));
621 SetValueImpl (value, index - GetLowerBound (0));
624 public void SetValue (object value, int index1, int index2)
626 int[] ind = {index1, index2};
627 SetValue (value, ind);
630 public void SetValue (object value, int index1, int index2, int index3)
632 int[] ind = {index1, index2, index3};
633 SetValue (value, ind);
636 public static Array CreateInstance (Type elementType, int length)
638 int[] lengths = {length};
640 return CreateInstance (elementType, lengths);
643 public static Array CreateInstance (Type elementType, int length1, int length2)
645 int[] lengths = {length1, length2};
647 return CreateInstance (elementType, lengths);
650 public static Array CreateInstance (Type elementType, int length1, int length2, int length3)
652 int[] lengths = {length1, length2, length3};
654 return CreateInstance (elementType, lengths);
657 public static Array CreateInstance (Type elementType, params int[] lengths)
659 if (elementType == null)
660 throw new ArgumentNullException ("elementType");
662 throw new ArgumentNullException ("lengths");
664 if (lengths.Length > 255)
665 throw new TypeLoadException ();
669 elementType = elementType.UnderlyingSystemType;
670 if (!elementType.IsSystemType)
671 throw new ArgumentException ("Type must be a type provided by the runtime.", "elementType");
672 if (elementType.Equals (typeof (void)))
673 throw new NotSupportedException ("Array type can not be void");
674 if (elementType.ContainsGenericParameters)
675 throw new NotSupportedException ("Array type can not be an open generic type");
676 if ((elementType is TypeBuilder) && !(elementType as TypeBuilder).IsCreated ())
677 throw new NotSupportedException ("Can't create an array of the unfinished type '" + elementType + "'.");
679 return CreateInstanceImpl (elementType, lengths, bounds);
682 public static Array CreateInstance (Type elementType, int[] lengths, int [] lowerBounds)
684 if (elementType == null)
685 throw new ArgumentNullException ("elementType");
687 throw new ArgumentNullException ("lengths");
688 if (lowerBounds == null)
689 throw new ArgumentNullException ("lowerBounds");
691 elementType = elementType.UnderlyingSystemType;
692 if (!elementType.IsSystemType)
693 throw new ArgumentException ("Type must be a type provided by the runtime.", "elementType");
694 if (elementType.Equals (typeof (void)))
695 throw new NotSupportedException ("Array type can not be void");
696 if (elementType.ContainsGenericParameters)
697 throw new NotSupportedException ("Array type can not be an open generic type");
699 if (lengths.Length < 1)
700 throw new ArgumentException (Locale.GetText ("Arrays must contain >= 1 elements."));
702 if (lengths.Length != lowerBounds.Length)
703 throw new ArgumentException (Locale.GetText ("Arrays must be of same size."));
705 for (int j = 0; j < lowerBounds.Length; j ++) {
707 throw new ArgumentOutOfRangeException ("lengths", Locale.GetText (
708 "Each value has to be >= 0."));
709 if ((long)lowerBounds [j] + (long)lengths [j] > (long)Int32.MaxValue)
710 throw new ArgumentOutOfRangeException ("lengths", Locale.GetText (
711 "Length + bound must not exceed Int32.MaxValue."));
714 if (lengths.Length > 255)
715 throw new TypeLoadException ();
717 return CreateInstanceImpl (elementType, lengths, lowerBounds);
720 static int [] GetIntArray (long [] values)
722 int len = values.Length;
723 int [] ints = new int [len];
724 for (int i = 0; i < len; i++) {
725 long current = values [i];
726 if (current < 0 || current > (long) Int32.MaxValue)
727 throw new ArgumentOutOfRangeException ("values", Locale.GetText (
728 "Each value has to be >= 0 and <= Int32.MaxValue."));
730 ints [i] = (int) current;
735 public static Array CreateInstance (Type elementType, params long [] lengths)
738 throw new ArgumentNullException ("lengths");
739 return CreateInstance (elementType, GetIntArray (lengths));
743 public object GetValue (params long [] indices)
746 throw new ArgumentNullException ("indices");
747 return GetValue (GetIntArray (indices));
751 public void SetValue (object value, params long [] indices)
754 throw new ArgumentNullException ("indices");
755 SetValue (value, GetIntArray (indices));
758 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
759 public static int BinarySearch (Array array, object value)
762 throw new ArgumentNullException ("array");
768 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
770 if (array.Length == 0)
773 if (!(value is IComparable))
774 throw new ArgumentException (Locale.GetText ("value does not support IComparable."));
776 return DoBinarySearch (array, array.GetLowerBound (0), array.GetLength (0), value, null);
779 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
780 public static int BinarySearch (Array array, object value, IComparer comparer)
783 throw new ArgumentNullException ("array");
786 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
788 if (array.Length == 0)
791 if ((comparer == null) && (value != null) && !(value is IComparable))
792 throw new ArgumentException (Locale.GetText (
793 "comparer is null and value does not support IComparable."));
795 return DoBinarySearch (array, array.GetLowerBound (0), array.GetLength (0), value, comparer);
798 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
799 public static int BinarySearch (Array array, int index, int length, object value)
802 throw new ArgumentNullException ("array");
805 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
807 if (index < array.GetLowerBound (0))
808 throw new ArgumentOutOfRangeException ("index", Locale.GetText (
809 "index is less than the lower bound of array."));
811 throw new ArgumentOutOfRangeException ("length", Locale.GetText (
812 "Value has to be >= 0."));
813 // re-ordered to avoid possible integer overflow
814 if (index > array.GetLowerBound (0) + array.GetLength (0) - length)
815 throw new ArgumentException (Locale.GetText (
816 "index and length do not specify a valid range in array."));
818 if (array.Length == 0)
821 if ((value != null) && (!(value is IComparable)))
822 throw new ArgumentException (Locale.GetText (
823 "value does not support IComparable"));
825 return DoBinarySearch (array, index, length, value, null);
828 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
829 public static int BinarySearch (Array array, int index, int length, object value, IComparer comparer)
832 throw new ArgumentNullException ("array");
835 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
837 if (index < array.GetLowerBound (0))
838 throw new ArgumentOutOfRangeException ("index", Locale.GetText (
839 "index is less than the lower bound of array."));
841 throw new ArgumentOutOfRangeException ("length", Locale.GetText (
842 "Value has to be >= 0."));
843 // re-ordered to avoid possible integer overflow
844 if (index > array.GetLowerBound (0) + array.GetLength (0) - length)
845 throw new ArgumentException (Locale.GetText (
846 "index and length do not specify a valid range in array."));
848 if (array.Length == 0)
851 if ((comparer == null) && (value != null) && !(value is IComparable))
852 throw new ArgumentException (Locale.GetText (
853 "comparer is null and value does not support IComparable."));
855 return DoBinarySearch (array, index, length, value, comparer);
858 static int DoBinarySearch (Array array, int index, int length, object value, IComparer comparer)
860 // cache this in case we need it
861 if (comparer == null)
862 comparer = Comparer.Default;
865 // Comment from Tum (tum@veridicus.com):
866 // *Must* start at index + length - 1 to pass rotor test co2460binarysearch_iioi
867 int iMax = index + length - 1;
870 while (iMin <= iMax) {
871 // Be careful with overflow
872 // http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html
873 int iMid = iMin + ((iMax - iMin) / 2);
874 object elt = array.GetValueImpl (iMid);
876 iCmp = comparer.Compare (elt, value);
883 iMin = iMid + 1; // compensate for the rounding down
886 catch (Exception e) {
887 throw new InvalidOperationException (Locale.GetText ("Comparer threw an exception."), e);
893 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
894 public static void Clear (Array array, int index, int length)
897 throw new ArgumentNullException ("array");
899 throw new IndexOutOfRangeException ("length < 0");
901 int low = array.GetLowerBound (0);
903 throw new IndexOutOfRangeException ("index < lower bound");
906 // re-ordered to avoid possible integer overflow
907 if (index > array.Length - length)
908 throw new IndexOutOfRangeException ("index + length > size");
910 ClearInternal (array, index, length);
913 [MethodImplAttribute (MethodImplOptions.InternalCall)]
914 static extern void ClearInternal (Array a, int index, int count);
916 [MethodImplAttribute (MethodImplOptions.InternalCall)]
917 public extern object Clone ();
919 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
920 public static void Copy (Array sourceArray, Array destinationArray, int length)
922 // need these checks here because we are going to use
923 // GetLowerBound() on source and dest.
924 if (sourceArray == null)
925 throw new ArgumentNullException ("sourceArray");
927 if (destinationArray == null)
928 throw new ArgumentNullException ("destinationArray");
930 Copy (sourceArray, sourceArray.GetLowerBound (0), destinationArray,
931 destinationArray.GetLowerBound (0), length);
934 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
935 public static void Copy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
937 if (sourceArray == null)
938 throw new ArgumentNullException ("sourceArray");
940 if (destinationArray == null)
941 throw new ArgumentNullException ("destinationArray");
944 throw new ArgumentOutOfRangeException ("length", Locale.GetText (
945 "Value has to be >= 0."));;
948 throw new ArgumentOutOfRangeException ("sourceIndex", Locale.GetText (
949 "Value has to be >= 0."));;
951 if (destinationIndex < 0)
952 throw new ArgumentOutOfRangeException ("destinationIndex", Locale.GetText (
953 "Value has to be >= 0."));;
955 if (FastCopy (sourceArray, sourceIndex, destinationArray, destinationIndex, length))
958 int source_pos = sourceIndex - sourceArray.GetLowerBound (0);
959 int dest_pos = destinationIndex - destinationArray.GetLowerBound (0);
961 // re-ordered to avoid possible integer overflow
962 if (source_pos > sourceArray.Length - length)
963 throw new ArgumentException ("length");
965 if (dest_pos > destinationArray.Length - length) {
966 string msg = "Destination array was not long enough. Check " +
967 "destIndex and length, and the array's lower bounds";
968 throw new ArgumentException (msg, string.Empty);
971 if (sourceArray.Rank != destinationArray.Rank)
972 throw new RankException (Locale.GetText ("Arrays must be of same size."));
974 Type src_type = sourceArray.GetType ().GetElementType ();
975 Type dst_type = destinationArray.GetType ().GetElementType ();
977 if (!Object.ReferenceEquals (sourceArray, destinationArray) || source_pos > dest_pos) {
978 for (int i = 0; i < length; i++) {
979 Object srcval = sourceArray.GetValueImpl (source_pos + i);
982 destinationArray.SetValueImpl (srcval, dest_pos + i);
984 if (src_type.Equals (typeof (Object)))
985 throw new InvalidCastException ();
987 throw new ArrayTypeMismatchException (String.Format (Locale.GetText (
988 "(Types: source={0}; target={1})"), src_type.FullName, dst_type.FullName));
993 for (int i = length - 1; i >= 0; i--) {
994 Object srcval = sourceArray.GetValueImpl (source_pos + i);
997 destinationArray.SetValueImpl (srcval, dest_pos + i);
999 if (src_type.Equals (typeof (Object)))
1000 throw new InvalidCastException ();
1002 throw new ArrayTypeMismatchException (String.Format (Locale.GetText (
1003 "(Types: source={0}; target={1})"), src_type.FullName, dst_type.FullName));
1009 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1010 public static void Copy (Array sourceArray, long sourceIndex, Array destinationArray,
1011 long destinationIndex, long length)
1013 if (sourceArray == null)
1014 throw new ArgumentNullException ("sourceArray");
1016 if (destinationArray == null)
1017 throw new ArgumentNullException ("destinationArray");
1019 if (sourceIndex < Int32.MinValue || sourceIndex > Int32.MaxValue)
1020 throw new ArgumentOutOfRangeException ("sourceIndex",
1021 Locale.GetText ("Must be in the Int32 range."));
1023 if (destinationIndex < Int32.MinValue || destinationIndex > Int32.MaxValue)
1024 throw new ArgumentOutOfRangeException ("destinationIndex",
1025 Locale.GetText ("Must be in the Int32 range."));
1027 if (length < 0 || length > Int32.MaxValue)
1028 throw new ArgumentOutOfRangeException ("length", Locale.GetText (
1029 "Value must be >= 0 and <= Int32.MaxValue."));
1031 Copy (sourceArray, (int) sourceIndex, destinationArray, (int) destinationIndex, (int) length);
1034 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1035 public static void Copy (Array sourceArray, Array destinationArray, long length)
1037 if (length < 0 || length > Int32.MaxValue)
1038 throw new ArgumentOutOfRangeException ("length", Locale.GetText (
1039 "Value must be >= 0 and <= Int32.MaxValue."));
1041 Copy (sourceArray, destinationArray, (int) length);
1044 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1045 public static int IndexOf (Array array, object value)
1048 throw new ArgumentNullException ("array");
1050 return IndexOf (array, value, 0, array.Length);
1053 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1054 public static int IndexOf (Array array, object value, int startIndex)
1057 throw new ArgumentNullException ("array");
1059 return IndexOf (array, value, startIndex, array.Length - startIndex);
1062 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1063 public static int IndexOf (Array array, object value, int startIndex, int count)
1066 throw new ArgumentNullException ("array");
1069 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
1071 // re-ordered to avoid possible integer overflow
1072 if (count < 0 || startIndex < array.GetLowerBound (0) || startIndex - 1 > array.GetUpperBound (0) - count)
1073 throw new ArgumentOutOfRangeException ();
1075 int max = startIndex + count;
1076 for (int i = startIndex; i < max; i++) {
1077 if (Object.Equals (array.GetValueImpl (i), value))
1081 return array.GetLowerBound (0) - 1;
1084 public void Initialize()
1086 //FIXME: We would like to find a compiler that uses
1087 // this method. It looks like this method do nothing
1088 // in C# so no exception is trown by the moment.
1091 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1092 public static int LastIndexOf (Array array, object value)
1095 throw new ArgumentNullException ("array");
1097 if (array.Length == 0)
1098 return array.GetLowerBound (0) - 1;
1099 return LastIndexOf (array, value, array.Length - 1);
1102 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1103 public static int LastIndexOf (Array array, object value, int startIndex)
1106 throw new ArgumentNullException ("array");
1108 return LastIndexOf (array, value, startIndex, startIndex - array.GetLowerBound (0) + 1);
1111 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1112 public static int LastIndexOf (Array array, object value, int startIndex, int count)
1115 throw new ArgumentNullException ("array");
1118 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
1120 int lb = array.GetLowerBound (0);
1121 // Empty arrays do not throw ArgumentOutOfRangeException
1122 if (array.Length == 0)
1125 if (count < 0 || startIndex < lb ||
1126 startIndex > array.GetUpperBound (0) || startIndex - count + 1 < lb)
1127 throw new ArgumentOutOfRangeException ();
1129 for (int i = startIndex; i >= startIndex - count + 1; i--) {
1130 if (Object.Equals (array.GetValueImpl (i), value))
1137 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1138 public static void Reverse (Array array)
1141 throw new ArgumentNullException ("array");
1143 Reverse (array, array.GetLowerBound (0), array.Length);
1146 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1147 public static void Reverse (Array array, int index, int length)
1150 throw new ArgumentNullException ("array");
1153 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
1155 if (index < array.GetLowerBound (0) || length < 0)
1156 throw new ArgumentOutOfRangeException ();
1158 // re-ordered to avoid possible integer overflow
1159 if (index > array.GetUpperBound (0) + 1 - length)
1160 throw new ArgumentException ();
1162 int end = index + length - 1;
1163 var et = array.GetType ().GetElementType ();
1164 switch (Type.GetTypeCode (et)) {
1165 case TypeCode.Boolean:
1166 while (index < end) {
1169 array.GetGenericValueImpl (index, out a);
1170 array.GetGenericValueImpl (end, out b);
1171 array.SetGenericValueImpl (index, ref b);
1172 array.SetGenericValueImpl (end, ref a);
1179 case TypeCode.SByte:
1180 while (index < end) {
1183 array.GetGenericValueImpl (index, out a);
1184 array.GetGenericValueImpl (end, out b);
1185 array.SetGenericValueImpl (index, ref b);
1186 array.SetGenericValueImpl (end, ref a);
1192 case TypeCode.Int16:
1193 case TypeCode.UInt16:
1195 while (index < end) {
1198 array.GetGenericValueImpl (index, out a);
1199 array.GetGenericValueImpl (end, out b);
1200 array.SetGenericValueImpl (index, ref b);
1201 array.SetGenericValueImpl (end, ref a);
1207 case TypeCode.Int32:
1208 case TypeCode.UInt32:
1209 case TypeCode.Single:
1210 while (index < end) {
1213 array.GetGenericValueImpl (index, out a);
1214 array.GetGenericValueImpl (end, out b);
1215 array.SetGenericValueImpl (index, ref b);
1216 array.SetGenericValueImpl (end, ref a);
1222 case TypeCode.Int64:
1223 case TypeCode.UInt64:
1224 case TypeCode.Double:
1225 while (index < end) {
1228 array.GetGenericValueImpl (index, out a);
1229 array.GetGenericValueImpl (end, out b);
1230 array.SetGenericValueImpl (index, ref b);
1231 array.SetGenericValueImpl (end, ref a);
1237 case TypeCode.Decimal:
1238 while (index < end) {
1241 array.GetGenericValueImpl (index, out a);
1242 array.GetGenericValueImpl (end, out b);
1243 array.SetGenericValueImpl (index, ref b);
1244 array.SetGenericValueImpl (end, ref a);
1250 case TypeCode.String:
1251 case TypeCode.Object:
1252 while (index < end) {
1255 array.GetGenericValueImpl (index, out a);
1256 array.GetGenericValueImpl (end, out b);
1257 array.SetGenericValueImpl (index, ref b);
1258 array.SetGenericValueImpl (end, ref a);
1264 if (array is object[])
1265 goto case TypeCode.Object;
1267 // Very slow fallback
1268 while (index < end) {
1269 object val = array.GetValueImpl (index);
1270 array.SetValueImpl (array.GetValueImpl (end), index);
1271 array.SetValueImpl (val, end);
1280 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1281 public static void Sort (Array array)
1283 Sort (array, (IComparer)null);
1286 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1287 public static void Sort (Array keys, Array items)
1289 Sort (keys, items, (IComparer)null);
1292 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1293 public static void Sort (Array array, IComparer comparer)
1296 throw new ArgumentNullException ("array");
1299 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
1301 SortImpl (array, null, array.GetLowerBound (0), array.GetLength (0), comparer);
1304 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1305 public static void Sort (Array array, int index, int length)
1307 Sort (array, index, length, (IComparer)null);
1310 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1311 public static void Sort (Array keys, Array items, IComparer comparer)
1313 if (items == null) {
1314 Sort (keys, comparer);
1319 throw new ArgumentNullException ("keys");
1321 if (keys.Rank > 1 || items.Rank > 1)
1322 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
1324 SortImpl (keys, items, keys.GetLowerBound (0), keys.GetLength (0), comparer);
1327 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1328 public static void Sort (Array keys, Array items, int index, int length)
1330 Sort (keys, items, index, length, (IComparer)null);
1333 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1334 public static void Sort (Array array, int index, int length, IComparer comparer)
1337 throw new ArgumentNullException ("array");
1340 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
1342 if (index < array.GetLowerBound (0))
1343 throw new ArgumentOutOfRangeException ("index");
1346 throw new ArgumentOutOfRangeException ("length", Locale.GetText (
1347 "Value has to be >= 0."));
1349 if (array.Length - (array.GetLowerBound (0) + index) < length)
1350 throw new ArgumentException ();
1352 SortImpl (array, null, index, length, comparer);
1355 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1356 public static void Sort (Array keys, Array items, int index, int length, IComparer comparer)
1358 if (items == null) {
1359 Sort (keys, index, length, comparer);
1364 throw new ArgumentNullException ("keys");
1366 if (keys.Rank > 1 || items.Rank > 1)
1367 throw new RankException ();
1369 if (keys.GetLowerBound (0) != items.GetLowerBound (0))
1370 throw new ArgumentException ();
1372 if (index < keys.GetLowerBound (0))
1373 throw new ArgumentOutOfRangeException ("index");
1376 throw new ArgumentOutOfRangeException ("length", Locale.GetText (
1377 "Value has to be >= 0."));
1379 if (items.Length - (index + items.GetLowerBound (0)) < length || keys.Length - (index + keys.GetLowerBound (0)) < length)
1380 throw new ArgumentException ();
1382 SortImpl (keys, items, index, length, comparer);
1385 private static void SortImpl (Array keys, Array items, int index, int length, IComparer comparer)
1391 int high = index + length - 1;
1393 #if !BOOTSTRAP_BASIC
1394 if (comparer == null && items is object[]) {
1395 /* Its better to compare typecodes as casts treat long/ulong/long based enums the same */
1396 switch (Type.GetTypeCode (keys.GetType ().GetElementType ())) {
1397 case TypeCode.Int32:
1398 qsort (keys as Int32[], items as object[], low, high);
1400 case TypeCode.Int64:
1401 qsort (keys as Int64[], items as object[], low, high);
1404 qsort (keys as byte[], items as object[], low, high);
1407 qsort (keys as char[], items as object[], low, high);
1409 case TypeCode.DateTime:
1410 qsort (keys as DateTime[], items as object[], low, high);
1412 case TypeCode.Decimal:
1413 qsort (keys as decimal[], items as object[], low, high);
1415 case TypeCode.Double:
1416 qsort (keys as double[], items as object[], low, high);
1418 case TypeCode.Int16:
1419 qsort (keys as Int16[], items as object[], low, high);
1421 case TypeCode.SByte:
1422 qsort (keys as SByte[], items as object[], low, high);
1424 case TypeCode.Single:
1425 qsort (keys as Single[], items as object[], low, high);
1427 case TypeCode.UInt16:
1428 qsort (keys as UInt16[], items as object[], low, high);
1430 case TypeCode.UInt32:
1431 qsort (keys as UInt32[], items as object[], low, high);
1433 case TypeCode.UInt64:
1434 qsort (keys as UInt64[], items as object[], low, high);
1442 if (comparer == null)
1443 CheckComparerAvailable (keys, low, high);
1446 qsort (keys, items, low, high, comparer);
1447 } catch (Exception e) {
1448 throw new InvalidOperationException (Locale.GetText ("The comparer threw an exception."), e);
1457 static bool QSortArrange (Array keys, Array items, int lo, ref object v0, int hi, ref object v1, IComparer comparer)
1462 if (comparer != null) {
1463 if (comparer.Compare (v1, v0) < 0) {
1464 swap (keys, items, lo, hi);
1471 } else if (v0 != null) {
1472 cmp = v1 as IComparable;
1474 if (v1 == null || cmp.CompareTo (v0) < 0) {
1475 swap (keys, items, lo, hi);
1487 private static void qsort (Array keys, Array items, int low0, int high0, IComparer comparer)
1489 QSortStack[] stack = new QSortStack[32];
1490 const int QSORT_THRESHOLD = 7;
1491 int high, low, mid, i, k;
1496 // initialize our stack
1497 stack[0].high = high0;
1498 stack[0].low = low0;
1503 high = stack[sp].high;
1504 low = stack[sp].low;
1506 if ((low + QSORT_THRESHOLD) > high) {
1507 // switch to insertion sort
1508 for (i = low + 1; i <= high; i++) {
1509 for (k = i; k > low; k--) {
1510 lo = keys.GetValueImpl (k - 1);
1511 hi = keys.GetValueImpl (k);
1512 if (comparer != null) {
1513 if (comparer.Compare (hi, lo) >= 0)
1520 cmp = hi as IComparable;
1521 if (cmp.CompareTo (lo) >= 0)
1526 swap (keys, items, k - 1, k);
1533 // calculate the middle element
1534 mid = low + ((high - low) / 2);
1537 key = keys.GetValueImpl (mid);
1538 hi = keys.GetValueImpl (high);
1539 lo = keys.GetValueImpl (low);
1541 // once we re-order the low, mid, and high elements to be in
1542 // ascending order, we'll use mid as our pivot.
1543 QSortArrange (keys, items, low, ref lo, mid, ref key, comparer);
1544 if (QSortArrange (keys, items, mid, ref key, high, ref hi, comparer))
1545 QSortArrange (keys, items, low, ref lo, mid, ref key, comparer);
1547 cmp = key as IComparable;
1549 // since we've already guaranteed that lo <= mid and mid <= hi,
1550 // we can skip comparing them again.
1555 // Move the walls in
1556 if (comparer != null) {
1557 // find the first element with a value >= pivot value
1558 while (i < k && comparer.Compare (key, keys.GetValueImpl (i)) > 0)
1561 // find the last element with a value <= pivot value
1562 while (k > i && comparer.Compare (key, keys.GetValueImpl (k)) < 0)
1564 } else if (cmp != null) {
1565 // find the first element with a value >= pivot value
1566 while (i < k && cmp.CompareTo (keys.GetValueImpl (i)) > 0)
1569 // find the last element with a value <= pivot value
1570 while (k > i && cmp.CompareTo (keys.GetValueImpl (k)) < 0)
1573 // This has the effect of moving the null values to the front if comparer is null
1574 while (i < k && keys.GetValueImpl (i) == null)
1577 while (k > i && keys.GetValueImpl (k) != null)
1584 swap (keys, items, i, k);
1590 // push our partitions onto the stack, largest first
1591 // (to make sure we don't run out of stack space)
1592 if ((high - k) >= (k - low)) {
1593 if ((k + 1) < high) {
1594 stack[sp].high = high;
1599 if ((k - 1) > low) {
1601 stack[sp].low = low;
1605 if ((k - 1) > low) {
1607 stack[sp].low = low;
1611 if ((k + 1) < high) {
1612 stack[sp].high = high;
1620 private static void CheckComparerAvailable (Array keys, int low, int high)
1622 // move null keys to beginning of array,
1623 // ensure that non-null keys implement IComparable
1624 for (int i = 0; i < high; i++) {
1625 object obj = keys.GetValueImpl (i);
1628 if (!(obj is IComparable)) {
1629 string msg = Locale.GetText ("No IComparable interface found for type '{0}'.");
1630 throw new InvalidOperationException (String.Format (msg, obj.GetType ()));
1635 private static void swap (Array keys, Array items, int i, int j)
1637 object tmp = keys.GetValueImpl (i);
1638 keys.SetValueImpl (keys.GetValueImpl (j), i);
1639 keys.SetValueImpl (tmp, j);
1641 if (items != null) {
1642 tmp = items.GetValueImpl (i);
1643 items.SetValueImpl (items.GetValueImpl (j), i);
1644 items.SetValueImpl (tmp, j);
1648 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1649 public static void Sort<T> (T [] array)
1651 Sort<T> (array, (IComparer<T>)null);
1654 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1655 public static void Sort<TKey, TValue> (TKey [] keys, TValue [] items)
1657 Sort<TKey, TValue> (keys, items, (IComparer<TKey>)null);
1660 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1661 public static void Sort<T> (T [] array, IComparer<T> comparer)
1664 throw new ArgumentNullException ("array");
1666 SortImpl<T> (array, 0, array.Length, comparer);
1669 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1670 public static void Sort<TKey, TValue> (TKey [] keys, TValue [] items, IComparer<TKey> comparer)
1672 if (items == null) {
1673 Sort<TKey> (keys, comparer);
1678 throw new ArgumentNullException ("keys");
1680 if (keys.Length != items.Length)
1681 throw new ArgumentException ("Length of keys and items does not match.");
1683 SortImpl<TKey, TValue> (keys, items, 0, keys.Length, comparer);
1686 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1687 public static void Sort<T> (T [] array, int index, int length)
1689 Sort<T> (array, index, length, (IComparer<T>)null);
1692 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1693 public static void Sort<TKey, TValue> (TKey [] keys, TValue [] items, int index, int length)
1695 Sort<TKey, TValue> (keys, items, index, length, (IComparer<TKey>)null);
1698 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1699 public static void Sort<T> (T [] array, int index, int length, IComparer<T> comparer)
1702 throw new ArgumentNullException ("array");
1705 throw new ArgumentOutOfRangeException ("index");
1708 throw new ArgumentOutOfRangeException ("length", Locale.GetText (
1709 "Value has to be >= 0."));
1711 if (index + length > array.Length)
1712 throw new ArgumentException ();
1714 SortImpl<T, T> (array, null, index, length, comparer);
1717 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
1718 public static void Sort<TKey, TValue> (TKey [] keys, TValue [] items, int index, int length, IComparer<TKey> comparer)
1720 if (items == null) {
1721 Sort<TKey> (keys, index, length, comparer);
1726 throw new ArgumentNullException ("keys");
1729 throw new ArgumentOutOfRangeException ("index");
1732 throw new ArgumentOutOfRangeException ("length");
1734 if (items.Length - index < length || keys.Length - index < length)
1735 throw new ArgumentException ();
1737 SortImpl<TKey, TValue> (keys, items, index, length, comparer);
1740 private static void SortImpl<TKey, TValue> (TKey [] keys, TValue [] items, int index, int length, IComparer<TKey> comparer)
1742 if (keys.Length <= 1)
1746 int high = index + length - 1;
1749 // Check for value types which can be sorted without Compare () method
1751 if (comparer == null) {
1752 #if !BOOTSTRAP_BASIC
1753 switch (Type.GetTypeCode (typeof (TKey))) {
1754 case TypeCode.Int32:
1755 qsort (keys as Int32[], items, low, high);
1757 case TypeCode.Int64:
1758 qsort (keys as Int64[], items, low, high);
1761 qsort (keys as byte[], items, low, high);
1764 qsort (keys as char[], items, low, high);
1766 case TypeCode.DateTime:
1767 qsort (keys as DateTime[], items, low, high);
1769 case TypeCode.Decimal:
1770 qsort (keys as decimal[], items, low, high);
1772 case TypeCode.Double:
1773 qsort (keys as double[], items, low, high);
1775 case TypeCode.Int16:
1776 qsort (keys as Int16[], items, low, high);
1778 case TypeCode.SByte:
1779 qsort (keys as SByte[], items, low, high);
1781 case TypeCode.Single:
1782 qsort (keys as Single[], items, low, high);
1784 case TypeCode.UInt16:
1785 qsort (keys as UInt16[], items, low, high);
1787 case TypeCode.UInt32:
1788 qsort (keys as UInt32[], items, low, high);
1790 case TypeCode.UInt64:
1791 qsort (keys as UInt64[], items, low, high);
1795 // Using Comparer<TKey> adds a small overload, but with value types it
1796 // helps us to not box them.
1797 if (typeof (IComparable<TKey>).IsAssignableFrom (typeof (TKey)) &&
1798 typeof (TKey).IsValueType)
1799 comparer = Comparer<TKey>.Default;
1802 if (comparer == null)
1803 CheckComparerAvailable<TKey> (keys, low, high);
1806 qsort (keys, items, low, high, comparer);
1807 //} catch (Exception e) {
1808 //throw new InvalidOperationException (Locale.GetText ("The comparer threw an exception."), e);
1812 // Specialized version for items==null
1813 private static void SortImpl<TKey> (TKey [] keys, int index, int length, IComparer<TKey> comparer)
1815 if (keys.Length <= 1)
1819 int high = index + length - 1;
1822 // Check for value types which can be sorted without Compare () method
1824 if (comparer == null) {
1825 #if !BOOTSTRAP_BASIC
1826 switch (Type.GetTypeCode (typeof (TKey))) {
1827 case TypeCode.Int32:
1828 qsort (keys as Int32[], low, high);
1830 case TypeCode.Int64:
1831 qsort (keys as Int64[], low, high);
1834 qsort (keys as byte[], low, high);
1837 qsort (keys as char[], low, high);
1839 case TypeCode.DateTime:
1840 qsort (keys as DateTime[], low, high);
1842 case TypeCode.Decimal:
1843 qsort (keys as decimal[], low, high);
1845 case TypeCode.Double:
1846 qsort (keys as double[], low, high);
1848 case TypeCode.Int16:
1849 qsort (keys as Int16[], low, high);
1851 case TypeCode.SByte:
1852 qsort (keys as SByte[], low, high);
1854 case TypeCode.Single:
1855 qsort (keys as Single[], low, high);
1857 case TypeCode.UInt16:
1858 qsort (keys as UInt16[], low, high);
1860 case TypeCode.UInt32:
1861 qsort (keys as UInt32[], low, high);
1863 case TypeCode.UInt64:
1864 qsort (keys as UInt64[], low, high);
1868 // Using Comparer<TKey> adds a small overload, but with value types it
1869 // helps us to not box them.
1870 if (typeof (IComparable<TKey>).IsAssignableFrom (typeof (TKey)) &&
1871 typeof (TKey).IsValueType)
1872 comparer = Comparer<TKey>.Default;
1875 if (comparer == null)
1876 CheckComparerAvailable<TKey> (keys, low, high);
1879 qsort<TKey> (keys, low, high, comparer);
1880 //} catch (Exception e) {
1881 //throw new InvalidOperationException (Locale.GetText ("The comparer threw an exception."), e);
1885 public static void Sort<T> (T [] array, Comparison<T> comparison)
1888 throw new ArgumentNullException ("array");
1890 if (comparison == null)
1891 throw new ArgumentNullException ("comparison");
1893 SortImpl<T> (array, array.Length, comparison);
1896 // used by List<T>.Sort (Comparison <T>)
1897 internal static void SortImpl<T> (T [] array, int length, Comparison<T> comparison)
1904 int high0 = length - 1;
1905 qsort<T> (array, low0, high0, comparison);
1906 } catch (InvalidOperationException) {
1908 } catch (Exception e) {
1909 throw new InvalidOperationException (Locale.GetText ("Comparison threw an exception."), e);
1913 static bool QSortArrange<T, U> (T [] keys, U [] items, int lo, int hi) where T : IComparable<T>
1915 if (keys[lo] != null) {
1916 if (keys[hi] == null || keys[hi].CompareTo (keys[lo]) < 0) {
1917 swap (keys, items, lo, hi);
1925 // Specialized version for items==null
1926 static bool QSortArrange<T> (T [] keys, int lo, int hi) where T : IComparable<T>
1928 if (keys[lo] != null) {
1929 if (keys[hi] == null || keys[hi].CompareTo (keys[lo]) < 0) {
1930 swap (keys, lo, hi);
1938 private static void qsort<T, U> (T[] keys, U[] items, int low0, int high0) where T : IComparable<T>
1940 QSortStack[] stack = new QSortStack[32];
1941 const int QSORT_THRESHOLD = 7;
1942 int high, low, mid, i, k;
1946 // initialize our stack
1947 stack[0].high = high0;
1948 stack[0].low = low0;
1953 high = stack[sp].high;
1954 low = stack[sp].low;
1956 if ((low + QSORT_THRESHOLD) > high) {
1957 // switch to insertion sort
1958 for (i = low + 1; i <= high; i++) {
1959 for (k = i; k > low; k--) {
1960 // if keys[k] >= keys[k-1], break
1961 if (keys[k-1] == null)
1964 if (keys[k] != null && keys[k].CompareTo (keys[k-1]) >= 0)
1967 swap (keys, items, k - 1, k);
1974 // calculate the middle element
1975 mid = low + ((high - low) / 2);
1977 // once we re-order the lo, mid, and hi elements to be in
1978 // ascending order, we'll use mid as our pivot.
1979 QSortArrange<T, U> (keys, items, low, mid);
1980 if (QSortArrange<T, U> (keys, items, mid, high))
1981 QSortArrange<T, U> (keys, items, low, mid);
1985 // since we've already guaranteed that lo <= mid and mid <= hi,
1986 // we can skip comparing them again
1992 // find the first element with a value >= pivot value
1993 while (i < k && key.CompareTo (keys[i]) > 0)
1996 // find the last element with a value <= pivot value
1997 while (k > i && key.CompareTo (keys[k]) < 0)
2000 while (i < k && keys[i] == null)
2003 while (k > i && keys[k] != null)
2010 swap (keys, items, i, k);
2016 // push our partitions onto the stack, largest first
2017 // (to make sure we don't run out of stack space)
2018 if ((high - k) >= (k - low)) {
2019 if ((k + 1) < high) {
2020 stack[sp].high = high;
2025 if ((k - 1) > low) {
2027 stack[sp].low = low;
2031 if ((k - 1) > low) {
2033 stack[sp].low = low;
2037 if ((k + 1) < high) {
2038 stack[sp].high = high;
2046 // Specialized version for items==null
2047 private static void qsort<T> (T[] keys, int low0, int high0) where T : IComparable<T>
2049 QSortStack[] stack = new QSortStack[32];
2050 const int QSORT_THRESHOLD = 7;
2051 int high, low, mid, i, k;
2055 // initialize our stack
2056 stack[0].high = high0;
2057 stack[0].low = low0;
2062 high = stack[sp].high;
2063 low = stack[sp].low;
2065 if ((low + QSORT_THRESHOLD) > high) {
2066 // switch to insertion sort
2067 for (i = low + 1; i <= high; i++) {
2068 for (k = i; k > low; k--) {
2069 // if keys[k] >= keys[k-1], break
2070 if (keys[k-1] == null)
2073 if (keys[k] != null && keys[k].CompareTo (keys[k-1]) >= 0)
2076 swap (keys, k - 1, k);
2083 // calculate the middle element
2084 mid = low + ((high - low) / 2);
2086 // once we re-order the lo, mid, and hi elements to be in
2087 // ascending order, we'll use mid as our pivot.
2088 QSortArrange<T> (keys, low, mid);
2089 if (QSortArrange<T> (keys, mid, high))
2090 QSortArrange<T> (keys, low, mid);
2094 // since we've already guaranteed that lo <= mid and mid <= hi,
2095 // we can skip comparing them again
2101 // find the first element with a value >= pivot value
2102 while (i < k && key.CompareTo (keys[i]) > 0)
2105 // find the last element with a value <= pivot value
2106 while (k >= i && key.CompareTo (keys[k]) < 0)
2109 while (i < k && keys[i] == null)
2112 while (k >= i && keys[k] != null)
2125 // push our partitions onto the stack, largest first
2126 // (to make sure we don't run out of stack space)
2127 if ((high - k) >= (k - low)) {
2128 if ((k + 1) < high) {
2129 stack[sp].high = high;
2134 if ((k - 1) > low) {
2136 stack[sp].low = low;
2140 if ((k - 1) > low) {
2142 stack[sp].low = low;
2146 if ((k + 1) < high) {
2147 stack[sp].high = high;
2155 static bool QSortArrange<K, V> (K [] keys, V [] items, int lo, int hi, IComparer<K> comparer)
2157 IComparable<K> gcmp;
2160 if (comparer != null) {
2161 if (comparer.Compare (keys[hi], keys[lo]) < 0) {
2162 swap<K, V> (keys, items, lo, hi);
2165 } else if (keys[lo] != null) {
2166 if (keys[hi] == null) {
2167 swap<K, V> (keys, items, lo, hi);
2171 gcmp = keys[hi] as IComparable<K>;
2173 if (gcmp.CompareTo (keys[lo]) < 0) {
2174 swap<K, V> (keys, items, lo, hi);
2181 cmp = keys[hi] as IComparable;
2183 if (cmp.CompareTo (keys[lo]) < 0) {
2184 swap<K, V> (keys, items, lo, hi);
2195 // Specialized version for items==null
2196 static bool QSortArrange<K> (K [] keys, int lo, int hi, IComparer<K> comparer)
2198 IComparable<K> gcmp;
2201 if (comparer != null) {
2202 if (comparer.Compare (keys[hi], keys[lo]) < 0) {
2203 swap<K> (keys, lo, hi);
2206 } else if (keys[lo] != null) {
2207 if (keys[hi] == null) {
2208 swap<K> (keys, lo, hi);
2212 gcmp = keys[hi] as IComparable<K>;
2214 if (gcmp.CompareTo (keys[lo]) < 0) {
2215 swap<K> (keys, lo, hi);
2222 cmp = keys[hi] as IComparable;
2224 if (cmp.CompareTo (keys[lo]) < 0) {
2225 swap<K> (keys, lo, hi);
2236 private static void qsort<K, V> (K [] keys, V [] items, int low0, int high0, IComparer<K> comparer)
2238 QSortStack[] stack = new QSortStack[32];
2239 const int QSORT_THRESHOLD = 7;
2240 int high, low, mid, i, k;
2241 IComparable<K> gcmp;
2246 // initialize our stack
2247 stack[0].high = high0;
2248 stack[0].low = low0;
2253 high = stack[sp].high;
2254 low = stack[sp].low;
2256 if ((low + QSORT_THRESHOLD) > high) {
2257 // switch to insertion sort
2258 for (i = low + 1; i <= high; i++) {
2259 for (k = i; k > low; k--) {
2260 // if keys[k] >= keys[k-1], break
2261 if (comparer != null) {
2262 if (comparer.Compare (keys[k], keys[k-1]) >= 0)
2265 if (keys[k-1] == null)
2268 if (keys[k] != null) {
2269 gcmp = keys[k] as IComparable<K>;
2270 cmp = keys[k] as IComparable;
2272 if (gcmp.CompareTo (keys[k-1]) >= 0)
2275 if (cmp.CompareTo (keys[k-1]) >= 0)
2281 swap<K, V> (keys, items, k - 1, k);
2288 // calculate the middle element
2289 mid = low + ((high - low) / 2);
2291 // once we re-order the low, mid, and high elements to be in
2292 // ascending order, we'll use mid as our pivot.
2293 QSortArrange<K, V> (keys, items, low, mid, comparer);
2294 if (QSortArrange<K, V> (keys, items, mid, high, comparer))
2295 QSortArrange<K, V> (keys, items, low, mid, comparer);
2298 gcmp = key as IComparable<K>;
2299 cmp = key as IComparable;
2301 // since we've already guaranteed that lo <= mid and mid <= hi,
2302 // we can skip comparing them again.
2307 // Move the walls in
2308 if (comparer != null) {
2309 // find the first element with a value >= pivot value
2310 while (i < k && comparer.Compare (key, keys[i]) > 0)
2313 // find the last element with a value <= pivot value
2314 while (k > i && comparer.Compare (key, keys[k]) < 0)
2318 // find the first element with a value >= pivot value
2319 while (i < k && gcmp.CompareTo (keys[i]) > 0)
2322 // find the last element with a value <= pivot value
2323 while (k > i && gcmp.CompareTo (keys[k]) < 0)
2325 } else if (cmp != null) {
2326 // find the first element with a value >= pivot value
2327 while (i < k && cmp.CompareTo (keys[i]) > 0)
2330 // find the last element with a value <= pivot value
2331 while (k > i && cmp.CompareTo (keys[k]) < 0)
2334 while (i < k && keys[i] == null)
2337 while (k > i && keys[k] != null)
2345 swap<K, V> (keys, items, i, k);
2351 // push our partitions onto the stack, largest first
2352 // (to make sure we don't run out of stack space)
2353 if ((high - k) >= (k - low)) {
2354 if ((k + 1) < high) {
2355 stack[sp].high = high;
2360 if ((k - 1) > low) {
2362 stack[sp].low = low;
2366 if ((k - 1) > low) {
2368 stack[sp].low = low;
2372 if ((k + 1) < high) {
2373 stack[sp].high = high;
2381 // Specialized version for items==null
2382 private static void qsort<K> (K [] keys, int low0, int high0, IComparer<K> comparer)
2384 QSortStack[] stack = new QSortStack[32];
2385 const int QSORT_THRESHOLD = 7;
2386 int high, low, mid, i, k;
2387 IComparable<K> gcmp;
2392 // initialize our stack
2393 stack[0].high = high0;
2394 stack[0].low = low0;
2399 high = stack[sp].high;
2400 low = stack[sp].low;
2402 if ((low + QSORT_THRESHOLD) > high) {
2403 // switch to insertion sort
2404 for (i = low + 1; i <= high; i++) {
2405 for (k = i; k > low; k--) {
2406 // if keys[k] >= keys[k-1], break
2407 if (comparer != null) {
2408 if (comparer.Compare (keys[k], keys[k-1]) >= 0)
2411 if (keys[k-1] == null)
2414 if (keys[k] != null) {
2415 gcmp = keys[k] as IComparable<K>;
2416 cmp = keys[k] as IComparable;
2418 if (gcmp.CompareTo (keys[k-1]) >= 0)
2421 if (cmp.CompareTo (keys[k-1]) >= 0)
2427 swap<K> (keys, k - 1, k);
2434 // calculate the middle element
2435 mid = low + ((high - low) / 2);
2437 // once we re-order the low, mid, and high elements to be in
2438 // ascending order, we'll use mid as our pivot.
2439 QSortArrange<K> (keys, low, mid, comparer);
2440 if (QSortArrange<K> (keys, mid, high, comparer))
2441 QSortArrange<K> (keys, low, mid, comparer);
2444 gcmp = key as IComparable<K>;
2445 cmp = key as IComparable;
2447 // since we've already guaranteed that lo <= mid and mid <= hi,
2448 // we can skip comparing them again.
2453 // Move the walls in
2454 if (comparer != null) {
2455 // find the first element with a value >= pivot value
2456 while (i < k && comparer.Compare (key, keys[i]) > 0)
2459 // find the last element with a value <= pivot value
2460 while (k > i && comparer.Compare (key, keys[k]) < 0)
2464 // find the first element with a value >= pivot value
2465 while (i < k && gcmp.CompareTo (keys[i]) > 0)
2468 // find the last element with a value <= pivot value
2469 while (k > i && gcmp.CompareTo (keys[k]) < 0)
2471 } else if (cmp != null) {
2472 // find the first element with a value >= pivot value
2473 while (i < k && cmp.CompareTo (keys[i]) > 0)
2476 // find the last element with a value <= pivot value
2477 while (k > i && cmp.CompareTo (keys[k]) < 0)
2480 while (i < k && keys[i] == null)
2483 while (k > i && keys[k] != null)
2491 swap<K> (keys, i, k);
2497 // push our partitions onto the stack, largest first
2498 // (to make sure we don't run out of stack space)
2499 if ((high - k) >= (k - low)) {
2500 if ((k + 1) < high) {
2501 stack[sp].high = high;
2506 if ((k - 1) > low) {
2508 stack[sp].low = low;
2512 if ((k - 1) > low) {
2514 stack[sp].low = low;
2518 if ((k + 1) < high) {
2519 stack[sp].high = high;
2527 static bool QSortArrange<T> (T [] array, int lo, int hi, Comparison<T> compare)
2529 if (array[lo] != null) {
2530 if (array[hi] == null || compare (array[hi], array[lo]) < 0) {
2531 swap<T> (array, lo, hi);
2539 private static void qsort<T> (T [] array, int low0, int high0, Comparison<T> compare)
2541 QSortStack[] stack = new QSortStack[32];
2542 const int QSORT_THRESHOLD = 7;
2543 int high, low, mid, i, k;
2547 // initialize our stack
2548 stack[0].high = high0;
2549 stack[0].low = low0;
2554 high = stack[sp].high;
2555 low = stack[sp].low;
2557 if ((low + QSORT_THRESHOLD) > high) {
2558 // switch to insertion sort
2559 for (i = low + 1; i <= high; i++) {
2560 for (k = i; k > low; k--) {
2561 // if keys[k] >= keys[k-1], break
2562 if (array[k-1] == null)
2565 if (array[k] != null && compare (array[k], array[k-1]) >= 0)
2568 swap<T> (array, k - 1, k);
2575 // calculate the middle element
2576 mid = low + ((high - low) / 2);
2578 // once we re-order the lo, mid, and hi elements to be in
2579 // ascending order, we'll use mid as our pivot.
2580 QSortArrange<T> (array, low, mid, compare);
2581 if (QSortArrange<T> (array, mid, high, compare))
2582 QSortArrange<T> (array, low, mid, compare);
2586 // since we've already guaranteed that lo <= mid and mid <= hi,
2587 // we can skip comparing them again
2592 // Move the walls in
2594 // find the first element with a value >= pivot value
2595 while (i < k && compare (key, array[i]) > 0)
2598 // find the last element with a value <= pivot value
2599 while (k > i && compare (key, array[k]) < 0)
2602 while (i < k && array[i] == null)
2605 while (k > i && array[k] != null)
2612 swap<T> (array, i, k);
2618 // push our partitions onto the stack, largest first
2619 // (to make sure we don't run out of stack space)
2620 if ((high - k) >= (k - low)) {
2621 if ((k + 1) < high) {
2622 stack[sp].high = high;
2627 if ((k - 1) > low) {
2629 stack[sp].low = low;
2633 if ((k - 1) > low) {
2635 stack[sp].low = low;
2639 if ((k + 1) < high) {
2640 stack[sp].high = high;
2648 private static void CheckComparerAvailable<K> (K [] keys, int low, int high)
2650 // move null keys to beginning of array,
2651 // ensure that non-null keys implement IComparable
2652 for (int i = low; i < high; i++) {
2655 if (!(key is IComparable<K>) && !(key is IComparable)) {
2656 string msg = Locale.GetText ("No IComparable<T> or IComparable interface found for type '{0}'.");
2657 throw new InvalidOperationException (String.Format (msg, key.GetType ()));
2663 private static void swap<K, V> (K [] keys, V [] items, int i, int j)
2668 keys [i] = keys [j];
2671 if (items != null) {
2674 items [i] = items [j];
2679 private static void swap<T> (T [] array, int i, int j)
2682 array [i] = array [j];
2686 public void CopyTo (Array array, int index)
2689 throw new ArgumentNullException ("array");
2691 // The order of these exception checks may look strange,
2692 // but that's how the microsoft runtime does it.
2694 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
2695 if (index + this.GetLength (0) > array.GetLowerBound (0) + array.GetLength (0))
2696 throw new ArgumentException ("Destination array was not long " +
2697 "enough. Check destIndex and length, and the array's " +
2700 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
2702 throw new ArgumentOutOfRangeException ("index", Locale.GetText (
2703 "Value has to be >= 0."));
2705 Copy (this, this.GetLowerBound (0), array, index, this.GetLength (0));
2708 [ComVisible (false)]
2709 public void CopyTo (Array array, long index)
2711 if (index < 0 || index > Int32.MaxValue)
2712 throw new ArgumentOutOfRangeException ("index", Locale.GetText (
2713 "Value must be >= 0 and <= Int32.MaxValue."));
2715 CopyTo (array, (int) index);
2718 internal class SimpleEnumerator : IEnumerator, ICloneable
2724 public SimpleEnumerator (Array arrayToEnumerate)
2726 this.enumeratee = arrayToEnumerate;
2727 this.currentpos = -1;
2728 this.length = arrayToEnumerate.Length;
2731 public object Current {
2733 // Exception messages based on MS implementation
2734 if (currentpos < 0 )
2735 throw new InvalidOperationException (Locale.GetText (
2736 "Enumeration has not started."));
2737 if (currentpos >= length)
2738 throw new InvalidOperationException (Locale.GetText (
2739 "Enumeration has already ended"));
2740 // Current should not increase the position. So no ++ over here.
2741 return enumeratee.GetValueImpl (currentpos);
2745 public bool MoveNext()
2747 //The docs say Current should throw an exception if last
2748 //call to MoveNext returned false. This means currentpos
2749 //should be set to length when returning false.
2750 if (currentpos < length)
2752 if(currentpos < length)
2763 public object Clone ()
2765 return MemberwiseClone ();
2769 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
2770 public static void Resize<T> (ref T [] array, int newSize)
2773 throw new ArgumentOutOfRangeException ();
2775 if (array == null) {
2776 array = new T [newSize];
2780 int length = array.Length;
2781 if (length == newSize)
2784 T [] a = new T [newSize];
2786 FastCopy (array, 0, a, 0, Math.Min (newSize, length));
2790 public static bool TrueForAll <T> (T [] array, Predicate <T> match)
2793 throw new ArgumentNullException ("array");
2795 throw new ArgumentNullException ("match");
2797 foreach (T t in array)
2804 public static void ForEach<T> (T [] array, Action <T> action)
2807 throw new ArgumentNullException ("array");
2809 throw new ArgumentNullException ("action");
2811 foreach (T t in array)
2815 public static TOutput[] ConvertAll<TInput, TOutput> (TInput [] array, Converter<TInput, TOutput> converter)
2818 throw new ArgumentNullException ("array");
2819 if (converter == null)
2820 throw new ArgumentNullException ("converter");
2822 TOutput [] output = new TOutput [array.Length];
2823 for (int i = 0; i < array.Length; i ++)
2824 output [i] = converter (array [i]);
2829 public static int FindLastIndex<T> (T [] array, Predicate <T> match)
2832 throw new ArgumentNullException ("array");
2834 return FindLastIndex<T> (array, 0, array.Length, match);
2837 public static int FindLastIndex<T> (T [] array, int startIndex, Predicate<T> match)
2840 throw new ArgumentNullException ();
2842 return FindLastIndex<T> (array, startIndex, array.Length - startIndex, match);
2845 public static int FindLastIndex<T> (T [] array, int startIndex, int count, Predicate<T> match)
2848 throw new ArgumentNullException ("array");
2850 throw new ArgumentNullException ("match");
2852 if (startIndex > array.Length || startIndex + count > array.Length)
2853 throw new ArgumentOutOfRangeException ();
2855 for (int i = startIndex + count - 1; i >= startIndex; i--)
2856 if (match (array [i]))
2862 public static int FindIndex<T> (T [] array, Predicate<T> match)
2865 throw new ArgumentNullException ("array");
2867 return FindIndex<T> (array, 0, array.Length, match);
2870 public static int FindIndex<T> (T [] array, int startIndex, Predicate<T> match)
2873 throw new ArgumentNullException ("array");
2875 return FindIndex<T> (array, startIndex, array.Length - startIndex, match);
2878 public static int FindIndex<T> (T [] array, int startIndex, int count, Predicate<T> match)
2881 throw new ArgumentNullException ("array");
2884 throw new ArgumentNullException ("match");
2886 if (startIndex > array.Length || startIndex + count > array.Length)
2887 throw new ArgumentOutOfRangeException ();
2889 for (int i = startIndex; i < startIndex + count; i ++)
2890 if (match (array [i]))
2896 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
2897 public static int BinarySearch<T> (T [] array, T value)
2900 throw new ArgumentNullException ("array");
2902 return BinarySearch<T> (array, 0, array.Length, value, null);
2905 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
2906 public static int BinarySearch<T> (T [] array, T value, IComparer<T> comparer)
2909 throw new ArgumentNullException ("array");
2911 return BinarySearch<T> (array, 0, array.Length, value, comparer);
2914 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
2915 public static int BinarySearch<T> (T [] array, int index, int length, T value)
2917 return BinarySearch<T> (array, index, length, value, null);
2920 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
2921 public static int BinarySearch<T> (T [] array, int index, int length, T value, IComparer<T> comparer)
2924 throw new ArgumentNullException ("array");
2926 throw new ArgumentOutOfRangeException ("index", Locale.GetText (
2927 "index is less than the lower bound of array."));
2929 throw new ArgumentOutOfRangeException ("length", Locale.GetText (
2930 "Value has to be >= 0."));
2931 // re-ordered to avoid possible integer overflow
2932 if (index > array.Length - length)
2933 throw new ArgumentException (Locale.GetText (
2934 "index and length do not specify a valid range in array."));
2935 if (comparer == null)
2936 comparer = Comparer <T>.Default;
2939 int iMax = index + length - 1;
2942 while (iMin <= iMax) {
2943 // Be careful with overflows
2944 int iMid = iMin + ((iMax - iMin) / 2);
2945 iCmp = comparer.Compare (array [iMid], value);
2953 iMin = iMid + 1; // compensate for the rounding down
2955 } catch (Exception e) {
2956 throw new InvalidOperationException (Locale.GetText ("Comparer threw an exception."), e);
2962 public static int IndexOf<T> (T [] array, T value)
2965 throw new ArgumentNullException ("array");
2967 return IndexOf<T> (array, value, 0, array.Length);
2970 public static int IndexOf<T> (T [] array, T value, int startIndex)
2973 throw new ArgumentNullException ("array");
2975 return IndexOf<T> (array, value, startIndex, array.Length - startIndex);
2978 public static int IndexOf<T> (T [] array, T value, int startIndex, int count)
2981 throw new ArgumentNullException ("array");
2983 // re-ordered to avoid possible integer overflow
2984 if (count < 0 || startIndex < array.GetLowerBound (0) || startIndex - 1 > array.GetUpperBound (0) - count)
2985 throw new ArgumentOutOfRangeException ();
2987 int max = startIndex + count;
2988 EqualityComparer<T> equalityComparer = EqualityComparer<T>.Default;
2989 for (int i = startIndex; i < max; i++) {
2990 if (equalityComparer.Equals (array [i], value))
2997 public static int LastIndexOf<T> (T [] array, T value)
3000 throw new ArgumentNullException ("array");
3002 if (array.Length == 0)
3004 return LastIndexOf<T> (array, value, array.Length - 1);
3007 public static int LastIndexOf<T> (T [] array, T value, int startIndex)
3010 throw new ArgumentNullException ("array");
3012 return LastIndexOf<T> (array, value, startIndex, startIndex + 1);
3015 public static int LastIndexOf<T> (T [] array, T value, int startIndex, int count)
3018 throw new ArgumentNullException ("array");
3020 if (count < 0 || startIndex < array.GetLowerBound (0) ||
3021 startIndex > array.GetUpperBound (0) || startIndex - count + 1 < array.GetLowerBound (0))
3022 throw new ArgumentOutOfRangeException ();
3024 EqualityComparer<T> equalityComparer = EqualityComparer<T>.Default;
3025 for (int i = startIndex; i >= startIndex - count + 1; i--) {
3026 if (equalityComparer.Equals (array [i], value))
3033 public static T [] FindAll<T> (T [] array, Predicate <T> match)
3036 throw new ArgumentNullException ("array");
3039 throw new ArgumentNullException ("match");
3042 T [] d = new T [array.Length];
3043 foreach (T t in array)
3047 Resize <T> (ref d, pos);
3051 public static bool Exists<T> (T [] array, Predicate <T> match)
3054 throw new ArgumentNullException ("array");
3057 throw new ArgumentNullException ("match");
3059 foreach (T t in array)
3065 public static ReadOnlyCollection<T> AsReadOnly<T> (T[] array)
3068 throw new ArgumentNullException ("array");
3070 return new ReadOnlyCollection<T> (array);
3073 public static T Find<T> (T [] array, Predicate<T> match)
3076 throw new ArgumentNullException ("array");
3079 throw new ArgumentNullException ("match");
3081 foreach (T t in array)
3088 public static T FindLast<T> (T [] array, Predicate <T> match)
3091 throw new ArgumentNullException ("array");
3094 throw new ArgumentNullException ("match");
3096 for (int i = array.Length - 1; i >= 0; i--)
3097 if (match (array [i]))
3103 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
3105 // The constrained copy should guarantee that if there is an exception thrown
3106 // during the copy, the destination array remains unchanged.
3107 // This is related to System.Runtime.Reliability.CER
3108 public static void ConstrainedCopy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
3110 Copy (sourceArray, sourceIndex, destinationArray, destinationIndex, length);
3113 internal static T UnsafeLoad<T> (T[] array, int index) {
3114 return array [index];
3117 internal static void UnsafeStore<T> (T[] array, int index, T value) {
3118 array [index] = value;