Guest User

Hashtable.cs

a guest
Oct 11th, 2012
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 166.56 KB | None | 0 0
  1. // ==++==
  2. //
  3. //   Copyright (c) Microsoft Corporation.  All rights reserved.
  4. //
  5. // ==--==
  6. /*============================================================
  7. **
  8. ** Class:  Hashtable
  9. **
  10. ** <OWNER>[....]</OWNER>
  11. **
  12. **
  13. ** Purpose: Hash table implementation
  14. **
  15. **
  16. ===========================================================*/
  17.  
  18. namespace System.Collections {
  19.     using System;
  20.     using System.Runtime;
  21.     using System.Runtime.Serialization;
  22.     using System.Security.Permissions;
  23.     using System.Diagnostics;
  24.     using System.Threading;
  25.     using System.Runtime.CompilerServices;
  26.     using System.Runtime.ConstrainedExecution;
  27.     using System.Diagnostics.Contracts;
  28.     using System.Security.Cryptography;
  29.  
  30.     // The Hashtable class represents a dictionary of associated keys and values
  31.     // with constant lookup time.
  32.     //
  33.     // Objects used as keys in a hashtable must implement the GetHashCode
  34.     // and Equals methods (or they can rely on the default implementations
  35.     // inherited from Object if key equality is simply reference
  36.     // equality). Furthermore, the GetHashCode and Equals methods of
  37.     // a key object must produce the same results given the same parameters for the
  38.     // entire time the key is present in the hashtable. In practical terms, this
  39.     // means that key objects should be immutable, at least for the time they are
  40.     // used as keys in a hashtable.
  41.     //
  42.     // When entries are added to a hashtable, they are placed into
  43.     // buckets based on the hashcode of their keys. Subsequent lookups of
  44.     // keys will use the hashcode of the keys to only search a particular bucket,
  45.     // thus substantially reducing the number of key comparisons required to find
  46.     // an entry. A hashtable's maximum load factor, which can be specified
  47.     // when the hashtable is instantiated, determines the maximum ratio of
  48.     // hashtable entries to hashtable buckets. Smaller load factors cause faster
  49.     // average lookup times at the cost of increased memory consumption. The
  50.     // default maximum load factor of 1.0 generally provides the best balance
  51.     // between speed and size. As entries are added to a hashtable, the hashtable's
  52.     // actual load factor increases, and when the actual load factor reaches the
  53.     // maximum load factor value, the number of buckets in the hashtable is
  54.     // automatically increased by approximately a factor of two (to be precise, the
  55.     // number of hashtable buckets is increased to the smallest prime number that
  56.     // is larger than twice the current number of hashtable buckets).
  57.     //
  58.     // Each object provides their own hash function, accessed by calling
  59.     // GetHashCode().  However, one can write their own object
  60.     // implementing IEqualityComparer and pass it to a constructor on
  61.     // the Hashtable.  That hash function (and the equals method on the
  62.     // IEqualityComparer) would be used for all objects in the table.
  63.     //
  64.     // Changes since V1 during Whidbey:
  65.     // *) Deprecated IHashCodeProvider, use IEqualityComparer instead.  This will
  66.     //    allow better performance for objects where equality checking can be
  67.     //    done much faster than establishing an ordering between two objects,
  68.     //    such as an ordinal string equality check.
  69.     //
  70.     [DebuggerTypeProxy(typeof(System.Collections.Hashtable.HashtableDebugView))]
  71.     [DebuggerDisplay("Count = {Count}")]
  72.     [System.Runtime.InteropServices.ComVisible(true)]
  73.     [Serializable]
  74.     public class Hashtable : IDictionary, ISerializable, IDeserializationCallback, ICloneable {
  75.         /*
  76.           Implementation Notes:
  77.           The generic Dictionary was copied from Hashtable's source - any bug
  78.           fixes here probably need to be made to the generic Dictionary as well.
  79.  
  80.           This Hashtable uses double hashing.  There are hashsize buckets in the
  81.           table, and each bucket can contain 0 or 1 element.  We a bit to mark
  82.           whether there's been a collision when we inserted multiple elements
  83.           (ie, an inserted item was hashed at least a second time and we probed
  84.           this bucket, but it was already in use).  Using the collision bit, we
  85.           can terminate lookups & removes for elements that aren't in the hash
  86.           table more quickly.  We steal the most significant bit from the hash code
  87.           to store the collision bit.
  88.  
  89.           Our hash function is of the following form:
  90.  
  91.           h(key, n) = h1(key) + n*h2(key)
  92.  
  93.           where n is the number of times we've hit a collided bucket and rehashed
  94.           (on this particular lookup).  Here are our hash functions:
  95.  
  96.           h1(key) = GetHash(key);  // default implementation calls key.GetHashCode();
  97.           h2(key) = 1 + (((h1(key) >> 5) + 1) % (hashsize - 1));
  98.  
  99.           The h1 can return any number.  h2 must return a number between 1 and
  100.           hashsize - 1 that is relatively prime to hashsize (not a problem if
  101.           hashsize is prime).  (Knuth's Art of Computer Programming, Vol. 3, p. 528-9)
  102.           If this is true, then we are guaranteed to visit every bucket in exactly
  103.           hashsize probes, since the least common multiple of hashsize and h2(key)
  104.           will be hashsize * h2(key).  (This is the first number where adding h2 to
  105.           h1 mod hashsize will be 0 and we will search the same bucket twice).
  106.  
  107.           We previously used a different h2(key, n) that was not constant.  That is a
  108.           horrifically bad idea, unless you can prove that series will never produce
  109.           any identical numbers that overlap when you mod them by hashsize, for all
  110.           subranges from i to i+hashsize, for all i.  It's not worth investigating,
  111.           since there was no clear benefit from using that hash function, and it was
  112.           broken.
  113.  
  114.           For efficiency reasons, we've implemented this by storing h1 and h2 in a
  115.           temporary, and setting a variable called seed equal to h1.  We do a probe,
  116.           and if we collided, we simply add h2 to seed each time through the loop.
  117.  
  118.           A good test for h2() is to subclass Hashtable, provide your own implementation
  119.           of GetHash() that returns a constant, then add many items to the hash table.
  120.           Make sure Count equals the number of items you inserted.
  121.  
  122.           Note that when we remove an item from the hash table, we set the key
  123.           equal to buckets, if there was a collision in this bucket.  Otherwise
  124.           we'd either wipe out the collision bit, or we'd still have an item in
  125.           the hash table.
  126.  
  127.            --
  128.         */
  129.  
  130.         internal const Int32 HashPrime = 101;
  131.         private const Int32 InitialSize = 3;
  132.         private const String LoadFactorName = "LoadFactor";
  133.         private const String VersionName = "Version";
  134.         private const String ComparerName = "Comparer";
  135.         private const String HashCodeProviderName = "HashCodeProvider";
  136.         private const String HashSizeName = "HashSize";  // Must save buckets.Length
  137.         private const String KeysName = "Keys";
  138.         private const String ValuesName = "Values";
  139.         private const String KeyComparerName = "KeyComparer";
  140.  
  141.         // Deleted entries have their key set to buckets
  142.  
  143.         // The hash table data.
  144.         // This cannot be serialised
  145.         private struct bucket {
  146.             public Object key;
  147.             public Object val;
  148.             public int hash_coll;   // Store hash code; sign bit means there was a collision.
  149.         }
  150.  
  151.         private bucket[] buckets;
  152.  
  153.         // The total number of entries in the hash table.
  154.         private  int count;
  155.  
  156.         // The total number of collision bits set in the hashtable
  157.         private int occupancy;
  158.  
  159.         private  int loadsize;
  160.         private  float loadFactor;
  161.  
  162.         private volatile int version;
  163.         private volatile bool isWriterInProgress;
  164.  
  165.         private ICollection keys;
  166.         private ICollection values;
  167.  
  168.         private IEqualityComparer _keycomparer;
  169.         private Object _syncRoot;
  170.  
  171.         [Obsolete("Please use EqualityComparer property.")]
  172.         protected IHashCodeProvider hcp
  173.         {
  174.             get
  175.             {
  176.                 if( _keycomparer is CompatibleComparer) {
  177.                     return ((CompatibleComparer)_keycomparer).HashCodeProvider;
  178.                 }
  179.                 else if( _keycomparer == null) {
  180.                     return null;
  181.                 }
  182.                 else {
  183.                     throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
  184.                 }
  185.             }
  186.             set
  187.             {
  188.                 if (_keycomparer is CompatibleComparer) {
  189.                     CompatibleComparer keyComparer = (CompatibleComparer)_keycomparer;
  190.                     _keycomparer = new CompatibleComparer(keyComparer.Comparer, value);
  191.                 }
  192.                 else if( _keycomparer == null) {
  193.                     _keycomparer = new CompatibleComparer((IComparer)null, value);
  194.                 }
  195.                 else {
  196.                     throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
  197.                 }
  198.             }
  199.         }
  200.  
  201.  
  202.         [Obsolete("Please use KeyComparer properties.")]
  203.         protected IComparer comparer
  204.         {
  205.             get
  206.             {
  207.                 if( _keycomparer is CompatibleComparer) {
  208.                     return ((CompatibleComparer)_keycomparer).Comparer;
  209.                 }
  210.                 else if( _keycomparer == null) {
  211.                     return null;
  212.                 }
  213.                 else {
  214.                     throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
  215.                 }
  216.             }
  217.             set
  218.             {
  219.                 if (_keycomparer is CompatibleComparer) {
  220.                     CompatibleComparer keyComparer = (CompatibleComparer)_keycomparer;
  221.                     _keycomparer = new CompatibleComparer(value, keyComparer.HashCodeProvider);
  222.                 }
  223.                 else if( _keycomparer == null) {
  224.                     _keycomparer = new CompatibleComparer(value, (IHashCodeProvider)null);
  225.                 }
  226.                 else {
  227.                     throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
  228.                 }
  229.             }
  230.         }
  231.  
  232.         protected IEqualityComparer EqualityComparer
  233.         {
  234.             get
  235.             {
  236.                 return _keycomparer;
  237.             }
  238.         }
  239.  
  240.         // Note: this constructor is a bogus constructor that does nothing
  241.         // and is for use only with SyncHashtable.
  242.         internal Hashtable( bool trash )
  243.         {
  244.         }
  245.  
  246.         // Constructs a new hashtable. The hashtable is created with an initial
  247.         // capacity of zero and a load factor of 1.0.
  248.         public Hashtable() : this(0, 1.0f) {
  249.         }
  250.  
  251.         // Constructs a new hashtable with the given initial capacity and a load
  252.         // factor of 1.0. The capacity argument serves as an indication of
  253.         // the number of entries the hashtable will contain. When this number (or
  254.         // an approximation) is known, specifying it in the constructor can
  255.         // eliminate a number of resizing operations that would otherwise be
  256.         // performed when elements are added to the hashtable.
  257.         //
  258.         public Hashtable(int capacity) : this(capacity, 1.0f) {
  259.         }
  260.  
  261.         // Constructs a new hashtable with the given initial capacity and load
  262.         // factor. The capacity argument serves as an indication of the
  263.         // number of entries the hashtable will contain. When this number (or an
  264.         // approximation) is known, specifying it in the constructor can eliminate
  265.         // a number of resizing operations that would otherwise be performed when
  266.         // elements are added to the hashtable. The loadFactor argument
  267.         // indicates the maximum ratio of hashtable entries to hashtable buckets.
  268.         // Smaller load factors cause faster average lookup times at the cost of
  269.         // increased memory consumption. A load factor of 1.0 generally provides
  270.         // the best balance between speed and size.
  271.         //
  272.         public Hashtable(int capacity, float loadFactor) {
  273.             if (capacity < 0)
  274.                 throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
  275.             if (!(loadFactor >= 0.1f && loadFactor <= 1.0f))
  276.                 throw new ArgumentOutOfRangeException("loadFactor", Environment.GetResourceString("ArgumentOutOfRange_HashtableLoadFactor", .1, 1.0));
  277.             Contract.EndContractBlock();
  278.  
  279.             // Based on perf work, .72 is the optimal load factor for this table.
  280.             this.loadFactor = 0.72f * loadFactor;
  281.  
  282.             double rawsize = capacity / this.loadFactor;
  283.             if (rawsize > Int32.MaxValue)
  284.                 throw new ArgumentException(Environment.GetResourceString("Arg_HTCapacityOverflow"));
  285.  
  286.             // Avoid awfully small sizes
  287.             int hashsize = (rawsize > InitialSize) ? HashHelpers.GetPrime((int)rawsize) : InitialSize;
  288.             buckets = new bucket[hashsize];
  289.  
  290.             loadsize = (int)(this.loadFactor * hashsize);
  291.             isWriterInProgress = false;
  292.             // Based on the current algorithm, loadsize must be less than hashsize.
  293.             Contract.Assert( loadsize < hashsize, "Invalid hashtable loadsize!");
  294.         }
  295.  
  296.         // Constructs a new hashtable with the given initial capacity and load
  297.         // factor. The capacity argument serves as an indication of the
  298.         // number of entries the hashtable will contain. When this number (or an
  299.         // approximation) is known, specifying it in the constructor can eliminate
  300.         // a number of resizing operations that would otherwise be performed when
  301.         // elements are added to the hashtable. The loadFactor argument
  302.         // indicates the maximum ratio of hashtable entries to hashtable buckets.
  303.         // Smaller load factors cause faster average lookup times at the cost of
  304.         // increased memory consumption. A load factor of 1.0 generally provides
  305.         // the best balance between speed and size.  The hcp argument
  306.         // is used to specify an Object that will provide hash codes for all
  307.         // the Objects in the table.  Using this, you can in effect override
  308.         // GetHashCode() on each Object using your own hash function.  The
  309.         // comparer argument will let you specify a custom function for
  310.         // comparing keys.  By specifying user-defined objects for hcp
  311.         // and comparer, users could make a hash table using strings
  312.         // as keys do case-insensitive lookups.
  313.         //
  314.         [Obsolete("Please use Hashtable(int, float, IEqualityComparer) instead.")]
  315.         public Hashtable(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer) : this(capacity, loadFactor) {
  316.             if (hcp == null && comparer == null) {
  317.                 this._keycomparer = null;
  318.             }
  319.             else {
  320.                 this._keycomparer = new CompatibleComparer(comparer,hcp);
  321.             }
  322.         }
  323.  
  324.         public Hashtable(int capacity, float loadFactor, IEqualityComparer equalityComparer) : this(capacity, loadFactor) {
  325.             this._keycomparer = equalityComparer;
  326.         }
  327.  
  328.         // Constructs a new hashtable using a custom hash function
  329.         // and a custom comparison function for keys.  This will enable scenarios
  330.         // such as doing lookups with case-insensitive strings.
  331.         //
  332.         [Obsolete("Please use Hashtable(IEqualityComparer) instead.")]
  333.         public Hashtable(IHashCodeProvider hcp, IComparer comparer) : this(0, 1.0f, hcp, comparer) {
  334.         }
  335.  
  336.         public Hashtable(IEqualityComparer equalityComparer) : this(0, 1.0f, equalityComparer) {
  337.         }
  338.  
  339.         // Constructs a new hashtable using a custom hash function
  340.         // and a custom comparison function for keys.  This will enable scenarios
  341.         // such as doing lookups with case-insensitive strings.
  342.         //
  343.         [Obsolete("Please use Hashtable(int, IEqualityComparer) instead.")]
  344.         public Hashtable(int capacity, IHashCodeProvider hcp, IComparer comparer)
  345.             : this(capacity, 1.0f, hcp, comparer) {
  346.         }
  347.  
  348.         public Hashtable(int capacity, IEqualityComparer equalityComparer)
  349.             : this(capacity, 1.0f, equalityComparer) {
  350.         }
  351.  
  352.         // Constructs a new hashtable containing a copy of the entries in the given
  353.         // dictionary. The hashtable is created with a load factor of 1.0.
  354.         //
  355.         public Hashtable(IDictionary d) : this(d, 1.0f) {
  356.         }
  357.  
  358.         // Constructs a new hashtable containing a copy of the entries in the given
  359.         // dictionary. The hashtable is created with the given load factor.
  360.         //
  361.         public Hashtable(IDictionary d, float loadFactor)
  362.             : this(d, loadFactor, (IEqualityComparer)null) {
  363.         }
  364.  
  365.         [Obsolete("Please use Hashtable(IDictionary, IEqualityComparer) instead.")]
  366.         public Hashtable(IDictionary d, IHashCodeProvider hcp, IComparer comparer)
  367.             : this(d, 1.0f, hcp, comparer)  {
  368.         }
  369.  
  370.         public Hashtable(IDictionary d, IEqualityComparer equalityComparer)
  371.             : this(d, 1.0f, equalityComparer)    {
  372.         }
  373.  
  374.         [Obsolete("Please use Hashtable(IDictionary, float, IEqualityComparer) instead.")]
  375.         public Hashtable(IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer)
  376.             : this((d != null ? d.Count : 0), loadFactor, hcp, comparer) {
  377.             if (d==null)
  378.                 throw new ArgumentNullException("d", Environment.GetResourceString("ArgumentNull_Dictionary"));
  379.             Contract.EndContractBlock();
  380.  
  381.             IDictionaryEnumerator e = d.GetEnumerator();
  382.             while (e.MoveNext()) Add(e.Key, e.Value);
  383.         }
  384.  
  385.         public Hashtable(IDictionary d, float loadFactor, IEqualityComparer equalityComparer)
  386.             : this((d != null ? d.Count : 0), loadFactor, equalityComparer) {
  387.             if (d==null)
  388.                 throw new ArgumentNullException("d", Environment.GetResourceString("ArgumentNull_Dictionary"));
  389.             Contract.EndContractBlock();
  390.  
  391.             IDictionaryEnumerator e = d.GetEnumerator();
  392.             while (e.MoveNext()) Add(e.Key, e.Value);
  393.         }
  394.  
  395.         protected Hashtable(SerializationInfo info, StreamingContext context) {
  396.             //We can't do anything with the keys and values until the entire graph has been deserialized
  397.             //and we have a reasonable estimate that GetHashCode is not going to fail.  For the time being,
  398.             //we'll just cache this.  The graph is not valid until OnDeserialization has been called.
  399.             HashHelpers.SerializationInfoTable.Add(this, info);
  400.         }
  401.  
  402.         // ‘InitHash’ is basically an implementation of classic DoubleHashing (see http://en.wikipedia.org/wiki/Double_hashing)
  403.         //
  404.         // 1) The only ‘correctness’ requirement is that the ‘increment’ used to probe
  405.         //    a. Be non-zero
  406.         //    b. Be relatively prime to the table size ‘hashSize’. (This is needed to insure you probe all entries in the table before you ‘wrap’ and visit entries already probed)
  407.         // 2) Because we choose table sizes to be primes, we just need to insure that the increment is 0 < incr < hashSize
  408.         //
  409.         // Thus this function would work: Incr = 1 + (seed % (hashSize-1))
  410.         //
  411.         // While this works well for ‘uniformly distributed’ keys, in practice, non-uniformity is common.
  412.         // In particular in practice we can see ‘mostly sequential’ where you get long clusters of keys that ‘pack’.
  413.         // To avoid bad behavior you want it to be the case that the increment is ‘large’ even for ‘small’ values (because small
  414.         // values tend to happen more in practice). Thus we multiply ‘seed’ by a number that will make these small values
  415.         // bigger (and not hurt large values). We picked HashPrime (101) because it was prime, and if ‘hashSize-1’ is not a multiple of HashPrime
  416.         // (enforced in GetPrime), then incr has the potential of being every value from 1 to hashSize-1. The choice was largely arbitrary.
  417.         //
  418.         // Computes the hash function:  H(key, i) = h1(key) + i*h2(key, hashSize).
  419.         // The out parameter seed is h1(key), while the out parameter
  420.         // incr is h2(key, hashSize).  Callers of this function should
  421.         // add incr each time through a loop.
  422.         private uint InitHash(Object key, int hashsize, out uint seed, out uint incr) {
  423.             // Hashcode must be positive.  Also, we must not use the sign bit, since
  424.             // that is used for the collision bit.
  425.             uint hashcode = (uint) GetHash(key) & 0x7FFFFFFF;
  426.             seed = (uint) hashcode;
  427.             // Restriction: incr MUST be between 1 and hashsize - 1, inclusive for
  428.             // the modular arithmetic to work correctly.  This guarantees you'll
  429.             // visit every bucket in the table exactly once within hashsize
  430.             // iterations.  Violate this and it'll cause obscure bugs forever.
  431.             // If you change this calculation for h2(key), update putEntry too!
  432.             incr = (uint)(1 + ((seed * HashPrime) % ((uint)hashsize - 1)));
  433.             return hashcode;
  434.         }
  435.  
  436.         // Adds an entry with the given key and value to this hashtable. An
  437.         // ArgumentException is thrown if the key is null or if the key is already
  438.         // present in the hashtable.
  439.         //
  440. #if !FEATURE_CORECLR
  441.         [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  442. #endif
  443.         public virtual void Add(Object key, Object value) {
  444.             Insert(key, value, true);
  445.         }
  446.  
  447.         // Removes all entries from this hashtable.
  448.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  449.         public virtual void Clear() {
  450.             Contract.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously!  Don't do that - use Hashtable.Synchronized.");
  451.  
  452.             if (count == 0 && occupancy == 0)
  453.                 return;
  454.  
  455. #if !FEATURE_CORECLR
  456.             Thread.BeginCriticalRegion();
  457. #endif
  458.             isWriterInProgress = true;
  459.             for (int i = 0; i < buckets.Length; i++){
  460.                 buckets[i].hash_coll = 0;
  461.                 buckets[i].key = null;
  462.                 buckets[i].val = null;
  463.             }
  464.  
  465.             count = 0;
  466.             occupancy = 0;
  467.             UpdateVersion();
  468.             isWriterInProgress = false;
  469. #if !FEATURE_CORECLR
  470.             Thread.EndCriticalRegion();
  471. #endif
  472.         }
  473.  
  474.         // Clone returns a virtually identical copy of this hash table.  This does
  475.         // a shallow copy - the Objects in the table aren't cloned, only the references
  476.         // to those Objects.
  477.         public virtual Object Clone()
  478.         {
  479.             bucket[] lbuckets = buckets;
  480.             Hashtable ht = new Hashtable(count,_keycomparer);
  481.             ht.version = version;
  482.             ht.loadFactor = loadFactor;
  483.             ht.count = 0;
  484.  
  485.             int bucket = lbuckets.Length;
  486.             while (bucket > 0) {
  487.                 bucket--;
  488.                 Object keyv = lbuckets[bucket].key;
  489.                 if ((keyv!= null) && (keyv != lbuckets)) {
  490.                     ht[keyv] = lbuckets[bucket].val;
  491.                 }
  492.             }
  493.  
  494.             return ht;
  495.         }
  496.  
  497.         // Checks if this hashtable contains the given key.
  498. #if !FEATURE_CORECLR
  499.         [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  500. #endif
  501.         public virtual bool Contains(Object key) {
  502.             return ContainsKey(key);
  503.         }
  504.  
  505.         // Checks if this hashtable contains an entry with the given key.  This is
  506.         // an O(1) operation.
  507.         //
  508.         public virtual bool ContainsKey(Object key) {
  509.             if (key == null) {
  510.                 throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
  511.             }
  512.             Contract.EndContractBlock();
  513.  
  514.             uint seed;
  515.             uint incr;
  516.             // Take a snapshot of buckets, in case another thread resizes table
  517.             bucket[] lbuckets = buckets;
  518.             uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr);
  519.             int  ntry = 0;
  520.  
  521.             bucket b;
  522.             int bucketNumber = (int) (seed % (uint)lbuckets.Length);
  523.             do {
  524.                 b = lbuckets[bucketNumber];
  525.                 if (b.key == null) {
  526.                     return false;
  527.                 }
  528.                 if (((b.hash_coll &  0x7FFFFFFF) == hashcode) &&
  529.                     KeyEquals (b.key, key))
  530.                     return true;
  531.                 bucketNumber = (int) (((long)bucketNumber + incr)% (uint)lbuckets.Length);
  532.             } while (b.hash_coll < 0 && ++ntry < lbuckets.Length);
  533.             return false;
  534.         }
  535.  
  536.  
  537.  
  538.         // Checks if this hashtable contains an entry with the given value. The
  539.         // values of the entries of the hashtable are compared to the given value
  540.         // using the Object.Equals method. This method performs a linear
  541.         // search and is thus be substantially slower than the ContainsKey
  542.         // method.
  543.         //
  544.         public virtual bool ContainsValue(Object value) {
  545.  
  546.             if (value == null) {
  547.                 for (int i = buckets.Length; --i >= 0;) {
  548.                     if (buckets[i].key != null && buckets[i].key != buckets && buckets[i].val == null)
  549.                         return true;
  550.                 }
  551.             }
  552.             else {
  553.                 for (int i = buckets.Length; --i >= 0;) {
  554.                   Object val = buckets[i].val;
  555.                   if (val!=null && val.Equals(value)) return true;
  556.                 }
  557.             }
  558.             return false;
  559.         }
  560.  
  561.         // Copies the keys of this hashtable to a given array starting at a given
  562.         // index. This method is used by the implementation of the CopyTo method in
  563.         // the KeyCollection class.
  564.         private void CopyKeys(Array array, int arrayIndex) {
  565.             Contract.Requires(array != null);
  566.             Contract.Requires(array.Rank == 1);
  567.  
  568.             bucket[] lbuckets = buckets;
  569.             for (int i = lbuckets.Length; --i >= 0;) {
  570.                 Object keyv = lbuckets[i].key;
  571.                 if ((keyv != null) && (keyv != buckets)){
  572.                     array.SetValue(keyv, arrayIndex++);
  573.                 }
  574.             }
  575.         }
  576.  
  577.         // Copies the keys of this hashtable to a given array starting at a given
  578.         // index. This method is used by the implementation of the CopyTo method in
  579.         // the KeyCollection class.
  580.         private void CopyEntries(Array array, int arrayIndex) {
  581.             Contract.Requires(array != null);
  582.             Contract.Requires(array.Rank == 1);
  583.  
  584.             bucket[] lbuckets = buckets;
  585.             for (int i = lbuckets.Length; --i >= 0;) {
  586.                 Object keyv = lbuckets[i].key;
  587.                 if ((keyv != null) && (keyv != buckets)){
  588.                     DictionaryEntry entry = new DictionaryEntry(keyv,lbuckets[i].val);
  589.                     array.SetValue(entry, arrayIndex++);
  590.                 }
  591.             }
  592.         }
  593.  
  594.         // Copies the values in this hash table to an array at
  595.         // a given index.  Note that this only copies values, and not keys.
  596.         public virtual void CopyTo(Array array, int arrayIndex)
  597.         {
  598.             if (array == null)
  599.                 throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Array"));
  600.             if (array.Rank != 1)
  601.                 throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
  602.             if (arrayIndex < 0)
  603.                 throw new ArgumentOutOfRangeException("arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
  604.             if (array.Length - arrayIndex < Count)
  605.                 throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
  606.             Contract.EndContractBlock();
  607.             CopyEntries(array, arrayIndex);
  608.         }
  609.  
  610.         // Copies the values in this Hashtable to an KeyValuePairs array.
  611.         // KeyValuePairs is different from Dictionary Entry in that it has special
  612.         // debugger attributes on its fields.
  613.  
  614.         internal virtual KeyValuePairs[] ToKeyValuePairsArray() {
  615.  
  616.             KeyValuePairs[] array = new KeyValuePairs[count];
  617.             int index = 0;
  618.             bucket[] lbuckets = buckets;
  619.             for (int i = lbuckets.Length; --i >= 0;) {
  620.                 Object keyv = lbuckets[i].key;
  621.                 if ((keyv != null) && (keyv != buckets)){
  622.                     array[index++] = new KeyValuePairs(keyv,lbuckets[i].val);
  623.                 }
  624.             }
  625.  
  626.             return array;
  627.         }
  628.  
  629.  
  630.         // Copies the values of this hashtable to a given array starting at a given
  631.         // index. This method is used by the implementation of the CopyTo method in
  632.         // the ValueCollection class.
  633.         private void CopyValues(Array array, int arrayIndex) {
  634.             Contract.Requires(array != null);
  635.             Contract.Requires(array.Rank == 1);
  636.  
  637.             bucket[] lbuckets = buckets;
  638.             for (int i = lbuckets.Length; --i >= 0;) {
  639.                 Object keyv = lbuckets[i].key;
  640.                 if ((keyv != null) && (keyv != buckets)){
  641.                     array.SetValue(lbuckets[i].val, arrayIndex++);
  642.                 }
  643.             }
  644.         }
  645.  
  646.         // Returns the value associated with the given key. If an entry with the
  647.         // given key is not found, the returned value is null.
  648.         //
  649.         public virtual Object this[Object key] {
  650.             get {
  651.                 if (key == null) {
  652.                     throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
  653.                 }
  654.                 Contract.EndContractBlock();
  655.  
  656.                 uint seed;
  657.                 uint incr;
  658.  
  659.  
  660.                 // Take a snapshot of buckets, in case another thread does a resize
  661.                 bucket[] lbuckets = buckets;
  662.                 uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr);
  663.                 int  ntry = 0;
  664.  
  665.                 bucket b;
  666.                 int bucketNumber = (int) (seed % (uint)lbuckets.Length);
  667.                 do
  668.                 {
  669.                     int currentversion;
  670.  
  671.                     //     A read operation on hashtable has three steps:
  672.                     //        (1) calculate the hash and find the slot number.
  673.                     //        (2) compare the hashcode, if equal, go to step 3. Otherwise end.
  674.                     //        (3) compare the key, if equal, go to step 4. Otherwise end.
  675.                     //        (4) return the value contained in the bucket.
  676.                     //     After step 3 and before step 4. A writer can kick in a remove the old item and add a new one
  677.                     //     in the same bukcet. So in the reader we need to check if the hash table is modified during above steps.
  678.                     //
  679.                     // Writers (Insert, Remove, Clear) will set 'isWriterInProgress' flag before it starts modifying
  680.                     // the hashtable and will ckear the flag when it is done.  When the flag is cleared, the 'version'
  681.                     // will be increased.  We will repeat the reading if a writer is in progress or done with the modification
  682.                     // during the read.
  683.                     //
  684.                     // Our memory model guarantee if we pick up the change in bucket from another processor,
  685.                     // we will see the 'isWriterProgress' flag to be true or 'version' is changed in the reader.
  686.                     //
  687.                     int spinCount = 0;
  688.                     do {
  689.                         // this is violate read, following memory accesses can not be moved ahead of it.
  690.                         currentversion = version;
  691.                         b = lbuckets[bucketNumber];
  692.  
  693.                         // The contention between reader and writer shouldn't happen frequently.
  694.                         // But just in case this will burn CPU, yield the control of CPU if we spinned a few times.
  695.                         // 8 is just a random number I pick.
  696.                         if( (++spinCount) % 8 == 0 ) {
  697.                             Thread.Sleep(1);   // 1 means we are yeilding control to all threads, including low-priority ones.
  698.                         }
  699.                     } while ( isWriterInProgress || (currentversion != version) );
  700.  
  701.                     if (b.key == null) {
  702.                         return null;
  703.                     }
  704.                     if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
  705.                         KeyEquals (b.key, key))
  706.                         return b.val;
  707.                     bucketNumber = (int) (((long)bucketNumber + incr)% (uint)lbuckets.Length);
  708.                 } while (b.hash_coll < 0 && ++ntry < lbuckets.Length);
  709.                 return null;
  710.             }
  711.  
  712. #if !FEATURE_CORECLR
  713.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  714. #endif
  715.             set {
  716.                 Insert(key, value, false);
  717.             }
  718.         }
  719.  
  720.         // Increases the bucket count of this hashtable. This method is called from
  721.         // the Insert method when the actual load factor of the hashtable reaches
  722.         // the upper limit specified when the hashtable was constructed. The number
  723.         // of buckets in the hashtable is increased to the smallest prime number
  724.         // that is larger than twice the current number of buckets, and the entries
  725.         // in the hashtable are redistributed into the new buckets using the cached
  726.         // hashcodes.
  727.         private void expand()  {
  728.             int rawsize = HashHelpers.ExpandPrime(buckets.Length);
  729.             rehash(rawsize, false);
  730.         }
  731.  
  732.         // We occationally need to rehash the table to clean up the collision bits.
  733.         private void rehash() {
  734.             rehash( buckets.Length, false );
  735.         }
  736.  
  737.         private void UpdateVersion() {
  738.             // Version might become negative when version is Int32.MaxValue, but the oddity will be still be correct.
  739.             // So we don't need to special case this.
  740.             version++;
  741.         }
  742.  
  743.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  744.         private void rehash( int newsize, bool forceNewHashCode ) {
  745.  
  746.             // reset occupancy
  747.             occupancy=0;
  748.  
  749.             // Don't replace any internal state until we've finished adding to the
  750.             // new bucket[].  This serves two purposes:
  751.             //   1) Allow concurrent readers to see valid hashtable contents
  752.             //      at all times
  753.             //   2) Protect against an OutOfMemoryException while allocating this
  754.             //      new bucket[].
  755.             bucket[] newBuckets = new bucket[newsize];
  756.  
  757.             // rehash table into new buckets
  758.             int nb;
  759.             for (nb = 0; nb < buckets.Length; nb++){
  760.                 bucket oldb = buckets[nb];
  761.                 if ((oldb.key != null) && (oldb.key != buckets)) {
  762.                     int hashcode = ((forceNewHashCode ? GetHash(oldb.key) : oldb.hash_coll) & 0x7FFFFFFF);
  763.                     putEntry(newBuckets, oldb.key, oldb.val, hashcode);
  764.                 }
  765.             }
  766.  
  767.             // New bucket[] is good to go - replace buckets and other internal state.
  768. #if !FEATURE_CORECLR
  769.             Thread.BeginCriticalRegion();
  770. #endif
  771.             isWriterInProgress = true;
  772.             buckets = newBuckets;
  773.             loadsize = (int)(loadFactor * newsize);
  774.             UpdateVersion();
  775.             isWriterInProgress = false;
  776. #if !FEATURE_CORECLR
  777.             Thread.EndCriticalRegion();
  778. #endif
  779.             // minimun size of hashtable is 3 now and maximum loadFactor is 0.72 now.
  780.             Contract.Assert(loadsize < newsize, "Our current implementaion means this is not possible.");
  781.             return;
  782.         }
  783.  
  784.         // Returns an enumerator for this hashtable.
  785.         // If modifications made to the hashtable while an enumeration is
  786.         // in progress, the MoveNext and Current methods of the
  787.         // enumerator will throw an exception.
  788.         //
  789. #if !FEATURE_CORECLR
  790.         [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  791. #endif
  792.         IEnumerator IEnumerable.GetEnumerator() {
  793.             return new HashtableEnumerator(this, HashtableEnumerator.DictEntry);
  794.         }
  795.  
  796.         // Returns a dictionary enumerator for this hashtable.
  797.         // If modifications made to the hashtable while an enumeration is
  798.         // in progress, the MoveNext and Current methods of the
  799.         // enumerator will throw an exception.
  800.         //
  801. #if !FEATURE_CORECLR
  802.         [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  803. #endif
  804.         public virtual IDictionaryEnumerator GetEnumerator() {
  805.             return new HashtableEnumerator(this, HashtableEnumerator.DictEntry);
  806.         }
  807.  
  808.         // Internal method to get the hash code for an Object.  This will call
  809.         // GetHashCode() on each object if you haven't provided an IHashCodeProvider
  810.         // instance.  Otherwise, it calls hcp.GetHashCode(obj).
  811. #if !FEATURE_CORECLR
  812.         [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  813. #endif
  814.         protected virtual int GetHash(Object key)
  815.         {
  816.             if (_keycomparer != null)
  817.                 return _keycomparer.GetHashCode(key);
  818.             return key.GetHashCode();
  819.         }
  820.  
  821.         // Is this Hashtable read-only?
  822.         public virtual bool IsReadOnly {
  823.             get { return false; }
  824.         }
  825.  
  826.         public virtual bool IsFixedSize {
  827.             get { return false; }
  828.         }
  829.  
  830.         // Is this Hashtable synchronized?  See SyncRoot property
  831.         public virtual bool IsSynchronized {
  832.             get { return false; }
  833.         }
  834.  
  835.         // Internal method to compare two keys.  If you have provided an IComparer
  836.         // instance in the constructor, this method will call comparer.Compare(item, key).
  837.         // Otherwise, it will call item.Equals(key).
  838.         //
  839.         protected virtual bool KeyEquals(Object item, Object key)
  840.         {
  841.             Contract.Assert(key != null, "key can't be null here!");
  842.             if( Object.ReferenceEquals(buckets, item)) {
  843.                 return false;
  844.             }
  845.  
  846.             if (Object.ReferenceEquals(item,key))
  847.                 return true;
  848.  
  849.             if (_keycomparer != null)
  850.                 return _keycomparer.Equals(item, key);
  851.             return item == null ? false : item.Equals(key);
  852.         }
  853.  
  854.         // Returns a collection representing the keys of this hashtable. The order
  855.         // in which the returned collection represents the keys is unspecified, but
  856.         // it is guaranteed to be          buckets = newBuckets; the same order in which a collection returned by
  857.         // GetValues represents the values of the hashtable.
  858.         //
  859.         // The returned collection is live in the sense that any changes
  860.         // to the hash table are reflected in this collection.  It is not
  861.         // a static copy of all the keys in the hash table.
  862.         //
  863.         public virtual ICollection Keys {
  864. #if !FEATURE_CORECLR
  865.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  866. #endif
  867.             get {
  868.                 if (keys == null) keys = new KeyCollection(this);
  869.                     return keys;
  870.             }
  871.         }
  872.  
  873.         // Returns a collection representing the values of this hashtable. The
  874.         // order in which the returned collection represents the values is
  875.         // unspecified, but it is guaranteed to be the same order in which a
  876.         // collection returned by GetKeys represents the keys of the
  877.         // hashtable.
  878.         //
  879.         // The returned collection is live in the sense that any changes
  880.         // to the hash table are reflected in this collection.  It is not
  881.         // a static copy of all the keys in the hash table.
  882.         //
  883.         public virtual ICollection Values {
  884. #if !FEATURE_CORECLR
  885.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  886. #endif
  887.             get {
  888.                 if (values == null) values = new ValueCollection(this);
  889.                     return values;
  890.             }
  891.         }
  892.  
  893.         // Inserts an entry into this hashtable. This method is called from the Set
  894.         // and Add methods. If the add parameter is true and the given key already
  895.         // exists in the hashtable, an exception is thrown.
  896.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  897.         private void Insert (Object key, Object nvalue, bool add) {
  898.             // @
  899.  
  900.  
  901.             if (key == null) {
  902.                 throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
  903.             }
  904.             Contract.EndContractBlock();
  905.             if (count >= loadsize) {
  906.                 expand();
  907.             }
  908.             else if(occupancy > loadsize && count > 100) {
  909.                 rehash();
  910.             }
  911.  
  912.             uint seed;
  913.             uint incr;
  914.             // Assume we only have one thread writing concurrently.  Modify
  915.             // buckets to contain new data, as long as we insert in the right order.
  916.             uint hashcode = InitHash(key, buckets.Length, out seed, out incr);
  917.             int  ntry = 0;
  918.             int emptySlotNumber = -1; // We use the empty slot number to cache the first empty slot. We chose to reuse slots
  919.             // create by remove that have the collision bit set over using up new slots.
  920.             int bucketNumber = (int) (seed % (uint)buckets.Length);
  921.             do {
  922.  
  923.                 // Set emptySlot number to current bucket if it is the first available bucket that we have seen
  924.                 // that once contained an entry and also has had a collision.
  925.                 // We need to search this entire collision chain because we have to ensure that there are no
  926.                 // duplicate entries in the table.
  927.                 if (emptySlotNumber == -1 && (buckets[bucketNumber].key == buckets) && (buckets[bucketNumber].hash_coll < 0))//(((buckets[bucketNumber].hash_coll & unchecked(0x80000000))!=0)))
  928.                     emptySlotNumber = bucketNumber;
  929.  
  930.                 // Insert the key/value pair into this bucket if this bucket is empty and has never contained an entry
  931.                 // OR
  932.                 // This bucket once contained an entry but there has never been a collision
  933.                 if ((buckets[bucketNumber].key == null) ||
  934.                     (buckets[bucketNumber].key == buckets && ((buckets[bucketNumber].hash_coll & unchecked(0x80000000))==0))) {
  935.  
  936.                     // If we have found an available bucket that has never had a collision, but we've seen an available
  937.                     // bucket in the past that has the collision bit set, use the previous bucket instead
  938.                     if (emptySlotNumber != -1) // Reuse slot
  939.                         bucketNumber = emptySlotNumber;
  940.  
  941.                     // We pretty much have to insert in this order.  Don't set hash
  942.                     // code until the value & key are set appropriately.
  943. #if !FEATURE_CORECLR
  944.                     Thread.BeginCriticalRegion();
  945. #endif
  946.                     isWriterInProgress = true;
  947.                     buckets[bucketNumber].val = nvalue;
  948.                     buckets[bucketNumber].key  = key;
  949.                     buckets[bucketNumber].hash_coll |= (int) hashcode;
  950.                     count++;
  951.                     UpdateVersion();
  952.                     isWriterInProgress = false;
  953. #if !FEATURE_CORECLR
  954.                     Thread.EndCriticalRegion();
  955. #endif
  956.  
  957. #if FEATURE_RANDOMIZED_STRING_HASHING
  958.                     if(ntry > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer))
  959.                     {
  960.                         // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
  961.                         // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
  962.                         if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
  963.                         {
  964.                             _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
  965.                             rehash(buckets.Length, true);
  966.                         }
  967.                     }
  968. #endif
  969.  
  970.                     return;
  971.                 }
  972.  
  973.                 // The current bucket is in use
  974.                 // OR
  975.                 // it is available, but has had the collision bit set and we have already found an available bucket
  976.                 if (((buckets[bucketNumber].hash_coll & 0x7FFFFFFF) == hashcode) &&
  977.                     KeyEquals (buckets[bucketNumber].key, key)) {
  978.                     if (add) {
  979.                         throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", buckets[bucketNumber].key, key));
  980.                     }
  981. #if !FEATURE_CORECLR
  982.                     Thread.BeginCriticalRegion();
  983. #endif
  984.                     isWriterInProgress = true;
  985.                     buckets[bucketNumber].val = nvalue;
  986.                     UpdateVersion();
  987.                     isWriterInProgress = false;
  988. #if !FEATURE_CORECLR
  989.                     Thread.EndCriticalRegion();
  990. #endif
  991.  
  992. #if FEATURE_RANDOMIZED_STRING_HASHING
  993.                     if(ntry > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer))
  994.                     {
  995.                         // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
  996.                         // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
  997.                         if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
  998.                         {
  999.                             _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
  1000.                             rehash(buckets.Length, true);
  1001.                         }
  1002.                     }
  1003. #endif
  1004.                     return;
  1005.                 }
  1006.  
  1007.                 // The current bucket is full, and we have therefore collided.  We need to set the collision bit
  1008.                 // UNLESS
  1009.                 // we have remembered an available slot previously.
  1010.                 if (emptySlotNumber == -1) {// We don't need to set the collision bit here since we already have an empty slot
  1011.                     if( buckets[bucketNumber].hash_coll >= 0 ) {
  1012.                         buckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
  1013.                         occupancy++;
  1014.                     }
  1015.                 }
  1016.  
  1017.                 bucketNumber = (int) (((long)bucketNumber + incr)% (uint)buckets.Length);
  1018.             } while (++ntry < buckets.Length);
  1019.  
  1020.             // This code is here if and only if there were no buckets without a collision bit set in the entire table
  1021.             if (emptySlotNumber != -1)
  1022.             {
  1023.                 // We pretty much have to insert in this order.  Don't set hash
  1024.                 // code until the value & key are set appropriately.
  1025. #if !FEATURE_CORECLR
  1026.                 Thread.BeginCriticalRegion();
  1027. #endif
  1028.                 isWriterInProgress = true;
  1029.                 buckets[emptySlotNumber].val = nvalue;
  1030.                 buckets[emptySlotNumber].key  = key;
  1031.                 buckets[emptySlotNumber].hash_coll |= (int) hashcode;
  1032.                 count++;
  1033.                 UpdateVersion();
  1034.                 isWriterInProgress = false;
  1035. #if !FEATURE_CORECLR
  1036.                 Thread.EndCriticalRegion();
  1037. #endif
  1038.  
  1039. #if FEATURE_RANDOMIZED_STRING_HASHING
  1040.                 if(buckets.Length > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer))
  1041.                 {
  1042.                     // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
  1043.                     // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
  1044.                     if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
  1045.                     {
  1046.                         _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
  1047.                         rehash(buckets.Length, true);
  1048.                     }
  1049.                 }
  1050. #endif
  1051.                 return;
  1052.             }
  1053.  
  1054.             // If you see this assert, make sure load factor & count are reasonable.
  1055.             // Then verify that our double hash function (h2, described at top of file)
  1056.             // meets the requirements described above. You should never see this assert.
  1057.             Contract.Assert(false, "hash table insert failed!  Load factor too high, or our double hashing function is incorrect.");
  1058.             throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HashInsertFailed"));
  1059.         }
  1060.  
  1061.         private void putEntry (bucket[] newBuckets, Object key, Object nvalue, int hashcode)
  1062.         {
  1063.             Contract.Assert(hashcode >= 0, "hashcode >= 0");  // make sure collision bit (sign bit) wasn't set.
  1064.  
  1065.             uint seed = (uint) hashcode;
  1066.             uint incr = (uint)(1 + ((seed * HashPrime) % ((uint)newBuckets.Length - 1)));
  1067.             int bucketNumber = (int) (seed % (uint)newBuckets.Length);
  1068.             do {
  1069.  
  1070.                 if ((newBuckets[bucketNumber].key == null) || (newBuckets[bucketNumber].key == buckets)) {
  1071.                     newBuckets[bucketNumber].val = nvalue;
  1072.                     newBuckets[bucketNumber].key = key;
  1073.                     newBuckets[bucketNumber].hash_coll |= hashcode;
  1074.                     return;
  1075.                 }
  1076.  
  1077.                 if( newBuckets[bucketNumber].hash_coll >= 0 ) {
  1078.                 newBuckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
  1079.                     occupancy++;
  1080.                 }
  1081.                 bucketNumber = (int) (((long)bucketNumber + incr)% (uint)newBuckets.Length);
  1082.             } while (true);
  1083.         }
  1084.  
  1085.         // Removes an entry from this hashtable. If an entry with the specified
  1086.         // key exists in the hashtable, it is removed. An ArgumentException is
  1087.         // thrown if the key is null.
  1088.         //
  1089.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  1090.         public virtual void Remove(Object key) {
  1091.             if (key == null) {
  1092.                 throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
  1093.             }
  1094.             Contract.EndContractBlock();
  1095.             Contract.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously!  Don't do that - use Hashtable.Synchronized.");
  1096.  
  1097.             uint seed;
  1098.             uint incr;
  1099.             // Assuming only one concurrent writer, write directly into buckets.
  1100.             uint hashcode = InitHash(key, buckets.Length, out seed, out incr);
  1101.             int ntry = 0;
  1102.  
  1103.             bucket b;
  1104.             int bn = (int) (seed % (uint)buckets.Length);  // bucketNumber
  1105.             do {
  1106.                 b = buckets[bn];
  1107.                 if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
  1108.                     KeyEquals (b.key, key)) {
  1109. #if !FEATURE_CORECLR
  1110.                     Thread.BeginCriticalRegion();
  1111. #endif
  1112.                     isWriterInProgress = true;
  1113.                     // Clear hash_coll field, then key, then value
  1114.                     buckets[bn].hash_coll &= unchecked((int)0x80000000);
  1115.                     if (buckets[bn].hash_coll != 0) {
  1116.                         buckets[bn].key = buckets;
  1117.                     }
  1118.                     else {
  1119.                         buckets[bn].key = null;
  1120.                     }
  1121.                     buckets[bn].val = null;  // Free object references sooner & simplify ContainsValue.
  1122.                     count--;
  1123.                     UpdateVersion();
  1124.                     isWriterInProgress = false;
  1125. #if !FEATURE_CORECLR
  1126.                     Thread.EndCriticalRegion();
  1127. #endif
  1128.                     return;
  1129.                 }
  1130.                 bn = (int) (((long)bn + incr)% (uint)buckets.Length);
  1131.             } while (b.hash_coll < 0 && ++ntry < buckets.Length);
  1132.  
  1133.             //throw new ArgumentException(Environment.GetResourceString("Arg_RemoveArgNotFound"));
  1134.         }
  1135.  
  1136.         // Returns the object to synchronize on for this hash table.
  1137.         public virtual Object SyncRoot {
  1138.             get {
  1139.                 if( _syncRoot == null) {
  1140.                     System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
  1141.                 }
  1142.                 return _syncRoot;
  1143.             }
  1144.         }
  1145.  
  1146.         // Returns the number of associations in this hashtable.
  1147.         //
  1148.         public virtual int Count {
  1149.             get { return count; }
  1150.         }
  1151.  
  1152.         // Returns a thread-safe wrapper for a Hashtable.
  1153.         //
  1154.         [HostProtection(Synchronization=true)]
  1155.         public static Hashtable Synchronized(Hashtable table) {
  1156.             if (table==null)
  1157.                 throw new ArgumentNullException("table");
  1158.             Contract.EndContractBlock();
  1159.             return new SyncHashtable(table);
  1160.         }
  1161.  
  1162.         //
  1163.         // The ISerializable Implementation
  1164.         //
  1165.  
  1166.         [System.Security.SecurityCritical]
  1167.         public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
  1168.             if (info==null) {
  1169.                 throw new ArgumentNullException("info");
  1170.             }
  1171.             Contract.EndContractBlock();
  1172.             // This is imperfect - it only works well if all other writes are
  1173.             // also using our synchronized wrapper.  But it's still a good idea.
  1174.             lock (SyncRoot) {
  1175.                 // This method hasn't been fully tweaked to be safe for a concurrent writer.
  1176.                 int oldVersion = version;
  1177.             info.AddValue(LoadFactorName, loadFactor);
  1178.             info.AddValue(VersionName, version);
  1179.  
  1180.             //
  1181.             // We need to maintain serialization compatibility with Everett and RTM.
  1182.             // If the comparer is null or a compatible comparer, serialize Hashtable
  1183.             // in a format that can be deserialized on Everett and RTM.
  1184.             //
  1185.             // Also, if the Hashtable is using randomized hashing, serialize the old
  1186.             // view of the _keycomparer so perevious frameworks don't see the new types
  1187. #pragma warning disable 618
  1188. #if FEATURE_RANDOMIZED_STRING_HASHING
  1189.             IEqualityComparer keyComparerForSerilization = (IEqualityComparer) HashHelpers.GetEqualityComparerForSerialization(_keycomparer);
  1190. #else
  1191.             IEqualityComparer keyComparerForSerilization = _keycomparer;
  1192. #endif
  1193.  
  1194.             if( keyComparerForSerilization == null) {
  1195.                 info.AddValue(ComparerName, null,typeof(IComparer));
  1196.                 info.AddValue(HashCodeProviderName, null, typeof(IHashCodeProvider));
  1197.             }
  1198.             else if(keyComparerForSerilization is CompatibleComparer) {
  1199.                 CompatibleComparer c = keyComparerForSerilization as CompatibleComparer;
  1200.                 info.AddValue(ComparerName, c.Comparer, typeof(IComparer));
  1201.                 info.AddValue(HashCodeProviderName, c.HashCodeProvider, typeof(IHashCodeProvider));
  1202.             }
  1203.             else {
  1204.                 info.AddValue(KeyComparerName, keyComparerForSerilization, typeof(IEqualityComparer));
  1205.             }
  1206. #pragma warning restore 618
  1207.  
  1208.             info.AddValue(HashSizeName, buckets.Length); //This is the length of the bucket array.
  1209.             Object [] serKeys = new Object[count];
  1210.             Object [] serValues = new Object[count];
  1211.             CopyKeys(serKeys, 0);
  1212.             CopyValues(serValues,0);
  1213.             info.AddValue(KeysName, serKeys, typeof(Object[]));
  1214.             info.AddValue(ValuesName, serValues, typeof(Object[]));
  1215.  
  1216.                 // Explicitly check to see if anyone changed the Hashtable while we
  1217.                 // were serializing it.  That's a ---- in their code.
  1218.                 if (version != oldVersion)
  1219.                     throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
  1220.         }
  1221.         }
  1222.  
  1223.         //
  1224.         // DeserializationEvent Listener
  1225.         //
  1226.         public virtual void OnDeserialization(Object sender) {
  1227.             if (buckets!=null) {
  1228.                 // Somebody had a dependency on this hashtable and fixed us up before the ObjectManager got to it.
  1229.                 return;
  1230.             }
  1231.  
  1232.             SerializationInfo siInfo;
  1233.             HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo);
  1234.  
  1235.             if (siInfo==null) {
  1236.                 throw new SerializationException(Environment.GetResourceString("Serialization_InvalidOnDeser"));
  1237.             }
  1238.  
  1239.             int hashsize = 0;
  1240.             IComparer c = null;
  1241.  
  1242. #pragma warning disable 618
  1243.             IHashCodeProvider hcp = null;
  1244. #pragma warning restore 618
  1245.  
  1246.             Object [] serKeys = null;
  1247.             Object [] serValues = null;
  1248.  
  1249.             SerializationInfoEnumerator enumerator = siInfo.GetEnumerator();
  1250.  
  1251.             while( enumerator.MoveNext())
  1252.             {
  1253.                 switch( enumerator.Name)
  1254.                 {
  1255.                     case LoadFactorName:
  1256.                         loadFactor = siInfo.GetSingle(LoadFactorName);
  1257.                         break;
  1258.                     case HashSizeName:
  1259.                         hashsize = siInfo.GetInt32(HashSizeName);
  1260.                         break;
  1261.                     case KeyComparerName:
  1262.                         _keycomparer = (IEqualityComparer)siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer));
  1263.                         break;
  1264.                     case ComparerName:
  1265.                         c = (IComparer)siInfo.GetValue(ComparerName, typeof(IComparer));
  1266.                         break;
  1267.                     case HashCodeProviderName:
  1268. #pragma warning disable 618
  1269.                         hcp = (IHashCodeProvider)siInfo.GetValue(HashCodeProviderName, typeof(IHashCodeProvider));
  1270. #pragma warning restore 618
  1271.                         break;
  1272.                     case KeysName:
  1273.                         serKeys = (Object[])siInfo.GetValue(KeysName, typeof(Object[]));
  1274.                         break;
  1275.                     case ValuesName:
  1276.                         serValues = (Object[])siInfo.GetValue(ValuesName, typeof(Object[]));
  1277.                         break;
  1278.                 }
  1279.             }
  1280.  
  1281.             loadsize   = (int)(loadFactor*hashsize);
  1282.  
  1283.             // V1 object doesn't has _keycomparer field.
  1284.             if ( (_keycomparer == null) && ( (c != null) || (hcp != null) ) ){
  1285.                 _keycomparer = new CompatibleComparer(c,hcp);
  1286.             }
  1287.  
  1288.             buckets = new bucket[hashsize];
  1289.  
  1290.             if (serKeys==null) {
  1291.                 throw new SerializationException(Environment.GetResourceString("Serialization_MissingKeys"));
  1292.             }
  1293.             if (serValues==null) {
  1294.                 throw new SerializationException(Environment.GetResourceString("Serialization_MissingValues"));
  1295.             }
  1296.             if (serKeys.Length!=serValues.Length) {
  1297.                 throw new SerializationException(Environment.GetResourceString("Serialization_KeyValueDifferentSizes"));
  1298.             }
  1299.             for (int i=0; i<serKeys.Length; i++) {
  1300.                 if (serKeys[i]==null) {
  1301.                     throw new SerializationException(Environment.GetResourceString("Serialization_NullKey"));
  1302.                 }
  1303.                 Insert(serKeys[i], serValues[i], true);
  1304.             }
  1305.  
  1306.             version = siInfo.GetInt32(VersionName);
  1307.  
  1308.             HashHelpers.SerializationInfoTable.Remove(this);
  1309.         }
  1310.  
  1311.  
  1312.         // Implements a Collection for the keys of a hashtable. An instance of this
  1313.         // class is created by the GetKeys method of a hashtable.
  1314.         [Serializable]
  1315.         private class KeyCollection : ICollection
  1316.         {
  1317.             private Hashtable _hashtable;
  1318.  
  1319.             internal KeyCollection(Hashtable hashtable) {
  1320.                 _hashtable = hashtable;
  1321.             }
  1322.  
  1323.             public virtual void CopyTo(Array array, int arrayIndex) {
  1324.                 if (array==null)
  1325.                     throw new ArgumentNullException("array");
  1326.                 if (array.Rank != 1)
  1327.                     throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
  1328.                 if (arrayIndex < 0)
  1329.                     throw new ArgumentOutOfRangeException("arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
  1330.                 Contract.EndContractBlock();
  1331.                 if (array.Length - arrayIndex < _hashtable.count)
  1332.                     throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
  1333.                 _hashtable.CopyKeys(array, arrayIndex);
  1334.             }
  1335.  
  1336. #if !FEATURE_CORECLR
  1337.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  1338. #endif
  1339.             public virtual IEnumerator GetEnumerator() {
  1340.                 return new HashtableEnumerator(_hashtable, HashtableEnumerator.Keys);
  1341.             }
  1342.  
  1343.             public virtual bool IsSynchronized {
  1344.                 get { return _hashtable.IsSynchronized; }
  1345.             }
  1346.  
  1347.             public virtual Object SyncRoot {
  1348.                 get { return _hashtable.SyncRoot; }
  1349.             }
  1350.  
  1351.             public virtual int Count {
  1352.                 get { return _hashtable.count; }
  1353.             }
  1354.         }
  1355.  
  1356.         // Implements a Collection for the values of a hashtable. An instance of
  1357.         // this class is created by the GetValues method of a hashtable.
  1358.         [Serializable]
  1359.         private class ValueCollection : ICollection
  1360.         {
  1361.             private Hashtable _hashtable;
  1362.  
  1363.             internal ValueCollection(Hashtable hashtable) {
  1364.                 _hashtable = hashtable;
  1365.             }
  1366.  
  1367.             public virtual void CopyTo(Array array, int arrayIndex) {
  1368.                 if (array==null)
  1369.                     throw new ArgumentNullException("array");
  1370.                 if (array.Rank != 1)
  1371.                     throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
  1372.                 if (arrayIndex < 0)
  1373.                     throw new ArgumentOutOfRangeException("arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
  1374.                 Contract.EndContractBlock();
  1375.                 if (array.Length - arrayIndex < _hashtable.count)
  1376.                     throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
  1377.                 _hashtable.CopyValues(array, arrayIndex);
  1378.             }
  1379.  
  1380. #if !FEATURE_CORECLR
  1381.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  1382. #endif
  1383.             public virtual IEnumerator GetEnumerator() {
  1384.                 return new HashtableEnumerator(_hashtable, HashtableEnumerator.Values);
  1385.             }
  1386.  
  1387.             public virtual bool IsSynchronized {
  1388.                 get { return _hashtable.IsSynchronized; }
  1389.             }
  1390.  
  1391.             public virtual Object SyncRoot {
  1392.                 get { return _hashtable.SyncRoot; }
  1393.             }
  1394.  
  1395.             public virtual int Count {
  1396.                 get { return _hashtable.count; }
  1397.             }
  1398.         }
  1399.  
  1400.         // Synchronized wrapper for hashtable
  1401.         [Serializable]
  1402.         private class SyncHashtable : Hashtable, IEnumerable
  1403.         {
  1404.             protected Hashtable _table;
  1405.  
  1406.             internal SyncHashtable(Hashtable table) : base(false) {
  1407.                 _table = table;
  1408.             }
  1409.  
  1410.             internal SyncHashtable(SerializationInfo info, StreamingContext context) : base (info, context) {
  1411.                 _table = (Hashtable)info.GetValue("ParentTable", typeof(Hashtable));
  1412.                 if (_table==null) {
  1413.                     throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
  1414.                 }
  1415.             }
  1416.  
  1417.  
  1418.             /*================================GetObjectData=================================
  1419.             **Action: Return a serialization info containing a reference to _table.  We need
  1420.             **        to implement this because our parent HT does and we don't want to actually
  1421.             **        serialize all of it's values (just a reference to the table, which will then
  1422.             **        be serialized separately.)
  1423.             **Returns: void
  1424.             **Arguments: info -- the SerializationInfo into which to store the data.
  1425.             **           context -- the StreamingContext for the current serialization (ignored)
  1426.             **Exceptions: ArgumentNullException if info is null.
  1427.             ==============================================================================*/
  1428.             [System.Security.SecurityCritical]  // auto-generated
  1429.             public override void GetObjectData(SerializationInfo info, StreamingContext context) {
  1430.                 if (info==null) {
  1431.                     throw new ArgumentNullException("info");
  1432.                 }
  1433.                 Contract.EndContractBlock();
  1434.                 // Our serialization code hasn't been fully tweaked to be safe
  1435.                 // for a concurrent writer.
  1436.                 lock (_table.SyncRoot) {
  1437.                 info.AddValue("ParentTable", _table, typeof(Hashtable));
  1438.             }
  1439.             }
  1440.  
  1441.             public override int Count {
  1442.                 get { return _table.Count; }
  1443.             }
  1444.  
  1445.             public override bool IsReadOnly {
  1446.                 get { return _table.IsReadOnly; }
  1447.             }
  1448.  
  1449.             public override bool IsFixedSize {
  1450.                 get { return _table.IsFixedSize; }
  1451.             }
  1452.  
  1453.             public override bool IsSynchronized {
  1454.                 get { return true; }
  1455.             }
  1456.  
  1457.             public override Object this[Object key] {
  1458. #if !FEATURE_CORECLR
  1459.                 [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  1460. #endif
  1461.                 get {
  1462.                         return _table[key];
  1463.                 }
  1464.                 set {
  1465.                     lock(_table.SyncRoot) {
  1466.                         _table[key] = value;
  1467.                     }
  1468.                 }
  1469.             }
  1470.  
  1471.             public override Object SyncRoot {
  1472.                 get { return _table.SyncRoot; }
  1473.             }
  1474.  
  1475.             public override void Add(Object key, Object value) {
  1476.                 lock(_table.SyncRoot) {
  1477.                     _table.Add(key, value);
  1478.                 }
  1479.             }
  1480.  
  1481.             public override void Clear() {
  1482.                 lock(_table.SyncRoot) {
  1483.                     _table.Clear();
  1484.                 }
  1485.             }
  1486.  
  1487. #if !FEATURE_CORECLR
  1488.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  1489. #endif
  1490.             public override bool Contains(Object key) {
  1491.                 return _table.Contains(key);
  1492.             }
  1493.  
  1494. #if !FEATURE_CORECLR
  1495.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  1496. #endif
  1497.             public override bool ContainsKey(Object key) {
  1498.                 if (key == null) {
  1499.                     throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
  1500.                 }
  1501.                 Contract.EndContractBlock();
  1502.                 return _table.ContainsKey(key);
  1503.             }
  1504.  
  1505.             public override bool ContainsValue(Object key) {
  1506.                 lock(_table.SyncRoot) {
  1507.                     return _table.ContainsValue(key);
  1508.                 }
  1509.             }
  1510.  
  1511.             public override void CopyTo(Array array, int arrayIndex) {
  1512.                 lock (_table.SyncRoot) {
  1513.                     _table.CopyTo(array, arrayIndex);
  1514.                 }
  1515.             }
  1516.  
  1517.             public override Object Clone() {
  1518.                 lock (_table.SyncRoot) {
  1519.                     return Hashtable.Synchronized((Hashtable)_table.Clone());
  1520.                 }
  1521.             }
  1522.  
  1523.             IEnumerator IEnumerable.GetEnumerator() {
  1524.                 return _table.GetEnumerator();
  1525.             }
  1526.  
  1527.             public override IDictionaryEnumerator GetEnumerator() {
  1528.                 return _table.GetEnumerator();
  1529.             }
  1530.  
  1531.             public override ICollection Keys {
  1532.                 get {
  1533.                     lock(_table.SyncRoot) {
  1534.                         return _table.Keys;
  1535.                     }
  1536.                 }
  1537.             }
  1538.  
  1539.             public override ICollection Values {
  1540.                 get {
  1541.                     lock(_table.SyncRoot) {
  1542.                         return _table.Values;
  1543.                     }
  1544.                 }
  1545.             }
  1546.  
  1547.             public override void Remove(Object key) {
  1548.                 lock(_table.SyncRoot) {
  1549.                     _table.Remove(key);
  1550.                 }
  1551.             }
  1552.  
  1553.             /*==============================OnDeserialization===============================
  1554.             **Action: Does nothing.  We have to implement this because our parent HT implements it,
  1555.             **        but it doesn't do anything meaningful.  The real work will be done when we
  1556.             **        call OnDeserialization on our parent table.
  1557.             **Returns: void
  1558.             **Arguments: None
  1559.             **Exceptions: None
  1560.             ==============================================================================*/
  1561.             public override void OnDeserialization(Object sender) {
  1562.                 return;
  1563.             }
  1564.  
  1565.             internal override KeyValuePairs[] ToKeyValuePairsArray() {
  1566.                 return _table.ToKeyValuePairsArray();
  1567.             }
  1568.  
  1569.         }
  1570.  
  1571.  
  1572.         // Implements an enumerator for a hashtable. The enumerator uses the
  1573.         // internal version number of the hashtabke to ensure that no modifications
  1574.         // are made to the hashtable while an enumeration is in progress.
  1575.         [Serializable]
  1576.         private class HashtableEnumerator : IDictionaryEnumerator, ICloneable
  1577.         {
  1578.             private Hashtable hashtable;
  1579.             private int bucket;
  1580.             private int version;
  1581.             private bool current;
  1582.             private int getObjectRetType;   // What should GetObject return?
  1583.             private Object currentKey;
  1584.             private Object currentValue;
  1585.  
  1586.             internal const int Keys = 1;
  1587.             internal const int Values = 2;
  1588.             internal const int DictEntry = 3;
  1589.  
  1590.             internal HashtableEnumerator(Hashtable hashtable, int getObjRetType) {
  1591.                 this.hashtable = hashtable;
  1592.                 bucket = hashtable.buckets.Length;
  1593.                 version = hashtable.version;
  1594.                 current = false;
  1595.                 getObjectRetType = getObjRetType;
  1596.             }
  1597.  
  1598.             public Object Clone() {
  1599.                 return MemberwiseClone();
  1600.             }
  1601.  
  1602.             public virtual Object Key {
  1603. #if !FEATURE_CORECLR
  1604.                 [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  1605. #endif
  1606.                 get {
  1607.                     if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
  1608.                     return currentKey;
  1609.                 }
  1610.             }
  1611.  
  1612.             public virtual bool MoveNext() {
  1613.                 if (version != hashtable.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
  1614.                 while (bucket > 0) {
  1615.                     bucket--;
  1616.                     Object keyv = hashtable.buckets[bucket].key;
  1617.                     if ((keyv!= null) && (keyv != hashtable.buckets)) {
  1618.                         currentKey = keyv;
  1619.                         currentValue = hashtable.buckets[bucket].val;
  1620.                         current = true;
  1621.                         return true;
  1622.                     }
  1623.                 }
  1624.                 current = false;
  1625.                 return false;
  1626.             }
  1627.  
  1628.             public virtual DictionaryEntry Entry {
  1629.                 get {
  1630.                     if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
  1631.                     return new DictionaryEntry(currentKey, currentValue);
  1632.                 }
  1633.             }
  1634.  
  1635.  
  1636.             public virtual Object Current {
  1637.                 get {
  1638.                     if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
  1639.  
  1640.                     if (getObjectRetType==Keys)
  1641.                         return currentKey;
  1642.                     else if (getObjectRetType==Values)
  1643.                         return currentValue;
  1644.                     else
  1645.                         return new DictionaryEntry(currentKey, currentValue);
  1646.                 }
  1647.             }
  1648.  
  1649.             public virtual Object Value {
  1650. #if !FEATURE_CORECLR
  1651.                 [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  1652. #endif
  1653.                 get {
  1654.                     if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
  1655.                     return currentValue;
  1656.                 }
  1657.             }
  1658.  
  1659.             public virtual void Reset() {
  1660.                 if (version != hashtable.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
  1661.                 current = false;
  1662.                 bucket = hashtable.buckets.Length;
  1663.                 currentKey = null;
  1664.                 currentValue = null;
  1665.             }
  1666.         }
  1667.  
  1668.         // internal debug view class for hashtable
  1669.         internal class HashtableDebugView {
  1670.             private Hashtable hashtable;
  1671.  
  1672.             public HashtableDebugView( Hashtable hashtable) {
  1673.                 if( hashtable == null) {
  1674.                     throw new ArgumentNullException( "hashtable");
  1675.                 }
  1676.                 Contract.EndContractBlock();
  1677.  
  1678.                 this.hashtable = hashtable;
  1679.             }
  1680.  
  1681.  
  1682.             [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
  1683.             public KeyValuePairs[] Items {
  1684.                 get {
  1685.                     return hashtable.ToKeyValuePairsArray();
  1686.                 }
  1687.             }
  1688.         }
  1689.     }
  1690.  
  1691.     [FriendAccessAllowed]
  1692.     internal static class HashHelpers
  1693.     {
  1694.  
  1695. #if FEATURE_RANDOMIZED_STRING_HASHING
  1696.         public const int HashCollisionThreshold = 100;
  1697.         public static bool s_UseRandomizedStringHashing = String.UseRandomizedHashing();
  1698. #endif
  1699.  
  1700.         // Table of prime numbers to use as hash table sizes.
  1701.         // A typical resize algorithm would pick the smallest prime number in this array
  1702.         // that is larger than twice the previous capacity.
  1703.         // Suppose our Hashtable currently has capacity x and enough elements are added
  1704.         // such that a resize needs to occur. Resizing first computes 2x then finds the
  1705.         // first prime in the table greater than 2x, i.e. if primes are ordered
  1706.         // p_1, p_2, ..., p_i, ..., it finds p_n such that p_n-1 < 2x < p_n.
  1707.         // Doubling is important for preserving the asymptotic complexity of the
  1708.         // hashtable operations such as add.  Having a prime guarantees that double
  1709.         // hashing does not lead to infinite loops.  IE, your hash function will be
  1710.         // h1(key) + i*h2(key), 0 <= i < size.  h2 and the size must be relatively prime.
  1711.         public static readonly int[] primes = {
  1712.             3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919,
  1713.             1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591,
  1714.             17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437,
  1715.             187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263,
  1716.             1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369};
  1717.  
  1718.         // Used by Hashtable and Dictionary's SeralizationInfo .ctor's to store the SeralizationInfo
  1719.         // object until OnDeserialization is called.
  1720.         private static ConditionalWeakTable<object, SerializationInfo> s_SerializationInfoTable;
  1721.  
  1722.         internal static ConditionalWeakTable<object, SerializationInfo> SerializationInfoTable
  1723.         {
  1724.             get
  1725.             {
  1726.                 if(s_SerializationInfoTable == null)
  1727.                 {
  1728.                     ConditionalWeakTable<object, SerializationInfo> newTable = new ConditionalWeakTable<object, SerializationInfo>();
  1729.                     Interlocked.CompareExchange(ref s_SerializationInfoTable, newTable, null);
  1730.                 }
  1731.  
  1732.                 return s_SerializationInfoTable;
  1733.             }
  1734.  
  1735.         }
  1736.  
  1737.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  1738.         public static bool IsPrime(int candidate)
  1739.         {
  1740.             if ((candidate & 1) != 0)
  1741.             {
  1742.                 int limit = (int)Math.Sqrt (candidate);
  1743.                 for (int divisor = 3; divisor <= limit; divisor+=2)
  1744.                 {
  1745.                     if ((candidate % divisor) == 0)
  1746.                         return false;
  1747.                 }
  1748.                 return true;
  1749.             }
  1750.             return (candidate == 2);
  1751.         }
  1752.  
  1753.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  1754.         public static int GetPrime(int min)
  1755.         {
  1756.             if (min < 0)
  1757.                 throw new ArgumentException(Environment.GetResourceString("Arg_HTCapacityOverflow"));
  1758.             Contract.EndContractBlock();
  1759.  
  1760.             for (int i = 0; i < primes.Length; i++)
  1761.             {
  1762.                 int prime = primes[i];
  1763.                 if (prime >= min) return prime;
  1764.             }
  1765.  
  1766.             //outside of our predefined table.
  1767.             //compute the hard way.
  1768.             for (int i = (min | 1); i < Int32.MaxValue;i+=2)
  1769.             {
  1770.                 if (IsPrime(i) && ((i - 1) % Hashtable.HashPrime != 0))
  1771.                     return i;
  1772.             }
  1773.             return min;
  1774.         }
  1775.  
  1776.         public static int GetMinPrime()
  1777.         {
  1778.             return primes[0];
  1779.         }
  1780.  
  1781.         // Returns size of hashtable to grow to.
  1782.         public static int ExpandPrime(int oldSize)
  1783.         {
  1784.             int newSize = 2 * oldSize;
  1785.  
  1786.             // Allow the hashtables to grow to maximum possible size (~2G elements) before encoutering capacity overflow.
  1787.             // Note that this check works even when _items.Length overflowed thanks to the (uint) cast
  1788.             if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize)
  1789.             {
  1790.                 Contract.Assert( MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
  1791.                 return MaxPrimeArrayLength;
  1792.             }
  1793.  
  1794.             return GetPrime(newSize);
  1795.         }
  1796.  
  1797.  
  1798.         // This is the maximum prime smaller than Array.MaxArrayLength
  1799.         public const int MaxPrimeArrayLength = 0x7FEFFFFD;
  1800.  
  1801. #if FEATURE_RANDOMIZED_STRING_HASHING
  1802.         public static bool IsWellKnownEqualityComparer(object comparer)
  1803.         {
  1804.             return (comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer);
  1805.         }
  1806.  
  1807.         public static IEqualityComparer GetRandomizedEqualityComparer(object comparer)
  1808.         {
  1809.             Contract.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer);
  1810.  
  1811.             if(comparer == null) {
  1812.                 return new System.Collections.Generic.RandomizedObjectEqualityComparer();
  1813.             }
  1814.  
  1815.             if(comparer == System.Collections.Generic.EqualityComparer<string>.Default) {
  1816.                 return new System.Collections.Generic.RandomizedStringEqualityComparer();
  1817.             }
  1818.  
  1819.             IWellKnownStringEqualityComparer cmp = comparer as IWellKnownStringEqualityComparer;
  1820.  
  1821.             if(cmp != null) {
  1822.                 return cmp.GetRandomizedEqualityComparer();
  1823.             }
  1824.  
  1825.             Contract.Assert(false, "Missing case in GetRandomizedEqualityComparer!");
  1826.  
  1827.             return null;
  1828.         }
  1829.  
  1830.         public static object GetEqualityComparerForSerialization(object comparer)
  1831.         {
  1832.             if(comparer == null)
  1833.             {
  1834.                 return null;
  1835.             }
  1836.  
  1837.             IWellKnownStringEqualityComparer cmp = comparer as IWellKnownStringEqualityComparer;
  1838.  
  1839.             if(cmp != null)
  1840.             {
  1841.                 return cmp.GetEqualityComparerForSerialization();
  1842.             }
  1843.  
  1844.             return comparer;
  1845.         }
  1846.  
  1847.         private const int bufferSize = 1024;
  1848.         private static RandomNumberGenerator rng;
  1849.         private static byte[] data;
  1850.         private static int currentIndex = bufferSize;
  1851.         private static readonly object lockObj = new Object();
  1852.  
  1853.         internal static long GetEntropy()
  1854.         {
  1855.             lock(lockObj) {
  1856.                 long ret;
  1857.  
  1858.                 if(currentIndex == bufferSize)
  1859.                 {
  1860.                     if(null == rng)
  1861.                     {
  1862.                         rng = RandomNumberGenerator.Create();
  1863.                         data = new byte[bufferSize];
  1864.                         Contract.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8");
  1865.                     }
  1866.  
  1867.                     rng.GetBytes(data);
  1868.                     currentIndex = 0;
  1869.                 }
  1870.  
  1871.                 ret = BitConverter.ToInt64(data, currentIndex);
  1872.                 currentIndex += 8;
  1873.  
  1874.                 return ret;
  1875.             }
  1876.         }
  1877. #endif // FEATURE_RANDOMIZED_STRING_HASHING
  1878.     }
  1879. }
  1880.  
  1881. // File provided for Reference Use Only by Microsoft Corporation (c) 2007.
  1882. // ==++==
  1883. //
  1884. //   Copyright (c) Microsoft Corporation.  All rights reserved.
  1885. //
  1886. // ==--==
  1887. /*============================================================
  1888. **
  1889. ** Class:  Hashtable
  1890. **
  1891. ** <OWNER>[....]</OWNER>
  1892. **
  1893. **
  1894. ** Purpose: Hash table implementation
  1895. **
  1896. **
  1897. ===========================================================*/
  1898.  
  1899. namespace System.Collections {
  1900.     using System;
  1901.     using System.Runtime;
  1902.     using System.Runtime.Serialization;
  1903.     using System.Security.Permissions;
  1904.     using System.Diagnostics;
  1905.     using System.Threading;
  1906.     using System.Runtime.CompilerServices;
  1907.     using System.Runtime.ConstrainedExecution;
  1908.     using System.Diagnostics.Contracts;
  1909.     using System.Security.Cryptography;
  1910.  
  1911.     // The Hashtable class represents a dictionary of associated keys and values
  1912.     // with constant lookup time.
  1913.     //
  1914.     // Objects used as keys in a hashtable must implement the GetHashCode
  1915.     // and Equals methods (or they can rely on the default implementations
  1916.     // inherited from Object if key equality is simply reference
  1917.     // equality). Furthermore, the GetHashCode and Equals methods of
  1918.     // a key object must produce the same results given the same parameters for the
  1919.     // entire time the key is present in the hashtable. In practical terms, this
  1920.     // means that key objects should be immutable, at least for the time they are
  1921.     // used as keys in a hashtable.
  1922.     //
  1923.     // When entries are added to a hashtable, they are placed into
  1924.     // buckets based on the hashcode of their keys. Subsequent lookups of
  1925.     // keys will use the hashcode of the keys to only search a particular bucket,
  1926.     // thus substantially reducing the number of key comparisons required to find
  1927.     // an entry. A hashtable's maximum load factor, which can be specified
  1928.     // when the hashtable is instantiated, determines the maximum ratio of
  1929.     // hashtable entries to hashtable buckets. Smaller load factors cause faster
  1930.     // average lookup times at the cost of increased memory consumption. The
  1931.     // default maximum load factor of 1.0 generally provides the best balance
  1932.     // between speed and size. As entries are added to a hashtable, the hashtable's
  1933.     // actual load factor increases, and when the actual load factor reaches the
  1934.     // maximum load factor value, the number of buckets in the hashtable is
  1935.     // automatically increased by approximately a factor of two (to be precise, the
  1936.     // number of hashtable buckets is increased to the smallest prime number that
  1937.     // is larger than twice the current number of hashtable buckets).
  1938.     //
  1939.     // Each object provides their own hash function, accessed by calling
  1940.     // GetHashCode().  However, one can write their own object
  1941.     // implementing IEqualityComparer and pass it to a constructor on
  1942.     // the Hashtable.  That hash function (and the equals method on the
  1943.     // IEqualityComparer) would be used for all objects in the table.
  1944.     //
  1945.     // Changes since V1 during Whidbey:
  1946.     // *) Deprecated IHashCodeProvider, use IEqualityComparer instead.  This will
  1947.     //    allow better performance for objects where equality checking can be
  1948.     //    done much faster than establishing an ordering between two objects,
  1949.     //    such as an ordinal string equality check.
  1950.     //
  1951.     [DebuggerTypeProxy(typeof(System.Collections.Hashtable.HashtableDebugView))]
  1952.     [DebuggerDisplay("Count = {Count}")]
  1953.     [System.Runtime.InteropServices.ComVisible(true)]
  1954.     [Serializable]
  1955.     public class Hashtable : IDictionary, ISerializable, IDeserializationCallback, ICloneable {
  1956.         /*
  1957.           Implementation Notes:
  1958.           The generic Dictionary was copied from Hashtable's source - any bug
  1959.           fixes here probably need to be made to the generic Dictionary as well.
  1960.  
  1961.           This Hashtable uses double hashing.  There are hashsize buckets in the
  1962.           table, and each bucket can contain 0 or 1 element.  We a bit to mark
  1963.           whether there's been a collision when we inserted multiple elements
  1964.           (ie, an inserted item was hashed at least a second time and we probed
  1965.           this bucket, but it was already in use).  Using the collision bit, we
  1966.           can terminate lookups & removes for elements that aren't in the hash
  1967.           table more quickly.  We steal the most significant bit from the hash code
  1968.           to store the collision bit.
  1969.  
  1970.           Our hash function is of the following form:
  1971.  
  1972.           h(key, n) = h1(key) + n*h2(key)
  1973.  
  1974.           where n is the number of times we've hit a collided bucket and rehashed
  1975.           (on this particular lookup).  Here are our hash functions:
  1976.  
  1977.           h1(key) = GetHash(key);  // default implementation calls key.GetHashCode();
  1978.           h2(key) = 1 + (((h1(key) >> 5) + 1) % (hashsize - 1));
  1979.  
  1980.           The h1 can return any number.  h2 must return a number between 1 and
  1981.           hashsize - 1 that is relatively prime to hashsize (not a problem if
  1982.           hashsize is prime).  (Knuth's Art of Computer Programming, Vol. 3, p. 528-9)
  1983.           If this is true, then we are guaranteed to visit every bucket in exactly
  1984.           hashsize probes, since the least common multiple of hashsize and h2(key)
  1985.           will be hashsize * h2(key).  (This is the first number where adding h2 to
  1986.           h1 mod hashsize will be 0 and we will search the same bucket twice).
  1987.  
  1988.           We previously used a different h2(key, n) that was not constant.  That is a
  1989.           horrifically bad idea, unless you can prove that series will never produce
  1990.           any identical numbers that overlap when you mod them by hashsize, for all
  1991.           subranges from i to i+hashsize, for all i.  It's not worth investigating,
  1992.           since there was no clear benefit from using that hash function, and it was
  1993.           broken.
  1994.  
  1995.           For efficiency reasons, we've implemented this by storing h1 and h2 in a
  1996.           temporary, and setting a variable called seed equal to h1.  We do a probe,
  1997.           and if we collided, we simply add h2 to seed each time through the loop.
  1998.  
  1999.           A good test for h2() is to subclass Hashtable, provide your own implementation
  2000.           of GetHash() that returns a constant, then add many items to the hash table.
  2001.           Make sure Count equals the number of items you inserted.
  2002.  
  2003.           Note that when we remove an item from the hash table, we set the key
  2004.           equal to buckets, if there was a collision in this bucket.  Otherwise
  2005.           we'd either wipe out the collision bit, or we'd still have an item in
  2006.           the hash table.
  2007.  
  2008.            --
  2009.         */
  2010.  
  2011.         internal const Int32 HashPrime = 101;
  2012.         private const Int32 InitialSize = 3;
  2013.         private const String LoadFactorName = "LoadFactor";
  2014.         private const String VersionName = "Version";
  2015.         private const String ComparerName = "Comparer";
  2016.         private const String HashCodeProviderName = "HashCodeProvider";
  2017.         private const String HashSizeName = "HashSize";  // Must save buckets.Length
  2018.         private const String KeysName = "Keys";
  2019.         private const String ValuesName = "Values";
  2020.         private const String KeyComparerName = "KeyComparer";
  2021.  
  2022.         // Deleted entries have their key set to buckets
  2023.  
  2024.         // The hash table data.
  2025.         // This cannot be serialised
  2026.         private struct bucket {
  2027.             public Object key;
  2028.             public Object val;
  2029.             public int hash_coll;   // Store hash code; sign bit means there was a collision.
  2030.         }
  2031.  
  2032.         private bucket[] buckets;
  2033.  
  2034.         // The total number of entries in the hash table.
  2035.         private  int count;
  2036.  
  2037.         // The total number of collision bits set in the hashtable
  2038.         private int occupancy;
  2039.  
  2040.         private  int loadsize;
  2041.         private  float loadFactor;
  2042.  
  2043.         private volatile int version;
  2044.         private volatile bool isWriterInProgress;
  2045.  
  2046.         private ICollection keys;
  2047.         private ICollection values;
  2048.  
  2049.         private IEqualityComparer _keycomparer;
  2050.         private Object _syncRoot;
  2051.  
  2052.         [Obsolete("Please use EqualityComparer property.")]
  2053.         protected IHashCodeProvider hcp
  2054.         {
  2055.             get
  2056.             {
  2057.                 if( _keycomparer is CompatibleComparer) {
  2058.                     return ((CompatibleComparer)_keycomparer).HashCodeProvider;
  2059.                 }
  2060.                 else if( _keycomparer == null) {
  2061.                     return null;
  2062.                 }
  2063.                 else {
  2064.                     throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
  2065.                 }
  2066.             }
  2067.             set
  2068.             {
  2069.                 if (_keycomparer is CompatibleComparer) {
  2070.                     CompatibleComparer keyComparer = (CompatibleComparer)_keycomparer;
  2071.                     _keycomparer = new CompatibleComparer(keyComparer.Comparer, value);
  2072.                 }
  2073.                 else if( _keycomparer == null) {
  2074.                     _keycomparer = new CompatibleComparer((IComparer)null, value);
  2075.                 }
  2076.                 else {
  2077.                     throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
  2078.                 }
  2079.             }
  2080.         }
  2081.  
  2082.  
  2083.         [Obsolete("Please use KeyComparer properties.")]
  2084.         protected IComparer comparer
  2085.         {
  2086.             get
  2087.             {
  2088.                 if( _keycomparer is CompatibleComparer) {
  2089.                     return ((CompatibleComparer)_keycomparer).Comparer;
  2090.                 }
  2091.                 else if( _keycomparer == null) {
  2092.                     return null;
  2093.                 }
  2094.                 else {
  2095.                     throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
  2096.                 }
  2097.             }
  2098.             set
  2099.             {
  2100.                 if (_keycomparer is CompatibleComparer) {
  2101.                     CompatibleComparer keyComparer = (CompatibleComparer)_keycomparer;
  2102.                     _keycomparer = new CompatibleComparer(value, keyComparer.HashCodeProvider);
  2103.                 }
  2104.                 else if( _keycomparer == null) {
  2105.                     _keycomparer = new CompatibleComparer(value, (IHashCodeProvider)null);
  2106.                 }
  2107.                 else {
  2108.                     throw new ArgumentException(Environment.GetResourceString("Arg_CannotMixComparisonInfrastructure"));
  2109.                 }
  2110.             }
  2111.         }
  2112.  
  2113.         protected IEqualityComparer EqualityComparer
  2114.         {
  2115.             get
  2116.             {
  2117.                 return _keycomparer;
  2118.             }
  2119.         }
  2120.  
  2121.         // Note: this constructor is a bogus constructor that does nothing
  2122.         // and is for use only with SyncHashtable.
  2123.         internal Hashtable( bool trash )
  2124.         {
  2125.         }
  2126.  
  2127.         // Constructs a new hashtable. The hashtable is created with an initial
  2128.         // capacity of zero and a load factor of 1.0.
  2129.         public Hashtable() : this(0, 1.0f) {
  2130.         }
  2131.  
  2132.         // Constructs a new hashtable with the given initial capacity and a load
  2133.         // factor of 1.0. The capacity argument serves as an indication of
  2134.         // the number of entries the hashtable will contain. When this number (or
  2135.         // an approximation) is known, specifying it in the constructor can
  2136.         // eliminate a number of resizing operations that would otherwise be
  2137.         // performed when elements are added to the hashtable.
  2138.         //
  2139.         public Hashtable(int capacity) : this(capacity, 1.0f) {
  2140.         }
  2141.  
  2142.         // Constructs a new hashtable with the given initial capacity and load
  2143.         // factor. The capacity argument serves as an indication of the
  2144.         // number of entries the hashtable will contain. When this number (or an
  2145.         // approximation) is known, specifying it in the constructor can eliminate
  2146.         // a number of resizing operations that would otherwise be performed when
  2147.         // elements are added to the hashtable. The loadFactor argument
  2148.         // indicates the maximum ratio of hashtable entries to hashtable buckets.
  2149.         // Smaller load factors cause faster average lookup times at the cost of
  2150.         // increased memory consumption. A load factor of 1.0 generally provides
  2151.         // the best balance between speed and size.
  2152.         //
  2153.         public Hashtable(int capacity, float loadFactor) {
  2154.             if (capacity < 0)
  2155.                 throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
  2156.             if (!(loadFactor >= 0.1f && loadFactor <= 1.0f))
  2157.                 throw new ArgumentOutOfRangeException("loadFactor", Environment.GetResourceString("ArgumentOutOfRange_HashtableLoadFactor", .1, 1.0));
  2158.             Contract.EndContractBlock();
  2159.  
  2160.             // Based on perf work, .72 is the optimal load factor for this table.
  2161.             this.loadFactor = 0.72f * loadFactor;
  2162.  
  2163.             double rawsize = capacity / this.loadFactor;
  2164.             if (rawsize > Int32.MaxValue)
  2165.                 throw new ArgumentException(Environment.GetResourceString("Arg_HTCapacityOverflow"));
  2166.  
  2167.             // Avoid awfully small sizes
  2168.             int hashsize = (rawsize > InitialSize) ? HashHelpers.GetPrime((int)rawsize) : InitialSize;
  2169.             buckets = new bucket[hashsize];
  2170.  
  2171.             loadsize = (int)(this.loadFactor * hashsize);
  2172.             isWriterInProgress = false;
  2173.             // Based on the current algorithm, loadsize must be less than hashsize.
  2174.             Contract.Assert( loadsize < hashsize, "Invalid hashtable loadsize!");
  2175.         }
  2176.  
  2177.         // Constructs a new hashtable with the given initial capacity and load
  2178.         // factor. The capacity argument serves as an indication of the
  2179.         // number of entries the hashtable will contain. When this number (or an
  2180.         // approximation) is known, specifying it in the constructor can eliminate
  2181.         // a number of resizing operations that would otherwise be performed when
  2182.         // elements are added to the hashtable. The loadFactor argument
  2183.         // indicates the maximum ratio of hashtable entries to hashtable buckets.
  2184.         // Smaller load factors cause faster average lookup times at the cost of
  2185.         // increased memory consumption. A load factor of 1.0 generally provides
  2186.         // the best balance between speed and size.  The hcp argument
  2187.         // is used to specify an Object that will provide hash codes for all
  2188.         // the Objects in the table.  Using this, you can in effect override
  2189.         // GetHashCode() on each Object using your own hash function.  The
  2190.         // comparer argument will let you specify a custom function for
  2191.         // comparing keys.  By specifying user-defined objects for hcp
  2192.         // and comparer, users could make a hash table using strings
  2193.         // as keys do case-insensitive lookups.
  2194.         //
  2195.         [Obsolete("Please use Hashtable(int, float, IEqualityComparer) instead.")]
  2196.         public Hashtable(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer) : this(capacity, loadFactor) {
  2197.             if (hcp == null && comparer == null) {
  2198.                 this._keycomparer = null;
  2199.             }
  2200.             else {
  2201.                 this._keycomparer = new CompatibleComparer(comparer,hcp);
  2202.             }
  2203.         }
  2204.  
  2205.         public Hashtable(int capacity, float loadFactor, IEqualityComparer equalityComparer) : this(capacity, loadFactor) {
  2206.             this._keycomparer = equalityComparer;
  2207.         }
  2208.  
  2209.         // Constructs a new hashtable using a custom hash function
  2210.         // and a custom comparison function for keys.  This will enable scenarios
  2211.         // such as doing lookups with case-insensitive strings.
  2212.         //
  2213.         [Obsolete("Please use Hashtable(IEqualityComparer) instead.")]
  2214.         public Hashtable(IHashCodeProvider hcp, IComparer comparer) : this(0, 1.0f, hcp, comparer) {
  2215.         }
  2216.  
  2217.         public Hashtable(IEqualityComparer equalityComparer) : this(0, 1.0f, equalityComparer) {
  2218.         }
  2219.  
  2220.         // Constructs a new hashtable using a custom hash function
  2221.         // and a custom comparison function for keys.  This will enable scenarios
  2222.         // such as doing lookups with case-insensitive strings.
  2223.         //
  2224.         [Obsolete("Please use Hashtable(int, IEqualityComparer) instead.")]
  2225.         public Hashtable(int capacity, IHashCodeProvider hcp, IComparer comparer)
  2226.             : this(capacity, 1.0f, hcp, comparer) {
  2227.         }
  2228.  
  2229.         public Hashtable(int capacity, IEqualityComparer equalityComparer)
  2230.             : this(capacity, 1.0f, equalityComparer) {
  2231.         }
  2232.  
  2233.         // Constructs a new hashtable containing a copy of the entries in the given
  2234.         // dictionary. The hashtable is created with a load factor of 1.0.
  2235.         //
  2236.         public Hashtable(IDictionary d) : this(d, 1.0f) {
  2237.         }
  2238.  
  2239.         // Constructs a new hashtable containing a copy of the entries in the given
  2240.         // dictionary. The hashtable is created with the given load factor.
  2241.         //
  2242.         public Hashtable(IDictionary d, float loadFactor)
  2243.             : this(d, loadFactor, (IEqualityComparer)null) {
  2244.         }
  2245.  
  2246.         [Obsolete("Please use Hashtable(IDictionary, IEqualityComparer) instead.")]
  2247.         public Hashtable(IDictionary d, IHashCodeProvider hcp, IComparer comparer)
  2248.             : this(d, 1.0f, hcp, comparer)  {
  2249.         }
  2250.  
  2251.         public Hashtable(IDictionary d, IEqualityComparer equalityComparer)
  2252.             : this(d, 1.0f, equalityComparer)    {
  2253.         }
  2254.  
  2255.         [Obsolete("Please use Hashtable(IDictionary, float, IEqualityComparer) instead.")]
  2256.         public Hashtable(IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer)
  2257.             : this((d != null ? d.Count : 0), loadFactor, hcp, comparer) {
  2258.             if (d==null)
  2259.                 throw new ArgumentNullException("d", Environment.GetResourceString("ArgumentNull_Dictionary"));
  2260.             Contract.EndContractBlock();
  2261.  
  2262.             IDictionaryEnumerator e = d.GetEnumerator();
  2263.             while (e.MoveNext()) Add(e.Key, e.Value);
  2264.         }
  2265.  
  2266.         public Hashtable(IDictionary d, float loadFactor, IEqualityComparer equalityComparer)
  2267.             : this((d != null ? d.Count : 0), loadFactor, equalityComparer) {
  2268.             if (d==null)
  2269.                 throw new ArgumentNullException("d", Environment.GetResourceString("ArgumentNull_Dictionary"));
  2270.             Contract.EndContractBlock();
  2271.  
  2272.             IDictionaryEnumerator e = d.GetEnumerator();
  2273.             while (e.MoveNext()) Add(e.Key, e.Value);
  2274.         }
  2275.  
  2276.         protected Hashtable(SerializationInfo info, StreamingContext context) {
  2277.             //We can't do anything with the keys and values until the entire graph has been deserialized
  2278.             //and we have a reasonable estimate that GetHashCode is not going to fail.  For the time being,
  2279.             //we'll just cache this.  The graph is not valid until OnDeserialization has been called.
  2280.             HashHelpers.SerializationInfoTable.Add(this, info);
  2281.         }
  2282.  
  2283.         // ‘InitHash’ is basically an implementation of classic DoubleHashing (see http://en.wikipedia.org/wiki/Double_hashing)
  2284.         //
  2285.         // 1) The only ‘correctness’ requirement is that the ‘increment’ used to probe
  2286.         //    a. Be non-zero
  2287.         //    b. Be relatively prime to the table size ‘hashSize’. (This is needed to insure you probe all entries in the table before you ‘wrap’ and visit entries already probed)
  2288.         // 2) Because we choose table sizes to be primes, we just need to insure that the increment is 0 < incr < hashSize
  2289.         //
  2290.         // Thus this function would work: Incr = 1 + (seed % (hashSize-1))
  2291.         //
  2292.         // While this works well for ‘uniformly distributed’ keys, in practice, non-uniformity is common.
  2293.         // In particular in practice we can see ‘mostly sequential’ where you get long clusters of keys that ‘pack’.
  2294.         // To avoid bad behavior you want it to be the case that the increment is ‘large’ even for ‘small’ values (because small
  2295.         // values tend to happen more in practice). Thus we multiply ‘seed’ by a number that will make these small values
  2296.         // bigger (and not hurt large values). We picked HashPrime (101) because it was prime, and if ‘hashSize-1’ is not a multiple of HashPrime
  2297.         // (enforced in GetPrime), then incr has the potential of being every value from 1 to hashSize-1. The choice was largely arbitrary.
  2298.         //
  2299.         // Computes the hash function:  H(key, i) = h1(key) + i*h2(key, hashSize).
  2300.         // The out parameter seed is h1(key), while the out parameter
  2301.         // incr is h2(key, hashSize).  Callers of this function should
  2302.         // add incr each time through a loop.
  2303.         private uint InitHash(Object key, int hashsize, out uint seed, out uint incr) {
  2304.             // Hashcode must be positive.  Also, we must not use the sign bit, since
  2305.             // that is used for the collision bit.
  2306.             uint hashcode = (uint) GetHash(key) & 0x7FFFFFFF;
  2307.             seed = (uint) hashcode;
  2308.             // Restriction: incr MUST be between 1 and hashsize - 1, inclusive for
  2309.             // the modular arithmetic to work correctly.  This guarantees you'll
  2310.             // visit every bucket in the table exactly once within hashsize
  2311.             // iterations.  Violate this and it'll cause obscure bugs forever.
  2312.             // If you change this calculation for h2(key), update putEntry too!
  2313.             incr = (uint)(1 + ((seed * HashPrime) % ((uint)hashsize - 1)));
  2314.             return hashcode;
  2315.         }
  2316.  
  2317.         // Adds an entry with the given key and value to this hashtable. An
  2318.         // ArgumentException is thrown if the key is null or if the key is already
  2319.         // present in the hashtable.
  2320.         //
  2321. #if !FEATURE_CORECLR
  2322.         [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  2323. #endif
  2324.         public virtual void Add(Object key, Object value) {
  2325.             Insert(key, value, true);
  2326.         }
  2327.  
  2328.         // Removes all entries from this hashtable.
  2329.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  2330.         public virtual void Clear() {
  2331.             Contract.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously!  Don't do that - use Hashtable.Synchronized.");
  2332.  
  2333.             if (count == 0 && occupancy == 0)
  2334.                 return;
  2335.  
  2336. #if !FEATURE_CORECLR
  2337.             Thread.BeginCriticalRegion();
  2338. #endif
  2339.             isWriterInProgress = true;
  2340.             for (int i = 0; i < buckets.Length; i++){
  2341.                 buckets[i].hash_coll = 0;
  2342.                 buckets[i].key = null;
  2343.                 buckets[i].val = null;
  2344.             }
  2345.  
  2346.             count = 0;
  2347.             occupancy = 0;
  2348.             UpdateVersion();
  2349.             isWriterInProgress = false;
  2350. #if !FEATURE_CORECLR
  2351.             Thread.EndCriticalRegion();
  2352. #endif
  2353.         }
  2354.  
  2355.         // Clone returns a virtually identical copy of this hash table.  This does
  2356.         // a shallow copy - the Objects in the table aren't cloned, only the references
  2357.         // to those Objects.
  2358.         public virtual Object Clone()
  2359.         {
  2360.             bucket[] lbuckets = buckets;
  2361.             Hashtable ht = new Hashtable(count,_keycomparer);
  2362.             ht.version = version;
  2363.             ht.loadFactor = loadFactor;
  2364.             ht.count = 0;
  2365.  
  2366.             int bucket = lbuckets.Length;
  2367.             while (bucket > 0) {
  2368.                 bucket--;
  2369.                 Object keyv = lbuckets[bucket].key;
  2370.                 if ((keyv!= null) && (keyv != lbuckets)) {
  2371.                     ht[keyv] = lbuckets[bucket].val;
  2372.                 }
  2373.             }
  2374.  
  2375.             return ht;
  2376.         }
  2377.  
  2378.         // Checks if this hashtable contains the given key.
  2379. #if !FEATURE_CORECLR
  2380.         [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  2381. #endif
  2382.         public virtual bool Contains(Object key) {
  2383.             return ContainsKey(key);
  2384.         }
  2385.  
  2386.         // Checks if this hashtable contains an entry with the given key.  This is
  2387.         // an O(1) operation.
  2388.         //
  2389.         public virtual bool ContainsKey(Object key) {
  2390.             if (key == null) {
  2391.                 throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
  2392.             }
  2393.             Contract.EndContractBlock();
  2394.  
  2395.             uint seed;
  2396.             uint incr;
  2397.             // Take a snapshot of buckets, in case another thread resizes table
  2398.             bucket[] lbuckets = buckets;
  2399.             uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr);
  2400.             int  ntry = 0;
  2401.  
  2402.             bucket b;
  2403.             int bucketNumber = (int) (seed % (uint)lbuckets.Length);
  2404.             do {
  2405.                 b = lbuckets[bucketNumber];
  2406.                 if (b.key == null) {
  2407.                     return false;
  2408.                 }
  2409.                 if (((b.hash_coll &  0x7FFFFFFF) == hashcode) &&
  2410.                     KeyEquals (b.key, key))
  2411.                     return true;
  2412.                 bucketNumber = (int) (((long)bucketNumber + incr)% (uint)lbuckets.Length);
  2413.             } while (b.hash_coll < 0 && ++ntry < lbuckets.Length);
  2414.             return false;
  2415.         }
  2416.  
  2417.  
  2418.  
  2419.         // Checks if this hashtable contains an entry with the given value. The
  2420.         // values of the entries of the hashtable are compared to the given value
  2421.         // using the Object.Equals method. This method performs a linear
  2422.         // search and is thus be substantially slower than the ContainsKey
  2423.         // method.
  2424.         //
  2425.         public virtual bool ContainsValue(Object value) {
  2426.  
  2427.             if (value == null) {
  2428.                 for (int i = buckets.Length; --i >= 0;) {
  2429.                     if (buckets[i].key != null && buckets[i].key != buckets && buckets[i].val == null)
  2430.                         return true;
  2431.                 }
  2432.             }
  2433.             else {
  2434.                 for (int i = buckets.Length; --i >= 0;) {
  2435.                   Object val = buckets[i].val;
  2436.                   if (val!=null && val.Equals(value)) return true;
  2437.                 }
  2438.             }
  2439.             return false;
  2440.         }
  2441.  
  2442.         // Copies the keys of this hashtable to a given array starting at a given
  2443.         // index. This method is used by the implementation of the CopyTo method in
  2444.         // the KeyCollection class.
  2445.         private void CopyKeys(Array array, int arrayIndex) {
  2446.             Contract.Requires(array != null);
  2447.             Contract.Requires(array.Rank == 1);
  2448.  
  2449.             bucket[] lbuckets = buckets;
  2450.             for (int i = lbuckets.Length; --i >= 0;) {
  2451.                 Object keyv = lbuckets[i].key;
  2452.                 if ((keyv != null) && (keyv != buckets)){
  2453.                     array.SetValue(keyv, arrayIndex++);
  2454.                 }
  2455.             }
  2456.         }
  2457.  
  2458.         // Copies the keys of this hashtable to a given array starting at a given
  2459.         // index. This method is used by the implementation of the CopyTo method in
  2460.         // the KeyCollection class.
  2461.         private void CopyEntries(Array array, int arrayIndex) {
  2462.             Contract.Requires(array != null);
  2463.             Contract.Requires(array.Rank == 1);
  2464.  
  2465.             bucket[] lbuckets = buckets;
  2466.             for (int i = lbuckets.Length; --i >= 0;) {
  2467.                 Object keyv = lbuckets[i].key;
  2468.                 if ((keyv != null) && (keyv != buckets)){
  2469.                     DictionaryEntry entry = new DictionaryEntry(keyv,lbuckets[i].val);
  2470.                     array.SetValue(entry, arrayIndex++);
  2471.                 }
  2472.             }
  2473.         }
  2474.  
  2475.         // Copies the values in this hash table to an array at
  2476.         // a given index.  Note that this only copies values, and not keys.
  2477.         public virtual void CopyTo(Array array, int arrayIndex)
  2478.         {
  2479.             if (array == null)
  2480.                 throw new ArgumentNullException("array", Environment.GetResourceString("ArgumentNull_Array"));
  2481.             if (array.Rank != 1)
  2482.                 throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
  2483.             if (arrayIndex < 0)
  2484.                 throw new ArgumentOutOfRangeException("arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
  2485.             if (array.Length - arrayIndex < Count)
  2486.                 throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
  2487.             Contract.EndContractBlock();
  2488.             CopyEntries(array, arrayIndex);
  2489.         }
  2490.  
  2491.         // Copies the values in this Hashtable to an KeyValuePairs array.
  2492.         // KeyValuePairs is different from Dictionary Entry in that it has special
  2493.         // debugger attributes on its fields.
  2494.  
  2495.         internal virtual KeyValuePairs[] ToKeyValuePairsArray() {
  2496.  
  2497.             KeyValuePairs[] array = new KeyValuePairs[count];
  2498.             int index = 0;
  2499.             bucket[] lbuckets = buckets;
  2500.             for (int i = lbuckets.Length; --i >= 0;) {
  2501.                 Object keyv = lbuckets[i].key;
  2502.                 if ((keyv != null) && (keyv != buckets)){
  2503.                     array[index++] = new KeyValuePairs(keyv,lbuckets[i].val);
  2504.                 }
  2505.             }
  2506.  
  2507.             return array;
  2508.         }
  2509.  
  2510.  
  2511.         // Copies the values of this hashtable to a given array starting at a given
  2512.         // index. This method is used by the implementation of the CopyTo method in
  2513.         // the ValueCollection class.
  2514.         private void CopyValues(Array array, int arrayIndex) {
  2515.             Contract.Requires(array != null);
  2516.             Contract.Requires(array.Rank == 1);
  2517.  
  2518.             bucket[] lbuckets = buckets;
  2519.             for (int i = lbuckets.Length; --i >= 0;) {
  2520.                 Object keyv = lbuckets[i].key;
  2521.                 if ((keyv != null) && (keyv != buckets)){
  2522.                     array.SetValue(lbuckets[i].val, arrayIndex++);
  2523.                 }
  2524.             }
  2525.         }
  2526.  
  2527.         // Returns the value associated with the given key. If an entry with the
  2528.         // given key is not found, the returned value is null.
  2529.         //
  2530.         public virtual Object this[Object key] {
  2531.             get {
  2532.                 if (key == null) {
  2533.                     throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
  2534.                 }
  2535.                 Contract.EndContractBlock();
  2536.  
  2537.                 uint seed;
  2538.                 uint incr;
  2539.  
  2540.  
  2541.                 // Take a snapshot of buckets, in case another thread does a resize
  2542.                 bucket[] lbuckets = buckets;
  2543.                 uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr);
  2544.                 int  ntry = 0;
  2545.  
  2546.                 bucket b;
  2547.                 int bucketNumber = (int) (seed % (uint)lbuckets.Length);
  2548.                 do
  2549.                 {
  2550.                     int currentversion;
  2551.  
  2552.                     //     A read operation on hashtable has three steps:
  2553.                     //        (1) calculate the hash and find the slot number.
  2554.                     //        (2) compare the hashcode, if equal, go to step 3. Otherwise end.
  2555.                     //        (3) compare the key, if equal, go to step 4. Otherwise end.
  2556.                     //        (4) return the value contained in the bucket.
  2557.                     //     After step 3 and before step 4. A writer can kick in a remove the old item and add a new one
  2558.                     //     in the same bukcet. So in the reader we need to check if the hash table is modified during above steps.
  2559.                     //
  2560.                     // Writers (Insert, Remove, Clear) will set 'isWriterInProgress' flag before it starts modifying
  2561.                     // the hashtable and will ckear the flag when it is done.  When the flag is cleared, the 'version'
  2562.                     // will be increased.  We will repeat the reading if a writer is in progress or done with the modification
  2563.                     // during the read.
  2564.                     //
  2565.                     // Our memory model guarantee if we pick up the change in bucket from another processor,
  2566.                     // we will see the 'isWriterProgress' flag to be true or 'version' is changed in the reader.
  2567.                     //
  2568.                     int spinCount = 0;
  2569.                     do {
  2570.                         // this is violate read, following memory accesses can not be moved ahead of it.
  2571.                         currentversion = version;
  2572.                         b = lbuckets[bucketNumber];
  2573.  
  2574.                         // The contention between reader and writer shouldn't happen frequently.
  2575.                         // But just in case this will burn CPU, yield the control of CPU if we spinned a few times.
  2576.                         // 8 is just a random number I pick.
  2577.                         if( (++spinCount) % 8 == 0 ) {
  2578.                             Thread.Sleep(1);   // 1 means we are yeilding control to all threads, including low-priority ones.
  2579.                         }
  2580.                     } while ( isWriterInProgress || (currentversion != version) );
  2581.  
  2582.                     if (b.key == null) {
  2583.                         return null;
  2584.                     }
  2585.                     if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
  2586.                         KeyEquals (b.key, key))
  2587.                         return b.val;
  2588.                     bucketNumber = (int) (((long)bucketNumber + incr)% (uint)lbuckets.Length);
  2589.                 } while (b.hash_coll < 0 && ++ntry < lbuckets.Length);
  2590.                 return null;
  2591.             }
  2592.  
  2593. #if !FEATURE_CORECLR
  2594.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  2595. #endif
  2596.             set {
  2597.                 Insert(key, value, false);
  2598.             }
  2599.         }
  2600.  
  2601.         // Increases the bucket count of this hashtable. This method is called from
  2602.         // the Insert method when the actual load factor of the hashtable reaches
  2603.         // the upper limit specified when the hashtable was constructed. The number
  2604.         // of buckets in the hashtable is increased to the smallest prime number
  2605.         // that is larger than twice the current number of buckets, and the entries
  2606.         // in the hashtable are redistributed into the new buckets using the cached
  2607.         // hashcodes.
  2608.         private void expand()  {
  2609.             int rawsize = HashHelpers.ExpandPrime(buckets.Length);
  2610.             rehash(rawsize, false);
  2611.         }
  2612.  
  2613.         // We occationally need to rehash the table to clean up the collision bits.
  2614.         private void rehash() {
  2615.             rehash( buckets.Length, false );
  2616.         }
  2617.  
  2618.         private void UpdateVersion() {
  2619.             // Version might become negative when version is Int32.MaxValue, but the oddity will be still be correct.
  2620.             // So we don't need to special case this.
  2621.             version++;
  2622.         }
  2623.  
  2624.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  2625.         private void rehash( int newsize, bool forceNewHashCode ) {
  2626.  
  2627.             // reset occupancy
  2628.             occupancy=0;
  2629.  
  2630.             // Don't replace any internal state until we've finished adding to the
  2631.             // new bucket[].  This serves two purposes:
  2632.             //   1) Allow concurrent readers to see valid hashtable contents
  2633.             //      at all times
  2634.             //   2) Protect against an OutOfMemoryException while allocating this
  2635.             //      new bucket[].
  2636.             bucket[] newBuckets = new bucket[newsize];
  2637.  
  2638.             // rehash table into new buckets
  2639.             int nb;
  2640.             for (nb = 0; nb < buckets.Length; nb++){
  2641.                 bucket oldb = buckets[nb];
  2642.                 if ((oldb.key != null) && (oldb.key != buckets)) {
  2643.                     int hashcode = ((forceNewHashCode ? GetHash(oldb.key) : oldb.hash_coll) & 0x7FFFFFFF);
  2644.                     putEntry(newBuckets, oldb.key, oldb.val, hashcode);
  2645.                 }
  2646.             }
  2647.  
  2648.             // New bucket[] is good to go - replace buckets and other internal state.
  2649. #if !FEATURE_CORECLR
  2650.             Thread.BeginCriticalRegion();
  2651. #endif
  2652.             isWriterInProgress = true;
  2653.             buckets = newBuckets;
  2654.             loadsize = (int)(loadFactor * newsize);
  2655.             UpdateVersion();
  2656.             isWriterInProgress = false;
  2657. #if !FEATURE_CORECLR
  2658.             Thread.EndCriticalRegion();
  2659. #endif
  2660.             // minimun size of hashtable is 3 now and maximum loadFactor is 0.72 now.
  2661.             Contract.Assert(loadsize < newsize, "Our current implementaion means this is not possible.");
  2662.             return;
  2663.         }
  2664.  
  2665.         // Returns an enumerator for this hashtable.
  2666.         // If modifications made to the hashtable while an enumeration is
  2667.         // in progress, the MoveNext and Current methods of the
  2668.         // enumerator will throw an exception.
  2669.         //
  2670. #if !FEATURE_CORECLR
  2671.         [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  2672. #endif
  2673.         IEnumerator IEnumerable.GetEnumerator() {
  2674.             return new HashtableEnumerator(this, HashtableEnumerator.DictEntry);
  2675.         }
  2676.  
  2677.         // Returns a dictionary enumerator for this hashtable.
  2678.         // If modifications made to the hashtable while an enumeration is
  2679.         // in progress, the MoveNext and Current methods of the
  2680.         // enumerator will throw an exception.
  2681.         //
  2682. #if !FEATURE_CORECLR
  2683.         [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  2684. #endif
  2685.         public virtual IDictionaryEnumerator GetEnumerator() {
  2686.             return new HashtableEnumerator(this, HashtableEnumerator.DictEntry);
  2687.         }
  2688.  
  2689.         // Internal method to get the hash code for an Object.  This will call
  2690.         // GetHashCode() on each object if you haven't provided an IHashCodeProvider
  2691.         // instance.  Otherwise, it calls hcp.GetHashCode(obj).
  2692. #if !FEATURE_CORECLR
  2693.         [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  2694. #endif
  2695.         protected virtual int GetHash(Object key)
  2696.         {
  2697.             if (_keycomparer != null)
  2698.                 return _keycomparer.GetHashCode(key);
  2699.             return key.GetHashCode();
  2700.         }
  2701.  
  2702.         // Is this Hashtable read-only?
  2703.         public virtual bool IsReadOnly {
  2704.             get { return false; }
  2705.         }
  2706.  
  2707.         public virtual bool IsFixedSize {
  2708.             get { return false; }
  2709.         }
  2710.  
  2711.         // Is this Hashtable synchronized?  See SyncRoot property
  2712.         public virtual bool IsSynchronized {
  2713.             get { return false; }
  2714.         }
  2715.  
  2716.         // Internal method to compare two keys.  If you have provided an IComparer
  2717.         // instance in the constructor, this method will call comparer.Compare(item, key).
  2718.         // Otherwise, it will call item.Equals(key).
  2719.         //
  2720.         protected virtual bool KeyEquals(Object item, Object key)
  2721.         {
  2722.             Contract.Assert(key != null, "key can't be null here!");
  2723.             if( Object.ReferenceEquals(buckets, item)) {
  2724.                 return false;
  2725.             }
  2726.  
  2727.             if (Object.ReferenceEquals(item,key))
  2728.                 return true;
  2729.  
  2730.             if (_keycomparer != null)
  2731.                 return _keycomparer.Equals(item, key);
  2732.             return item == null ? false : item.Equals(key);
  2733.         }
  2734.  
  2735.         // Returns a collection representing the keys of this hashtable. The order
  2736.         // in which the returned collection represents the keys is unspecified, but
  2737.         // it is guaranteed to be          buckets = newBuckets; the same order in which a collection returned by
  2738.         // GetValues represents the values of the hashtable.
  2739.         //
  2740.         // The returned collection is live in the sense that any changes
  2741.         // to the hash table are reflected in this collection.  It is not
  2742.         // a static copy of all the keys in the hash table.
  2743.         //
  2744.         public virtual ICollection Keys {
  2745. #if !FEATURE_CORECLR
  2746.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  2747. #endif
  2748.             get {
  2749.                 if (keys == null) keys = new KeyCollection(this);
  2750.                     return keys;
  2751.             }
  2752.         }
  2753.  
  2754.         // Returns a collection representing the values of this hashtable. The
  2755.         // order in which the returned collection represents the values is
  2756.         // unspecified, but it is guaranteed to be the same order in which a
  2757.         // collection returned by GetKeys represents the keys of the
  2758.         // hashtable.
  2759.         //
  2760.         // The returned collection is live in the sense that any changes
  2761.         // to the hash table are reflected in this collection.  It is not
  2762.         // a static copy of all the keys in the hash table.
  2763.         //
  2764.         public virtual ICollection Values {
  2765. #if !FEATURE_CORECLR
  2766.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  2767. #endif
  2768.             get {
  2769.                 if (values == null) values = new ValueCollection(this);
  2770.                     return values;
  2771.             }
  2772.         }
  2773.  
  2774.         // Inserts an entry into this hashtable. This method is called from the Set
  2775.         // and Add methods. If the add parameter is true and the given key already
  2776.         // exists in the hashtable, an exception is thrown.
  2777.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  2778.         private void Insert (Object key, Object nvalue, bool add) {
  2779.             // @
  2780.  
  2781.  
  2782.             if (key == null) {
  2783.                 throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
  2784.             }
  2785.             Contract.EndContractBlock();
  2786.             if (count >= loadsize) {
  2787.                 expand();
  2788.             }
  2789.             else if(occupancy > loadsize && count > 100) {
  2790.                 rehash();
  2791.             }
  2792.  
  2793.             uint seed;
  2794.             uint incr;
  2795.             // Assume we only have one thread writing concurrently.  Modify
  2796.             // buckets to contain new data, as long as we insert in the right order.
  2797.             uint hashcode = InitHash(key, buckets.Length, out seed, out incr);
  2798.             int  ntry = 0;
  2799.             int emptySlotNumber = -1; // We use the empty slot number to cache the first empty slot. We chose to reuse slots
  2800.             // create by remove that have the collision bit set over using up new slots.
  2801.             int bucketNumber = (int) (seed % (uint)buckets.Length);
  2802.             do {
  2803.  
  2804.                 // Set emptySlot number to current bucket if it is the first available bucket that we have seen
  2805.                 // that once contained an entry and also has had a collision.
  2806.                 // We need to search this entire collision chain because we have to ensure that there are no
  2807.                 // duplicate entries in the table.
  2808.                 if (emptySlotNumber == -1 && (buckets[bucketNumber].key == buckets) && (buckets[bucketNumber].hash_coll < 0))//(((buckets[bucketNumber].hash_coll & unchecked(0x80000000))!=0)))
  2809.                     emptySlotNumber = bucketNumber;
  2810.  
  2811.                 // Insert the key/value pair into this bucket if this bucket is empty and has never contained an entry
  2812.                 // OR
  2813.                 // This bucket once contained an entry but there has never been a collision
  2814.                 if ((buckets[bucketNumber].key == null) ||
  2815.                     (buckets[bucketNumber].key == buckets && ((buckets[bucketNumber].hash_coll & unchecked(0x80000000))==0))) {
  2816.  
  2817.                     // If we have found an available bucket that has never had a collision, but we've seen an available
  2818.                     // bucket in the past that has the collision bit set, use the previous bucket instead
  2819.                     if (emptySlotNumber != -1) // Reuse slot
  2820.                         bucketNumber = emptySlotNumber;
  2821.  
  2822.                     // We pretty much have to insert in this order.  Don't set hash
  2823.                     // code until the value & key are set appropriately.
  2824. #if !FEATURE_CORECLR
  2825.                     Thread.BeginCriticalRegion();
  2826. #endif
  2827.                     isWriterInProgress = true;
  2828.                     buckets[bucketNumber].val = nvalue;
  2829.                     buckets[bucketNumber].key  = key;
  2830.                     buckets[bucketNumber].hash_coll |= (int) hashcode;
  2831.                     count++;
  2832.                     UpdateVersion();
  2833.                     isWriterInProgress = false;
  2834. #if !FEATURE_CORECLR
  2835.                     Thread.EndCriticalRegion();
  2836. #endif
  2837.  
  2838. #if FEATURE_RANDOMIZED_STRING_HASHING
  2839.                     if(ntry > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer))
  2840.                     {
  2841.                         // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
  2842.                         // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
  2843.                         if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
  2844.                         {
  2845.                             _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
  2846.                             rehash(buckets.Length, true);
  2847.                         }
  2848.                     }
  2849. #endif
  2850.  
  2851.                     return;
  2852.                 }
  2853.  
  2854.                 // The current bucket is in use
  2855.                 // OR
  2856.                 // it is available, but has had the collision bit set and we have already found an available bucket
  2857.                 if (((buckets[bucketNumber].hash_coll & 0x7FFFFFFF) == hashcode) &&
  2858.                     KeyEquals (buckets[bucketNumber].key, key)) {
  2859.                     if (add) {
  2860.                         throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", buckets[bucketNumber].key, key));
  2861.                     }
  2862. #if !FEATURE_CORECLR
  2863.                     Thread.BeginCriticalRegion();
  2864. #endif
  2865.                     isWriterInProgress = true;
  2866.                     buckets[bucketNumber].val = nvalue;
  2867.                     UpdateVersion();
  2868.                     isWriterInProgress = false;
  2869. #if !FEATURE_CORECLR
  2870.                     Thread.EndCriticalRegion();
  2871. #endif
  2872.  
  2873. #if FEATURE_RANDOMIZED_STRING_HASHING
  2874.                     if(ntry > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer))
  2875.                     {
  2876.                         // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
  2877.                         // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
  2878.                         if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
  2879.                         {
  2880.                             _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
  2881.                             rehash(buckets.Length, true);
  2882.                         }
  2883.                     }
  2884. #endif
  2885.                     return;
  2886.                 }
  2887.  
  2888.                 // The current bucket is full, and we have therefore collided.  We need to set the collision bit
  2889.                 // UNLESS
  2890.                 // we have remembered an available slot previously.
  2891.                 if (emptySlotNumber == -1) {// We don't need to set the collision bit here since we already have an empty slot
  2892.                     if( buckets[bucketNumber].hash_coll >= 0 ) {
  2893.                         buckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
  2894.                         occupancy++;
  2895.                     }
  2896.                 }
  2897.  
  2898.                 bucketNumber = (int) (((long)bucketNumber + incr)% (uint)buckets.Length);
  2899.             } while (++ntry < buckets.Length);
  2900.  
  2901.             // This code is here if and only if there were no buckets without a collision bit set in the entire table
  2902.             if (emptySlotNumber != -1)
  2903.             {
  2904.                 // We pretty much have to insert in this order.  Don't set hash
  2905.                 // code until the value & key are set appropriately.
  2906. #if !FEATURE_CORECLR
  2907.                 Thread.BeginCriticalRegion();
  2908. #endif
  2909.                 isWriterInProgress = true;
  2910.                 buckets[emptySlotNumber].val = nvalue;
  2911.                 buckets[emptySlotNumber].key  = key;
  2912.                 buckets[emptySlotNumber].hash_coll |= (int) hashcode;
  2913.                 count++;
  2914.                 UpdateVersion();
  2915.                 isWriterInProgress = false;
  2916. #if !FEATURE_CORECLR
  2917.                 Thread.EndCriticalRegion();
  2918. #endif
  2919.  
  2920. #if FEATURE_RANDOMIZED_STRING_HASHING
  2921.                 if(buckets.Length > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer))
  2922.                 {
  2923.                     // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
  2924.                     // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
  2925.                     if(_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
  2926.                     {
  2927.                         _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
  2928.                         rehash(buckets.Length, true);
  2929.                     }
  2930.                 }
  2931. #endif
  2932.                 return;
  2933.             }
  2934.  
  2935.             // If you see this assert, make sure load factor & count are reasonable.
  2936.             // Then verify that our double hash function (h2, described at top of file)
  2937.             // meets the requirements described above. You should never see this assert.
  2938.             Contract.Assert(false, "hash table insert failed!  Load factor too high, or our double hashing function is incorrect.");
  2939.             throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HashInsertFailed"));
  2940.         }
  2941.  
  2942.         private void putEntry (bucket[] newBuckets, Object key, Object nvalue, int hashcode)
  2943.         {
  2944.             Contract.Assert(hashcode >= 0, "hashcode >= 0");  // make sure collision bit (sign bit) wasn't set.
  2945.  
  2946.             uint seed = (uint) hashcode;
  2947.             uint incr = (uint)(1 + ((seed * HashPrime) % ((uint)newBuckets.Length - 1)));
  2948.             int bucketNumber = (int) (seed % (uint)newBuckets.Length);
  2949.             do {
  2950.  
  2951.                 if ((newBuckets[bucketNumber].key == null) || (newBuckets[bucketNumber].key == buckets)) {
  2952.                     newBuckets[bucketNumber].val = nvalue;
  2953.                     newBuckets[bucketNumber].key = key;
  2954.                     newBuckets[bucketNumber].hash_coll |= hashcode;
  2955.                     return;
  2956.                 }
  2957.  
  2958.                 if( newBuckets[bucketNumber].hash_coll >= 0 ) {
  2959.                 newBuckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
  2960.                     occupancy++;
  2961.                 }
  2962.                 bucketNumber = (int) (((long)bucketNumber + incr)% (uint)newBuckets.Length);
  2963.             } while (true);
  2964.         }
  2965.  
  2966.         // Removes an entry from this hashtable. If an entry with the specified
  2967.         // key exists in the hashtable, it is removed. An ArgumentException is
  2968.         // thrown if the key is null.
  2969.         //
  2970.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
  2971.         public virtual void Remove(Object key) {
  2972.             if (key == null) {
  2973.                 throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
  2974.             }
  2975.             Contract.EndContractBlock();
  2976.             Contract.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously!  Don't do that - use Hashtable.Synchronized.");
  2977.  
  2978.             uint seed;
  2979.             uint incr;
  2980.             // Assuming only one concurrent writer, write directly into buckets.
  2981.             uint hashcode = InitHash(key, buckets.Length, out seed, out incr);
  2982.             int ntry = 0;
  2983.  
  2984.             bucket b;
  2985.             int bn = (int) (seed % (uint)buckets.Length);  // bucketNumber
  2986.             do {
  2987.                 b = buckets[bn];
  2988.                 if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
  2989.                     KeyEquals (b.key, key)) {
  2990. #if !FEATURE_CORECLR
  2991.                     Thread.BeginCriticalRegion();
  2992. #endif
  2993.                     isWriterInProgress = true;
  2994.                     // Clear hash_coll field, then key, then value
  2995.                     buckets[bn].hash_coll &= unchecked((int)0x80000000);
  2996.                     if (buckets[bn].hash_coll != 0) {
  2997.                         buckets[bn].key = buckets;
  2998.                     }
  2999.                     else {
  3000.                         buckets[bn].key = null;
  3001.                     }
  3002.                     buckets[bn].val = null;  // Free object references sooner & simplify ContainsValue.
  3003.                     count--;
  3004.                     UpdateVersion();
  3005.                     isWriterInProgress = false;
  3006. #if !FEATURE_CORECLR
  3007.                     Thread.EndCriticalRegion();
  3008. #endif
  3009.                     return;
  3010.                 }
  3011.                 bn = (int) (((long)bn + incr)% (uint)buckets.Length);
  3012.             } while (b.hash_coll < 0 && ++ntry < buckets.Length);
  3013.  
  3014.             //throw new ArgumentException(Environment.GetResourceString("Arg_RemoveArgNotFound"));
  3015.         }
  3016.  
  3017.         // Returns the object to synchronize on for this hash table.
  3018.         public virtual Object SyncRoot {
  3019.             get {
  3020.                 if( _syncRoot == null) {
  3021.                     System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
  3022.                 }
  3023.                 return _syncRoot;
  3024.             }
  3025.         }
  3026.  
  3027.         // Returns the number of associations in this hashtable.
  3028.         //
  3029.         public virtual int Count {
  3030.             get { return count; }
  3031.         }
  3032.  
  3033.         // Returns a thread-safe wrapper for a Hashtable.
  3034.         //
  3035.         [HostProtection(Synchronization=true)]
  3036.         public static Hashtable Synchronized(Hashtable table) {
  3037.             if (table==null)
  3038.                 throw new ArgumentNullException("table");
  3039.             Contract.EndContractBlock();
  3040.             return new SyncHashtable(table);
  3041.         }
  3042.  
  3043.         //
  3044.         // The ISerializable Implementation
  3045.         //
  3046.  
  3047.         [System.Security.SecurityCritical]
  3048.         public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
  3049.             if (info==null) {
  3050.                 throw new ArgumentNullException("info");
  3051.             }
  3052.             Contract.EndContractBlock();
  3053.             // This is imperfect - it only works well if all other writes are
  3054.             // also using our synchronized wrapper.  But it's still a good idea.
  3055.             lock (SyncRoot) {
  3056.                 // This method hasn't been fully tweaked to be safe for a concurrent writer.
  3057.                 int oldVersion = version;
  3058.             info.AddValue(LoadFactorName, loadFactor);
  3059.             info.AddValue(VersionName, version);
  3060.  
  3061.             //
  3062.             // We need to maintain serialization compatibility with Everett and RTM.
  3063.             // If the comparer is null or a compatible comparer, serialize Hashtable
  3064.             // in a format that can be deserialized on Everett and RTM.
  3065.             //
  3066.             // Also, if the Hashtable is using randomized hashing, serialize the old
  3067.             // view of the _keycomparer so perevious frameworks don't see the new types
  3068. #pragma warning disable 618
  3069. #if FEATURE_RANDOMIZED_STRING_HASHING
  3070.             IEqualityComparer keyComparerForSerilization = (IEqualityComparer) HashHelpers.GetEqualityComparerForSerialization(_keycomparer);
  3071. #else
  3072.             IEqualityComparer keyComparerForSerilization = _keycomparer;
  3073. #endif
  3074.  
  3075.             if( keyComparerForSerilization == null) {
  3076.                 info.AddValue(ComparerName, null,typeof(IComparer));
  3077.                 info.AddValue(HashCodeProviderName, null, typeof(IHashCodeProvider));
  3078.             }
  3079.             else if(keyComparerForSerilization is CompatibleComparer) {
  3080.                 CompatibleComparer c = keyComparerForSerilization as CompatibleComparer;
  3081.                 info.AddValue(ComparerName, c.Comparer, typeof(IComparer));
  3082.                 info.AddValue(HashCodeProviderName, c.HashCodeProvider, typeof(IHashCodeProvider));
  3083.             }
  3084.             else {
  3085.                 info.AddValue(KeyComparerName, keyComparerForSerilization, typeof(IEqualityComparer));
  3086.             }
  3087. #pragma warning restore 618
  3088.  
  3089.             info.AddValue(HashSizeName, buckets.Length); //This is the length of the bucket array.
  3090.             Object [] serKeys = new Object[count];
  3091.             Object [] serValues = new Object[count];
  3092.             CopyKeys(serKeys, 0);
  3093.             CopyValues(serValues,0);
  3094.             info.AddValue(KeysName, serKeys, typeof(Object[]));
  3095.             info.AddValue(ValuesName, serValues, typeof(Object[]));
  3096.  
  3097.                 // Explicitly check to see if anyone changed the Hashtable while we
  3098.                 // were serializing it.  That's a ---- in their code.
  3099.                 if (version != oldVersion)
  3100.                     throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
  3101.         }
  3102.         }
  3103.  
  3104.         //
  3105.         // DeserializationEvent Listener
  3106.         //
  3107.         public virtual void OnDeserialization(Object sender) {
  3108.             if (buckets!=null) {
  3109.                 // Somebody had a dependency on this hashtable and fixed us up before the ObjectManager got to it.
  3110.                 return;
  3111.             }
  3112.  
  3113.             SerializationInfo siInfo;
  3114.             HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo);
  3115.  
  3116.             if (siInfo==null) {
  3117.                 throw new SerializationException(Environment.GetResourceString("Serialization_InvalidOnDeser"));
  3118.             }
  3119.  
  3120.             int hashsize = 0;
  3121.             IComparer c = null;
  3122.  
  3123. #pragma warning disable 618
  3124.             IHashCodeProvider hcp = null;
  3125. #pragma warning restore 618
  3126.  
  3127.             Object [] serKeys = null;
  3128.             Object [] serValues = null;
  3129.  
  3130.             SerializationInfoEnumerator enumerator = siInfo.GetEnumerator();
  3131.  
  3132.             while( enumerator.MoveNext())
  3133.             {
  3134.                 switch( enumerator.Name)
  3135.                 {
  3136.                     case LoadFactorName:
  3137.                         loadFactor = siInfo.GetSingle(LoadFactorName);
  3138.                         break;
  3139.                     case HashSizeName:
  3140.                         hashsize = siInfo.GetInt32(HashSizeName);
  3141.                         break;
  3142.                     case KeyComparerName:
  3143.                         _keycomparer = (IEqualityComparer)siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer));
  3144.                         break;
  3145.                     case ComparerName:
  3146.                         c = (IComparer)siInfo.GetValue(ComparerName, typeof(IComparer));
  3147.                         break;
  3148.                     case HashCodeProviderName:
  3149. #pragma warning disable 618
  3150.                         hcp = (IHashCodeProvider)siInfo.GetValue(HashCodeProviderName, typeof(IHashCodeProvider));
  3151. #pragma warning restore 618
  3152.                         break;
  3153.                     case KeysName:
  3154.                         serKeys = (Object[])siInfo.GetValue(KeysName, typeof(Object[]));
  3155.                         break;
  3156.                     case ValuesName:
  3157.                         serValues = (Object[])siInfo.GetValue(ValuesName, typeof(Object[]));
  3158.                         break;
  3159.                 }
  3160.             }
  3161.  
  3162.             loadsize   = (int)(loadFactor*hashsize);
  3163.  
  3164.             // V1 object doesn't has _keycomparer field.
  3165.             if ( (_keycomparer == null) && ( (c != null) || (hcp != null) ) ){
  3166.                 _keycomparer = new CompatibleComparer(c,hcp);
  3167.             }
  3168.  
  3169.             buckets = new bucket[hashsize];
  3170.  
  3171.             if (serKeys==null) {
  3172.                 throw new SerializationException(Environment.GetResourceString("Serialization_MissingKeys"));
  3173.             }
  3174.             if (serValues==null) {
  3175.                 throw new SerializationException(Environment.GetResourceString("Serialization_MissingValues"));
  3176.             }
  3177.             if (serKeys.Length!=serValues.Length) {
  3178.                 throw new SerializationException(Environment.GetResourceString("Serialization_KeyValueDifferentSizes"));
  3179.             }
  3180.             for (int i=0; i<serKeys.Length; i++) {
  3181.                 if (serKeys[i]==null) {
  3182.                     throw new SerializationException(Environment.GetResourceString("Serialization_NullKey"));
  3183.                 }
  3184.                 Insert(serKeys[i], serValues[i], true);
  3185.             }
  3186.  
  3187.             version = siInfo.GetInt32(VersionName);
  3188.  
  3189.             HashHelpers.SerializationInfoTable.Remove(this);
  3190.         }
  3191.  
  3192.  
  3193.         // Implements a Collection for the keys of a hashtable. An instance of this
  3194.         // class is created by the GetKeys method of a hashtable.
  3195.         [Serializable]
  3196.         private class KeyCollection : ICollection
  3197.         {
  3198.             private Hashtable _hashtable;
  3199.  
  3200.             internal KeyCollection(Hashtable hashtable) {
  3201.                 _hashtable = hashtable;
  3202.             }
  3203.  
  3204.             public virtual void CopyTo(Array array, int arrayIndex) {
  3205.                 if (array==null)
  3206.                     throw new ArgumentNullException("array");
  3207.                 if (array.Rank != 1)
  3208.                     throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
  3209.                 if (arrayIndex < 0)
  3210.                     throw new ArgumentOutOfRangeException("arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
  3211.                 Contract.EndContractBlock();
  3212.                 if (array.Length - arrayIndex < _hashtable.count)
  3213.                     throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
  3214.                 _hashtable.CopyKeys(array, arrayIndex);
  3215.             }
  3216.  
  3217. #if !FEATURE_CORECLR
  3218.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  3219. #endif
  3220.             public virtual IEnumerator GetEnumerator() {
  3221.                 return new HashtableEnumerator(_hashtable, HashtableEnumerator.Keys);
  3222.             }
  3223.  
  3224.             public virtual bool IsSynchronized {
  3225.                 get { return _hashtable.IsSynchronized; }
  3226.             }
  3227.  
  3228.             public virtual Object SyncRoot {
  3229.                 get { return _hashtable.SyncRoot; }
  3230.             }
  3231.  
  3232.             public virtual int Count {
  3233.                 get { return _hashtable.count; }
  3234.             }
  3235.         }
  3236.  
  3237.         // Implements a Collection for the values of a hashtable. An instance of
  3238.         // this class is created by the GetValues method of a hashtable.
  3239.         [Serializable]
  3240.         private class ValueCollection : ICollection
  3241.         {
  3242.             private Hashtable _hashtable;
  3243.  
  3244.             internal ValueCollection(Hashtable hashtable) {
  3245.                 _hashtable = hashtable;
  3246.             }
  3247.  
  3248.             public virtual void CopyTo(Array array, int arrayIndex) {
  3249.                 if (array==null)
  3250.                     throw new ArgumentNullException("array");
  3251.                 if (array.Rank != 1)
  3252.                     throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
  3253.                 if (arrayIndex < 0)
  3254.                     throw new ArgumentOutOfRangeException("arrayIndex", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
  3255.                 Contract.EndContractBlock();
  3256.                 if (array.Length - arrayIndex < _hashtable.count)
  3257.                     throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
  3258.                 _hashtable.CopyValues(array, arrayIndex);
  3259.             }
  3260.  
  3261. #if !FEATURE_CORECLR
  3262.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  3263. #endif
  3264.             public virtual IEnumerator GetEnumerator() {
  3265.                 return new HashtableEnumerator(_hashtable, HashtableEnumerator.Values);
  3266.             }
  3267.  
  3268.             public virtual bool IsSynchronized {
  3269.                 get { return _hashtable.IsSynchronized; }
  3270.             }
  3271.  
  3272.             public virtual Object SyncRoot {
  3273.                 get { return _hashtable.SyncRoot; }
  3274.             }
  3275.  
  3276.             public virtual int Count {
  3277.                 get { return _hashtable.count; }
  3278.             }
  3279.         }
  3280.  
  3281.         // Synchronized wrapper for hashtable
  3282.         [Serializable]
  3283.         private class SyncHashtable : Hashtable, IEnumerable
  3284.         {
  3285.             protected Hashtable _table;
  3286.  
  3287.             internal SyncHashtable(Hashtable table) : base(false) {
  3288.                 _table = table;
  3289.             }
  3290.  
  3291.             internal SyncHashtable(SerializationInfo info, StreamingContext context) : base (info, context) {
  3292.                 _table = (Hashtable)info.GetValue("ParentTable", typeof(Hashtable));
  3293.                 if (_table==null) {
  3294.                     throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
  3295.                 }
  3296.             }
  3297.  
  3298.  
  3299.             /*================================GetObjectData=================================
  3300.             **Action: Return a serialization info containing a reference to _table.  We need
  3301.             **        to implement this because our parent HT does and we don't want to actually
  3302.             **        serialize all of it's values (just a reference to the table, which will then
  3303.             **        be serialized separately.)
  3304.             **Returns: void
  3305.             **Arguments: info -- the SerializationInfo into which to store the data.
  3306.             **           context -- the StreamingContext for the current serialization (ignored)
  3307.             **Exceptions: ArgumentNullException if info is null.
  3308.             ==============================================================================*/
  3309.             [System.Security.SecurityCritical]  // auto-generated
  3310.             public override void GetObjectData(SerializationInfo info, StreamingContext context) {
  3311.                 if (info==null) {
  3312.                     throw new ArgumentNullException("info");
  3313.                 }
  3314.                 Contract.EndContractBlock();
  3315.                 // Our serialization code hasn't been fully tweaked to be safe
  3316.                 // for a concurrent writer.
  3317.                 lock (_table.SyncRoot) {
  3318.                 info.AddValue("ParentTable", _table, typeof(Hashtable));
  3319.             }
  3320.             }
  3321.  
  3322.             public override int Count {
  3323.                 get { return _table.Count; }
  3324.             }
  3325.  
  3326.             public override bool IsReadOnly {
  3327.                 get { return _table.IsReadOnly; }
  3328.             }
  3329.  
  3330.             public override bool IsFixedSize {
  3331.                 get { return _table.IsFixedSize; }
  3332.             }
  3333.  
  3334.             public override bool IsSynchronized {
  3335.                 get { return true; }
  3336.             }
  3337.  
  3338.             public override Object this[Object key] {
  3339. #if !FEATURE_CORECLR
  3340.                 [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  3341. #endif
  3342.                 get {
  3343.                         return _table[key];
  3344.                 }
  3345.                 set {
  3346.                     lock(_table.SyncRoot) {
  3347.                         _table[key] = value;
  3348.                     }
  3349.                 }
  3350.             }
  3351.  
  3352.             public override Object SyncRoot {
  3353.                 get { return _table.SyncRoot; }
  3354.             }
  3355.  
  3356.             public override void Add(Object key, Object value) {
  3357.                 lock(_table.SyncRoot) {
  3358.                     _table.Add(key, value);
  3359.                 }
  3360.             }
  3361.  
  3362.             public override void Clear() {
  3363.                 lock(_table.SyncRoot) {
  3364.                     _table.Clear();
  3365.                 }
  3366.             }
  3367.  
  3368. #if !FEATURE_CORECLR
  3369.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  3370. #endif
  3371.             public override bool Contains(Object key) {
  3372.                 return _table.Contains(key);
  3373.             }
  3374.  
  3375. #if !FEATURE_CORECLR
  3376.             [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  3377. #endif
  3378.             public override bool ContainsKey(Object key) {
  3379.                 if (key == null) {
  3380.                     throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
  3381.                 }
  3382.                 Contract.EndContractBlock();
  3383.                 return _table.ContainsKey(key);
  3384.             }
  3385.  
  3386.             public override bool ContainsValue(Object key) {
  3387.                 lock(_table.SyncRoot) {
  3388.                     return _table.ContainsValue(key);
  3389.                 }
  3390.             }
  3391.  
  3392.             public override void CopyTo(Array array, int arrayIndex) {
  3393.                 lock (_table.SyncRoot) {
  3394.                     _table.CopyTo(array, arrayIndex);
  3395.                 }
  3396.             }
  3397.  
  3398.             public override Object Clone() {
  3399.                 lock (_table.SyncRoot) {
  3400.                     return Hashtable.Synchronized((Hashtable)_table.Clone());
  3401.                 }
  3402.             }
  3403.  
  3404.             IEnumerator IEnumerable.GetEnumerator() {
  3405.                 return _table.GetEnumerator();
  3406.             }
  3407.  
  3408.             public override IDictionaryEnumerator GetEnumerator() {
  3409.                 return _table.GetEnumerator();
  3410.             }
  3411.  
  3412.             public override ICollection Keys {
  3413.                 get {
  3414.                     lock(_table.SyncRoot) {
  3415.                         return _table.Keys;
  3416.                     }
  3417.                 }
  3418.             }
  3419.  
  3420.             public override ICollection Values {
  3421.                 get {
  3422.                     lock(_table.SyncRoot) {
  3423.                         return _table.Values;
  3424.                     }
  3425.                 }
  3426.             }
  3427.  
  3428.             public override void Remove(Object key) {
  3429.                 lock(_table.SyncRoot) {
  3430.                     _table.Remove(key);
  3431.                 }
  3432.             }
  3433.  
  3434.             /*==============================OnDeserialization===============================
  3435.             **Action: Does nothing.  We have to implement this because our parent HT implements it,
  3436.             **        but it doesn't do anything meaningful.  The real work will be done when we
  3437.             **        call OnDeserialization on our parent table.
  3438.             **Returns: void
  3439.             **Arguments: None
  3440.             **Exceptions: None
  3441.             ==============================================================================*/
  3442.             public override void OnDeserialization(Object sender) {
  3443.                 return;
  3444.             }
  3445.  
  3446.             internal override KeyValuePairs[] ToKeyValuePairsArray() {
  3447.                 return _table.ToKeyValuePairsArray();
  3448.             }
  3449.  
  3450.         }
  3451.  
  3452.  
  3453.         // Implements an enumerator for a hashtable. The enumerator uses the
  3454.         // internal version number of the hashtabke to ensure that no modifications
  3455.         // are made to the hashtable while an enumeration is in progress.
  3456.         [Serializable]
  3457.         private class HashtableEnumerator : IDictionaryEnumerator, ICloneable
  3458.         {
  3459.             private Hashtable hashtable;
  3460.             private int bucket;
  3461.             private int version;
  3462.             private bool current;
  3463.             private int getObjectRetType;   // What should GetObject return?
  3464.             private Object currentKey;
  3465.             private Object currentValue;
  3466.  
  3467.             internal const int Keys = 1;
  3468.             internal const int Values = 2;
  3469.             internal const int DictEntry = 3;
  3470.  
  3471.             internal HashtableEnumerator(Hashtable hashtable, int getObjRetType) {
  3472.                 this.hashtable = hashtable;
  3473.                 bucket = hashtable.buckets.Length;
  3474.                 version = hashtable.version;
  3475.                 current = false;
  3476.                 getObjectRetType = getObjRetType;
  3477.             }
  3478.  
  3479.             public Object Clone() {
  3480.                 return MemberwiseClone();
  3481.             }
  3482.  
  3483.             public virtual Object Key {
  3484. #if !FEATURE_CORECLR
  3485.                 [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  3486. #endif
  3487.                 get {
  3488.                     if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
  3489.                     return currentKey;
  3490.                 }
  3491.             }
  3492.  
  3493.             public virtual bool MoveNext() {
  3494.                 if (version != hashtable.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
  3495.                 while (bucket > 0) {
  3496.                     bucket--;
  3497.                     Object keyv = hashtable.buckets[bucket].key;
  3498.                     if ((keyv!= null) && (keyv != hashtable.buckets)) {
  3499.                         currentKey = keyv;
  3500.                         currentValue = hashtable.buckets[bucket].val;
  3501.                         current = true;
  3502.                         return true;
  3503.                     }
  3504.                 }
  3505.                 current = false;
  3506.                 return false;
  3507.             }
  3508.  
  3509.             public virtual DictionaryEntry Entry {
  3510.                 get {
  3511.                     if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
  3512.                     return new DictionaryEntry(currentKey, currentValue);
  3513.                 }
  3514.             }
  3515.  
  3516.  
  3517.             public virtual Object Current {
  3518.                 get {
  3519.                     if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
  3520.  
  3521.                     if (getObjectRetType==Keys)
  3522.                         return currentKey;
  3523.                     else if (getObjectRetType==Values)
  3524.                         return currentValue;
  3525.                     else
  3526.                         return new DictionaryEntry(currentKey, currentValue);
  3527.                 }
  3528.             }
  3529.  
  3530.             public virtual Object Value {
  3531. #if !FEATURE_CORECLR
  3532.                 [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  3533. #endif
  3534.                 get {
  3535.                     if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
  3536.                     return currentValue;
  3537.                 }
  3538.             }
  3539.  
  3540.             public virtual void Reset() {
  3541.                 if (version != hashtable.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
  3542.                 current = false;
  3543.                 bucket = hashtable.buckets.Length;
  3544.                 currentKey = null;
  3545.                 currentValue = null;
  3546.             }
  3547.         }
  3548.  
  3549.         // internal debug view class for hashtable
  3550.         internal class HashtableDebugView {
  3551.             private Hashtable hashtable;
  3552.  
  3553.             public HashtableDebugView( Hashtable hashtable) {
  3554.                 if( hashtable == null) {
  3555.                     throw new ArgumentNullException( "hashtable");
  3556.                 }
  3557.                 Contract.EndContractBlock();
  3558.  
  3559.                 this.hashtable = hashtable;
  3560.             }
  3561.  
  3562.  
  3563.             [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
  3564.             public KeyValuePairs[] Items {
  3565.                 get {
  3566.                     return hashtable.ToKeyValuePairsArray();
  3567.                 }
  3568.             }
  3569.         }
  3570.     }
  3571.  
  3572.     [FriendAccessAllowed]
  3573.     internal static class HashHelpers
  3574.     {
  3575.  
  3576. #if FEATURE_RANDOMIZED_STRING_HASHING
  3577.         public const int HashCollisionThreshold = 100;
  3578.         public static bool s_UseRandomizedStringHashing = String.UseRandomizedHashing();
  3579. #endif
  3580.  
  3581.         // Table of prime numbers to use as hash table sizes.
  3582.         // A typical resize algorithm would pick the smallest prime number in this array
  3583.         // that is larger than twice the previous capacity.
  3584.         // Suppose our Hashtable currently has capacity x and enough elements are added
  3585.         // such that a resize needs to occur. Resizing first computes 2x then finds the
  3586.         // first prime in the table greater than 2x, i.e. if primes are ordered
  3587.         // p_1, p_2, ..., p_i, ..., it finds p_n such that p_n-1 < 2x < p_n.
  3588.         // Doubling is important for preserving the asymptotic complexity of the
  3589.         // hashtable operations such as add.  Having a prime guarantees that double
  3590.         // hashing does not lead to infinite loops.  IE, your hash function will be
  3591.         // h1(key) + i*h2(key), 0 <= i < size.  h2 and the size must be relatively prime.
  3592.         public static readonly int[] primes = {
  3593.             3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919,
  3594.             1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591,
  3595.             17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437,
  3596.             187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263,
  3597.             1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369};
  3598.  
  3599.         // Used by Hashtable and Dictionary's SeralizationInfo .ctor's to store the SeralizationInfo
  3600.         // object until OnDeserialization is called.
  3601.         private static ConditionalWeakTable<object, SerializationInfo> s_SerializationInfoTable;
  3602.  
  3603.         internal static ConditionalWeakTable<object, SerializationInfo> SerializationInfoTable
  3604.         {
  3605.             get
  3606.             {
  3607.                 if(s_SerializationInfoTable == null)
  3608.                 {
  3609.                     ConditionalWeakTable<object, SerializationInfo> newTable = new ConditionalWeakTable<object, SerializationInfo>();
  3610.                     Interlocked.CompareExchange(ref s_SerializationInfoTable, newTable, null);
  3611.                 }
  3612.  
  3613.                 return s_SerializationInfoTable;
  3614.             }
  3615.  
  3616.         }
  3617.  
  3618.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  3619.         public static bool IsPrime(int candidate)
  3620.         {
  3621.             if ((candidate & 1) != 0)
  3622.             {
  3623.                 int limit = (int)Math.Sqrt (candidate);
  3624.                 for (int divisor = 3; divisor <= limit; divisor+=2)
  3625.                 {
  3626.                     if ((candidate % divisor) == 0)
  3627.                         return false;
  3628.                 }
  3629.                 return true;
  3630.             }
  3631.             return (candidate == 2);
  3632.         }
  3633.  
  3634.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  3635.         public static int GetPrime(int min)
  3636.         {
  3637.             if (min < 0)
  3638.                 throw new ArgumentException(Environment.GetResourceString("Arg_HTCapacityOverflow"));
  3639.             Contract.EndContractBlock();
  3640.  
  3641.             for (int i = 0; i < primes.Length; i++)
  3642.             {
  3643.                 int prime = primes[i];
  3644.                 if (prime >= min) return prime;
  3645.             }
  3646.  
  3647.             //outside of our predefined table.
  3648.             //compute the hard way.
  3649.             for (int i = (min | 1); i < Int32.MaxValue;i+=2)
  3650.             {
  3651.                 if (IsPrime(i) && ((i - 1) % Hashtable.HashPrime != 0))
  3652.                     return i;
  3653.             }
  3654.             return min;
  3655.         }
  3656.  
  3657.         public static int GetMinPrime()
  3658.         {
  3659.             return primes[0];
  3660.         }
  3661.  
  3662.         // Returns size of hashtable to grow to.
  3663.         public static int ExpandPrime(int oldSize)
  3664.         {
  3665.             int newSize = 2 * oldSize;
  3666.  
  3667.             // Allow the hashtables to grow to maximum possible size (~2G elements) before encoutering capacity overflow.
  3668.             // Note that this check works even when _items.Length overflowed thanks to the (uint) cast
  3669.             if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize)
  3670.             {
  3671.                 Contract.Assert( MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
  3672.                 return MaxPrimeArrayLength;
  3673.             }
  3674.  
  3675.             return GetPrime(newSize);
  3676.         }
  3677.  
  3678.  
  3679.         // This is the maximum prime smaller than Array.MaxArrayLength
  3680.         public const int MaxPrimeArrayLength = 0x7FEFFFFD;
  3681.  
  3682. #if FEATURE_RANDOMIZED_STRING_HASHING
  3683.         public static bool IsWellKnownEqualityComparer(object comparer)
  3684.         {
  3685.             return (comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer);
  3686.         }
  3687.  
  3688.         public static IEqualityComparer GetRandomizedEqualityComparer(object comparer)
  3689.         {
  3690.             Contract.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer);
  3691.  
  3692.             if(comparer == null) {
  3693.                 return new System.Collections.Generic.RandomizedObjectEqualityComparer();
  3694.             }
  3695.  
  3696.             if(comparer == System.Collections.Generic.EqualityComparer<string>.Default) {
  3697.                 return new System.Collections.Generic.RandomizedStringEqualityComparer();
  3698.             }
  3699.  
  3700.             IWellKnownStringEqualityComparer cmp = comparer as IWellKnownStringEqualityComparer;
  3701.  
  3702.             if(cmp != null) {
  3703.                 return cmp.GetRandomizedEqualityComparer();
  3704.             }
  3705.  
  3706.             Contract.Assert(false, "Missing case in GetRandomizedEqualityComparer!");
  3707.  
  3708.             return null;
  3709.         }
  3710.  
  3711.         public static object GetEqualityComparerForSerialization(object comparer)
  3712.         {
  3713.             if(comparer == null)
  3714.             {
  3715.                 return null;
  3716.             }
  3717.  
  3718.             IWellKnownStringEqualityComparer cmp = comparer as IWellKnownStringEqualityComparer;
  3719.  
  3720.             if(cmp != null)
  3721.             {
  3722.                 return cmp.GetEqualityComparerForSerialization();
  3723.             }
  3724.  
  3725.             return comparer;
  3726.         }
  3727.  
  3728.         private const int bufferSize = 1024;
  3729.         private static RandomNumberGenerator rng;
  3730.         private static byte[] data;
  3731.         private static int currentIndex = bufferSize;
  3732.         private static readonly object lockObj = new Object();
  3733.  
  3734.         internal static long GetEntropy()
  3735.         {
  3736.             lock(lockObj) {
  3737.                 long ret;
  3738.  
  3739.                 if(currentIndex == bufferSize)
  3740.                 {
  3741.                     if(null == rng)
  3742.                     {
  3743.                         rng = RandomNumberGenerator.Create();
  3744.                         data = new byte[bufferSize];
  3745.                         Contract.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8");
  3746.                     }
  3747.  
  3748.                     rng.GetBytes(data);
  3749.                     currentIndex = 0;
  3750.                 }
  3751.  
  3752.                 ret = BitConverter.ToInt64(data, currentIndex);
  3753.                 currentIndex += 8;
  3754.  
  3755.                 return ret;
  3756.             }
  3757.         }
  3758. #endif // FEATURE_RANDOMIZED_STRING_HASHING
  3759.     }
  3760. }
  3761.  
  3762. // File provided for Reference Use Only by Microsoft Corporation (c) 2007.
Add Comment
Please, Sign In to add comment