2007-10-27 Marek Safar <marek.safar@gmail.com>
[mono.git] / mcs / class / corlib / System / Array.cs
index c6ec70bf2a105f20118e5b23134cfc37c04faa98..b0653b0169a5da70c7b59b05bbeca7238b9ac337 100644 (file)
@@ -8,10 +8,7 @@
 //   Gonzalo Paniagua Javier (gonzalo@ximian.com)
 //
 // (C) 2001-2003 Ximian, Inc.  http://www.ximian.com
-//
-
-//
-// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -39,15 +36,18 @@ using System.Runtime.InteropServices;
 
 #if NET_2_0
 using System.Collections.Generic;
+using System.Collections.ObjectModel;
 using System.Runtime.ConstrainedExecution;
 #endif
 
 namespace System
 {
-
        [Serializable]
-       [MonoTODO ("We are doing way to many double/triple exception checks for the overloaded functions")]
-       [MonoTODO ("Sort overloads parameter checks are VERY inconsistent")]
+#if NET_2_0
+       [ComVisible (true)]
+#endif
+       // FIXME: We are doing way to many double/triple exception checks for the overloaded functions"
+       // FIXME: Sort overloads parameter checks are VERY inconsistent"
        public abstract class Array : ICloneable, ICollection, IList, IEnumerable
        {
                // Constructor
@@ -55,6 +55,200 @@ namespace System
                {
                }
 
+#if NET_2_0
+               // FIXME: they should not be exposed, but there are some
+               // dependent code in the runtime.
+               protected int InternalArray__ICollection_get_Count<T> ()
+               {
+                       return Length;
+               }
+
+               protected IEnumerator<T> InternalArray__IEnumerable_GetEnumerator<T> ()
+               {
+                       return new InternalEnumerator<T> (this);
+               }
+
+               protected void InternalArray__ICollection_Clear<T> ()
+               {
+                       throw new NotSupportedException ("Collection is read-only");
+               }
+
+               protected void InternalArray__ICollection_Add<T> (T item)
+               {
+                       throw new NotSupportedException ("Collection is read-only");
+               }
+
+               protected bool InternalArray__ICollection_Remove<T> (T item)
+               {
+                       throw new NotSupportedException ("Collection is read-only");
+               }
+
+               protected bool InternalArray__ICollection_Contains<T> (T item)
+               {
+                       if (this.Rank > 1)
+                               throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
+
+                       int length = this.Length;
+                       for (int i = 0; i < length; i++) {
+                               T value;
+                               GetGenericValueImpl (i, out value);
+                               if (item == null){
+                                       if (value == null)
+                                               return true;
+                                       else
+                                               return false;
+                               }
+                               
+                               if (item.Equals (value))
+                                       return true;
+                       }
+
+                       return false;
+               }
+
+               protected void InternalArray__ICollection_CopyTo<T> (T[] array, int index)
+               {
+                       if (array == null)
+                               throw new ArgumentNullException ("array");
+
+                       // The order of these exception checks may look strange,
+                       // but that's how the microsoft runtime does it.
+                       if (this.Rank > 1)
+                               throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
+                       if (index + this.GetLength (0) > array.GetLowerBound (0) + array.GetLength (0))
+                               throw new ArgumentException ("Destination array was not long " +
+                                       "enough. Check destIndex and length, and the array's " +
+                                       "lower bounds.");
+                       if (array.Rank > 1)
+                               throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
+                       if (index < 0)
+                               throw new ArgumentOutOfRangeException (
+                                       "index", Locale.GetText ("Value has to be >= 0."));
+
+                       Copy (this, this.GetLowerBound (0), array, index, this.GetLength (0));
+               }
+
+               protected void InternalArray__Insert<T> (int index, T item)
+               {
+                       throw new NotSupportedException ("Collection is read-only");
+               }
+
+               protected void InternalArray__RemoveAt<T> (int index)
+               {
+                       throw new NotSupportedException ("Collection is read-only");
+               }
+
+               protected int InternalArray__IndexOf<T> (T item)
+               {
+                       if (this.Rank > 1)
+                               throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
+
+                       int length = this.Length;
+                       for (int i = 0; i < length; i++) {
+                               T value;
+                               GetGenericValueImpl (i, out value);
+                               if (item == null){
+                                       if (value == null)
+                                               return i + this.GetLowerBound (0);
+                                       else {
+                                               unchecked {
+                                                       return this.GetLowerBound (0) - 1;
+                                               }
+                                       }
+                               }
+                               if (item.Equals (value))
+                                       // array index may not be zero-based.
+                                       // use lower bound
+                                       return i + this.GetLowerBound (0);
+                       }
+
+                       int retVal;
+                       unchecked {
+                               // lower bound may be MinValue
+                               retVal = this.GetLowerBound (0) - 1;
+                       }
+
+                       return retVal;
+               }
+
+               protected T InternalArray__get_Item<T> (int index)
+               {
+                       if (unchecked ((uint) index) >= unchecked ((uint) Length))
+                               throw new ArgumentOutOfRangeException ("index");
+
+                       T value;
+                       GetGenericValueImpl (index, out value);
+                       return value;
+               }
+
+               protected void InternalArray__set_Item<T> (int index, T item)
+               {
+                       if (unchecked ((uint) index) >= unchecked ((uint) Length))
+                               throw new ArgumentOutOfRangeException ("index");
+
+                       SetGenericValueImpl (index, ref item);
+               }
+
+               // CAUTION! No bounds checking!
+               [MethodImplAttribute (MethodImplOptions.InternalCall)]
+               internal extern void GetGenericValueImpl<T> (int pos, out T value);
+
+               // CAUTION! No bounds checking!
+               [MethodImplAttribute (MethodImplOptions.InternalCall)]
+               internal extern void SetGenericValueImpl<T> (int pos, ref T value);
+
+               internal struct InternalEnumerator<T> : IEnumerator<T>
+               {
+                       const int NOT_STARTED = -2;
+                       
+                       // this MUST be -1, because we depend on it in move next.
+                       // we just decr the size, so, 0 - 1 == FINISHED
+                       const int FINISHED = -1;
+                       
+                       Array array;
+                       int idx;
+
+                       internal InternalEnumerator (Array array)
+                       {
+                               this.array = array;
+                               idx = NOT_STARTED;
+                       }
+
+                       public void Dispose ()
+                       {
+                               idx = NOT_STARTED;
+                       }
+
+                       public bool MoveNext ()
+                       {
+                               if (idx == NOT_STARTED)
+                                       idx = array.Length;
+
+                               return idx != FINISHED && -- idx != FINISHED;
+                       }
+
+                       public T Current {
+                               get {
+                                       if (idx < 0)
+                                               throw new InvalidOperationException ();
+
+                                       return array.InternalArray__get_Item<T> (array.Length - 1 - idx);
+                               }
+                       }
+
+                       void IEnumerator.Reset ()
+                       {
+                               throw new NotImplementedException ();
+                       }
+
+                       object IEnumerator.Current {
+                               get {
+                                       return Current;
+                               }
+                       }
+               }
+#endif
+
                // Properties
                public int Length {
 #if NET_2_0
@@ -168,7 +362,7 @@ namespace System
 
                // InternalCall Methods
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               private extern int GetRank ();
+               extern int GetRank ();
 
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
                public extern int GetLength (int dimension);
@@ -214,31 +408,51 @@ namespace System
                        }
                }
 
-               public virtual bool IsSynchronized {
+               public
+#if !NET_2_0
+               virtual
+#endif
+               bool IsSynchronized {
                        get {
                                return false;
                        }
                }
 
-               public virtual object SyncRoot {
+               public
+#if !NET_2_0
+               virtual
+#endif
+               object SyncRoot {
                        get {
                                return this;
                        }
                }
 
-               public virtual bool IsFixedSize {
+               public
+#if !NET_2_0
+               virtual
+#endif
+               bool IsFixedSize {
                        get {
                                return true;
                        }
                }
 
-               public virtual bool IsReadOnly {
+               public
+#if !NET_2_0
+               virtual
+#endif
+               bool IsReadOnly {
                        get {
                                return false;
                        }
                }
 
-               public virtual IEnumerator GetEnumerator ()
+               public
+#if !NET_2_0
+               virtual
+#endif
+               IEnumerator GetEnumerator ()
                {
                        return new SimpleEnumerator (this);
                }
@@ -406,7 +620,7 @@ namespace System
                        return CreateInstance (elementType, lengths);
                }
 
-               public static Array CreateInstance (Type elementType, int[] lengths)
+               public static Array CreateInstance (Type elementType, params int[] lengths)
                {
                        if (elementType == null)
                                throw new ArgumentNullException ("elementType");
@@ -477,33 +691,30 @@ namespace System
 
                public static Array CreateInstance (Type elementType, params long [] lengths)
                {
-                       if (lengths == null) {
-                               // LAMESPEC: Docs say we should throw a ArgumentNull, but .NET
-                               // 1.1 actually throws a NullReference.
-                               throw new NullReferenceException (Locale.GetText ("'lengths' cannot be null."));
-                       }
+#if NET_2_0
+                       if (lengths == null)
+                               throw new ArgumentNullException ("lengths");
+#endif
                        return CreateInstance (elementType, GetIntArray (lengths));
                }
 
                [ComVisible (false)]
                public object GetValue (params long [] indices)
                {
-                       if (indices == null) {
-                               // LAMESPEC: Docs say we should throw a ArgumentNull, but .NET
-                               // 1.1 actually throws a NullReference.
-                               throw new NullReferenceException (Locale.GetText ("'indices' cannot be null."));
-                       }
+#if NET_2_0
+                       if (indices == null)
+                               throw new ArgumentNullException ("indices");
+#endif
                        return GetValue (GetIntArray (indices));
                }
 
                [ComVisible (false)]
                public void SetValue (object value, params long [] indices)
                {
-                       if (indices == null) {
-                               // LAMESPEC: Docs say we should throw a ArgumentNull, but .NET
-                               // 1.1 actually throws a NullReference.
-                               throw new NullReferenceException (Locale.GetText ("'indices' cannot be null."));
-                       }
+#if NET_2_0
+                       if (indices == null)
+                               throw new ArgumentNullException ("indices");
+#endif
                        SetValue (value, GetIntArray (indices));
                }
 #endif
@@ -522,6 +733,9 @@ namespace System
                        if (array.Rank > 1)
                                throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
 
+                       if (array.Length == 0)
+                               return -1;
+
                        if (!(value is IComparable))
                                throw new ArgumentException (Locale.GetText ("value does not support IComparable."));
 
@@ -529,7 +743,7 @@ namespace System
                }
 
 #if NET_2_0
-       [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
+               [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
 #endif
                public static int BinarySearch (Array array, object value, IComparer comparer)
                {
@@ -539,6 +753,9 @@ namespace System
                        if (array.Rank > 1)
                                throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
 
+                       if (array.Length == 0)
+                               return -1;
+
                        if ((comparer == null) && (value != null) && !(value is IComparable))
                                throw new ArgumentException (Locale.GetText (
                                        "comparer is null and value does not support IComparable."));
@@ -567,6 +784,10 @@ namespace System
                        if (index > array.GetLowerBound (0) + array.GetLength (0) - length)
                                throw new ArgumentException (Locale.GetText (
                                        "index and length do not specify a valid range in array."));
+
+                       if (array.Length == 0)
+                               return -1;
+
                        if ((value != null) && (!(value is IComparable)))
                                throw new ArgumentException (Locale.GetText (
                                        "value does not support IComparable"));
@@ -596,6 +817,9 @@ namespace System
                                throw new ArgumentException (Locale.GetText (
                                        "index and length do not specify a valid range in array."));
 
+                       if (array.Length == 0)
+                               return -1;
+
                        if ((comparer == null) && (value != null) && !(value is IComparable))
                                throw new ArgumentException (Locale.GetText (
                                        "comparer is null and value does not support IComparable."));
@@ -616,7 +840,9 @@ namespace System
                        int iCmp = 0;
                        try {
                                while (iMin <= iMax) {
-                                       int iMid = (iMin + iMax) / 2;
+                                       // Be careful with overflow
+                                       // http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html
+                                       int iMid = iMin + ((iMax - iMin) / 2);
                                        object elt = array.GetValueImpl (iMid);
 
                                        iCmp = comparer.Compare (elt, value);
@@ -662,7 +888,11 @@ namespace System
                static extern void ClearInternal (Array a, int index, int count);
 
                [MethodImplAttribute (MethodImplOptions.InternalCall)]
-               public virtual extern object Clone ();
+               public
+#if !NET_2_0
+               virtual
+#endif
+               extern object Clone ();
 
 #if NET_2_0
                [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
@@ -711,9 +941,19 @@ namespace System
                        int dest_pos = destinationIndex - destinationArray.GetLowerBound (0);
 
                        // re-ordered to avoid possible integer overflow
-                       if (source_pos > sourceArray.Length - length || dest_pos > destinationArray.Length - length)
+                       if (source_pos > sourceArray.Length - length)
                                throw new ArgumentException ("length");
 
+                       if (dest_pos > destinationArray.Length - length) {
+                               string msg = "Destination array was not long enough. Check " +
+                                       "destIndex and length, and the array's lower bounds";
+#if NET_2_0
+                               throw new ArgumentException (msg, string.Empty);
+#else
+                               throw new ArgumentException (msg);
+#endif
+                       }
+
                        if (sourceArray.Rank != destinationArray.Rank)
                                throw new RankException (Locale.GetText ("Arrays must be of same size."));
 
@@ -841,7 +1081,6 @@ namespace System
                        return array.GetLowerBound (0) - 1;
                }
 
-               [MonoTODO]
                public void Initialize()
                {
                        //FIXME: We would like to find a compiler that uses
@@ -911,6 +1150,20 @@ namespace System
                        return new Swapper (array.slow_swapper);
                }
 
+#if NET_2_0
+               static Swapper get_swapper<T> (T [] array)
+               {
+                       if (array is int[])
+                               return new Swapper (array.int_swapper);
+                       if (array is double[])
+                               return new Swapper (array.double_swapper);
+
+                       // gmcs refuses to compile this
+                       //return new Swapper (array.generic_swapper<T>);
+                       return new Swapper (array.slow_swapper);
+               }
+#endif
+
 #if NET_2_0
                [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
 #endif
@@ -1136,6 +1389,15 @@ namespace System
                        array [j] = val;
                }
 
+#if NET_2_0
+               void generic_swapper<T> (int i, int j) {
+                       T[] array = this as T[];
+                       T val = array [i];
+                       array [i] = array [j];
+                       array [j] = val;
+               }
+#endif
+
                static int new_gap (int gap)
                {
                        gap = (gap * 10) / 13;
@@ -1226,7 +1488,9 @@ namespace System
                        int low = low0;
                        int high = high0;
 
-                       object objPivot = keys.GetValueImpl ((low + high) / 2);
+                       // Be careful with overflows
+                       int mid = low + ((high - low) / 2);
+                       object objPivot = keys.GetValueImpl (mid);
 
                        while (low <= high) {
                                // Move the walls in
@@ -1275,7 +1539,259 @@ namespace System
                                return comparer.Compare (value1, value2);
                }
        
-               public virtual void CopyTo (Array array, int index)
+#if NET_2_0
+               [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
+               public static void Sort<T> (T [] array)
+               {
+                       if (array == null)
+                               throw new ArgumentNullException ("array");
+
+                       Sort<T, T> (array, null, 0, array.Length, null);
+               }
+
+               [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
+               public static void Sort<TKey, TValue> (TKey [] keys, TValue [] items)
+               {
+                       if (keys == null)
+                               throw new ArgumentNullException ("keys");
+                       
+                       Sort<TKey, TValue> (keys, items, 0, keys.Length, null);
+               }
+
+               [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
+               public static void Sort<T> (T [] array, IComparer<T> comparer)
+               {
+                       if (array == null)
+                               throw new ArgumentNullException ("array");
+
+                       Sort<T, T> (array, null, 0, array.Length, comparer);
+               }
+
+               [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
+               public static void Sort<TKey, TValue> (TKey [] keys, TValue [] items, IComparer<TKey> comparer)
+               {
+                       if (keys == null)
+                               throw new ArgumentNullException ("keys");
+                       
+                       Sort<TKey, TValue> (keys, items, 0, keys.Length, comparer);
+               }
+
+               [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
+               public static void Sort<T> (T [] array, int index, int length)
+               {
+                       if (array == null)
+                               throw new ArgumentNullException ("array");
+                       
+                       Sort<T, T> (array, null, index, length, null);
+               }
+
+               [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
+               public static void Sort<TKey, TValue> (TKey [] keys, TValue [] items, int index, int length)
+               {
+                       Sort<TKey, TValue> (keys, items, index, length, null);
+               }
+
+               [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
+               public static void Sort<T> (T [] array, int index, int length, IComparer<T> comparer)
+               {
+                       if (array == null)
+                               throw new ArgumentNullException ("array");
+
+                       Sort<T, T> (array, null, index, length, comparer);
+               }
+
+               [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
+               public static void Sort<TKey, TValue> (TKey [] keys, TValue [] items, int index, int length, IComparer<TKey> comparer)
+               {
+                       if (keys == null)
+                               throw new ArgumentNullException ("keys");
+
+                       if (index < 0)
+                               throw new ArgumentOutOfRangeException ("index");
+
+                       if (length < 0)
+                               throw new ArgumentOutOfRangeException ("length");
+
+                       if (keys.Length - index < length
+                               || (items != null && index > items.Length - length))
+                               throw new ArgumentException ();
+
+                       if (length <= 1)
+                               return;
+                       
+                       //
+                       // Check for value types which can be sorted without Compare () method
+                       //
+                       if (comparer == null) {
+                               Swapper iswapper;
+                               if (items == null)
+                                       iswapper = null;
+                               else 
+                                       iswapper = get_swapper<TValue> (items);
+                               if (keys is double[]) {
+                                       combsort (keys as double[], index, length, iswapper);
+                                       return;
+                               }
+                               if (keys is int[]) {
+                                       combsort (keys as int[], index, length, iswapper);
+                                       return;
+                               }
+                               if (keys is char[]) {
+                                       combsort (keys as char[], index, length, iswapper);
+                                       return;
+                               }
+
+                               // Use Comparer<T>.Default instead
+                               // comparer = Comparer<K>.Default;
+                       }
+                       
+                       try {
+                               int low0 = index;
+                               int high0 = index + length - 1;
+                               qsort<TKey, TValue> (keys, items, low0, high0, comparer);
+                       }
+                       catch (Exception e) {
+                               throw new InvalidOperationException (Locale.GetText ("The comparer threw an exception."), e);
+                       }
+               }
+
+               public static void Sort<T> (T [] array, Comparison<T> comparison)
+               {
+                       if (array == null)
+                               throw new ArgumentNullException ("array");
+                       Sort<T> (array, array.Length, comparison);
+               }
+
+               internal static void Sort<T> (T [] array, int length, Comparison<T> comparison)
+               {
+                       if (comparison == null)
+                               throw new ArgumentNullException ("comparison");
+
+                       if (length <= 1 || array.Length <= 1)
+                               return;
+                       
+                       try {
+                               int low0 = 0;
+                               int high0 = length - 1;
+                               qsort<T> (array, low0, high0, comparison);
+                       }
+                       catch (Exception e) {
+                               throw new InvalidOperationException (Locale.GetText ("Comparison threw an exception."), e);
+                       }
+               }
+
+               private static void qsort<K, V> (K [] keys, V [] items, int low0, int high0, IComparer<K> comparer)
+               {
+                       if (low0 >= high0)
+                               return;
+
+                       int low = low0;
+                       int high = high0;
+
+                       // Be careful with overflows
+                       int mid = low + ((high - low) / 2);
+                       K keyPivot = keys [mid];
+
+                       while (low <= high) {
+                               // Move the walls in
+                               //while (low < high0 && comparer.Compare (keys [low], keyPivot) < 0)
+                               while (low < high0 && compare (keys [low], keyPivot, comparer) < 0)
+                                       ++low;
+                               //while (high > low0 && comparer.Compare (keyPivot, keys [high]) < 0)
+                               while (high > low0 && compare (keyPivot, keys [high], comparer) < 0)
+                                       --high;
+
+                               if (low <= high) {
+                                       swap<K, V> (keys, items, low, high);
+                                       ++low;
+                                       --high;
+                               }
+                       }
+
+                       if (low0 < high)
+                               qsort<K, V> (keys, items, low0, high, comparer);
+                       if (low < high0)
+                               qsort<K, V> (keys, items, low, high0, comparer);
+               }
+
+               private static int compare<T> (T value1, T value2, IComparer<T> comparer)
+               {
+                       if (comparer != null)
+                               return comparer.Compare (value1, value2);
+                       else if (value1 == null)
+                               return value2 == null ? 0 : -1;
+                       else if (value2 == null)
+                               return 1;
+                       else if (value1 is IComparable<T>)
+                               return ((IComparable<T>) value1).CompareTo (value2);
+                       else if (value1 is IComparable)
+                               return ((IComparable) value1).CompareTo (value2);
+
+                       string msg = Locale.GetText ("No IComparable or IComparable<T> interface found for type '{0}'.");
+                       throw new InvalidOperationException (String.Format (msg, typeof (T)));
+               }
+
+               private static void qsort<T> (T [] array, int low0, int high0, Comparison<T> comparison)
+               {
+                       if (low0 >= high0)
+                               return;
+
+                       int low = low0;
+                       int high = high0;
+
+                       // Be careful with overflows
+                       int mid = low + ((high - low) / 2);
+                       T keyPivot = array [mid];
+
+                       while (low <= high) {
+                               // Move the walls in
+                               while (low < high0 && comparison (array [low], keyPivot) < 0)
+                                       ++low;
+                               while (high > low0 && comparison (keyPivot, array [high]) < 0)
+                                       --high;
+
+                               if (low <= high) {
+                                       swap<T> (array, low, high);
+                                       ++low;
+                                       --high;
+                               }
+                       }
+
+                       if (low0 < high)
+                               qsort<T> (array, low0, high, comparison);
+                       if (low < high0)
+                               qsort<T> (array, low, high0, comparison);
+               }
+
+               private static void swap<K, V> (K [] keys, V [] items, int i, int j)
+               {
+                       K tmp;
+
+                       tmp = keys [i];
+                       keys [i] = keys [j];
+                       keys [j] = tmp;
+
+                       if (items != null) {
+                               V itmp;
+                               itmp = items [i];
+                               items [i] = items [j];
+                               items [j] = itmp;
+                       }
+               }
+
+               private static void swap<T> (T [] array, int i, int j)
+               {
+                       T tmp = array [i];
+                       array [i] = array [j];
+                       array [j] = tmp;
+               }
+#endif
+               
+               public
+#if !NET_2_0
+               virtual
+#endif
+               void CopyTo (Array array, int index)
                {
                        if (array == null)
                                throw new ArgumentNullException ("array");
@@ -1285,7 +1801,9 @@ namespace System
                        if (this.Rank > 1)
                                throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
                        if (index + this.GetLength (0) > array.GetLowerBound (0) + array.GetLength (0))
-                               throw new ArgumentException ();
+                               throw new ArgumentException ("Destination array was not long " +
+                                       "enough. Check destIndex and length, and the array's " +
+                                       "lower bounds.");
                        if (array.Rank > 1)
                                throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
                        if (index < 0)
@@ -1297,7 +1815,11 @@ namespace System
 
 #if NET_1_1
                [ComVisible (false)]
-               public virtual void CopyTo (Array array, long index)
+               public
+#if !NET_2_0
+               virtual
+#endif
+               void CopyTo (Array array, long index)
                {
                        if (index < 0 || index > Int32.MaxValue)
                                throw new ArgumentOutOfRangeException ("index", Locale.GetText (
@@ -1359,9 +1881,10 @@ namespace System
                }
 
 #if NET_2_0
+               [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
                public static void Resize<T> (ref T [] array, int newSize)
                {
-                       Resize<T> (ref array, array.Length, newSize);
+                       Resize<T> (ref array, array == null ? 0 : array.Length, newSize);
                }
 
                internal static void Resize<T> (ref T[] array, int length, int newSize)
@@ -1506,6 +2029,7 @@ namespace System
                        return BinarySearch<T> (array, 0, array.Length, value, comparer);
                }
                
+               [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
                public static int BinarySearch<T> (T [] array, int offset, int length, T value)
                {
                        return BinarySearch<T> (array, offset, length, value, null);
@@ -1534,7 +2058,8 @@ namespace System
                        int iCmp = 0;
                        try {
                                while (iMin <= iMax) {
-                                       int iMid = (iMin + iMax) / 2;
+                                       // Be careful with overflows
+                                       int iMid = iMin + ((iMax - iMin) / 2);
                                        iCmp = comparer.Compare (value, array [iMid]);
 
                                        if (iCmp == 0)
@@ -1556,7 +2081,7 @@ namespace System
                        if (array == null)
                                throw new ArgumentNullException ("array");
        
-                       return IndexOf (array, value, 0, array.Length);
+                       return IndexOf<T> (array, value, 0, array.Length);
                }
 
                public static int IndexOf<T> (T [] array, T value, int startIndex)
@@ -1564,7 +2089,7 @@ namespace System
                        if (array == null)
                                throw new ArgumentNullException ("array");
 
-                       return IndexOf (array, value, startIndex, array.Length - startIndex);
+                       return IndexOf<T> (array, value, startIndex, array.Length - startIndex);
                }
 
                public static int IndexOf<T> (T [] array, T value, int startIndex, int count)
@@ -1577,8 +2102,9 @@ namespace System
                                throw new ArgumentOutOfRangeException ();
 
                        int max = startIndex + count;
+                       EqualityComparer<T> equalityComparer = EqualityComparer<T>.Default;
                        for (int i = startIndex; i < max; i++) {
-                               if (Object.Equals (value, array [i]))
+                               if (equalityComparer.Equals (value, array [i]))
                                        return i;
                        }
 
@@ -1590,7 +2116,7 @@ namespace System
                        if (array == null)
                                throw new ArgumentNullException ("array");
 
-                       return LastIndexOf (array, value, array.Length - 1);
+                       return LastIndexOf<T> (array, value, array.Length - 1);
                }
 
                public static int LastIndexOf<T> (T [] array, T value, int startIndex)
@@ -1598,7 +2124,7 @@ namespace System
                        if (array == null)
                                throw new ArgumentNullException ("array");
 
-                       return LastIndexOf (array, value, startIndex, startIndex + 1);
+                       return LastIndexOf<T> (array, value, startIndex, startIndex + 1);
                }
 
                public static int LastIndexOf<T> (T [] array, T value, int startIndex, int count)
@@ -1609,8 +2135,9 @@ namespace System
                        if (count < 0 || startIndex > array.Length || startIndex - count + 1 < 0)
                                throw new ArgumentOutOfRangeException ();
 
+                       EqualityComparer<T> equalityComparer = EqualityComparer<T>.Default;
                        for (int i = startIndex; i >= startIndex - count + 1; i--) {
-                               if (Object.Equals (value, array [i]))
+                               if (equalityComparer.Equals (value, array [i]))
                                        return i;
                        }
 
@@ -1649,14 +2176,14 @@ namespace System
                        return false;
                }
 
-               public static IList<T> AsReadOnly<T> (T[] array)
+               public static ReadOnlyCollection<T> AsReadOnly<T> (T[] array)
                {
                        if (array == null)
                                throw new ArgumentNullException ("array");
-                       return new ReadOnlyArray<T> (array);
+                       return new ReadOnlyCollection<T> (new ArrayReadOnlyList<T> (array));
                }
 
-               public static Nullable<T> Find<T> (T [] array, Predicate<T> match)
+               public static T Find<T> (T [] array, Predicate<T> match)
                {
                        if (array == null)
                                throw new ArgumentNullException ("array");
@@ -1666,12 +2193,12 @@ namespace System
                        
                        foreach (T t in array)
                                if (match (t))
-                                       return new Nullable <T> (t);
+                                       return t;
                                
-                       return default (Nullable <T>);
+                       return default (T);
                }
                
-               public static Nullable<T> FindLast<T> (T [] array, Predicate <T> match)
+               public static T FindLast<T> (T [] array, Predicate <T> match)
                {
                        if (array == null)
                                throw new ArgumentNullException ("array");
@@ -1681,9 +2208,9 @@ namespace System
                        
                        for (int i = array.Length - 1; i >= 0; i--)
                                if (match (array [i]))
-                                       return new Nullable <T> (array [i]);
+                                       return array [i];
                                
-                       return default (Nullable <T>);
+                       return default (T);
                }
 
                [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]           
@@ -1698,319 +2225,92 @@ namespace System
 #endif 
 
 #if NET_2_0
-               //
-               // This is used internally by the runtime to represent arrays; see #74953.
-               //
-               // Note that you normally can't derive a class from System.Array (CS0644),
-               // but GMCS makes an exception here for all classes which are nested inside
-               // System.Array.
-               //
-               internal class InternalArray<T> : Array, IList<T>
+               class ArrayReadOnlyList<T> : IList<T>
                {
-                       new public IEnumerator<T> GetEnumerator ()
+                       T [] array;
+                       bool is_value_type;
+
+                       public ArrayReadOnlyList (T [] array)
                        {
-                               return new InternalEnumerator (this);
+                               this.array = array;
+                               is_value_type = typeof (T).IsValueType;
                        }
 
-                       public int Count {
+                       public T this [int index] {
                                get {
-                                       return Length;
+                                       if (unchecked ((uint) index) >= unchecked ((uint) array.Length))
+                                               throw new ArgumentOutOfRangeException ("index");
+                                       return array [index];
                                }
+                               set { throw ReadOnlyError (); }
                        }
 
-                       bool ICollection<T>.IsReadOnly {
-                               get {
-                                       return true;
-                               }
+                       public int Count {
+                               get { return array.Length; }
                        }
 
-                       void ICollection<T>.Clear ()
-                       {
-                               throw new NotSupportedException ("Collection is read-only");
+                       public bool IsReadOnly {
+                               get { return true; }
                        }
 
-                       void ICollection<T>.Add (T item)
+                       public void Add (T item)
                        {
-                               throw new NotSupportedException ("Collection is read-only");
+                               throw ReadOnlyError ();
                        }
 
-                       bool ICollection<T>.Remove (T item)
+                       public void Clear ()
                        {
-                               throw new NotSupportedException ("Collection is read-only");
+                               throw ReadOnlyError ();
                        }
 
                        public bool Contains (T item)
                        {
-                               if (this.Rank > 1)
-                                       throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
-
-                               int length = this.Length;
-                               for (int i = 0; i < length; i++) {
-                                       T value;
-                                       GetGenericValueImpl (i, out value);
-                                       if (item.Equals (value))
-                                               return true;
-                               }
-
-                               return false;
+                               return Array.IndexOf<T> (array, item) >= 0;
                        }
 
-                       public void CopyTo (T[] array, int index)
+                       public void CopyTo (T [] array, int index)
                        {
-                               if (array == null)
-                                       throw new ArgumentNullException ("array");
-
-                               // The order of these exception checks may look strange,
-                               // but that's how the microsoft runtime does it.
-                               if (this.Rank > 1)
-                                       throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
-                               if (index + this.GetLength (0) > array.GetLowerBound (0) + array.GetLength (0))
-                                       throw new ArgumentException ();
-                               if (array.Rank > 1)
-                                       throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
-                               if (index < 0)
-                                       throw new ArgumentOutOfRangeException (
-                                               "index", Locale.GetText ("Value has to be >= 0."));
-
-                               Copy (this, this.GetLowerBound (0), array, index, this.GetLength (0));
+                               array.CopyTo (array, index);
                        }
 
-                       new public T this [int index] {
-                               get {
-                                       if (unchecked ((uint) index) >= unchecked ((uint) Length))
-                                               throw new ArgumentOutOfRangeException ("index");
-
-                                       T value;
-                                       GetGenericValueImpl (index, out value);
-                                       return value;
-                               }
-
-                               set {
-                                       throw new NotSupportedException ("Collection is read-only");
-                               }
-                       }
-
-                       void IList<T>.Insert (int index, T item)
+                       IEnumerator IEnumerable.GetEnumerator ()
                        {
-                               throw new NotSupportedException ("Collection is read-only");
+                               return GetEnumerator ();
                        }
 
-                       void IList<T>.RemoveAt (int index)
+                       public IEnumerator<T> GetEnumerator ()
                        {
-                               throw new NotSupportedException ("Collection is read-only");
+                               for (int i = 0; i < array.Length; i++)
+                                       yield return array [i];
                        }
 
                        public int IndexOf (T item)
                        {
-                               if (this.Rank > 1)
-                                       throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
-
-                               int length = this.Length;
-                               for (int i = 0; i < length; i++) {
-                                       T value;
-                                       GetGenericValueImpl (i, out value);
-                                       if (item.Equals (value))
-                                               // array index may not be zero-based.
-                                               // use lower bound
-                                               return i + this.GetLowerBound (0);
-                               }
-
-                               int retVal;
-                               unchecked {
-                                       // lower bound may be MinValue
-                                       retVal = this.GetLowerBound (0) - 1;
-                               }
-
-                               return retVal;
+                               return Array.IndexOf<T> (array, item);
                        }
 
-                       // CAUTION! No bounds checking!
-                       [MethodImplAttribute (MethodImplOptions.InternalCall)]
-                       protected extern void GetGenericValueImpl (int pos, out T value);
-
-                       internal struct InternalEnumerator : IEnumerator<T>
+                       public void Insert (int index, T item)
                        {
-                               const int NOT_STARTED = -2;
-                       
-                               // this MUST be -1, because we depend on it in move next.
-                               // we just decr the size, so, 0 - 1 == FINISHED
-                               const int FINISHED = -1;
-                       
-                               InternalArray<T> array;
-                               int idx;
-
-                               internal InternalEnumerator (InternalArray<T> array)
-                               {
-                                       this.array = array;
-                                       idx = NOT_STARTED;
-                               }
-
-                               public void Dispose ()
-                               {
-                                       idx = NOT_STARTED;
-                               }
-
-                               public bool MoveNext ()
-                               {
-                                       if (idx == NOT_STARTED)
-                                               idx = array.Length;
-
-                                       return idx != FINISHED && -- idx != FINISHED;
-                               }
-
-                               public T Current {
-                                       get {
-                                               if (idx < 0)
-                                                       throw new InvalidOperationException ();
-
-                                               return array [array.Length - 1 - idx];
-                                       }
-                               }
-
-                               void IEnumerator.Reset ()
-                               {
-                                       throw new NotImplementedException ();
-                               }
-
-                               object IEnumerator.Current {
-                                       get {
-                                               return Current;
-                                       }
-                               }
-                       }
-               }
-#endif
-       }
-
-#if NET_2_0
-
-       internal struct ReadOnlyArrayEnumerator <T> : IEnumerator <T> {
-               const int NOT_STARTED = -2;
-                       
-               // this MUST be -1, because we depend on it in move next.
-               // we just decr the size, so, 0 - 1 == FINISHED
-               const int FINISHED = -1;
-                       
-               ReadOnlyArray <T> array;
-               int idx;
-                       
-               internal ReadOnlyArrayEnumerator (ReadOnlyArray<T> array)
-               {
-                       this.array = array;
-                       idx = NOT_STARTED;
-               }
-                       
-               public void Dispose ()
-               {
-                       idx = NOT_STARTED;
-               }
-                       
-               public bool MoveNext ()
-               {
-                       if (idx == NOT_STARTED)
-                               idx = array.Count;
-                               
-                       return idx != FINISHED && -- idx != FINISHED;
-               }
-                       
-               public T Current {
-                       get {
-                               if (idx < 0)
-                                       throw new InvalidOperationException ();
-                                       
-                               return array [array.Count - 1 - idx];
+                               throw ReadOnlyError ();
                        }
-               }
-
-               void IEnumerator.Reset ()
-               {
-                       throw new NotImplementedException ();
-               }
 
-               object IEnumerator.Current {
-                       get {
-                               return Current;
-                       }
-               }
-       }
-
-       internal class ReadOnlyArray <T> : ICollection <T>, IList <T>, IEnumerable <T>
-       {
-               T[] arr;
-
-               internal ReadOnlyArray (T[] array) {
-                       arr = array;
-               }
-
-               // ICollection<T> interface
-               public int Count {
-                       get {
-                               return arr.Length;
+                       public bool Remove (T item)
+                       {
+                               throw ReadOnlyError ();
                        }
-               }
 
-               public bool IsReadOnly {
-                       get {
-                               return true;
+                       public void RemoveAt (int index)
+                       {
+                               throw ReadOnlyError ();
                        }
-               }
-
-               public void Add (T item) {
-                       throw new NotSupportedException ("Collection is read-only");
-               }
 
-               public bool Remove (T item) {
-                       throw new NotSupportedException ("Collection is read-only");
-               }
-
-               public void Clear () {
-                       throw new NotSupportedException ("Collection is read-only");
-               }
-
-               public void CopyTo (T[] array, int index) {
-                       arr.CopyTo (array, index);
-               }
-
-               public bool Contains (T item) {
-                       return Array.IndexOf <T> (arr, item) != -1;
-               }
-
-               // IList<T> interface
-               public T this [int index] {
-                       get {
-                               if (unchecked ((uint) index) >= unchecked ((uint) arr.Length))
-                                       throw new ArgumentOutOfRangeException ("index");
-                               return arr [index];
-                       } 
-                       set {
-                               if (unchecked ((uint) index) >= unchecked ((uint) arr.Length))
-                                       throw new ArgumentOutOfRangeException ("index");
-                               arr [index] = value;
+                       Exception ReadOnlyError ()
+                       {
+                               return new NotSupportedException ("This collection is read-only.");
                        }
                }
-
-               public void Insert (int index, T item) {
-                       throw new NotSupportedException ("Collection is read-only");
-               }
-
-               public void RemoveAt (int index) {
-                       throw new NotSupportedException ("Collection is read-only");
-               }
-
-               public int IndexOf (T item) {
-                       return Array.IndexOf <T> (arr, item);
-               }
-
-               // IEnumerable<T> interface
-               public IEnumerator<T> GetEnumerator () {
-                       return new ReadOnlyArrayEnumerator <T> (this);
-               }
-
-               IEnumerator IEnumerable.GetEnumerator () {
-                       return new ReadOnlyArrayEnumerator <T> (this);
-               }
-       }
 #endif
+       }
 
 #if BOOTSTRAP_WITH_OLDLIB
        /* delegate used to swap array elements, keep defined outside Array */