2 // System.Collections.Hashtable.cs
5 // Sergey Chaban (serge@wildwestsoftware.com)
9 // Copyright (C) 2004-2005 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;
36 using System.Runtime.ConstrainedExecution;
37 using System.Runtime.InteropServices;
40 namespace System.Collections {
46 public class Hashtable : IDictionary, ICollection,
47 IEnumerable, ICloneable, ISerializable, IDeserializationCallback
51 internal struct Slot {
54 internal Object value;
56 // Hashcode. Chains are also marked through this.
61 internal class KeyMarker: IObjectReference
63 public readonly static KeyMarker Removed = new KeyMarker();
64 public object GetRealObject (StreamingContext context)
65 { return KeyMarker.Removed; }
72 const int CHAIN_MARKER = ~Int32.MaxValue;
76 private int modificationCount;
77 private float loadFactor;
78 private Slot [] table;
79 private int threshold;
81 private HashKeys hashKeys;
82 private HashValues hashValues;
84 private IHashCodeProvider hcpRef;
85 private IComparer comparerRef;
86 private SerializationInfo serializationInfo;
89 private IEqualityComparer equalityComparer;
92 private static readonly int [] primeTbl = {
133 public Hashtable () : this (0, 1.0f) {}
136 [Obsolete ("Please use Hashtable(int, float, IEqualityComparer) instead")]
138 public Hashtable (int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer) {
140 throw new ArgumentOutOfRangeException ("capacity", "negative capacity");
142 if (loadFactor < 0.1f || loadFactor > 1.0f || Single.IsNaN (loadFactor))
143 throw new ArgumentOutOfRangeException ("loadFactor", "load factor");
145 if (capacity == 0) ++capacity;
146 this.loadFactor = 0.75f*loadFactor;
147 double tableSize = capacity / this.loadFactor;
149 if (tableSize > Int32.MaxValue)
150 throw new ArgumentException ("Size is too big");
152 int size = (int) tableSize;
153 size = ToPrime (size);
154 this.SetTable (new Slot [size]);
157 this.comparer = comparer;
160 this.modificationCount = 0;
163 public Hashtable (int capacity, float loadFactor) :
164 this (capacity, loadFactor, null, null)
168 public Hashtable (int capacity) : this (capacity, 1.0f)
173 [Obsolete ("Please use Hashtable(int, IEqualityComparer) instead")]
175 public Hashtable (int capacity,
176 IHashCodeProvider hcp,
178 : this (capacity, 1.0f, hcp, comparer)
183 [Obsolete ("Please use Hashtable(IDictionary, float, IEqualityComparer) instead")]
185 public Hashtable (IDictionary d, float loadFactor,
186 IHashCodeProvider hcp, IComparer comparer)
187 : this (d!=null ? d.Count : 0,
188 loadFactor, hcp, comparer)
192 throw new ArgumentNullException ("dictionary");
194 IDictionaryEnumerator it = d.GetEnumerator ();
195 while (it.MoveNext ()) {
196 Add (it.Key, it.Value);
201 public Hashtable (IDictionary d, float loadFactor)
202 : this (d, loadFactor, null, null)
207 public Hashtable (IDictionary d) : this (d, 1.0f)
212 [Obsolete ("Please use Hashtable(IDictionary, IEqualityComparer) instead")]
214 public Hashtable (IDictionary d, IHashCodeProvider hcp, IComparer comparer)
215 : this (d, 1.0f, hcp, comparer)
220 [Obsolete ("Please use Hashtable(IEqualityComparer) instead")]
222 public Hashtable (IHashCodeProvider hcp, IComparer comparer)
223 : this (1, 1.0f, hcp, comparer)
227 protected Hashtable (SerializationInfo info, StreamingContext context)
229 serializationInfo = info;
233 public Hashtable (IDictionary d, IEqualityComparer equalityComparer) : this (d, 1.0f, equalityComparer)
237 public Hashtable (IDictionary d, float loadFactor, IEqualityComparer equalityComparer) : this (d, loadFactor)
239 this.equalityComparer = equalityComparer;
242 public Hashtable (IEqualityComparer equalityComparer) : this (1, 1.0f, equalityComparer)
246 public Hashtable (int capacity, IEqualityComparer equalityComparer) : this (capacity, 1.0f, equalityComparer)
250 public Hashtable (int capacity, float loadFactor, IEqualityComparer equalityComparer) : this (capacity, loadFactor)
252 this.equalityComparer = equalityComparer;
261 [Obsolete ("Please use EqualityComparer property.")]
263 protected IComparer comparer {
273 [Obsolete ("Please use EqualityComparer property.")]
275 protected IHashCodeProvider hcp {
285 protected IEqualityComparer EqualityComparer {
287 return equalityComparer;
294 public virtual int Count {
300 public virtual bool IsSynchronized {
306 public virtual Object SyncRoot {
316 public virtual bool IsFixedSize {
323 public virtual bool IsReadOnly {
329 public virtual ICollection Keys {
331 if (this.hashKeys == null)
332 this.hashKeys = new HashKeys (this);
333 return this.hashKeys;
337 public virtual ICollection Values {
339 if (this.hashValues == null)
340 this.hashValues = new HashValues (this);
341 return this.hashValues;
347 public virtual Object this [Object key] {
350 throw new ArgumentNullException ("key", "null key");
352 Slot [] table = this.table;
353 uint size = (uint) table.Length;
354 int h = this.GetHash (key) & Int32.MaxValue;
356 uint step = (uint) ((h >> 5)+1) % (size-1)+1;
359 for (uint i = size; i > 0; i--) {
361 Slot entry = table [indx];
362 Object k = entry.key;
366 if (k == key || ((entry.hashMix & Int32.MaxValue) == h
367 && this.KeyEquals (key, k))) {
371 if ((entry.hashMix & CHAIN_MARKER) == 0)
381 PutImpl (key, value, true);
395 IEnumerator IEnumerable.GetEnumerator ()
397 return new Enumerator (this, EnumeratorMode.ENTRY_MODE);
402 public virtual void CopyTo (Array array, int arrayIndex)
405 throw new ArgumentNullException ("array");
408 throw new ArgumentOutOfRangeException ("arrayIndex");
411 throw new ArgumentException ("array is multidimensional");
413 if ((array.Length > 0) && (arrayIndex >= array.Length))
414 throw new ArgumentException ("arrayIndex is equal to or greater than array.Length");
416 if (arrayIndex + this.inUse > array.Length)
417 throw new ArgumentException ("Not enough room from arrayIndex to end of array for this Hashtable");
419 IDictionaryEnumerator it = GetEnumerator ();
422 while (it.MoveNext ()) {
423 array.SetValue (it.Entry, i++);
430 public virtual void Add (Object key, Object value)
432 PutImpl (key, value, false);
436 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
438 public virtual void Clear ()
440 for (int i = 0;i<table.Length;i++) {
441 table [i].key = null;
442 table [i].value = null;
443 table [i].hashMix = 0;
450 public virtual bool Contains (Object key)
452 return (Find (key) >= 0);
455 public virtual IDictionaryEnumerator GetEnumerator ()
457 return new Enumerator (this, EnumeratorMode.ENTRY_MODE);
461 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
463 public virtual void Remove (Object key)
467 Slot [] table = this.table;
468 int h = table [i].hashMix;
470 table [i].hashMix = h;
471 table [i].key = (h != 0)
474 table [i].value = null;
480 public virtual bool ContainsKey (object key)
482 return Contains (key);
485 public virtual bool ContainsValue (object value)
487 int size = this.table.Length;
488 Slot [] table = this.table;
490 for (int i = 0; i < size; i++) {
491 Slot entry = table [i];
492 if (entry.key != null && entry.key!= KeyMarker.Removed
493 && entry.value == null) {
498 for (int i = 0; i < size; i++) {
499 Slot entry = table [i];
500 if (entry.key != null && entry.key!= KeyMarker.Removed
501 && value.Equals (entry.value)) {
512 public virtual object Clone ()
515 Hashtable ht = new Hashtable (Count, equalityComparer);
517 ht.comparer = this.comparer;
519 Hashtable ht = new Hashtable (Count, hcp, comparer);
522 ht.loadFactor = this.loadFactor;
524 // FIXME: maybe it's faster to simply
525 // copy the back-end array?
527 IDictionaryEnumerator it = GetEnumerator ();
528 while (it.MoveNext ()) {
529 ht [it.Key] = it.Value;
536 [MonoTODO ("Serialize equalityComparer")]
538 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
541 throw new ArgumentNullException ("info");
543 info.AddValue ("LoadFactor", loadFactor);
544 info.AddValue ("Version", modificationCount);
545 info.AddValue ("Comparer", comparerRef);
546 info.AddValue ("HashCodeProvider", hcpRef);
547 info.AddValue ("HashSize", this.table.Length);
549 Object [] keys = new Object[inUse];
550 CopyToArray(keys, 0, EnumeratorMode.KEY_MODE);
553 Object [] values = new Object[inUse];
554 CopyToArray(values, 0, EnumeratorMode.VALUE_MODE);
556 info.AddValue ("Keys", keys);
557 info.AddValue ("Values", values);
562 [MonoTODO ("Serialize equalityComparer")]
564 public virtual void OnDeserialization (object sender)
566 if (serializationInfo == null) return;
568 loadFactor = (float) serializationInfo.GetValue ("LoadFactor", typeof(float));
569 modificationCount = (int) serializationInfo.GetValue ("Version", typeof(int));
570 comparerRef = (IComparer) serializationInfo.GetValue ("Comparer", typeof (object));
571 hcpRef = (IHashCodeProvider) serializationInfo.GetValue ("HashCodeProvider", typeof (object));
572 int size = (int) serializationInfo.GetValue ("HashSize", typeof(int));
574 Object [] keys = (Object []) serializationInfo.GetValue("Keys", typeof(Object [] ));
575 Object [] values = (Object []) serializationInfo.GetValue("Values", typeof(Object [] ));
577 if (keys.Length != values.Length)
578 throw new SerializationException("Keys and values of uneven size");
580 size = ToPrime (size);
581 this.SetTable (new Slot [size]);
583 for(int i=0;i<keys.Length;i++)
584 Add(keys[i], values[i]);
588 serializationInfo = null;
592 /// Returns a synchronized (thread-safe)
593 /// wrapper for the Hashtable.
595 public static Hashtable Synchronized (Hashtable table)
598 throw new ArgumentNullException("table");
599 return new SyncHashtable (table);
605 // Protected instance methods
608 /// <summary>Returns the hash code for the specified key.</summary>
609 protected virtual int GetHash (Object key)
612 if (equalityComparer != null)
613 return equalityComparer.GetHashCode (key);
616 return key.GetHashCode ();
618 return hcpRef.GetHashCode (key);
622 /// Compares a specific Object with a specific key
623 /// in the Hashtable.
625 protected virtual bool KeyEquals (Object item, Object key)
628 if (equalityComparer != null)
629 return equalityComparer.Equals (item, key);
631 if (comparerRef == null)
632 return item.Equals (key);
634 return comparerRef.Compare (item, key) == 0;
640 // Private instance methods
643 private void AdjustThreshold ()
645 int size = table.Length;
647 threshold = (int) (size*loadFactor);
648 if (this.threshold >= size)
652 private void SetTable (Slot [] table)
655 throw new ArgumentNullException ("table");
661 private int Find (Object key)
664 throw new ArgumentNullException ("key", "null key");
666 Slot [] table = this.table;
667 uint size = (uint) table.Length;
668 int h = this.GetHash (key) & Int32.MaxValue;
670 uint step = (uint) ((h >> 5)+1) % (size-1)+1;
673 for (uint i = size; i > 0; i--) {
675 Slot entry = table [indx];
676 Object k = entry.key;
680 if (k == key || ((entry.hashMix & Int32.MaxValue) == h
681 && this.KeyEquals (key, k))) {
685 if ((entry.hashMix & CHAIN_MARKER) == 0)
694 private void Rehash ()
696 int oldSize = this.table.Length;
698 // From the SDK docs:
699 // Hashtable is automatically increased
700 // to the smallest prime number that is larger
701 // than twice the current number of Hashtable buckets
702 uint newSize = (uint)ToPrime ((oldSize<<1)|1);
705 Slot [] newTable = new Slot [newSize];
706 Slot [] table = this.table;
708 for (int i = 0;i<oldSize;i++) {
711 int h = s.hashMix & Int32.MaxValue;
713 uint step = ((uint) (h>>5)+1)% (newSize-1)+1;
714 for (uint j = spot%newSize;;spot+= step, j = spot%newSize) {
715 // No check for KeyMarker.Removed here,
716 // because the table is just allocated.
717 if (newTable [j].key == null) {
718 newTable [j].key = s.key;
719 newTable [j].value = s.value;
720 newTable [j].hashMix |= h;
723 newTable [j].hashMix |= CHAIN_MARKER;
729 ++this.modificationCount;
731 this.SetTable (newTable);
735 private void PutImpl (Object key, Object value, bool overwrite)
738 throw new ArgumentNullException ("key", "null key");
740 if (this.inUse >= this.threshold)
743 uint size = (uint)this.table.Length;
745 int h = this.GetHash (key) & Int32.MaxValue;
747 uint step = (uint) ((spot>>5)+1)% (size-1)+1;
748 Slot [] table = this.table;
752 for (int i = 0; i < size; i++) {
753 int indx = (int) (spot % size);
754 entry = table [indx];
757 && entry.key == KeyMarker.Removed
758 && (entry.hashMix & CHAIN_MARKER) != 0)
761 if (entry.key == null ||
762 (entry.key == KeyMarker.Removed
763 && (entry.hashMix & CHAIN_MARKER) == 0)) {
770 if ((entry.hashMix & Int32.MaxValue) == h && KeyEquals (key, entry.key)) {
772 table [indx].value = value;
773 ++this.modificationCount;
776 // An entry with the same key already exists in the Hashtable.
777 throw new ArgumentException (
778 "Key duplication when adding: " + key);
783 if (freeIndx == -1) {
784 table [indx].hashMix |= CHAIN_MARKER;
792 table [freeIndx].key = key;
793 table [freeIndx].value = value;
794 table [freeIndx].hashMix |= h;
797 ++this.modificationCount;
802 private void CopyToArray (Array arr, int i,
805 IEnumerator it = new Enumerator (this, mode);
807 while (it.MoveNext ()) {
808 arr.SetValue (it.Current, i++);
815 // Private static methods
817 internal static bool TestPrime (int x)
820 int top = (int)Math.Sqrt (x);
822 for (int n = 3; n < top; n += 2) {
828 // There is only one even prime - 2.
832 internal static int CalcPrime (int x)
834 for (int i = (x & (~1))-1; i< Int32.MaxValue; i += 2) {
835 if (TestPrime (i)) return i;
840 internal static int ToPrime (int x)
842 for (int i = 0; i < primeTbl.Length; i++) {
843 if (x <= primeTbl [i])
846 return CalcPrime (x);
856 private enum EnumeratorMode : int {KEY_MODE = 0, VALUE_MODE, ENTRY_MODE};
859 private sealed class Enumerator : IDictionaryEnumerator, IEnumerator {
861 private Hashtable host;
865 private EnumeratorMode mode;
867 private Object currentKey;
868 private Object currentValue;
870 private readonly static string xstr = "Hashtable.Enumerator: snapshot out of sync.";
872 public Enumerator (Hashtable host, EnumeratorMode mode) {
874 stamp = host.modificationCount;
875 size = host.table.Length;
880 public Enumerator (Hashtable host)
881 : this (host, EnumeratorMode.KEY_MODE) {}
884 private void FailFast ()
886 if (host.modificationCount != stamp) {
887 throw new InvalidOperationException (xstr);
900 public bool MoveNext ()
905 while (++pos < size) {
906 Slot entry = host.table [pos];
908 if (entry.key != null && entry.key != KeyMarker.Removed) {
909 currentKey = entry.key;
910 currentValue = entry.value;
921 public DictionaryEntry Entry
924 if (currentKey == null) throw new InvalidOperationException ();
926 return new DictionaryEntry (currentKey, currentValue);
932 if (currentKey == null) throw new InvalidOperationException ();
938 public Object Value {
940 if (currentKey == null) throw new InvalidOperationException ();
946 public Object Current {
948 if (currentKey == null) throw new InvalidOperationException ();
951 case EnumeratorMode.KEY_MODE:
953 case EnumeratorMode.VALUE_MODE:
955 case EnumeratorMode.ENTRY_MODE:
956 return new DictionaryEntry (currentKey, currentValue);
958 throw new Exception ("should never happen");
964 private class HashKeys : ICollection, IEnumerable {
966 private Hashtable host;
968 public HashKeys (Hashtable host) {
970 throw new ArgumentNullException ();
977 public virtual int Count {
983 public virtual bool IsSynchronized {
985 return host.IsSynchronized;
989 public virtual Object SyncRoot {
990 get {return host.SyncRoot;}
993 public virtual void CopyTo (Array array, int arrayIndex)
996 throw new ArgumentNullException ("array");
998 throw new ArgumentException ("array");
1000 throw new ArgumentOutOfRangeException ("arrayIndex");
1001 if (array.Length - arrayIndex < Count)
1002 throw new ArgumentException ("not enough space");
1004 host.CopyToArray (array, arrayIndex, EnumeratorMode.KEY_MODE);
1009 public virtual IEnumerator GetEnumerator ()
1011 return new Hashtable.Enumerator (host, EnumeratorMode.KEY_MODE);
1016 private class HashValues : ICollection, IEnumerable {
1018 private Hashtable host;
1020 public HashValues (Hashtable host) {
1022 throw new ArgumentNullException ();
1029 public virtual int Count {
1035 public virtual bool IsSynchronized {
1037 return host.IsSynchronized;
1041 public virtual Object SyncRoot {
1043 return host.SyncRoot;
1047 public virtual void CopyTo (Array array, int arrayIndex)
1050 throw new ArgumentNullException ("array");
1051 if (array.Rank != 1)
1052 throw new ArgumentException ("array");
1054 throw new ArgumentOutOfRangeException ("arrayIndex");
1055 if (array.Length - arrayIndex < Count)
1056 throw new ArgumentException ("not enough space");
1058 host.CopyToArray (array, arrayIndex, EnumeratorMode.VALUE_MODE);
1063 public virtual IEnumerator GetEnumerator ()
1065 return new Hashtable.Enumerator (host, EnumeratorMode.VALUE_MODE);
1071 private class SyncHashtable : Hashtable, IEnumerable {
1073 private Hashtable host;
1075 public SyncHashtable (Hashtable host) {
1077 throw new ArgumentNullException ();
1082 internal SyncHashtable (SerializationInfo info, StreamingContext context)
1084 host = (Hashtable) info.GetValue("ParentTable", typeof(Hashtable));
1087 public override void GetObjectData (SerializationInfo info, StreamingContext context)
1089 info.AddValue ("ParentTable", host);
1094 public override int Count {
1100 public override bool IsSynchronized {
1106 public override Object SyncRoot {
1108 return host.SyncRoot;
1116 public override bool IsFixedSize {
1118 return host.IsFixedSize;
1123 public override bool IsReadOnly {
1125 return host.IsReadOnly;
1129 public override ICollection Keys {
1131 ICollection keys = null;
1132 lock (host.SyncRoot) {
1139 public override ICollection Values {
1141 ICollection vals = null;
1142 lock (host.SyncRoot) {
1151 public override Object this [Object key] {
1156 lock (host.SyncRoot) {
1164 IEnumerator IEnumerable.GetEnumerator ()
1166 return new Enumerator (host, EnumeratorMode.ENTRY_MODE);
1174 public override void CopyTo (Array array, int arrayIndex)
1176 host.CopyTo (array, arrayIndex);
1182 public override void Add (Object key, Object value)
1184 lock (host.SyncRoot) {
1185 host.Add (key, value);
1189 public override void Clear ()
1191 lock (host.SyncRoot) {
1196 public override bool Contains (Object key)
1198 return (host.Find (key) >= 0);
1201 public override IDictionaryEnumerator GetEnumerator ()
1203 return new Enumerator (host, EnumeratorMode.ENTRY_MODE);
1206 public override void Remove (Object key)
1208 lock (host.SyncRoot) {
1215 public override bool ContainsKey (object key)
1217 return host.Contains (key);
1220 public override bool ContainsValue (object value)
1222 return host.ContainsValue (value);
1228 public override object Clone ()
1230 lock(host.SyncRoot) {
1231 return new SyncHashtable( (Hashtable) host.Clone () );