Merge pull request #439 from mono-soc-2012/garyb/iconfix
[mono.git] / mcs / class / System / System.Collections.Specialized / NameObjectCollectionBase.cs
1 //
2 // System.Collections.Specialized.NameObjectCollectionBase.cs
3 //
4 // Author:
5 //   Gleb Novodran
6 //   Andreas Nahr (ClassDevelopment@A-SoftTech.com)
7 //
8 // (C) Ximian, Inc.  http://www.ximian.com
9 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System;
32 using System.Collections;
33 using System.Runtime.Serialization;
34
35 namespace System.Collections.Specialized
36 {
37         [Serializable]
38         public abstract class NameObjectCollectionBase : ICollection, IEnumerable, ISerializable, IDeserializationCallback
39         {
40                 private Hashtable m_ItemsContainer;
41                 /// <summary>
42                 /// Extends Hashtable based Items container to support storing null-key pairs
43                 /// </summary>
44                 private _Item m_NullKeyItem;
45                 private ArrayList m_ItemsArray;
46                 private IHashCodeProvider m_hashprovider;
47                 private IComparer m_comparer;
48                 private int m_defCapacity;
49                 private bool m_readonly;
50                 SerializationInfo infoCopy;
51                 private KeysCollection keyscoll;
52                 private IEqualityComparer equality_comparer;
53
54                 internal IEqualityComparer EqualityComparer {
55                         get { return equality_comparer; }
56                 }
57
58                 internal IComparer Comparer {
59                         get {return m_comparer;}
60                 }
61
62                 internal IHashCodeProvider HashCodeProvider {
63                         get {return m_hashprovider;}
64                 }
65
66                 internal class _Item
67                 {
68                         public string key;
69                         public object value;
70                         public _Item(string key, object value)
71                         {
72                                 this.key = key;
73                                 this.value = value;
74                         }
75                 }               
76                 /// <summary>
77                 /// Implements IEnumerable interface for KeysCollection
78                 /// </summary>
79                 [Serializable]
80                 internal class _KeysEnumerator : IEnumerator
81                 {
82                         private NameObjectCollectionBase m_collection;
83                         private int m_position;
84
85                         internal _KeysEnumerator(NameObjectCollectionBase collection)
86                         {
87                                 m_collection = collection;
88                                 Reset();
89                         }
90                         public object Current 
91                         {
92                                 
93                                 get{
94                                         if ((m_position<m_collection.Count)||(m_position<0))
95                                                 return m_collection.BaseGetKey(m_position);
96                                         else 
97                                                 throw new InvalidOperationException();
98                                 }
99                                 
100                         }
101                         public bool MoveNext()
102                         {
103                                 return ((++m_position) < m_collection.Count);
104                         }
105                         public void Reset()
106                         {
107                                 m_position = -1;
108                         }
109                 }
110                 
111                 /// <summary>
112                 /// SDK: Represents a collection of the String keys of a collection.
113                 /// </summary>
114                 [Serializable]
115                 public class KeysCollection : ICollection, IEnumerable
116                 {
117                         private NameObjectCollectionBase m_collection;
118
119                         internal KeysCollection (NameObjectCollectionBase collection)
120                         {
121                                 this.m_collection = collection;
122                         }
123
124                         public virtual string Get( int index )
125                         {
126                                 return m_collection.BaseGetKey(index);
127                         }
128                         
129                         // ICollection methods -----------------------------------
130                         void ICollection.CopyTo (Array array, int arrayIndex)
131                         {
132                                 ArrayList items = m_collection.m_ItemsArray;
133                                 if (null == array)
134                                         throw new ArgumentNullException ("array");
135
136                                 if (arrayIndex < 0)
137                                         throw new ArgumentOutOfRangeException ("arrayIndex");
138
139                                 if ((array.Length > 0) && (arrayIndex >= array.Length))
140                                         throw new ArgumentException ("arrayIndex is equal to or greater than array.Length");
141
142                                 if (arrayIndex + items.Count > array.Length)
143                                         throw new ArgumentException ("Not enough room from arrayIndex to end of array for this KeysCollection");
144
145                                 if (array != null && array.Rank > 1)
146                                         throw new ArgumentException ("array is multidimensional");
147                                 
148                                 object[] objArray = (object[])array;
149                                 for (int i = 0; i < items.Count; i++, arrayIndex++)
150                                         objArray [arrayIndex] = ((_Item)items [i]).key;
151                         }
152
153                         bool ICollection.IsSynchronized
154                         {
155                                 get{
156                                         return false;
157                                 }
158                         }
159                         object ICollection.SyncRoot
160                         {
161                                 get{
162                                         return m_collection;
163                                 }
164                         }
165                         /// <summary>
166                         /// Gets the number of keys in the NameObjectCollectionBase.KeysCollection
167                         /// </summary>
168                         public int Count 
169                         {
170                                 get{
171                                         return m_collection.Count;
172                                 }
173                         }
174
175                         public string this [int index] {
176                                 get { return Get (index); }
177                         }
178
179                         // IEnumerable methods --------------------------------
180                         /// <summary>
181                         /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.KeysCollection.
182                         /// </summary>
183                         /// <returns></returns>
184                         public IEnumerator GetEnumerator()
185                         {
186                                 return new _KeysEnumerator(m_collection);
187                         }
188                 }
189
190                 //--------------- Protected Instance Constructors --------------
191                 
192                 /// <summary>
193                 /// SDK: Initializes a new instance of the NameObjectCollectionBase class that is empty.
194                 /// </summary>
195                 protected NameObjectCollectionBase ()
196                 {
197                         m_readonly = false;
198                         m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
199                         m_comparer = CaseInsensitiveComparer.DefaultInvariant;
200                         m_defCapacity = 0;
201                         Init();
202                 }
203                 
204                 protected NameObjectCollectionBase( int capacity )
205                 {
206                         m_readonly = false;
207                         m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
208                         m_comparer = CaseInsensitiveComparer.DefaultInvariant;
209                         m_defCapacity = capacity;
210                         Init();
211                 }               
212
213                 internal NameObjectCollectionBase (IEqualityComparer equalityComparer, IComparer comparer, IHashCodeProvider hcp)
214                 {
215                         equality_comparer = equalityComparer;
216                         m_comparer = comparer;
217                         m_hashprovider = hcp;
218                         m_readonly = false;
219                         m_defCapacity = 0;
220                         Init ();
221                 }
222
223                 protected NameObjectCollectionBase (IEqualityComparer equalityComparer) : this( (equalityComparer == null ? StringComparer.InvariantCultureIgnoreCase : equalityComparer), null, null)
224                 {                       
225                 }               
226
227                 [Obsolete ("Use NameObjectCollectionBase(IEqualityComparer)")]
228                 protected NameObjectCollectionBase( IHashCodeProvider hashProvider, IComparer comparer )
229                 {                       
230                         m_comparer = comparer;
231                         m_hashprovider = hashProvider;
232                         m_readonly = false;
233                         m_defCapacity = 0;
234                         Init ();
235                 }
236
237                 protected NameObjectCollectionBase (SerializationInfo info, StreamingContext context)
238                 {
239                         infoCopy = info;
240                 }
241
242                 protected NameObjectCollectionBase (int capacity, IEqualityComparer equalityComparer)
243                 {
244                         m_readonly = false;
245                         equality_comparer = (equalityComparer == null ? StringComparer.InvariantCultureIgnoreCase : equalityComparer);
246                         m_defCapacity = capacity;
247                         Init();
248                 }
249
250                 [Obsolete ("Use NameObjectCollectionBase(int,IEqualityComparer)")]
251                 protected NameObjectCollectionBase( int capacity, IHashCodeProvider hashProvider, IComparer comparer )
252                 {
253                         m_readonly = false;
254                         
255                         m_hashprovider = hashProvider;
256                         m_comparer = comparer;
257                         m_defCapacity = capacity;
258                         Init();
259                 }
260                 
261                 private void Init ()
262                 {
263                         if (m_ItemsContainer != null) {
264                                 m_ItemsContainer.Clear ();
265                                 m_ItemsContainer = null;
266                         }
267                         
268                         if (m_ItemsArray != null) {
269                                 m_ItemsArray.Clear ();
270                                 m_ItemsArray = null;
271                         }
272                         if (equality_comparer != null)
273                                 m_ItemsContainer = new Hashtable (m_defCapacity, equality_comparer);
274                         else
275                                 m_ItemsContainer = new Hashtable (m_defCapacity, m_hashprovider, m_comparer);
276                         m_ItemsArray = new ArrayList();
277                         m_NullKeyItem = null;   
278                 }
279
280                 //--------------- Public Instance Properties -------------------
281
282                 public virtual NameObjectCollectionBase.KeysCollection Keys {
283                         get {
284                                 if (keyscoll == null)
285                                         keyscoll = new KeysCollection (this);
286                                 return keyscoll;
287                         }
288                 }
289                                 
290                 //--------------- Public Instance Methods ----------------------
291                 // 
292                 /// <summary>
293                 /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.
294                 /// 
295                 /// <remark>This enumerator returns the keys of the collection as strings.</remark>
296                 /// </summary>
297                 /// <returns></returns>
298                 public virtual IEnumerator GetEnumerator()
299                 {
300                         return new _KeysEnumerator(this);
301                 }
302
303                 // ISerializable
304                 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
305                 {
306                         if (info == null)
307                                 throw new ArgumentNullException ("info");
308
309                         int count = Count;
310                         string [] keys = new string [count];
311                         object [] values = new object [count];
312                         int i = 0;
313                         foreach (_Item item in m_ItemsArray) {
314                                 keys [i] = item.key;
315                                 values [i] = item.value;
316                                 i++;
317                         }
318
319                         if (equality_comparer != null) {
320                                 info.AddValue ("KeyComparer", equality_comparer, typeof (IEqualityComparer));
321                                 info.AddValue ("Version", 4, typeof (int));
322                         } else {
323                                 info.AddValue ("HashProvider", m_hashprovider, typeof (IHashCodeProvider));
324                                 info.AddValue ("Comparer", m_comparer, typeof (IComparer));
325                                 info.AddValue ("Version", 2, typeof (int));
326                         }
327                         info.AddValue("ReadOnly", m_readonly);
328                         info.AddValue("Count", count);
329                         info.AddValue("Keys", keys, typeof(string[]));
330                         info.AddValue("Values", values, typeof(object[]));
331                 }
332
333                 // ICollection
334                 public virtual int Count 
335                 {
336                         get{
337                                 return m_ItemsArray.Count;
338                         }
339                 }
340
341                 bool ICollection.IsSynchronized
342                 {
343                         get { return false; }
344                 }
345
346                 object ICollection.SyncRoot
347                 {
348                         get { return this; }
349                 }
350
351                 void ICollection.CopyTo (Array array, int index)
352                 {
353                         ((ICollection)Keys).CopyTo (array, index);
354                 }
355
356                 // IDeserializationCallback
357                 public virtual void OnDeserialization (object sender)
358                 {
359                         SerializationInfo info = infoCopy;
360                         
361                         // If a subclass overrides the serialization constructor
362                         // and inplements its own serialization process, infoCopy will
363                         // be null and we can ignore this callback.
364                         if (info == null)
365                                 return;
366
367                         infoCopy = null;
368                         m_hashprovider = (IHashCodeProvider) info.GetValue ("HashProvider",
369                                                                             typeof (IHashCodeProvider));
370                         if (m_hashprovider == null) {
371                                 equality_comparer = (IEqualityComparer) info.GetValue ("KeyComparer", typeof (IEqualityComparer));
372                         } else {
373                                 m_comparer = (IComparer) info.GetValue ("Comparer", typeof (IComparer));
374                                 if (m_comparer == null)
375                                         throw new SerializationException ("The comparer is null");
376                         }
377                         m_readonly = info.GetBoolean ("ReadOnly");
378                         string [] keys = (string []) info.GetValue ("Keys", typeof (string []));
379                         if (keys == null)
380                                 throw new SerializationException ("keys is null");
381
382                         object [] values = (object []) info.GetValue ("Values", typeof (object []));
383                         if (values == null)
384                                 throw new SerializationException ("values is null");
385
386                         Init ();
387                         int count = keys.Length;
388                         for (int i = 0; i < count; i++)
389                                 BaseAdd (keys [i], values [i]);
390                 }
391
392                 //--------------- Protected Instance Properties ----------------
393                 /// <summary>
394                 /// SDK: Gets or sets a value indicating whether the NameObjectCollectionBase instance is read-only.
395                 /// </summary>
396                 protected bool IsReadOnly 
397                 {
398                         get{
399                                 return m_readonly;
400                         }
401                         set{
402                                 m_readonly=value;
403                         }
404                 }
405                 
406                 //--------------- Protected Instance Methods -------------------
407                 /// <summary>
408                 /// Adds an Item with the specified key and value into the <see cref="NameObjectCollectionBase"/>NameObjectCollectionBase instance.
409                 /// </summary>
410                 /// <param name="name"></param>
411                 /// <param name="value"></param>
412                 protected void BaseAdd( string name, object value )
413                 {
414                         if (this.IsReadOnly)
415                                 throw new NotSupportedException("Collection is read-only");
416                         
417                         _Item newitem=new _Item(name, value);
418
419                         if (name==null){
420                                 //todo: consider nullkey entry
421                                 if (m_NullKeyItem==null)
422                                         m_NullKeyItem = newitem;
423                         }
424                         else
425                                 if (m_ItemsContainer[name]==null){
426                                         m_ItemsContainer.Add(name,newitem);
427                                 }
428                         m_ItemsArray.Add(newitem);
429                 }
430
431                 protected void BaseClear()
432                 {
433                         if (this.IsReadOnly)
434                                 throw new NotSupportedException("Collection is read-only");
435                         Init();
436                 }
437
438                 /// <summary>
439                 /// SDK: Gets the value of the entry at the specified index of the NameObjectCollectionBase instance.
440                 /// </summary>
441                 /// <param name="index"></param>
442                 /// <returns></returns>
443                 protected object BaseGet( int index )
444                 {
445                         return ((_Item)m_ItemsArray[index]).value;
446                 }
447
448                 /// <summary>
449                 /// SDK: Gets the value of the first entry with the specified key from the NameObjectCollectionBase instance.
450                 /// </summary>
451                 /// <remark>CAUTION: The BaseGet method does not distinguish between a null reference which is returned because the specified key is not found and a null reference which is returned because the value associated with the key is a null reference.</remark>
452                 /// <param name="name"></param>
453                 /// <returns></returns>
454                 protected object BaseGet( string name )
455                 {
456                         _Item item = FindFirstMatchedItem(name);
457                         /// CAUTION: The BaseGet method does not distinguish between a null reference which is returned because the specified key is not found and a null reference which is returned because the value associated with the key is a null reference.
458                         if (item==null)
459                                 return null;
460                         else
461                                 return item.value;
462                 }
463
464                 /// <summary>
465                 /// SDK:Returns a String array that contains all the keys in the NameObjectCollectionBase instance.
466                 /// </summary>
467                 /// <returns>A String array that contains all the keys in the NameObjectCollectionBase instance.</returns>
468                 protected string[] BaseGetAllKeys()
469                 {
470                         int cnt = m_ItemsArray.Count;
471                         string[] allKeys = new string[cnt];
472                         for(int i=0; i<cnt; i++)
473                                 allKeys[i] = BaseGetKey(i);//((_Item)m_ItemsArray[i]).key;
474                         
475                         return allKeys;
476                 }
477
478                 /// <summary>
479                 /// SDK: Returns an Object array that contains all the values in the NameObjectCollectionBase instance.
480                 /// </summary>
481                 /// <returns>An Object array that contains all the values in the NameObjectCollectionBase instance.</returns>
482                 protected object[] BaseGetAllValues()
483                 {
484                         int cnt = m_ItemsArray.Count;
485                         object[] allValues = new object[cnt];
486                         for(int i=0; i<cnt; i++)
487                                 allValues[i] = BaseGet(i);
488                         
489                         return allValues;
490                 }
491
492                 protected object[] BaseGetAllValues( Type type )
493                 {
494                         if (type == null)
495                                 throw new ArgumentNullException("'type' argument can't be null");
496                         int cnt = m_ItemsArray.Count;
497                         object[] allValues = (object[]) Array.CreateInstance (type, cnt);
498                         for(int i=0; i<cnt; i++)
499                                 allValues[i] = BaseGet(i);
500                         
501                         return allValues;
502                 }
503                 
504                 protected string BaseGetKey( int index )
505                 {
506                         return ((_Item)m_ItemsArray[index]).key;
507                 }
508
509                 /// <summary>
510                 /// Gets a value indicating whether the NameObjectCollectionBase instance contains entries whose keys are not a null reference 
511                 /// </summary>
512                 /// <returns>true if the NameObjectCollectionBase instance contains entries whose keys are not a null reference otherwise, false.</returns>
513                 protected bool BaseHasKeys()
514                 {
515                         return (m_ItemsContainer.Count>0);
516                 }
517
518                 protected void BaseRemove( string name )
519                 {
520                         int cnt = 0;
521                         String key;
522                         if (this.IsReadOnly)
523                                 throw new NotSupportedException("Collection is read-only");
524                         if (name!=null)
525                         {
526                                 m_ItemsContainer.Remove(name);
527                         }
528                         else {
529                                 m_NullKeyItem = null;
530                         }
531                         
532                         cnt = m_ItemsArray.Count;
533                         for (int i=0 ; i< cnt; ){
534                                 key=BaseGetKey(i);
535                                 if (Equals (key, name)) {
536                                         m_ItemsArray.RemoveAt(i);
537                                         cnt--;
538                                 }
539                                 else 
540                                         i++;
541                         }
542                 }
543
544                 /// <summary>
545                 /// 
546                 /// </summary>
547                 /// <param name="index"></param>
548                 /// <LAME>This function implemented the way Microsoft implemented it - 
549                 /// item is removed from hashtable and array without considering the case when there are two items with the same key but different values in array.
550                 /// E.g. if
551                 /// hashtable is [("Key1","value1")] and array contains [("Key1","value1")("Key1","value2")] then
552                 /// after RemoveAt(1) the collection will be in following state:
553                 /// hashtable:[] 
554                 /// array: [("Key1","value1")] 
555                 /// It's ok only then the key is uniquely assosiated with the value
556                 /// To fix it a comparsion of objects stored under the same key in the hashtable and in the arraylist should be added 
557                 /// </LAME>>
558                 protected void BaseRemoveAt( int index )
559                 {
560                         if (this.IsReadOnly)
561                                 throw new NotSupportedException("Collection is read-only");
562                         string key = BaseGetKey(index);
563                         if (key!=null){
564                                 // TODO: see LAME description above
565                                 m_ItemsContainer.Remove(key);
566                         }
567                         else
568                                 m_NullKeyItem = null;
569                         m_ItemsArray.RemoveAt(index);
570                 }
571
572                 /// <summary>
573                 /// SDK: Sets the value of the entry at the specified index of the NameObjectCollectionBase instance.
574                 /// </summary>
575                 /// <param name="index"></param>
576                 /// <param name="value"></param>
577                 protected void BaseSet( int index, object value )
578                 {
579                         if (this.IsReadOnly)
580                                 throw new NotSupportedException("Collection is read-only");
581                         _Item item = (_Item)m_ItemsArray[index];
582                         item.value = value;
583                 }
584
585                 /// <summary>
586                 /// Sets the value of the first entry with the specified key in the NameObjectCollectionBase instance, if found; otherwise, adds an entry with the specified key and value into the NameObjectCollectionBase instance.
587                 /// </summary>
588                 /// <param name="name">The String key of the entry to set. The key can be a null reference </param>
589                 /// <param name="value">The Object that represents the new value of the entry to set. The value can be a null reference</param>
590                 protected void BaseSet( string name, object value )
591                 {
592                         if (this.IsReadOnly)
593                                 throw new NotSupportedException("Collection is read-only");
594                         _Item item = FindFirstMatchedItem(name);
595                         if (item!=null)
596                                 item.value=value;
597                         else 
598                                 BaseAdd(name, value);
599                 }
600
601                 [MonoTODO]
602                 private _Item FindFirstMatchedItem(string name)
603                 {
604                         if (name!=null)
605                                 return (_Item)m_ItemsContainer[name];
606                         else {
607                                 //TODO: consider null key case
608                                 return m_NullKeyItem;
609                         }
610                 }
611
612                 internal bool Equals (string s1, string s2)
613                 {
614                         if (m_comparer != null)
615                                 return (m_comparer.Compare (s1, s2) == 0);
616                         else
617                                 return equality_comparer.Equals (s1, s2);
618                 }
619         }
620 }