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;
46 public abstract partial class Array
54 * These methods are used to implement the implicit generic interfaces
55 * implemented by arrays in NET 2.0.
56 * Only make those methods generic which really need it, to avoid
57 * creating useless instantiations.
59 internal int InternalArray__ICollection_get_Count ()
64 internal bool InternalArray__ICollection_get_IsReadOnly ()
69 internal IEnumerator<T> InternalArray__IEnumerable_GetEnumerator<T> ()
71 return new InternalEnumerator<T> (this);
74 internal void InternalArray__ICollection_Clear ()
76 throw new NotSupportedException ("Collection is read-only");
79 internal void InternalArray__ICollection_Add<T> (T item)
81 throw new NotSupportedException ("Collection is of a fixed size");
84 internal bool InternalArray__ICollection_Remove<T> (T item)
86 throw new NotSupportedException ("Collection is of a fixed size");
89 internal bool InternalArray__ICollection_Contains<T> (T item)
92 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
94 int length = this.Length;
95 for (int i = 0; i < length; i++) {
97 GetGenericValueImpl (i, out value);
106 if (item.Equals (value)) {
114 internal void InternalArray__ICollection_CopyTo<T> (T[] array, int arrayIndex)
116 Copy (this, GetLowerBound (0), array, arrayIndex, Length);
119 internal T InternalArray__IReadOnlyList_get_Item<T> (int index)
121 if (unchecked ((uint) index) >= unchecked ((uint) Length))
122 throw new ArgumentOutOfRangeException ("index");
125 GetGenericValueImpl (index, out value);
129 internal int InternalArray__IReadOnlyCollection_get_Count ()
134 internal void InternalArray__Insert<T> (int index, T item)
136 throw new NotSupportedException ("Collection is of a fixed size");
139 internal void InternalArray__RemoveAt (int index)
141 throw new NotSupportedException ("Collection is of a fixed size");
144 internal int InternalArray__IndexOf<T> (T item)
147 throw new RankException (Locale.GetText ("Only single dimension arrays are supported."));
149 int length = this.Length;
150 for (int i = 0; i < length; i++) {
152 GetGenericValueImpl (i, out value);
155 return i + this.GetLowerBound (0);
159 if (value.Equals (item))
160 // array index may not be zero-based.
162 return i + this.GetLowerBound (0);
166 // lower bound may be MinValue
167 return this.GetLowerBound (0) - 1;
171 internal T InternalArray__get_Item<T> (int index)
173 if (unchecked ((uint) index) >= unchecked ((uint) Length))
174 throw new ArgumentOutOfRangeException ("index");
177 GetGenericValueImpl (index, out value);
181 internal void InternalArray__set_Item<T> (int index, T item)
183 if (unchecked ((uint) index) >= unchecked ((uint) Length))
184 throw new ArgumentOutOfRangeException ("index");
186 object[] oarray = this as object [];
187 if (oarray != null) {
188 oarray [index] = (object)item;
191 SetGenericValueImpl (index, ref item);
194 // CAUTION! No bounds checking!
195 [MethodImplAttribute (MethodImplOptions.InternalCall)]
196 internal extern void GetGenericValueImpl<T> (int pos, out T value);
198 // CAUTION! No bounds checking!
199 [MethodImplAttribute (MethodImplOptions.InternalCall)]
200 internal extern void SetGenericValueImpl<T> (int pos, ref T value);
202 internal struct InternalEnumerator<T> : IEnumerator<T>
204 const int NOT_STARTED = -2;
206 // this MUST be -1, because we depend on it in move next.
207 // we just decr the size, so, 0 - 1 == FINISHED
208 const int FINISHED = -1;
210 readonly Array array;
213 internal InternalEnumerator (Array array)
219 public void Dispose ()
223 public bool MoveNext ()
225 if (idx == NOT_STARTED)
228 return idx != FINISHED && -- idx != FINISHED;
233 if (idx == NOT_STARTED)
234 throw new InvalidOperationException ("Enumeration has not started. Call MoveNext");
236 throw new InvalidOperationException ("Enumeration already finished");
238 return array.InternalArray__get_Item<T> (array.Length - 1 - idx);
242 void IEnumerator.Reset ()
247 object IEnumerator.Current {
256 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
258 int length = this.GetLength (0);
260 for (int i = 1; i < this.Rank; i++) {
261 length *= this.GetLength (i);
268 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
270 return this.GetRank ();
274 // InternalCall Methods
275 [MethodImplAttribute (MethodImplOptions.InternalCall)]
276 extern int GetRank ();
278 [MethodImplAttribute (MethodImplOptions.InternalCall)]
279 public extern int GetLength (int dimension);
281 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
282 [MethodImplAttribute (MethodImplOptions.InternalCall)]
283 public extern int GetLowerBound (int dimension);
285 [MethodImplAttribute (MethodImplOptions.InternalCall)]
286 public extern object GetValue (params int[] indices);
288 [MethodImplAttribute (MethodImplOptions.InternalCall)]
289 public extern void SetValue (object value, params int[] indices);
291 // CAUTION! No bounds checking!
292 [MethodImplAttribute (MethodImplOptions.InternalCall)]
293 internal extern object GetValueImpl (int pos);
295 // CAUTION! No bounds checking!
296 [MethodImplAttribute (MethodImplOptions.InternalCall)]
297 internal extern void SetValueImpl (object value, int pos);
299 [MethodImplAttribute (MethodImplOptions.InternalCall)]
300 internal extern static bool FastCopy (Array source, int source_idx, Array dest, int dest_idx, int length);
302 [MethodImplAttribute (MethodImplOptions.InternalCall)]
303 internal extern static Array CreateInstanceImpl (Type elementType, int[] lengths, int[] bounds);
305 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
306 public int GetUpperBound (int dimension)
308 return GetLowerBound (dimension) + GetLength (dimension) - 1;
311 public object GetValue (int index)
314 throw new ArgumentException (SR.Arg_RankMultiDimNotSupported);
316 var lb = GetLowerBound (0);
317 if (index < lb || index > GetUpperBound (0))
318 throw new IndexOutOfRangeException (Locale.GetText (
319 "Index has to be between upper and lower bound of the array."));
321 if (GetType ().GetElementType ().IsPointer)
322 throw new NotSupportedException ("Type is not supported");
324 return GetValueImpl (index - lb);
327 public object GetValue (int index1, int index2)
329 int[] ind = {index1, index2};
330 return GetValue (ind);
333 public object GetValue (int index1, int index2, int index3)
335 int[] ind = {index1, index2, index3};
336 return GetValue (ind);
339 public void SetValue (object value, int index)
342 throw new ArgumentException (SR.Arg_RankMultiDimNotSupported);
344 var lb = GetLowerBound (0);
345 if (index < lb || index > GetUpperBound (0))
346 throw new IndexOutOfRangeException (Locale.GetText (
347 "Index has to be >= lower bound and <= upper bound of the array."));
349 if (GetType ().GetElementType ().IsPointer)
350 throw new NotSupportedException ("Type is not supported");
352 SetValueImpl (value, index - lb);
355 public void SetValue (object value, int index1, int index2)
357 int[] ind = {index1, index2};
358 SetValue (value, ind);
361 public void SetValue (object value, int index1, int index2, int index3)
363 int[] ind = {index1, index2, index3};
364 SetValue (value, ind);
367 internal static Array UnsafeCreateInstance(Type elementType, int[] lengths, int[] lowerBounds)
369 return CreateInstance(elementType, lengths, lowerBounds);
372 internal static Array UnsafeCreateInstance (Type elementType, int length1, int length2)
374 return CreateInstance (elementType, length1, length2);
377 internal static Array UnsafeCreateInstance (Type elementType, params int[] lengths)
379 return CreateInstance(elementType, lengths);
382 public static Array CreateInstance (Type elementType, int length)
384 int[] lengths = {length};
386 return CreateInstance (elementType, lengths);
389 public static Array CreateInstance (Type elementType, int length1, int length2)
391 int[] lengths = {length1, length2};
393 return CreateInstance (elementType, lengths);
396 public static Array CreateInstance (Type elementType, int length1, int length2, int length3)
398 int[] lengths = {length1, length2, length3};
400 return CreateInstance (elementType, lengths);
403 public static Array CreateInstance (Type elementType, params int[] lengths)
405 if (elementType == null)
406 throw new ArgumentNullException ("elementType");
408 throw new ArgumentNullException ("lengths");
410 if (lengths.Length > 255)
411 throw new TypeLoadException ();
415 elementType = elementType.UnderlyingSystemType as RuntimeType;
416 if (elementType == null)
417 throw new ArgumentException ("Type must be a type provided by the runtime.", "elementType");
418 if (elementType.Equals (typeof (void)))
419 throw new NotSupportedException ("Array type can not be void");
420 if (elementType.ContainsGenericParameters)
421 throw new NotSupportedException ("Array type can not be an open generic type");
423 return CreateInstanceImpl (elementType, lengths, bounds);
426 public static Array CreateInstance (Type elementType, int[] lengths, int [] lowerBounds)
428 if (elementType == null)
429 throw new ArgumentNullException ("elementType");
431 throw new ArgumentNullException ("lengths");
432 if (lowerBounds == null)
433 throw new ArgumentNullException ("lowerBounds");
435 elementType = elementType.UnderlyingSystemType as RuntimeType;
436 if (elementType == null)
437 throw new ArgumentException ("Type must be a type provided by the runtime.", "elementType");
438 if (elementType.Equals (typeof (void)))
439 throw new NotSupportedException ("Array type can not be void");
440 if (elementType.ContainsGenericParameters)
441 throw new NotSupportedException ("Array type can not be an open generic type");
443 if (lengths.Length < 1)
444 throw new ArgumentException (Locale.GetText ("Arrays must contain >= 1 elements."));
446 if (lengths.Length != lowerBounds.Length)
447 throw new ArgumentException (Locale.GetText ("Arrays must be of same size."));
449 for (int j = 0; j < lowerBounds.Length; j ++) {
451 throw new ArgumentOutOfRangeException ("lengths", Locale.GetText (
452 "Each value has to be >= 0."));
453 if ((long)lowerBounds [j] + (long)lengths [j] > (long)Int32.MaxValue)
454 throw new ArgumentOutOfRangeException ("lengths", Locale.GetText (
455 "Length + bound must not exceed Int32.MaxValue."));
458 if (lengths.Length > 255)
459 throw new TypeLoadException ();
461 return CreateInstanceImpl (elementType, lengths, lowerBounds);
464 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
465 public static void Clear (Array array, int index, int length)
468 throw new ArgumentNullException ("array");
470 throw new IndexOutOfRangeException ("length < 0");
472 int low = array.GetLowerBound (0);
474 throw new IndexOutOfRangeException ("index < lower bound");
477 // re-ordered to avoid possible integer overflow
478 if (index > array.Length - length)
479 throw new IndexOutOfRangeException ("index + length > size");
481 ClearInternal (array, index, length);
484 [MethodImplAttribute (MethodImplOptions.InternalCall)]
485 static extern void ClearInternal (Array a, int index, int count);
487 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
488 public static void Copy (Array sourceArray, Array destinationArray, int length)
490 // need these checks here because we are going to use
491 // GetLowerBound() on source and dest.
492 if (sourceArray == null)
493 throw new ArgumentNullException ("sourceArray");
495 if (destinationArray == null)
496 throw new ArgumentNullException ("destinationArray");
498 Copy (sourceArray, sourceArray.GetLowerBound (0), destinationArray,
499 destinationArray.GetLowerBound (0), length);
502 [ReliabilityContractAttribute (Consistency.MayCorruptInstance, Cer.MayFail)]
503 public static void Copy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
505 if (sourceArray == null)
506 throw new ArgumentNullException ("sourceArray");
508 if (destinationArray == null)
509 throw new ArgumentNullException ("destinationArray");
512 throw new ArgumentOutOfRangeException ("length", Locale.GetText (
513 "Value has to be >= 0."));;
515 if (sourceArray.Rank != destinationArray.Rank)
516 throw new RankException(SR.Rank_MultiDimNotSupported);
519 throw new ArgumentOutOfRangeException ("sourceIndex", Locale.GetText (
520 "Value has to be >= 0."));;
522 if (destinationIndex < 0)
523 throw new ArgumentOutOfRangeException ("destinationIndex", Locale.GetText (
524 "Value has to be >= 0."));;
526 if (FastCopy (sourceArray, sourceIndex, destinationArray, destinationIndex, length))
529 int source_pos = sourceIndex - sourceArray.GetLowerBound (0);
530 int dest_pos = destinationIndex - destinationArray.GetLowerBound (0);
533 throw new ArgumentOutOfRangeException ("destinationIndex", "Index was less than the array's lower bound in the first dimension.");
535 // re-ordered to avoid possible integer overflow
536 if (source_pos > sourceArray.Length - length)
537 throw new ArgumentException ("length");
539 if (dest_pos > destinationArray.Length - length) {
540 string msg = "Destination array was not long enough. Check " +
541 "destIndex and length, and the array's lower bounds";
542 throw new ArgumentException (msg, string.Empty);
545 Type src_type = sourceArray.GetType ().GetElementType ();
546 Type dst_type = destinationArray.GetType ().GetElementType ();
548 if (!Object.ReferenceEquals (sourceArray, destinationArray) || source_pos > dest_pos) {
549 for (int i = 0; i < length; i++) {
550 Object srcval = sourceArray.GetValueImpl (source_pos + i);
553 destinationArray.SetValueImpl (srcval, dest_pos + i);
554 } catch (ArgumentException) {
555 throw CreateArrayTypeMismatchException ();
557 if (CanAssignArrayElement (src_type, dst_type))
560 throw CreateArrayTypeMismatchException ();
565 for (int i = length - 1; i >= 0; i--) {
566 Object srcval = sourceArray.GetValueImpl (source_pos + i);
569 destinationArray.SetValueImpl (srcval, dest_pos + i);
570 } catch (ArgumentException) {
571 throw CreateArrayTypeMismatchException ();
573 if (CanAssignArrayElement (src_type, dst_type))
576 throw CreateArrayTypeMismatchException ();
582 static Exception CreateArrayTypeMismatchException ()
584 return new ArrayTypeMismatchException ();
587 static bool CanAssignArrayElement (Type source, Type target)
589 if (source.IsValueType)
590 return source.IsAssignableFrom (target);
592 if (source.IsInterface)
593 return !target.IsValueType;
595 if (target.IsInterface)
596 return !source.IsValueType;
598 return source.IsAssignableFrom (target) || target.IsAssignableFrom (source);
601 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
603 // The constrained copy should guarantee that if there is an exception thrown
604 // during the copy, the destination array remains unchanged.
605 // This is related to System.Runtime.Reliability.CER
606 public static void ConstrainedCopy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
608 Copy (sourceArray, sourceIndex, destinationArray, destinationIndex, length);
611 public static T[] Empty<T>()
613 return EmptyArray<T>.Value;
616 public void Initialize()
621 static int IndexOfImpl<T>(T[] array, T value, int startIndex, int count)
623 return EqualityComparer<T>.Default.IndexOf (array, value, startIndex, count);
626 static int LastIndexOfImpl<T>(T[] array, T value, int startIndex, int count)
628 return EqualityComparer<T>.Default.LastIndexOf (array, value, startIndex, count);
631 static void SortImpl (Array keys, Array items, int index, int length, IComparer comparer)
633 Object[] objKeys = keys as Object[];
634 Object[] objItems = null;
636 objItems = items as Object[];
638 if (objKeys != null && (items == null || objItems != null)) {
639 SorterObjectArray sorter = new SorterObjectArray(objKeys, objItems, comparer);
640 sorter.Sort(index, length);
642 SorterGenericArray sorter = new SorterGenericArray(keys, items, comparer);
643 sorter.Sort(index, length);
647 #region Unsafe array operations
650 // Loads array index with no safety checks (JIT intristics)
652 internal static T UnsafeLoad<T> (T[] array, int index) {
653 return array [index];
657 // Stores values at specified array index with no safety checks (JIT intristics)
659 internal static void UnsafeStore<T> (T[] array, int index, T value) {
660 array [index] = value;
664 // Moved value from instance into target of different type with no checks (JIT intristics)
668 // S and R must either:
669 // both be blitable valuetypes
670 // both be reference types (IOW, an unsafe cast)
671 // S and R cannot be float or double
672 // S and R must either:
675 // S and R must either:
677 // both be a scalar of size <= 4
679 internal static R UnsafeMov<S,R> (S instance) {
680 return (R)(object) instance;
685 internal sealed class FunctorComparer<T> : IComparer<T> {
686 Comparison<T> comparison;
688 public FunctorComparer(Comparison<T> comparison) {
689 this.comparison = comparison;
692 public int Compare(T x, T y) {
693 return comparison(x, y);
697 partial class ArrayEnumerator
699 public Object Current {
701 if (_index < 0) throw new InvalidOperationException (SR.InvalidOperation_EnumNotStarted);
702 if (_index >= _endIndex) throw new InvalidOperationException (SR.InvalidOperation_EnumEnded);
703 if (_index == 0 && _array.GetType ().GetElementType ().IsPointer) throw new NotSupportedException ("Type is not supported");
704 return _array.GetValueImpl(_index);