2 // System.Collections.Hashtable.cs
5 // Sergey Chaban (serge@wildwestsoftware.com)
9 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
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:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
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.
32 using System.Collections;
33 using System.Runtime.Serialization;
35 namespace System.Collections {
38 public class Hashtable : IDictionary, ICollection,
39 IEnumerable, ICloneable, ISerializable, IDeserializationCallback
43 internal struct Slot {
46 internal Object value;
48 // Hashcode. Chains are also marked through this.
53 internal class KeyMarker: IObjectReference
55 public readonly static KeyMarker Removed = new KeyMarker();
56 public object GetRealObject (StreamingContext context)
57 { return KeyMarker.Removed; }
64 const int CHAIN_MARKER = ~Int32.MaxValue;
68 private int modificationCount;
69 private float loadFactor;
70 private Slot [] table;
71 private int threshold;
73 private HashKeys hashKeys;
74 private HashValues hashValues;
76 private IHashCodeProvider hcpRef;
77 private IComparer comparerRef;
78 private SerializationInfo serializationInfo;
80 private static readonly int [] primeTbl = {
121 public Hashtable () : this (0, 1.0f) {}
124 public Hashtable (int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer) {
126 throw new ArgumentOutOfRangeException ("capacity", "negative capacity");
128 if (loadFactor < 0.1f || loadFactor > 1.0f || Single.IsNaN (loadFactor))
129 throw new ArgumentOutOfRangeException ("loadFactor", "load factor");
131 if (capacity == 0) ++capacity;
132 this.loadFactor = 0.75f*loadFactor;
133 double tableSize = capacity / this.loadFactor;
135 if (tableSize > Int32.MaxValue)
136 throw new ArgumentException ("Size is too big");
138 int size = (int) tableSize;
139 size = ToPrime (size);
140 this.SetTable (new Slot [size]);
143 this.comparer = comparer;
146 this.modificationCount = 0;
150 public Hashtable (int capacity, float loadFactor) :
151 this (capacity, loadFactor, null, null)
155 public Hashtable (int capacity) : this (capacity, 1.0f)
159 public Hashtable (int capacity,
160 IHashCodeProvider hcp,
162 : this (capacity, 1.0f, hcp, comparer)
167 public Hashtable (IDictionary d, float loadFactor,
168 IHashCodeProvider hcp, IComparer comparer)
169 : this (d!=null ? d.Count : 0,
170 loadFactor, hcp, comparer)
174 throw new ArgumentNullException ("dictionary");
176 IDictionaryEnumerator it = d.GetEnumerator ();
177 while (it.MoveNext ()) {
178 Add (it.Key, it.Value);
183 public Hashtable (IDictionary d, float loadFactor)
184 : this (d, loadFactor, null, null)
189 public Hashtable (IDictionary d) : this (d, 1.0f)
193 public Hashtable (IDictionary d, IHashCodeProvider hcp, IComparer comparer)
194 : this (d, 1.0f, hcp, comparer)
198 public Hashtable (IHashCodeProvider hcp, IComparer comparer)
199 : this (1, 1.0f, hcp, comparer)
203 protected Hashtable (SerializationInfo info, StreamingContext context)
205 serializationInfo = info;
212 protected IComparer comparer {
221 protected IHashCodeProvider hcp {
232 public virtual int Count {
238 public virtual bool IsSynchronized {
244 public virtual Object SyncRoot {
254 public virtual bool IsFixedSize {
261 public virtual bool IsReadOnly {
267 public virtual ICollection Keys {
269 if (this.hashKeys == null)
270 this.hashKeys = new HashKeys (this);
271 return this.hashKeys;
275 public virtual ICollection Values {
277 if (this.hashValues == null)
278 this.hashValues = new HashValues (this);
279 return this.hashValues;
285 public virtual Object this [Object key] {
290 return table [i].value;
295 PutImpl (key, value, true);
309 IEnumerator IEnumerable.GetEnumerator ()
311 return new Enumerator (this, EnumeratorMode.ENTRY_MODE);
316 public virtual void CopyTo (Array array, int arrayIndex)
319 throw new ArgumentNullException ("array");
322 throw new ArgumentOutOfRangeException ("arrayIndex");
325 throw new ArgumentException ("array is multidimensional");
327 if ((array.Length > 0) && (arrayIndex >= array.Length))
328 throw new ArgumentException ("arrayIndex is equal to or greater than array.Length");
330 if (arrayIndex + this.inUse > array.Length)
331 throw new ArgumentException ("Not enough room from arrayIndex to end of array for this Hashtable");
333 IDictionaryEnumerator it = GetEnumerator ();
336 while (it.MoveNext ()) {
337 array.SetValue (it.Entry, i++);
344 public virtual void Add (Object key, Object value)
346 PutImpl (key, value, false);
349 public virtual void Clear ()
351 for (int i = 0;i<table.Length;i++) {
352 table [i].key = null;
353 table [i].value = null;
354 table [i].hashMix = 0;
361 public virtual bool Contains (Object key)
363 return (Find (key) >= 0);
366 public virtual IDictionaryEnumerator GetEnumerator ()
368 return new Enumerator (this, EnumeratorMode.ENTRY_MODE);
371 public virtual void Remove (Object key)
375 Slot [] table = this.table;
376 int h = table [i].hashMix;
378 table [i].hashMix = h;
379 table [i].key = (h != 0)
382 table [i].value = null;
388 public virtual bool ContainsKey (object key)
390 return Contains (key);
393 public virtual bool ContainsValue (object value)
395 int size = this.table.Length;
396 Slot [] table = this.table;
398 for (int i = 0; i < size; i++) {
399 Slot entry = table [i];
400 if (entry.key != null && entry.key!= KeyMarker.Removed
401 && entry.value == null) {
406 for (int i = 0; i < size; i++) {
407 Slot entry = table [i];
408 if (entry.key != null && entry.key!= KeyMarker.Removed
409 && value.Equals (entry.value)) {
420 public virtual object Clone ()
422 Hashtable ht = new Hashtable (Count, hcp, comparer);
424 ht.loadFactor = this.loadFactor;
426 // FIXME: maybe it's faster to simply
427 // copy the back-end array?
429 IDictionaryEnumerator it = GetEnumerator ();
430 while (it.MoveNext ()) {
431 ht [it.Key] = it.Value;
437 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
440 throw new ArgumentNullException ("info");
442 info.AddValue ("LoadFactor", loadFactor);
443 info.AddValue ("Version", modificationCount);
444 info.AddValue ("Comparer", comparerRef);
445 info.AddValue ("HashCodeProvider", hcpRef);
446 info.AddValue ("HashSize", this.table.Length);
448 Object [] keys = new Object[inUse];
449 CopyToArray(keys, 0, EnumeratorMode.KEY_MODE);
452 Object [] values = new Object[inUse];
453 CopyToArray(values, 0, EnumeratorMode.VALUE_MODE);
455 info.AddValue ("Keys", keys);
456 info.AddValue ("Values", values);
460 public virtual void OnDeserialization (object sender)
462 if (serializationInfo == null) return;
464 loadFactor = (float) serializationInfo.GetValue ("LoadFactor", typeof(float));
465 modificationCount = (int) serializationInfo.GetValue ("Version", typeof(int));
466 comparerRef = (IComparer) serializationInfo.GetValue ("Comparer", typeof (object));
467 hcpRef = (IHashCodeProvider) serializationInfo.GetValue ("HashCodeProvider", typeof (object));
468 int size = (int) serializationInfo.GetValue ("HashSize", typeof(int));
470 Object [] keys = (Object []) serializationInfo.GetValue("Keys", typeof(Object [] ));
471 Object [] values = (Object []) serializationInfo.GetValue("Values", typeof(Object [] ));
473 if (keys.Length != values.Length)
474 throw new SerializationException("Keys and values of uneven size");
476 size = ToPrime (size);
477 this.SetTable (new Slot [size]);
479 for(int i=0;i<keys.Length;i++)
480 Add(keys[i], values[i]);
484 serializationInfo = null;
488 /// Returns a synchronized (thread-safe)
489 /// wrapper for the Hashtable.
491 public static Hashtable Synchronized (Hashtable table)
494 throw new ArgumentNullException("table");
495 return new SyncHashtable (table);
501 // Protected instance methods
504 /// <summary>Returns the hash code for the specified key.</summary>
505 protected virtual int GetHash (Object key)
508 return key.GetHashCode ();
510 return hcpRef.GetHashCode (key);
514 /// Compares a specific Object with a specific key
515 /// in the Hashtable.
517 protected virtual bool KeyEquals (Object item, Object key)
519 if (comparerRef == null)
520 return item.Equals (key);
522 return comparerRef.Compare (item, key) == 0;
528 // Private instance methods
531 private void AdjustThreshold ()
533 int size = table.Length;
535 threshold = (int) (size*loadFactor);
536 if (this.threshold >= size)
540 private void SetTable (Slot [] table)
543 throw new ArgumentNullException ("table");
549 private int Find (Object key)
552 throw new ArgumentNullException ("key", "null key");
554 Slot [] table = this.table;
555 uint size = (uint) table.Length;
556 int h = this.GetHash (key) & Int32.MaxValue;
558 uint step = (uint) ((h >> 5)+1) % (size-1)+1;
561 for (uint i = size; i > 0; i--) {
563 Slot entry = table [indx];
564 Object k = entry.key;
567 if (k == key || ((entry.hashMix & Int32.MaxValue) == h
568 && this.KeyEquals (key, k))) {
572 if ((entry.hashMix & CHAIN_MARKER) == 0)
581 private void Rehash ()
583 int oldSize = this.table.Length;
585 // From the SDK docs:
586 // Hashtable is automatically increased
587 // to the smallest prime number that is larger
588 // than twice the current number of Hashtable buckets
589 uint newSize = (uint)ToPrime ((oldSize<<1)|1);
592 Slot [] newTable = new Slot [newSize];
593 Slot [] table = this.table;
595 for (int i = 0;i<oldSize;i++) {
598 int h = s.hashMix & Int32.MaxValue;
600 uint step = ((uint) (h>>5)+1)% (newSize-1)+1;
601 for (uint j = spot%newSize;;spot+= step, j = spot%newSize) {
602 // No check for KeyMarker.Removed here,
603 // because the table is just allocated.
604 if (newTable [j].key == null) {
605 newTable [j].key = s.key;
606 newTable [j].value = s.value;
607 newTable [j].hashMix |= h;
610 newTable [j].hashMix |= CHAIN_MARKER;
616 ++this.modificationCount;
618 this.SetTable (newTable);
622 private void PutImpl (Object key, Object value, bool overwrite)
625 throw new ArgumentNullException ("key", "null key");
627 uint size = (uint)this.table.Length;
628 if (this.inUse >= this.threshold) {
630 size = (uint)this.table.Length;
633 int h = this.GetHash (key) & Int32.MaxValue;
635 uint step = (uint) ((spot>>5)+1)% (size-1)+1;
636 Slot [] table = this.table;
640 for (int i = 0; i < size; i++) {
641 int indx = (int) (spot % size);
642 entry = table [indx];
645 && entry.key == KeyMarker.Removed
646 && (entry.hashMix & CHAIN_MARKER) != 0)
649 if (entry.key == null ||
650 (entry.key == KeyMarker.Removed
651 && (entry.hashMix & CHAIN_MARKER) == 0)) {
658 if ((entry.hashMix & Int32.MaxValue) == h && KeyEquals (key, entry.key)) {
660 table [indx].value = value;
661 ++this.modificationCount;
664 // An entry with the same key already exists in the Hashtable.
665 throw new ArgumentException (
666 "Key duplication when adding: " + key);
671 if (freeIndx == -1) {
672 table [indx].hashMix |= CHAIN_MARKER;
680 table [freeIndx].key = key;
681 table [freeIndx].value = value;
682 table [freeIndx].hashMix |= h;
685 ++this.modificationCount;
690 private void CopyToArray (Array arr, int i,
693 IEnumerator it = new Enumerator (this, mode);
695 while (it.MoveNext ()) {
696 arr.SetValue (it.Current, i++);
703 // Private static methods
705 private static bool TestPrime (int x)
708 for (int n = 3; n< (int)Math.Sqrt (x); n += 2) {
714 // There is only one even prime - 2.
718 private static int CalcPrime (int x)
720 for (int i = (x & (~1))-1; i< Int32.MaxValue; i += 2) {
721 if (TestPrime (i)) return i;
726 private static int ToPrime (int x)
728 for (int i = 0; i < primeTbl.Length; i++) {
729 if (x <= primeTbl [i])
732 return CalcPrime (x);
742 private enum EnumeratorMode : int {KEY_MODE = 0, VALUE_MODE, ENTRY_MODE};
744 private sealed class Enumerator : IDictionaryEnumerator, IEnumerator {
746 private Hashtable host;
750 private EnumeratorMode mode;
752 private Object currentKey;
753 private Object currentValue;
755 private readonly static string xstr = "Hashtable.Enumerator: snapshot out of sync.";
757 public Enumerator (Hashtable host, EnumeratorMode mode) {
759 stamp = host.modificationCount;
760 size = host.table.Length;
765 public Enumerator (Hashtable host)
766 : this (host, EnumeratorMode.KEY_MODE) {}
769 private void FailFast ()
771 if (host.modificationCount != stamp) {
772 throw new InvalidOperationException (xstr);
785 public bool MoveNext ()
790 while (++pos < size) {
791 Slot entry = host.table [pos];
793 if (entry.key != null && entry.key != KeyMarker.Removed) {
794 currentKey = entry.key;
795 currentValue = entry.value;
806 public DictionaryEntry Entry
809 if (currentKey == null) throw new InvalidOperationException ();
811 return new DictionaryEntry (currentKey, currentValue);
817 if (currentKey == null) throw new InvalidOperationException ();
823 public Object Value {
825 if (currentKey == null) throw new InvalidOperationException ();
831 public Object Current {
833 if (currentKey == null) throw new InvalidOperationException ();
836 case EnumeratorMode.KEY_MODE:
838 case EnumeratorMode.VALUE_MODE:
840 case EnumeratorMode.ENTRY_MODE:
841 return new DictionaryEntry (currentKey, currentValue);
843 throw new Exception ("should never happen");
850 private class HashKeys : ICollection, IEnumerable {
852 private Hashtable host;
854 public HashKeys (Hashtable host) {
856 throw new ArgumentNullException ();
863 public virtual int Count {
869 public virtual bool IsSynchronized {
871 return host.IsSynchronized;
875 public virtual Object SyncRoot {
876 get {return host.SyncRoot;}
879 public virtual void CopyTo (Array array, int arrayIndex)
882 throw new ArgumentNullException ("array");
884 throw new ArgumentException ("array");
886 throw new ArgumentOutOfRangeException ("arrayIndex");
887 if (array.Length - arrayIndex < Count)
888 throw new ArgumentException ("not enough space");
890 host.CopyToArray (array, arrayIndex, EnumeratorMode.KEY_MODE);
895 public virtual IEnumerator GetEnumerator ()
897 return new Hashtable.Enumerator (host, EnumeratorMode.KEY_MODE);
902 private class HashValues : ICollection, IEnumerable {
904 private Hashtable host;
906 public HashValues (Hashtable host) {
908 throw new ArgumentNullException ();
915 public virtual int Count {
921 public virtual bool IsSynchronized {
923 return host.IsSynchronized;
927 public virtual Object SyncRoot {
929 return host.SyncRoot;
933 public virtual void CopyTo (Array array, int arrayIndex)
936 throw new ArgumentNullException ("array");
938 throw new ArgumentException ("array");
940 throw new ArgumentOutOfRangeException ("arrayIndex");
941 if (array.Length - arrayIndex < Count)
942 throw new ArgumentException ("not enough space");
944 host.CopyToArray (array, arrayIndex, EnumeratorMode.VALUE_MODE);
949 public virtual IEnumerator GetEnumerator ()
951 return new Hashtable.Enumerator (host, EnumeratorMode.VALUE_MODE);
957 private class SyncHashtable : Hashtable, IEnumerable {
959 private Hashtable host;
961 public SyncHashtable (Hashtable host) {
963 throw new ArgumentNullException ();
968 internal SyncHashtable (SerializationInfo info, StreamingContext context)
970 host = (Hashtable) info.GetValue("ParentTable", typeof(Hashtable));
973 public override void GetObjectData (SerializationInfo info, StreamingContext context)
975 info.AddValue ("ParentTable", host);
980 public override int Count {
986 public override bool IsSynchronized {
992 public override Object SyncRoot {
994 return host.SyncRoot;
1002 public override bool IsFixedSize {
1004 return host.IsFixedSize;
1009 public override bool IsReadOnly {
1011 return host.IsReadOnly;
1015 public override ICollection Keys {
1017 ICollection keys = null;
1018 lock (host.SyncRoot) {
1025 public override ICollection Values {
1027 ICollection vals = null;
1028 lock (host.SyncRoot) {
1037 public override Object this [Object key] {
1042 lock (host.SyncRoot) {
1050 IEnumerator IEnumerable.GetEnumerator ()
1052 return new Enumerator (host, EnumeratorMode.KEY_MODE);
1060 public override void CopyTo (Array array, int arrayIndex)
1062 host.CopyTo (array, arrayIndex);
1068 public override void Add (Object key, Object value)
1070 lock (host.SyncRoot) {
1071 host.Add (key, value);
1075 public override void Clear ()
1077 lock (host.SyncRoot) {
1082 public override bool Contains (Object key)
1084 return (host.Find (key) >= 0);
1087 public override IDictionaryEnumerator GetEnumerator ()
1089 return new Enumerator (host, EnumeratorMode.ENTRY_MODE);
1092 public override void Remove (Object key)
1094 lock (host.SyncRoot) {
1101 public override bool ContainsKey (object key)
1103 return host.Contains (key);
1106 public override bool ContainsValue (object value)
1108 return host.ContainsValue (value);
1114 public override object Clone ()
1116 lock(host.SyncRoot) {
1117 return new SyncHashtable( (Hashtable) host.Clone () );