source: trunk/CrypPlugins/WorkspaceManager/View/VisualComponents/CryptoLineView/PowerCollections/CollectionBase.cs @ 1927

Last change on this file since 1927 was 1927, checked in by matkovic, 11 years ago

-added PowerCollection library
-added QuadTree
-improved path finding performance

File size: 16.8 KB
Line 
1//******************************
2// Written by Peter Golde
3// Copyright (c) 2004-2007, Wintellect
4//
5// Use and restribution of this code is subject to the license agreement
6// contained in the file "License.txt" accompanying this file.
7//******************************
8
9using System;
10using System.Collections;
11using System.Collections.Generic;
12using System.Diagnostics;
13
14namespace Wintellect.PowerCollections
15{
16    /// <summary>
17    /// CollectionBase is a base class that can be used to more easily implement the
18    /// generic ICollection&lt;T&gt; and non-generic ICollection interfaces.
19    /// </summary>
20    /// <remarks>
21    /// <para>To use CollectionBase as a base class, the derived class must override
22    /// the Count, GetEnumerator, Add, Clear, and Remove methods. </para>
23    /// <para>ICollection&lt;T&gt;.Contains need not be implemented by the
24    /// derived class, but it should be strongly considered, because the CollectionBase implementation
25    /// may not be very efficient.</para>
26    /// </remarks>
27    /// <typeparam name="T">The item type of the collection.</typeparam>
28    [Serializable]
29    [DebuggerDisplay("{DebuggerDisplayString()}")]
30    public abstract class CollectionBase<T> : ICollection<T>, ICollection
31    {
32
33        /// <summary>
34        /// Shows the string representation of the collection. The string representation contains
35        /// a list of the items in the collection. Contained collections (except string) are expanded
36        /// recursively.
37        /// </summary>
38        /// <returns>The string representation of the collection.</returns>
39        public override string ToString()
40        {
41            return Algorithms.ToString(this);
42        }
43
44
45        #region ICollection<T> Members
46
47        /// <summary>
48        /// Must be overridden to allow adding items to this collection.
49        /// </summary>
50        /// <remarks><p>This method is not abstract, although derived classes should always
51        /// override it. It is not abstract because some derived classes may wish to reimplement
52        /// Add with a different return type (typically bool). In C#, this can be accomplished
53        /// with code like the following:</p>
54        /// <code>
55        ///     public class MyCollection&lt;T&gt;: CollectionBase&lt;T&gt;, ICollection&lt;T&gt;
56        ///     {
57        ///         public new bool Add(T item) {
58        ///             /* Add the item */
59        ///         }
60        /// 
61        ///         void ICollection&lt;T&gt;.Add(T item) {
62        ///             Add(item);
63        ///         }
64        ///     }
65        /// </code>
66        /// </remarks>
67        /// <param name="item">Item to be added to the collection.</param>
68        /// <exception cref="NotImplementedException">Always throws this exception to indicated
69        /// that the method must be overridden or re-implemented in the derived class.</exception>
70        public virtual void Add(T item)
71        {
72            throw new NotImplementedException(Strings.MustOverrideOrReimplement);
73        }
74
75
76        /// <summary>
77        /// Must be overridden to allow clearing this collection.
78        /// </summary>
79        public abstract void Clear();
80
81        /// <summary>
82        /// Must be overridden to allow removing items from this collection.
83        /// </summary>
84        /// <returns>True if <paramref name="item"/> existed in the collection and
85        /// was removed. False if <paramref name="item"/> did not exist in the collection.</returns>
86        public abstract bool Remove(T item);
87
88        /// <summary>
89        /// Determines if the collection contains a particular item. This default implementation
90        /// iterates all of the items in the collection via GetEnumerator, testing each item
91        /// against <paramref name="item"/> using IComparable&lt;T&gt;.Equals or
92        /// Object.Equals.
93        /// </summary>
94        /// <remarks>You should strongly consider overriding this method to provide
95        /// a more efficient implementation, or if the default equality comparison
96        /// is inappropriate.</remarks>
97        /// <param name="item">The item to check for in the collection.</param>
98        /// <returns>True if the collection contains <paramref name="item"/>, false otherwise.</returns>
99        public virtual bool Contains(T item)
100        {
101            IEqualityComparer<T> equalityComparer = EqualityComparer<T>.Default;
102            foreach (T i in this) {
103                if (equalityComparer.Equals(i, item))
104                    return true;
105            }
106            return false;
107        }
108
109        /// <summary>
110        /// Copies all the items in the collection into an array. Implemented by
111        /// using the enumerator returned from GetEnumerator to get all the items
112        /// and copy them to the provided array.
113        /// </summary>
114        /// <param name="array">Array to copy to.</param>
115        /// <param name="arrayIndex">Starting index in <paramref name="array"/> to copy to.</param>
116        public virtual void CopyTo(T[] array, int arrayIndex)
117        {
118            int count = this.Count;
119
120            if (count == 0)
121                return;
122
123            if (array == null)
124                throw new ArgumentNullException("array");
125            if (count < 0)
126                throw new IndexOutOfRangeException(Strings.ArgMustNotBeNegative);
127            if (arrayIndex < 0)
128                throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, Strings.ArgMustNotBeNegative);
129            if (arrayIndex >= array.Length || count > array.Length - arrayIndex)
130                throw new ArgumentException("arrayIndex", Strings.ArrayTooSmall);
131
132            int index = arrayIndex, i = 0;
133            foreach (T item in this) {
134                if (i >= count)
135                    break;
136
137                array[index] = item;
138                ++index;
139                ++i;
140            }
141        }
142
143        /// <summary>
144        /// Creates an array of the correct size, and copies all the items in the
145        /// collection into the array, by calling CopyTo.
146        /// </summary>
147        /// <returns>An array containing all the elements in the collection, in order.</returns>
148        public virtual T[] ToArray()
149        {
150            int count = this.Count;
151
152            T[] array = new T[count];
153            CopyTo(array, 0);
154            return array;
155        }
156
157        /// <summary>
158        /// Must be overridden to provide the number of items in the collection.
159        /// </summary>
160        /// <value>The number of items in the collection.</value>
161        public abstract int Count { get; }
162
163        /// <summary>
164        /// Indicates whether the collection is read-only. Always returns false.
165        /// </summary>
166        /// <value>Always returns false.</value>
167        bool ICollection<T>.IsReadOnly
168        {
169            get { return false; }
170        }
171
172        /// <summary>
173        /// Provides a read-only view of this collection. The returned ICollection&lt;T&gt; provides
174        /// a view of the collection that prevents modifications to the collection. Use the method to provide
175        /// access to the collection without allowing changes. Since the returned object is just a view,
176        /// changes to the collection will be reflected in the view.
177        /// </summary>
178        /// <returns>An ICollection&lt;T&gt; that provides read-only access to the collection.</returns>
179        public virtual ICollection<T> AsReadOnly()
180        {
181            return Algorithms.ReadOnly(this);
182        }
183
184        #endregion
185
186        #region Delegate operations
187
188        /// <summary>
189        /// Determines if the collection contains any item that satisfies the condition
190        /// defined by <paramref name="predicate"/>.
191        /// </summary>
192        /// <param name="predicate">A delegate that defines the condition to check for.</param>
193        /// <returns>True if the collection contains one or more items that satisfy the condition
194        /// defined by <paramref name="predicate"/>. False if the collection does not contain
195        /// an item that satisfies <paramref name="predicate"/>.</returns>
196        public virtual bool Exists(Predicate<T> predicate)
197        {
198            if (predicate == null)
199                throw new ArgumentNullException("predicate");
200
201            return Algorithms.Exists(this, predicate);
202        }
203
204        /// <summary>
205        /// Determines if all of the items in the collection satisfy the condition
206        /// defined by <paramref name="predicate"/>.
207        /// </summary>
208        /// <param name="predicate">A delegate that defines the condition to check for.</param>
209        /// <returns>True if all of the items in the collection satisfy the condition
210        /// defined by <paramref name="predicate"/>, or if the collection is empty. False if one or more items
211        /// in the collection do not satisfy <paramref name="predicate"/>.</returns>
212        public virtual bool TrueForAll(Predicate<T> predicate)
213        {
214            if (predicate == null)
215                throw new ArgumentNullException("predicate");
216
217            return Algorithms.TrueForAll(this, predicate);
218        }
219
220        /// <summary>
221        /// Counts the number of items in the collection that satisfy the condition
222        /// defined by <paramref name="predicate"/>.
223        /// </summary>
224        /// <param name="predicate">A delegate that defines the condition to check for.</param>
225        /// <returns>The number of items in the collection that satisfy <paramref name="predicate"/>.</returns>
226        public virtual int CountWhere(Predicate<T> predicate)
227        {
228            if (predicate == null)
229                throw new ArgumentNullException("predicate");
230
231            return Algorithms.CountWhere(this, predicate);
232        }
233
234        /// <summary>
235        /// Enumerates the items in the collection that satisfy the condition defined
236        /// by <paramref name="predicate"/>.
237        /// </summary>
238        /// <param name="predicate">A delegate that defines the condition to check for.</param>
239        /// <returns>An IEnumerable&lt;T&gt; that enumerates the items that satisfy the condition.</returns>
240        public virtual IEnumerable<T> FindAll(Predicate<T> predicate)
241        {
242            if (predicate == null)
243                throw new ArgumentNullException("predicate");
244
245            return Algorithms.FindWhere(this, predicate);
246        }
247
248        /// <summary>
249        /// Removes all the items in the collection that satisfy the condition
250        /// defined by <paramref name="predicate"/>.
251        /// </summary>
252        /// <param name="predicate">A delegate that defines the condition to check for.</param>
253        /// <returns>Returns a collection of the items that were removed, in sorted order.</returns>
254        public virtual ICollection<T> RemoveAll(Predicate<T> predicate)
255        {
256            if (predicate == null)
257                throw new ArgumentNullException("predicate");
258
259            return Algorithms.RemoveWhere(this, predicate);
260        }
261
262        /// <summary>
263        /// Performs the specified action on each item in this collection.
264        /// </summary>
265        /// <param name="action">An Action delegate which is invoked for each item in this collection.</param>
266        public virtual void ForEach(Action<T> action)
267        {
268            if (action == null)
269                throw new ArgumentNullException("action");
270
271            Algorithms.ForEach(this, action);
272        }
273
274        /// <summary>
275        /// Convert this collection of items by applying a delegate to each item in the collection. The resulting enumeration
276        /// contains the result of applying <paramref name="converter"/> to each item in this collection, in
277        /// order.
278        /// </summary>
279        /// <typeparam name="TOutput">The type each item is being converted to.</typeparam>
280        /// <param name="converter">A delegate to the method to call, passing each item in this collection.</param>
281        /// <returns>An IEnumerable&lt;TOutput^gt; that enumerates the resulting collection from applying <paramref name="converter"/> to each item in this collection in
282        /// order.</returns>
283        /// <exception cref="ArgumentNullException"><paramref name="converter"/> is null.</exception>
284        public virtual IEnumerable<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter)
285        {
286            if (converter == null)
287                throw new ArgumentNullException("converter");
288
289            return Algorithms.Convert(this, converter);
290        }
291
292        #endregion
293
294        #region IEnumerable<T> Members
295
296        /// <summary>
297        /// Must be overridden to enumerate all the members of the collection.
298        /// </summary>
299        /// <returns>A generic IEnumerator&lt;T&gt; that can be used
300        /// to enumerate all the items in the collection.</returns>
301        public abstract IEnumerator<T> GetEnumerator();
302
303        #endregion
304
305        #region ICollection Members
306
307        /// <summary>
308        /// Copies all the items in the collection into an array. Implemented by
309        /// using the enumerator returned from GetEnumerator to get all the items
310        /// and copy them to the provided array.
311        /// </summary>
312        /// <param name="array">Array to copy to.</param>
313        /// <param name="index">Starting index in <paramref name="array"/> to copy to.</param>
314        void ICollection.CopyTo(Array array, int index)
315        {
316            int count = this.Count;
317
318            if (count == 0)
319                return;
320
321            if (array == null)
322                throw new ArgumentNullException("array");
323            if (index < 0)
324                throw new ArgumentOutOfRangeException("index", index, Strings.ArgMustNotBeNegative);
325            if (index >= array.Length || count > array.Length - index)
326                throw new ArgumentException("index", Strings.ArrayTooSmall);
327
328            int i = 0;
329            //TODO: Look into this
330            foreach (object o in (ICollection) this) {
331                if (i >= count)
332                    break;
333
334                array.SetValue(o, index);
335                ++index;
336                ++i;
337            }
338        }
339
340        /// <summary>
341        /// Indicates whether the collection is synchronized.
342        /// </summary>
343        /// <value>Always returns false, indicating that the collection is not synchronized.</value>
344        bool ICollection.IsSynchronized
345        {
346            get { return false; }
347        }
348
349        /// <summary>
350        /// Indicates the synchronization object for this collection.
351        /// </summary>
352        /// <value>Always returns this.</value>
353        object ICollection.SyncRoot
354        {
355            get { return this; }
356        }
357
358        #endregion
359
360        #region IEnumerable Members
361
362        /// <summary>
363        /// Provides an IEnumerator that can be used to iterate all the members of the
364        /// collection. This implementation uses the IEnumerator&lt;T&gt; that was overridden
365        /// by the derived classes to enumerate the members of the collection.
366        /// </summary>
367        /// <returns>An IEnumerator that can be used to iterate the collection.</returns>
368        IEnumerator IEnumerable.GetEnumerator()
369        {
370            foreach (T item in this) {
371                yield return item;
372            }
373        }
374
375        #endregion
376
377        /// <summary>
378        /// Display the contents of the collection in the debugger. This is intentionally private, it is called
379        /// only from the debugger due to the presence of the DebuggerDisplay attribute. It is similar
380        /// format to ToString(), but is limited to 250-300 characters or so, so as not to overload the debugger.
381        /// </summary>
382        /// <returns>The string representation of the items in the collection, similar in format to ToString().</returns>
383        internal string DebuggerDisplayString()
384        {
385            const int MAXLENGTH = 250;
386
387            System.Text.StringBuilder builder = new System.Text.StringBuilder();
388
389            builder.Append('{');
390
391            // Call ToString on each item and put it in.
392            bool firstItem = true;
393            foreach (T item in this) {
394                if (builder.Length >= MAXLENGTH) {
395                    builder.Append(",...");
396                    break;
397                }
398
399                if (!firstItem)
400                    builder.Append(',');
401
402                if (item == null)
403                    builder.Append("null");
404                else
405                    builder.Append(item.ToString());
406
407                firstItem = false;
408            }
409
410            builder.Append('}');
411            return builder.ToString();
412        }
413
414    }
415}
Note: See TracBrowser for help on using the repository browser.