New test.
[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 #if NET_2_0
53                 private IEqualityComparer equality_comparer;
54
55                 internal IEqualityComparer EqualityComparer {
56                         get { return equality_comparer; }
57                 }
58 #endif
59                 internal IComparer Comparer {
60                         get {return m_comparer;}
61                 }
62
63                 internal IHashCodeProvider HashCodeProvider {
64                         get {return m_hashprovider;}
65                 }
66
67                 internal class _Item
68                 {
69                         public string key;
70                         public object value;
71                         public _Item(string key, object value)
72                         {
73                                 this.key = key;
74                                 this.value = value;
75                         }
76                 }               
77                 /// <summary>
78                 /// Implements IEnumerable interface for KeysCollection
79                 /// </summary>
80                 [Serializable]
81                 internal class _KeysEnumerator : IEnumerator
82                 {
83                         private NameObjectCollectionBase m_collection;
84                         private int m_position;
85
86                         internal _KeysEnumerator(NameObjectCollectionBase collection)
87                         {
88                                 m_collection = collection;
89                                 Reset();
90                         }
91                         public object Current 
92                         {
93                                 
94                                 get{
95                                         if ((m_position<m_collection.Count)||(m_position<0))
96                                                 return m_collection.BaseGetKey(m_position);
97                                         else 
98                                                 throw new InvalidOperationException();
99                                 }
100                                 
101                         }
102                         public bool MoveNext()
103                         {
104                                 return ((++m_position)<m_collection.Count)?true:false;
105                         }
106                         public void Reset()
107                         {
108                                 m_position = -1;
109                         }
110                 }
111                 
112                 /// <summary>
113                 /// SDK: Represents a collection of the String keys of a collection.
114                 /// </summary>
115                 [Serializable]
116                 public class KeysCollection : ICollection, IEnumerable
117                 {
118                         private NameObjectCollectionBase m_collection;
119
120                         internal KeysCollection (NameObjectCollectionBase collection)
121                         {
122                                 this.m_collection = collection;
123                         }
124
125                         public virtual string Get( int index )
126                         {
127                                 return m_collection.BaseGetKey(index);
128                         }
129                         
130                         // ICollection methods -----------------------------------
131                         void ICollection.CopyTo(Array arr, int index)
132                         {
133                                 if (arr==null)
134                                         throw new ArgumentNullException("array can't be null");
135                                 IEnumerator en = this.GetEnumerator();
136                                 int i = index;
137                                 while (en.MoveNext())
138                                 {
139                                         arr.SetValue(en.Current,i);
140                                         i++;
141                                 }                       
142                         }
143
144                         bool ICollection.IsSynchronized
145                         {
146                                 get{
147                                         return false;
148                                 }
149                         }
150                         object ICollection.SyncRoot
151                         {
152                                 get{
153                                         return m_collection;
154                                 }
155                         }
156                         /// <summary>
157                         /// Gets the number of keys in the NameObjectCollectionBase.KeysCollection
158                         /// </summary>
159                         public int Count 
160                         {
161                                 get{
162                                         return m_collection.Count;
163                                 }
164                         }
165
166                         public string this [int index] {
167                                 get { return Get (index); }
168                         }
169
170                         // IEnumerable methods --------------------------------
171                         /// <summary>
172                         /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.KeysCollection.
173                         /// </summary>
174                         /// <returns></returns>
175                         public IEnumerator GetEnumerator()
176                         {
177                                 return new _KeysEnumerator(m_collection);
178                         }
179                 }
180
181                 //--------------- Protected Instance Constructors --------------
182                 
183                 /// <summary>
184                 /// SDK: Initializes a new instance of the NameObjectCollectionBase class that is empty.
185                 /// </summary>
186                 protected NameObjectCollectionBase ()
187                 {
188                         m_readonly = false;
189 #if NET_1_0
190                         m_hashprovider = CaseInsensitiveHashCodeProvider.Default;
191                         m_comparer = CaseInsensitiveComparer.Default;
192 #else
193                         m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
194                         m_comparer = CaseInsensitiveComparer.DefaultInvariant;
195 #endif
196                         m_defCapacity = 0;
197                         Init();
198                 }
199                 
200                 protected NameObjectCollectionBase( int capacity )
201                 {
202                         m_readonly = false;
203 #if NET_1_0
204                         m_hashprovider = CaseInsensitiveHashCodeProvider.Default;
205                         m_comparer = CaseInsensitiveComparer.Default;
206 #else
207                         m_hashprovider = CaseInsensitiveHashCodeProvider.DefaultInvariant;
208                         m_comparer = CaseInsensitiveComparer.DefaultInvariant;
209 #endif
210                         m_defCapacity = capacity;
211                         Init();
212                 }
213
214 #if NET_2_0
215                 protected NameObjectCollectionBase (IEqualityComparer equalityComparer)
216                 {
217                         m_readonly = false;
218                         equality_comparer = equalityComparer;
219                         m_defCapacity = 0;
220                         Init();
221                 }
222
223                 [Obsolete ("Use NameObjectCollectionBase(IEqualityComparer)")]
224 #endif
225                 protected NameObjectCollectionBase( IHashCodeProvider hashProvider, IComparer comparer )
226                 {
227                         m_readonly = false;
228                         
229                         m_hashprovider = hashProvider;
230                         m_comparer = comparer;
231                         m_defCapacity = 0;
232                         Init();
233                 }
234
235                 protected NameObjectCollectionBase (SerializationInfo info, StreamingContext context)
236                 {
237                         infoCopy = info;
238                 }
239
240 #if NET_2_0
241                 protected NameObjectCollectionBase (int capacity, IEqualityComparer equalityComparer)
242                 {
243                         m_readonly = false;
244                         equality_comparer = equalityComparer;
245                         m_defCapacity = capacity;
246                         Init();
247                 }
248
249                 [Obsolete ("Use NameObjectCollectionBase(int,IEqualityComparer)")]
250 #endif
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 NET_2_0
264                         if (equality_comparer != null)
265                                 m_ItemsContainer = new Hashtable (m_defCapacity, equality_comparer);
266                         else
267                                 m_ItemsContainer = new Hashtable (m_defCapacity, m_hashprovider, m_comparer);
268 #else
269                         m_ItemsContainer = new Hashtable (m_defCapacity, m_hashprovider, m_comparer);
270 #endif
271                         m_ItemsArray = new ArrayList();
272                         m_NullKeyItem = null;   
273                 }
274
275                 //--------------- Public Instance Properties -------------------
276
277                 public virtual NameObjectCollectionBase.KeysCollection Keys {
278                         get {
279                                 if (keyscoll == null)
280                                         keyscoll = new KeysCollection (this);
281                                 return keyscoll;
282                         }
283                 }
284                                 
285                 //--------------- Public Instance Methods ----------------------
286                 // 
287                 /// <summary>
288                 /// SDK: Returns an enumerator that can iterate through the NameObjectCollectionBase.
289                 /// 
290                 /// <remark>This enumerator returns the keys of the collection as strings.</remark>
291                 /// </summary>
292                 /// <returns></returns>
293                 public
294 #if NET_2_0             
295                 virtual
296 #endif
297                 IEnumerator GetEnumerator()
298                 {
299                         return new _KeysEnumerator(this);
300                 }
301
302                 // ISerializable
303                 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
304                 {
305                         if (info == null)
306                                 throw new ArgumentNullException ("info");
307
308                         int count = Count;
309                         string [] keys = new string [count];
310                         object [] values = new object [count];
311                         int i = 0;
312                         foreach (_Item item in m_ItemsArray) {
313                                 keys [i] = item.key;
314                                 values [i] = item.value;
315                                 i++;
316                         }
317
318 #if NET_2_0
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 #else
328                         info.AddValue ("HashProvider", m_hashprovider, typeof (IHashCodeProvider));
329                         info.AddValue ("Comparer", m_comparer, typeof (IComparer));
330 #endif
331                         info.AddValue("ReadOnly", m_readonly);
332                         info.AddValue("Count", count);
333                         info.AddValue("Keys", keys, typeof(string[]));
334                         info.AddValue("Values", values, typeof(object[]));
335                 }
336
337                 // ICollection
338                 public virtual int Count 
339                 {
340                         get{
341                                 return m_ItemsArray.Count;
342                         }
343                 }
344
345                 bool ICollection.IsSynchronized
346                 {
347                         get { return false; }
348                 }
349
350                 object ICollection.SyncRoot
351                 {
352                         get { return this; }
353                 }
354
355                 void ICollection.CopyTo (Array array, int index)
356                 {
357                         (Keys as ICollection).CopyTo (array, index);
358                 }
359
360                 // IDeserializationCallback
361                 public virtual void OnDeserialization (object sender)
362                 {
363                         SerializationInfo info = infoCopy;
364                         
365                         // If a subclass overrides the serialization constructor
366                         // and inplements its own serialization process, infoCopy will
367                         // be null and we can ignore this callback.
368                         if (info == null)
369                                 return;
370
371                         infoCopy = null;
372                         m_hashprovider = (IHashCodeProvider) info.GetValue ("HashProvider",
373                                                                             typeof (IHashCodeProvider));
374 #if NET_2_0
375                         if (m_hashprovider == null) {
376                                 equality_comparer = (IEqualityComparer) info.GetValue ("KeyComparer", typeof (IEqualityComparer));
377                         } else {
378                                 m_comparer = (IComparer) info.GetValue ("Comparer", typeof (IComparer));
379                                 if (m_comparer == null)
380                                         throw new SerializationException ("The comparer is null");
381                         }
382 #else
383                         if (m_hashprovider == null)
384                                 throw new SerializationException ("The hash provider is null");
385
386                         m_comparer = (IComparer) info.GetValue ("Comparer", typeof (IComparer));
387                         if (m_comparer == null)
388                                 throw new SerializationException ("The comparer is null");
389 #endif
390                         m_readonly = info.GetBoolean ("ReadOnly");
391                         string [] keys = (string []) info.GetValue ("Keys", typeof (string []));
392                         if (keys == null)
393                                 throw new SerializationException ("keys is null");
394
395                         object [] values = (object []) info.GetValue ("Values", typeof (object []));
396                         if (values == null)
397                                 throw new SerializationException ("values is null");
398
399                         Init ();
400                         int count = keys.Length;
401                         for (int i = 0; i < count; i++)
402                                 BaseAdd (keys [i], values [i]);
403                 }
404
405                 //--------------- Protected Instance Properties ----------------
406                 /// <summary>
407                 /// SDK: Gets or sets a value indicating whether the NameObjectCollectionBase instance is read-only.
408                 /// </summary>
409                 protected bool IsReadOnly 
410                 {
411                         get{
412                                 return m_readonly;
413                         }
414                         set{
415                                 m_readonly=value;
416                         }
417                 }
418                 
419                 //--------------- Protected Instance Methods -------------------
420                 /// <summary>
421                 /// Adds an Item with the specified key and value into the <see cref="NameObjectCollectionBase"/>NameObjectCollectionBase instance.
422                 /// </summary>
423                 /// <param name="name"></param>
424                 /// <param name="value"></param>
425                 protected void BaseAdd( string name, object value )
426                 {
427                         if (this.IsReadOnly)
428                                 throw new NotSupportedException("Collection is read-only");
429                         
430                         _Item newitem=new _Item(name, value);
431
432                         if (name==null){
433                                 //todo: consider nullkey entry
434                                 if (m_NullKeyItem==null)
435                                         m_NullKeyItem = newitem;
436                         }
437                         else
438                                 if (m_ItemsContainer[name]==null){
439                                         m_ItemsContainer.Add(name,newitem);
440                                 }
441                         m_ItemsArray.Add(newitem);
442                 }
443
444                 protected void BaseClear()
445                 {
446                         if (this.IsReadOnly)
447                                 throw new NotSupportedException("Collection is read-only");
448                         Init();
449                 }
450
451                 /// <summary>
452                 /// SDK: Gets the value of the entry at the specified index of the NameObjectCollectionBase instance.
453                 /// </summary>
454                 /// <param name="index"></param>
455                 /// <returns></returns>
456                 protected object BaseGet( int index )
457                 {
458                         return ((_Item)m_ItemsArray[index]).value;
459                 }
460
461                 /// <summary>
462                 /// SDK: Gets the value of the first entry with the specified key from the NameObjectCollectionBase instance.
463                 /// </summary>
464                 /// <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>
465                 /// <param name="name"></param>
466                 /// <returns></returns>
467                 protected object BaseGet( string name )
468                 {
469                         _Item item = FindFirstMatchedItem(name);
470                         /// 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.
471                         if (item==null)
472                                 return null;
473                         else
474                                 return item.value;
475                 }
476
477                 /// <summary>
478                 /// SDK:Returns a String array that contains all the keys in the NameObjectCollectionBase instance.
479                 /// </summary>
480                 /// <returns>A String array that contains all the keys in the NameObjectCollectionBase instance.</returns>
481                 protected string[] BaseGetAllKeys()
482                 {
483                         int cnt = m_ItemsArray.Count;
484                         string[] allKeys = new string[cnt];
485                         for(int i=0; i<cnt; i++)
486                                 allKeys[i] = BaseGetKey(i);//((_Item)m_ItemsArray[i]).key;
487                         
488                         return allKeys;
489                 }
490
491                 /// <summary>
492                 /// SDK: Returns an Object array that contains all the values in the NameObjectCollectionBase instance.
493                 /// </summary>
494                 /// <returns>An Object array that contains all the values in the NameObjectCollectionBase instance.</returns>
495                 protected object[] BaseGetAllValues()
496                 {
497                         int cnt = m_ItemsArray.Count;
498                         object[] allValues = new object[cnt];
499                         for(int i=0; i<cnt; i++)
500                                 allValues[i] = BaseGet(i);
501                         
502                         return allValues;
503                 }
504
505                 protected object[] BaseGetAllValues( Type type )
506                 {
507                         if (type == null)
508                                 throw new ArgumentNullException("'type' argument can't be null");
509                         int cnt = m_ItemsArray.Count;
510                         object[] allValues = (object[]) Array.CreateInstance (type, cnt);
511                         for(int i=0; i<cnt; i++)
512                                 allValues[i] = BaseGet(i);
513                         
514                         return allValues;
515                 }
516                 
517                 protected string BaseGetKey( int index )
518                 {
519                         return ((_Item)m_ItemsArray[index]).key;
520                 }
521
522                 /// <summary>
523                 /// Gets a value indicating whether the NameObjectCollectionBase instance contains entries whose keys are not a null reference 
524                 /// </summary>
525                 /// <returns>true if the NameObjectCollectionBase instance contains entries whose keys are not a null reference otherwise, false.</returns>
526                 protected bool BaseHasKeys()
527                 {
528                         return (m_ItemsContainer.Count>0);
529                 }
530
531                 protected void BaseRemove( string name )
532                 {
533                         int cnt = 0;
534                         String key;
535                         if (this.IsReadOnly)
536                                 throw new NotSupportedException("Collection is read-only");
537                         if (name!=null)
538                         {
539                                 m_ItemsContainer.Remove(name);
540                         }
541                         else {
542                                 m_NullKeyItem = null;
543                         }
544                         
545                         cnt = m_ItemsArray.Count;
546                         for (int i=0 ; i< cnt; ){
547                                 key=BaseGetKey(i);
548                                 if (Equals (key, name)) {
549                                         m_ItemsArray.RemoveAt(i);
550                                         cnt--;
551                                 }
552                                 else 
553                                         i++;
554                         }
555                 }
556
557                 /// <summary>
558                 /// 
559                 /// </summary>
560                 /// <param name="index"></param>
561                 /// <LAME>This function implemented the way Microsoft implemented it - 
562                 /// 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.
563                 /// E.g. if
564                 /// hashtable is [("Key1","value1")] and array contains [("Key1","value1")("Key1","value2")] then
565                 /// after RemoveAt(1) the collection will be in following state:
566                 /// hashtable:[] 
567                 /// array: [("Key1","value1")] 
568                 /// It's ok only then the key is uniquely assosiated with the value
569                 /// To fix it a comparsion of objects stored under the same key in the hashtable and in the arraylist should be added 
570                 /// </LAME>>
571                 [MonoTODO]
572                 protected void BaseRemoveAt( int index )
573                 {
574                         if (this.IsReadOnly)
575                                 throw new NotSupportedException("Collection is read-only");
576                         string key = BaseGetKey(index);
577                         if (key!=null){
578                                 // TODO: see LAME description above
579                                 m_ItemsContainer.Remove(key);
580                         }
581                         else
582                                 m_NullKeyItem = null;
583                         m_ItemsArray.RemoveAt(index);
584                 }
585
586                 /// <summary>
587                 /// SDK: Sets the value of the entry at the specified index of the NameObjectCollectionBase instance.
588                 /// </summary>
589                 /// <param name="index"></param>
590                 /// <param name="value"></param>
591                 protected void BaseSet( int index, object value )
592                 {
593                         if (this.IsReadOnly)
594                                 throw new NotSupportedException("Collection is read-only");
595                         _Item item = (_Item)m_ItemsArray[index];
596                         item.value = value;
597                 }
598
599                 /// <summary>
600                 /// 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.
601                 /// </summary>
602                 /// <param name="name">The String key of the entry to set. The key can be a null reference </param>
603                 /// <param name="value">The Object that represents the new value of the entry to set. The value can be a null reference</param>
604                 protected void BaseSet( string name, object value )
605                 {
606                         if (this.IsReadOnly)
607                                 throw new NotSupportedException("Collection is read-only");
608                         _Item item = FindFirstMatchedItem(name);
609                         if (item!=null)
610                                 item.value=value;
611                         else 
612                                 BaseAdd(name, value);
613                 }
614
615                 [MonoTODO]
616                 private _Item FindFirstMatchedItem(string name)
617                 {
618                         if (name!=null)
619                                 return (_Item)m_ItemsContainer[name];
620                         else {
621                                 //TODO: consider null key case
622                                 return m_NullKeyItem;
623                         }
624                 }
625
626                 internal bool Equals (string s1, string s2)
627                 {
628 #if NET_2_0
629                         if (m_comparer != null)
630                                 return (m_comparer.Compare (s1, s2) == 0);
631                         else
632                                 return equality_comparer.Equals (s1, s2);
633 #else
634                         return (m_comparer.Compare (s1, s2) == 0);
635 #endif
636                 }
637         }
638 }