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] {
287 return GetImpl (key);
290 PutImpl (key, value, true);
304 IEnumerator IEnumerable.GetEnumerator ()
306 return new Enumerator (this, EnumeratorMode.ENTRY_MODE);
311 public virtual void CopyTo (Array array, int arrayIndex)
314 throw new ArgumentNullException ("array");
317 throw new ArgumentOutOfRangeException ("arrayIndex");
320 throw new ArgumentException ("array is multidimensional");
322 if ((array.Length > 0) && (arrayIndex >= array.Length))
323 throw new ArgumentException ("arrayIndex is equal to or greater than array.Length");
325 if (arrayIndex + this.inUse > array.Length)
326 throw new ArgumentException ("Not enough room from arrayIndex to end of array for this Hashtable");
328 IDictionaryEnumerator it = GetEnumerator ();
331 while (it.MoveNext ()) {
332 array.SetValue (it.Entry, i++);
339 public virtual void Add (Object key, Object value)
341 PutImpl (key, value, false);
344 public virtual void Clear ()
346 for (int i = 0;i<table.Length;i++) {
347 table [i].key = null;
348 table [i].value = null;
349 table [i].hashMix = 0;
356 public virtual bool Contains (Object key)
358 return (Find (key) >= 0);
361 public virtual IDictionaryEnumerator GetEnumerator ()
363 return new Enumerator (this, EnumeratorMode.ENTRY_MODE);
366 public virtual void Remove (Object key)
370 Slot [] table = this.table;
371 int h = table [i].hashMix;
373 table [i].hashMix = h;
374 table [i].key = (h != 0)
377 table [i].value = null;
383 public virtual bool ContainsKey (object key)
385 return Contains (key);
388 public virtual bool ContainsValue (object value)
390 int size = this.table.Length;
391 Slot [] table = this.table;
393 for (int i = 0; i < size; i++) {
394 Slot entry = table [i];
395 if (entry.key != null && entry.key!= KeyMarker.Removed
396 && entry.value == null) {
401 for (int i = 0; i < size; i++) {
402 Slot entry = table [i];
403 if (entry.key != null && entry.key!= KeyMarker.Removed
404 && value.Equals (entry.value)) {
415 public virtual object Clone ()
417 Hashtable ht = new Hashtable (Count, hcp, comparer);
419 ht.loadFactor = this.loadFactor;
421 // FIXME: maybe it's faster to simply
422 // copy the back-end array?
424 IDictionaryEnumerator it = GetEnumerator ();
425 while (it.MoveNext ()) {
426 ht [it.Key] = it.Value;
432 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
435 throw new ArgumentNullException ("info");
437 info.AddValue ("LoadFactor", loadFactor);
438 info.AddValue ("Version", modificationCount);
439 info.AddValue ("Comparer", comparerRef);
440 info.AddValue ("HashCodeProvider", hcpRef);
441 info.AddValue ("HashSize", this.table.Length);
443 Object [] keys = new Object[inUse];
444 CopyToArray(keys, 0, EnumeratorMode.KEY_MODE);
447 Object [] values = new Object[inUse];
448 CopyToArray(values, 0, EnumeratorMode.VALUE_MODE);
450 info.AddValue ("Keys", keys);
451 info.AddValue ("Values", values);
455 public virtual void OnDeserialization (object sender)
457 loadFactor = (float) serializationInfo.GetValue ("LoadFactor", typeof(float));
458 modificationCount = (int) serializationInfo.GetValue ("Version", typeof(int));
459 comparerRef = (IComparer) serializationInfo.GetValue ("Comparer", typeof (object));
460 hcpRef = (IHashCodeProvider) serializationInfo.GetValue ("HashCodeProvider", typeof (object));
461 int size = (int) serializationInfo.GetValue ("HashSize", typeof(int));
463 Object [] keys = (Object []) serializationInfo.GetValue("Keys", typeof(Object [] ));
464 Object [] values = (Object []) serializationInfo.GetValue("Values", typeof(Object [] ));
466 if (keys.Length != values.Length)
467 throw new SerializationException("Keys and values of uneven size");
469 size = ToPrime (size);
470 this.SetTable (new Slot [size]);
472 for(int i=0;i<keys.Length;i++)
473 Add(keys[i], values[i]);
477 serializationInfo = null;
481 /// Returns a synchronized (thread-safe)
482 /// wrapper for the Hashtable.
484 public static Hashtable Synchronized (Hashtable table)
487 throw new ArgumentNullException("table");
488 return new SyncHashtable (table);
494 // Protected instance methods
497 /// <summary>Returns the hash code for the specified key.</summary>
498 protected virtual int GetHash (Object key)
500 IHashCodeProvider hcp = this.hcp;
502 ? hcp.GetHashCode (key)
503 : key.GetHashCode ();
507 /// Compares a specific Object with a specific key
508 /// in the Hashtable.
510 protected virtual bool KeyEquals (Object item, Object key)
512 IComparer c = this.comparer;
514 return (c.Compare (item, key) == 0);
516 return item.Equals (key);
522 // Private instance methods
525 private void AdjustThreshold ()
527 int size = table.Length;
529 threshold = (int) (size*loadFactor);
530 if (this.threshold >= size)
534 private void SetTable (Slot [] table)
537 throw new ArgumentNullException ("table");
543 private Object GetImpl (Object key)
548 return table [i].value;
554 private int Find (Object key)
557 throw new ArgumentNullException ("key", "null key");
559 uint size = (uint) this.table.Length;
560 int h = this.GetHash (key) & Int32.MaxValue;
562 uint step = (uint) ((h >> 5)+1) % (size-1)+1;
563 Slot[] table = this.table;
565 for (int i = 0; i < size;i++) {
566 int indx = (int) (spot % size);
567 Slot entry = table [indx];
568 Object k = entry.key;
571 if ((entry.hashMix & Int32.MaxValue) == h
572 && this.KeyEquals (key, k)) {
576 if ((entry.hashMix & CHAIN_MARKER) == 0)
585 private void Rehash ()
587 int oldSize = this.table.Length;
589 // From the SDK docs:
590 // Hashtable is automatically increased
591 // to the smallest prime number that is larger
592 // than twice the current number of Hashtable buckets
593 uint newSize = (uint)ToPrime ((oldSize<<1)|1);
596 Slot [] newTable = new Slot [newSize];
597 Slot [] table = this.table;
599 for (int i = 0;i<oldSize;i++) {
602 int h = s.hashMix & Int32.MaxValue;
604 uint step = ((uint) (h>>5)+1)% (newSize-1)+1;
605 for (uint j = spot%newSize;;spot+= step, j = spot%newSize) {
606 // No check for KeyMarker.Removed here,
607 // because the table is just allocated.
608 if (newTable [j].key == null) {
609 newTable [j].key = s.key;
610 newTable [j].value = s.value;
611 newTable [j].hashMix |= h;
614 newTable [j].hashMix |= CHAIN_MARKER;
620 ++this.modificationCount;
622 this.SetTable (newTable);
626 private void PutImpl (Object key, Object value, bool overwrite)
629 throw new ArgumentNullException ("key", "null key");
631 uint size = (uint)this.table.Length;
632 if (this.inUse >= this.threshold) {
634 size = (uint)this.table.Length;
637 int h = this.GetHash (key) & Int32.MaxValue;
639 uint step = (uint) ((spot>>5)+1)% (size-1)+1;
640 Slot [] table = this.table;
644 for (int i = 0; i < size; i++) {
645 int indx = (int) (spot % size);
646 entry = table [indx];
649 && entry.key == KeyMarker.Removed
650 && (entry.hashMix & CHAIN_MARKER) != 0)
653 if (entry.key == null ||
654 (entry.key == KeyMarker.Removed
655 && (entry.hashMix & CHAIN_MARKER) == 0)) {
662 if ((entry.hashMix & Int32.MaxValue) == h && KeyEquals (key, entry.key)) {
664 table [indx].value = value;
665 ++this.modificationCount;
668 // An entry with the same key already exists in the Hashtable.
669 throw new ArgumentException (
670 "Key duplication when adding: " + key);
675 if (freeIndx == -1) {
676 table [indx].hashMix |= CHAIN_MARKER;
684 table [freeIndx].key = key;
685 table [freeIndx].value = value;
686 table [freeIndx].hashMix |= h;
689 ++this.modificationCount;
694 private void CopyToArray (Array arr, int i,
697 IEnumerator it = new Enumerator (this, mode);
699 while (it.MoveNext ()) {
700 arr.SetValue (it.Current, i++);
707 // Private static methods
709 private static bool TestPrime (int x)
712 for (int n = 3; n< (int)Math.Sqrt (x); n += 2) {
718 // There is only one even prime - 2.
722 private static int CalcPrime (int x)
724 for (int i = (x & (~1))-1; i< Int32.MaxValue; i += 2) {
725 if (TestPrime (i)) return i;
730 private static int ToPrime (int x)
732 for (int i = 0; i < primeTbl.Length; i++) {
733 if (x <= primeTbl [i])
736 return CalcPrime (x);
746 private enum EnumeratorMode : int {KEY_MODE = 0, VALUE_MODE, ENTRY_MODE};
748 private sealed class Enumerator : IDictionaryEnumerator, IEnumerator {
750 private Hashtable host;
754 private EnumeratorMode mode;
756 private Object currentKey;
757 private Object currentValue;
759 private readonly static string xstr = "Hashtable.Enumerator: snapshot out of sync.";
761 public Enumerator (Hashtable host, EnumeratorMode mode) {
763 stamp = host.modificationCount;
764 size = host.table.Length;
769 public Enumerator (Hashtable host)
770 : this (host, EnumeratorMode.KEY_MODE) {}
773 private void FailFast ()
775 if (host.modificationCount != stamp) {
776 throw new InvalidOperationException (xstr);
789 public bool MoveNext ()
794 while (++pos < size) {
795 Slot entry = host.table [pos];
797 if (entry.key != null && entry.key != KeyMarker.Removed) {
798 currentKey = entry.key;
799 currentValue = entry.value;
810 public DictionaryEntry Entry
813 if (currentKey == null) throw new InvalidOperationException ();
815 return new DictionaryEntry (currentKey, currentValue);
821 if (currentKey == null) throw new InvalidOperationException ();
827 public Object Value {
829 if (currentKey == null) throw new InvalidOperationException ();
835 public Object Current {
837 if (currentKey == null) throw new InvalidOperationException ();
840 case EnumeratorMode.KEY_MODE:
842 case EnumeratorMode.VALUE_MODE:
844 case EnumeratorMode.ENTRY_MODE:
845 return new DictionaryEntry (currentKey, currentValue);
847 throw new Exception ("should never happen");
854 private class HashKeys : ICollection, IEnumerable {
856 private Hashtable host;
858 public HashKeys (Hashtable host) {
860 throw new ArgumentNullException ();
867 public virtual int Count {
873 public virtual bool IsSynchronized {
875 return host.IsSynchronized;
879 public virtual Object SyncRoot {
880 get {return host.SyncRoot;}
883 public virtual void CopyTo (Array array, int arrayIndex)
886 throw new ArgumentNullException ("array");
888 throw new ArgumentException ("array");
890 throw new ArgumentOutOfRangeException ("arrayIndex");
891 if (array.Length - arrayIndex < Count)
892 throw new ArgumentException ("not enough space");
894 host.CopyToArray (array, arrayIndex, EnumeratorMode.KEY_MODE);
899 public virtual IEnumerator GetEnumerator ()
901 return new Hashtable.Enumerator (host, EnumeratorMode.KEY_MODE);
906 private class HashValues : ICollection, IEnumerable {
908 private Hashtable host;
910 public HashValues (Hashtable host) {
912 throw new ArgumentNullException ();
919 public virtual int Count {
925 public virtual bool IsSynchronized {
927 return host.IsSynchronized;
931 public virtual Object SyncRoot {
933 return host.SyncRoot;
937 public virtual void CopyTo (Array array, int arrayIndex)
940 throw new ArgumentNullException ("array");
942 throw new ArgumentException ("array");
944 throw new ArgumentOutOfRangeException ("arrayIndex");
945 if (array.Length - arrayIndex < Count)
946 throw new ArgumentException ("not enough space");
948 host.CopyToArray (array, arrayIndex, EnumeratorMode.VALUE_MODE);
953 public virtual IEnumerator GetEnumerator ()
955 return new Hashtable.Enumerator (host, EnumeratorMode.VALUE_MODE);
961 private class SyncHashtable : Hashtable, IEnumerable {
963 private Hashtable host;
965 public SyncHashtable (Hashtable host) {
967 throw new ArgumentNullException ();
972 internal SyncHashtable (SerializationInfo info, StreamingContext context)
974 host = (Hashtable) info.GetValue("ParentTable", typeof(Hashtable));
977 public override void GetObjectData (SerializationInfo info, StreamingContext context)
979 info.AddValue ("ParentTable", host);
984 public override int Count {
990 public override bool IsSynchronized {
996 public override Object SyncRoot {
998 return host.SyncRoot;
1006 public override bool IsFixedSize {
1008 return host.IsFixedSize;
1013 public override bool IsReadOnly {
1015 return host.IsReadOnly;
1019 public override ICollection Keys {
1021 ICollection keys = null;
1022 lock (host.SyncRoot) {
1029 public override ICollection Values {
1031 ICollection vals = null;
1032 lock (host.SyncRoot) {
1041 public override Object this [Object key] {
1043 return host.GetImpl (key);
1046 lock (host.SyncRoot) {
1047 host.PutImpl (key, value, true);
1054 IEnumerator IEnumerable.GetEnumerator ()
1056 return new Enumerator (host, EnumeratorMode.KEY_MODE);
1064 public override void CopyTo (Array array, int arrayIndex)
1066 host.CopyTo (array, arrayIndex);
1072 public override void Add (Object key, Object value)
1074 lock (host.SyncRoot) {
1075 host.PutImpl (key, value, false);
1079 public override void Clear ()
1081 lock (host.SyncRoot) {
1086 public override bool Contains (Object key)
1088 return (host.Find (key) >= 0);
1091 public override IDictionaryEnumerator GetEnumerator ()
1093 return new Enumerator (host, EnumeratorMode.ENTRY_MODE);
1096 public override void Remove (Object key)
1098 lock (host.SyncRoot) {
1105 public override bool ContainsKey (object key)
1107 return host.Contains (key);
1110 public override bool ContainsValue (object value)
1112 return host.ContainsValue (value);
1118 public override object Clone ()
1120 lock(host.SyncRoot) {
1121 return new SyncHashtable( (Hashtable) host.Clone () );