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