2 // System.Collections.Generic.List
5 // Ben Maurer (bmaurer@ximian.com)
6 // Martin Baulig (martin@ximian.com)
7 // Carlos Alberto Cortez (calberto.cortez@gmail.com)
8 // David Waite (mass@akuma.org)
10 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
11 // Copyright (C) 2005 David Waite
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Collections.ObjectModel;
36 using System.Runtime.InteropServices;
38 namespace System.Collections.Generic {
40 public class List <T> : IList <T>, IList, ICollection {
45 static readonly T [] EmptyArray = new T [0];
46 const int DefaultCapacity = 4;
53 public List (IEnumerable <T> collection)
55 CheckCollection (collection);
57 // initialize to needed size (if determinable)
58 ICollection <T> c = collection as ICollection <T>;
62 AddEnumerable (collection);
66 _items = new T [c.Count];
71 public List (int capacity)
74 throw new ArgumentOutOfRangeException ("capacity");
75 _items = new T [capacity];
78 internal List (T [] data, int size)
83 public void Add (T item)
86 _items [_size ++] = item;
90 void GrowIfNeeded (int newCount)
92 int minimumSize = _size + newCount;
93 if (minimumSize > _items.Length)
94 Capacity = Math.Max (Math.Max (Capacity * 2, DefaultCapacity), minimumSize);
97 void CheckRange (int idx, int count)
100 throw new ArgumentOutOfRangeException ("index");
103 throw new ArgumentOutOfRangeException ("count");
105 if ((uint) idx + (uint) count > (uint) _size)
106 throw new ArgumentException ("index and count exceed length of list");
109 void AddCollection (ICollection <T> collection)
111 int collectionCount = collection.Count;
112 GrowIfNeeded (collectionCount);
113 collection.CopyTo (_items, _size);
114 _size += collectionCount;
116 void AddEnumerable (IEnumerable <T> enumerable)
118 foreach (T t in enumerable)
124 public void AddRange (IEnumerable <T> collection)
126 CheckCollection (collection);
128 ICollection <T> c = collection as ICollection <T>;
132 AddEnumerable (collection);
136 public ReadOnlyCollection <T> AsReadOnly ()
138 return new ReadOnlyCollection <T> (this);
141 public int BinarySearch (T item)
143 return Array.BinarySearch <T> (_items, 0, _size, item);
146 public int BinarySearch (T item, IComparer <T> comparer)
148 return Array.BinarySearch <T> (_items, 0, _size, item, comparer);
151 public int BinarySearch (int index, int count, T item, IComparer <T> comparer)
153 CheckRange (index, count);
154 return Array.BinarySearch <T> (_items, index, count, item, comparer);
159 Array.Clear (_items, 0, _items.Length);
164 public bool Contains (T item)
166 EqualityComparer<T> equalityComparer = EqualityComparer<T>.Default;
167 for (int i = 0; i < _size; i++)
168 if (equalityComparer.Equals (_items[i], item))
173 public List <TOutput> ConvertAll <TOutput> (Converter <T, TOutput> converter)
175 if (converter == null)
176 throw new ArgumentNullException ("converter");
177 List <TOutput> u = new List <TOutput> (_size);
178 foreach (T t in this)
179 u.Add (converter (t));
183 public void CopyTo (T [] array)
185 Array.Copy (_items, 0, array, 0, _size);
188 public void CopyTo (T [] array, int arrayIndex)
190 Array.Copy (_items, 0, array, arrayIndex, _size);
193 public void CopyTo (int index, T [] array, int arrayIndex, int count)
195 CheckRange (index, count);
196 Array.Copy (_items, index, array, arrayIndex, count);
199 public bool Exists (Predicate <T> match)
201 return FindIndex (match) != -1;
204 public T Find (Predicate <T> match)
206 int i = FindIndex (match);
207 return (i != -1) ? _items [i] : default (T);
209 void CheckMatch (Predicate <T> match)
212 throw new ArgumentNullException ("match");
215 // Maybe we could make this faster. For example, you could
216 // make a bit set with stackalloc for which elements to copy
217 // then you could size the array correctly.
218 public List <T> FindAll (Predicate <T> match)
221 List <T> f = new List <T> ();
223 foreach (T t in this)
230 public int FindIndex (Predicate <T> match)
233 return GetIndex (0, _size, match);
236 public int FindIndex (int startIndex, Predicate <T> match)
239 CheckIndex (startIndex);
240 return GetIndex (startIndex, _size - startIndex, match);
242 public int FindIndex (int startIndex, int count, Predicate <T> match)
245 CheckRange (startIndex, count);
246 return GetIndex (startIndex, count, match);
248 int GetIndex (int startIndex, int count, Predicate <T> match)
250 for (int i = startIndex; i < startIndex + count; i ++)
251 if (match (_items [i]))
257 public T FindLast (Predicate <T> match)
260 int i = GetLastIndex (0, _size, match);
261 return i == -1 ? default (T) : this [i];
264 public int FindLastIndex (Predicate <T> match)
267 return GetLastIndex (0, _size, match);
270 public int FindLastIndex (int startIndex, Predicate <T> match)
273 CheckIndex (startIndex);
274 return GetLastIndex (0, startIndex + 1, match);
277 public int FindLastIndex (int startIndex, int count, Predicate <T> match)
280 int start = startIndex - count + 1;
281 CheckRange (start, count);
282 return GetLastIndex (start, count, match);
285 int GetLastIndex (int startIndex, int count, Predicate <T> match)
287 // unlike FindLastIndex, takes regular params for search range
288 for (int i = startIndex + count; i != startIndex;)
289 if (match (_items [--i]))
294 public void ForEach (Action <T> action)
297 throw new ArgumentNullException ("action");
298 foreach (T t in this)
302 public Enumerator GetEnumerator ()
304 return new Enumerator (this);
307 public List <T> GetRange (int index, int count)
309 CheckRange (index, count);
310 T [] tmpArray = new T [count];
311 Array.Copy (_items, index, tmpArray, 0, count);
312 return new List <T> (tmpArray, count);
315 public int IndexOf (T item)
317 return Array.IndexOf<T> (_items, item, 0, _size);
320 public int IndexOf (T item, int index)
323 return Array.IndexOf<T> (_items, item, index, _size - index);
326 public int IndexOf (T item, int index, int count)
329 throw new ArgumentOutOfRangeException ("index");
332 throw new ArgumentOutOfRangeException ("count");
334 if ((uint) index + (uint) count > (uint) _size)
335 throw new ArgumentOutOfRangeException ("index and count exceed length of list");
337 return Array.IndexOf<T> (_items, item, index, count);
340 void Shift (int start, int delta)
345 Array.Copy (_items, start, _items, start + delta, _size - start);
350 void CheckIndex (int index)
352 if (index < 0 || (uint) index > (uint) _size)
353 throw new ArgumentOutOfRangeException ("index");
356 public void Insert (int index, T item)
365 void CheckCollection (IEnumerable <T> collection)
367 if (collection == null)
368 throw new ArgumentNullException ("collection");
371 public void InsertRange (int index, IEnumerable <T> collection)
373 CheckCollection (collection);
375 if (collection == this) {
376 T[] buffer = new T[_size];
378 GrowIfNeeded (_size);
379 Shift (index, buffer.Length);
380 Array.Copy (buffer, 0, _items, index, buffer.Length);
382 ICollection <T> c = collection as ICollection <T>;
384 InsertCollection (index, c);
386 InsertEnumeration (index, collection);
391 void InsertCollection (int index, ICollection <T> collection)
393 int collectionCount = collection.Count;
394 GrowIfNeeded (collectionCount);
396 Shift (index, collectionCount);
397 collection.CopyTo (_items, index);
399 void InsertEnumeration (int index, IEnumerable <T> enumerable)
401 foreach (T t in enumerable)
405 public int LastIndexOf (T item)
407 return Array.LastIndexOf<T> (_items, item, _size - 1, _size);
410 public int LastIndexOf (T item, int index)
413 return Array.LastIndexOf<T> (_items, item, index, index + 1);
416 public int LastIndexOf (T item, int index, int count)
419 throw new ArgumentOutOfRangeException ("index", index, "index is negative");
422 throw new ArgumentOutOfRangeException ("count", count, "count is negative");
424 if (index - count + 1 < 0)
425 throw new ArgumentOutOfRangeException ("cound", count, "count is too large");
427 return Array.LastIndexOf<T> (_items, item, index, count);
430 public bool Remove (T item)
432 int loc = IndexOf (item);
439 // FIXME: this could probably be made faster.
440 public int RemoveAll (Predicate <T> match)
446 while ((index = GetIndex (index, _size - index, match)) != -1) {
451 Array.Clear (_items, _size, c);
455 public void RemoveAt (int index)
459 Array.Clear (_items, _size, 0);
463 public void RemoveRange (int index, int count)
465 CheckRange (index, count);
467 Shift (index, -count);
468 Array.Clear (_items, _size, count);
473 public void Reverse ()
475 Array.Reverse (_items, 0, _size);
478 public void Reverse (int index, int count)
480 CheckRange (index, count);
481 Array.Reverse (_items, index, count);
487 Array.Sort<T> (_items, 0, _size, Comparer <T>.Default);
490 public void Sort (IComparer <T> comparer)
492 Array.Sort<T> (_items, 0, _size, comparer);
496 public void Sort (Comparison <T> comparison)
498 Array.Sort<T> (_items, _size, comparison);
502 public void Sort (int index, int count, IComparer <T> comparer)
504 CheckRange (index, count);
505 Array.Sort<T> (_items, index, count, comparer);
509 public T [] ToArray ()
511 T [] t = new T [_size];
512 Array.Copy (_items, t, _size);
517 public void TrimExcess ()
522 public bool TrueForAll (Predicate <T> match)
526 foreach (T t in this)
533 public int Capacity {
535 return _items.Length;
538 if ((uint) value < (uint) _size)
539 throw new ArgumentOutOfRangeException ();
541 Array.Resize (ref _items, value);
546 get { return _size; }
549 public T this [int index] {
551 if ((uint) index >= (uint) _size)
552 throw new ArgumentOutOfRangeException ("index");
553 return _items [index];
557 if ((uint) index == (uint) _size)
558 throw new ArgumentOutOfRangeException ("index");
559 _items [index] = value;
563 #region Interface implementations.
564 IEnumerator <T> IEnumerable <T>.GetEnumerator ()
566 return GetEnumerator ();
569 void ICollection.CopyTo (Array array, int arrayIndex)
571 Array.Copy (_items, 0, array, arrayIndex, _size);
574 IEnumerator IEnumerable.GetEnumerator ()
576 return GetEnumerator ();
579 int IList.Add (object item)
583 } catch (InvalidCastException) {
584 throw new ArgumentException("item");
589 bool IList.Contains (object item)
592 return Contains ((T) item);
593 } catch (InvalidCastException) {
598 int IList.IndexOf (object item)
601 return IndexOf((T) item);
602 } catch (InvalidCastException) {
607 void IList.Insert (int index, object item)
609 // We need to check this first because, even if the
610 // item is null or not the correct type, we need to
611 // return an ArgumentOutOfRange exception if the
612 // index is out of range
615 Insert (index, (T) item);
616 } catch (InvalidCastException) {
617 throw new ArgumentException("item");
621 void IList.Remove (object item)
625 } catch (InvalidCastException) {
626 // Swallow the exception--if we
627 // can't cast to the correct type
628 // then we've already "succeeded"
629 // in removing the item from the
634 bool ICollection <T>.IsReadOnly {
635 get { return false; }
637 bool ICollection.IsSynchronized {
638 get { return false; }
641 object ICollection.SyncRoot {
644 bool IList.IsFixedSize {
645 get { return false; }
648 bool IList.IsReadOnly {
649 get { return false; }
652 object IList.this [int index] {
653 get { return this [index]; }
654 set { this [index] = (T) value; }
659 public struct Enumerator : IEnumerator <T>, IDisposable {
660 const int NOT_STARTED = -2;
662 // this MUST be -1, because we depend on it in move next.
663 // we just decr the size, so, 0 - 1 == FINISHED
664 const int FINISHED = -1;
670 internal Enumerator (List <T> l)
677 // for some fucked up reason, MSFT added a useless dispose to this class
678 // It means that in foreach, we must still do a try/finally. Broken, very
680 public void Dispose ()
685 public bool MoveNext ()
687 if (ver != l._version)
688 throw new InvalidOperationException ("Collection was modified;"
689 + "enumeration operation may not execute.");
691 if (idx == NOT_STARTED)
694 return idx != FINISHED && -- idx != FINISHED;
700 throw new InvalidOperationException ();
702 return l._items [l._size - 1 - idx];
706 void IEnumerator.Reset ()
708 if (ver != l._version)
709 throw new InvalidOperationException ("Collection was modified;"
710 + "enumeration operation may not execute.");
715 object IEnumerator.Current {
716 get { return Current; }