Hashtable.cs 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. /*============================================================
  5. **
  6. ** Class: Hashtable
  7. **
  8. ** Purpose: Represents a collection of key/value pairs
  9. ** that are organized based on the hash code
  10. ** of the key.
  11. **
  12. ===========================================================*/
  13. using System.Diagnostics;
  14. using System.Runtime.CompilerServices;
  15. using System.Runtime.Serialization;
  16. using System.Threading;
  17. namespace System.Collections
  18. {
  19. // The Hashtable class represents a dictionary of associated keys and values
  20. // with constant lookup time.
  21. //
  22. // Objects used as keys in a hashtable must implement the GetHashCode
  23. // and Equals methods (or they can rely on the default implementations
  24. // inherited from Object if key equality is simply reference
  25. // equality). Furthermore, the GetHashCode and Equals methods of
  26. // a key object must produce the same results given the same parameters for the
  27. // entire time the key is present in the hashtable. In practical terms, this
  28. // means that key objects should be immutable, at least for the time they are
  29. // used as keys in a hashtable.
  30. //
  31. // When entries are added to a hashtable, they are placed into
  32. // buckets based on the hashcode of their keys. Subsequent lookups of
  33. // keys will use the hashcode of the keys to only search a particular bucket,
  34. // thus substantially reducing the number of key comparisons required to find
  35. // an entry. A hashtable's maximum load factor, which can be specified
  36. // when the hashtable is instantiated, determines the maximum ratio of
  37. // hashtable entries to hashtable buckets. Smaller load factors cause faster
  38. // average lookup times at the cost of increased memory consumption. The
  39. // default maximum load factor of 1.0 generally provides the best balance
  40. // between speed and size. As entries are added to a hashtable, the hashtable's
  41. // actual load factor increases, and when the actual load factor reaches the
  42. // maximum load factor value, the number of buckets in the hashtable is
  43. // automatically increased by approximately a factor of two (to be precise, the
  44. // number of hashtable buckets is increased to the smallest prime number that
  45. // is larger than twice the current number of hashtable buckets).
  46. //
  47. // Each object provides their own hash function, accessed by calling
  48. // GetHashCode(). However, one can write their own object
  49. // implementing IEqualityComparer and pass it to a constructor on
  50. // the Hashtable. That hash function (and the equals method on the
  51. // IEqualityComparer) would be used for all objects in the table.
  52. //
  53. [DebuggerTypeProxy(typeof(System.Collections.Hashtable.HashtableDebugView))]
  54. [DebuggerDisplay("Count = {Count}")]
  55. [Serializable]
  56. [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
  57. public class Hashtable : IDictionary, ISerializable, IDeserializationCallback, ICloneable
  58. {
  59. /*
  60. This Hashtable uses double hashing. There are hashsize buckets in the
  61. table, and each bucket can contain 0 or 1 element. We use a bit to mark
  62. whether there's been a collision when we inserted multiple elements
  63. (ie, an inserted item was hashed at least a second time and we probed
  64. this bucket, but it was already in use). Using the collision bit, we
  65. can terminate lookups & removes for elements that aren't in the hash
  66. table more quickly. We steal the most significant bit from the hash code
  67. to store the collision bit.
  68. Our hash function is of the following form:
  69. h(key, n) = h1(key) + n*h2(key)
  70. where n is the number of times we've hit a collided bucket and rehashed
  71. (on this particular lookup). Here are our hash functions:
  72. h1(key) = GetHash(key); // default implementation calls key.GetHashCode();
  73. h2(key) = 1 + (((h1(key) >> 5) + 1) % (hashsize - 1));
  74. The h1 can return any number. h2 must return a number between 1 and
  75. hashsize - 1 that is relatively prime to hashsize (not a problem if
  76. hashsize is prime). (Knuth's Art of Computer Programming, Vol. 3, p. 528-9)
  77. If this is true, then we are guaranteed to visit every bucket in exactly
  78. hashsize probes, since the least common multiple of hashsize and h2(key)
  79. will be hashsize * h2(key). (This is the first number where adding h2 to
  80. h1 mod hashsize will be 0 and we will search the same bucket twice).
  81. We previously used a different h2(key, n) that was not constant. That is a
  82. horrifically bad idea, unless you can prove that series will never produce
  83. any identical numbers that overlap when you mod them by hashsize, for all
  84. subranges from i to i+hashsize, for all i. It's not worth investigating,
  85. since there was no clear benefit from using that hash function, and it was
  86. broken.
  87. For efficiency reasons, we've implemented this by storing h1 and h2 in a
  88. temporary, and setting a variable called seed equal to h1. We do a probe,
  89. and if we collided, we simply add h2 to seed each time through the loop.
  90. A good test for h2() is to subclass Hashtable, provide your own implementation
  91. of GetHash() that returns a constant, then add many items to the hash table.
  92. Make sure Count equals the number of items you inserted.
  93. Note that when we remove an item from the hash table, we set the key
  94. equal to buckets, if there was a collision in this bucket. Otherwise
  95. we'd either wipe out the collision bit, or we'd still have an item in
  96. the hash table.
  97. --
  98. */
  99. private const int InitialSize = 3;
  100. private const string LoadFactorName = "LoadFactor"; // Do not rename (binary serialization)
  101. private const string VersionName = "Version"; // Do not rename (binary serialization)
  102. private const string ComparerName = "Comparer"; // Do not rename (binary serialization)
  103. private const string HashCodeProviderName = "HashCodeProvider"; // Do not rename (binary serialization)
  104. private const string HashSizeName = "HashSize"; // Must save buckets.Length. Do not rename (binary serialization)
  105. private const string KeysName = "Keys"; // Do not rename (binary serialization)
  106. private const string ValuesName = "Values"; // Do not rename (binary serialization)
  107. private const string KeyComparerName = "KeyComparer"; // Do not rename (binary serialization)
  108. // Deleted entries have their key set to buckets
  109. // The hash table data.
  110. // This cannot be serialized
  111. private struct bucket
  112. {
  113. public object key;
  114. public object val;
  115. public int hash_coll; // Store hash code; sign bit means there was a collision.
  116. }
  117. private bucket[] _buckets;
  118. // The total number of entries in the hash table.
  119. private int _count;
  120. // The total number of collision bits set in the hashtable
  121. private int _occupancy;
  122. private int _loadsize;
  123. private float _loadFactor;
  124. private volatile int _version;
  125. private volatile bool _isWriterInProgress;
  126. private ICollection _keys;
  127. private ICollection _values;
  128. private IEqualityComparer _keycomparer;
  129. private object _syncRoot;
  130. [Obsolete("Please use EqualityComparer property.")]
  131. protected IHashCodeProvider hcp
  132. {
  133. get
  134. {
  135. if (_keycomparer is CompatibleComparer)
  136. {
  137. return ((CompatibleComparer)_keycomparer).HashCodeProvider;
  138. }
  139. else if (_keycomparer == null)
  140. {
  141. return null;
  142. }
  143. else
  144. {
  145. throw new ArgumentException(SR.Arg_CannotMixComparisonInfrastructure);
  146. }
  147. }
  148. set
  149. {
  150. if (_keycomparer is CompatibleComparer)
  151. {
  152. CompatibleComparer keyComparer = (CompatibleComparer)_keycomparer;
  153. _keycomparer = new CompatibleComparer(value, keyComparer.Comparer);
  154. }
  155. else if (_keycomparer == null)
  156. {
  157. _keycomparer = new CompatibleComparer(value, (IComparer)null);
  158. }
  159. else
  160. {
  161. throw new ArgumentException(SR.Arg_CannotMixComparisonInfrastructure);
  162. }
  163. }
  164. }
  165. [Obsolete("Please use KeyComparer properties.")]
  166. protected IComparer comparer
  167. {
  168. get
  169. {
  170. if (_keycomparer is CompatibleComparer)
  171. {
  172. return ((CompatibleComparer)_keycomparer).Comparer;
  173. }
  174. else if (_keycomparer == null)
  175. {
  176. return null;
  177. }
  178. else
  179. {
  180. throw new ArgumentException(SR.Arg_CannotMixComparisonInfrastructure);
  181. }
  182. }
  183. set
  184. {
  185. if (_keycomparer is CompatibleComparer)
  186. {
  187. CompatibleComparer keyComparer = (CompatibleComparer)_keycomparer;
  188. _keycomparer = new CompatibleComparer(keyComparer.HashCodeProvider, value);
  189. }
  190. else if (_keycomparer == null)
  191. {
  192. _keycomparer = new CompatibleComparer((IHashCodeProvider)null, value);
  193. }
  194. else
  195. {
  196. throw new ArgumentException(SR.Arg_CannotMixComparisonInfrastructure);
  197. }
  198. }
  199. }
  200. protected IEqualityComparer EqualityComparer
  201. {
  202. get
  203. {
  204. return _keycomparer;
  205. }
  206. }
  207. // Note: this constructor is a bogus constructor that does nothing
  208. // and is for use only with SyncHashtable.
  209. internal Hashtable(bool trash)
  210. {
  211. }
  212. // Constructs a new hashtable. The hashtable is created with an initial
  213. // capacity of zero and a load factor of 1.0.
  214. public Hashtable() : this(0, 1.0f)
  215. {
  216. }
  217. // Constructs a new hashtable with the given initial capacity and a load
  218. // factor of 1.0. The capacity argument serves as an indication of
  219. // the number of entries the hashtable will contain. When this number (or
  220. // an approximation) is known, specifying it in the constructor can
  221. // eliminate a number of resizing operations that would otherwise be
  222. // performed when elements are added to the hashtable.
  223. //
  224. public Hashtable(int capacity) : this(capacity, 1.0f)
  225. {
  226. }
  227. // Constructs a new hashtable with the given initial capacity and load
  228. // factor. The capacity argument serves as an indication of the
  229. // number of entries the hashtable will contain. When this number (or an
  230. // approximation) is known, specifying it in the constructor can eliminate
  231. // a number of resizing operations that would otherwise be performed when
  232. // elements are added to the hashtable. The loadFactor argument
  233. // indicates the maximum ratio of hashtable entries to hashtable buckets.
  234. // Smaller load factors cause faster average lookup times at the cost of
  235. // increased memory consumption. A load factor of 1.0 generally provides
  236. // the best balance between speed and size.
  237. //
  238. public Hashtable(int capacity, float loadFactor)
  239. {
  240. if (capacity < 0)
  241. throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
  242. if (!(loadFactor >= 0.1f && loadFactor <= 1.0f))
  243. throw new ArgumentOutOfRangeException(nameof(loadFactor), SR.Format(SR.ArgumentOutOfRange_HashtableLoadFactor, .1, 1.0));
  244. // Based on perf work, .72 is the optimal load factor for this table.
  245. _loadFactor = 0.72f * loadFactor;
  246. double rawsize = capacity / _loadFactor;
  247. if (rawsize > int.MaxValue)
  248. throw new ArgumentException(SR.Arg_HTCapacityOverflow, nameof(capacity));
  249. // Avoid awfully small sizes
  250. int hashsize = (rawsize > InitialSize) ? HashHelpers.GetPrime((int)rawsize) : InitialSize;
  251. _buckets = new bucket[hashsize];
  252. _loadsize = (int)(_loadFactor * hashsize);
  253. _isWriterInProgress = false;
  254. // Based on the current algorithm, loadsize must be less than hashsize.
  255. Debug.Assert(_loadsize < hashsize, "Invalid hashtable loadsize!");
  256. }
  257. public Hashtable(int capacity, float loadFactor, IEqualityComparer equalityComparer) : this(capacity, loadFactor)
  258. {
  259. _keycomparer = equalityComparer;
  260. }
  261. [Obsolete("Please use Hashtable(IEqualityComparer) instead.")]
  262. public Hashtable(IHashCodeProvider hcp, IComparer comparer)
  263. : this(0, 1.0f, hcp, comparer)
  264. {
  265. }
  266. public Hashtable(IEqualityComparer equalityComparer) : this(0, 1.0f, equalityComparer)
  267. {
  268. }
  269. [Obsolete("Please use Hashtable(int, IEqualityComparer) instead.")]
  270. public Hashtable(int capacity, IHashCodeProvider hcp, IComparer comparer)
  271. : this(capacity, 1.0f, hcp, comparer)
  272. {
  273. }
  274. public Hashtable(int capacity, IEqualityComparer equalityComparer)
  275. : this(capacity, 1.0f, equalityComparer)
  276. {
  277. }
  278. // Constructs a new hashtable containing a copy of the entries in the given
  279. // dictionary. The hashtable is created with a load factor of 1.0.
  280. //
  281. public Hashtable(IDictionary d) : this(d, 1.0f)
  282. {
  283. }
  284. // Constructs a new hashtable containing a copy of the entries in the given
  285. // dictionary. The hashtable is created with the given load factor.
  286. //
  287. public Hashtable(IDictionary d, float loadFactor)
  288. : this(d, loadFactor, (IEqualityComparer)null)
  289. {
  290. }
  291. [Obsolete("Please use Hashtable(IDictionary, IEqualityComparer) instead.")]
  292. public Hashtable(IDictionary d, IHashCodeProvider hcp, IComparer comparer)
  293. : this(d, 1.0f, hcp, comparer)
  294. {
  295. }
  296. public Hashtable(IDictionary d, IEqualityComparer equalityComparer)
  297. : this(d, 1.0f, equalityComparer)
  298. {
  299. }
  300. [Obsolete("Please use Hashtable(int, float, IEqualityComparer) instead.")]
  301. public Hashtable(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer)
  302. : this(capacity, loadFactor)
  303. {
  304. if (hcp != null || comparer != null)
  305. {
  306. _keycomparer = new CompatibleComparer(hcp, comparer);
  307. }
  308. }
  309. [Obsolete("Please use Hashtable(IDictionary, float, IEqualityComparer) instead.")]
  310. public Hashtable(IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer)
  311. : this((d != null ? d.Count : 0), loadFactor, hcp, comparer)
  312. {
  313. if (d == null)
  314. throw new ArgumentNullException(nameof(d), SR.ArgumentNull_Dictionary);
  315. IDictionaryEnumerator e = d.GetEnumerator();
  316. while (e.MoveNext())
  317. Add(e.Key, e.Value);
  318. }
  319. public Hashtable(IDictionary d, float loadFactor, IEqualityComparer equalityComparer)
  320. : this((d != null ? d.Count : 0), loadFactor, equalityComparer)
  321. {
  322. if (d == null)
  323. throw new ArgumentNullException(nameof(d), SR.ArgumentNull_Dictionary);
  324. IDictionaryEnumerator e = d.GetEnumerator();
  325. while (e.MoveNext())
  326. Add(e.Key, e.Value);
  327. }
  328. protected Hashtable(SerializationInfo info, StreamingContext context)
  329. {
  330. //We can't do anything with the keys and values until the entire graph has been deserialized
  331. //and we have a reasonable estimate that GetHashCode is not going to fail. For the time being,
  332. //we'll just cache this. The graph is not valid until OnDeserialization has been called.
  333. HashHelpers.SerializationInfoTable.Add(this, info);
  334. }
  335. // ?InitHash? is basically an implementation of classic DoubleHashing (see http://en.wikipedia.org/wiki/Double_hashing)
  336. //
  337. // 1) The only ?correctness? requirement is that the ?increment? used to probe
  338. // a. Be non-zero
  339. // 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)
  340. // 2) Because we choose table sizes to be primes, we just need to insure that the increment is 0 < incr < hashSize
  341. //
  342. // Thus this function would work: Incr = 1 + (seed % (hashSize-1))
  343. //
  344. // While this works well for ?uniformly distributed? keys, in practice, non-uniformity is common.
  345. // In particular in practice we can see ?mostly sequential? where you get long clusters of keys that ?pack?.
  346. // To avoid bad behavior you want it to be the case that the increment is ?large? even for ?small? values (because small
  347. // values tend to happen more in practice). Thus we multiply ?seed? by a number that will make these small values
  348. // bigger (and not hurt large values). We picked HashPrime (101) because it was prime, and if ?hashSize-1? is not a multiple of HashPrime
  349. // (enforced in GetPrime), then incr has the potential of being every value from 1 to hashSize-1. The choice was largely arbitrary.
  350. //
  351. // Computes the hash function: H(key, i) = h1(key) + i*h2(key, hashSize).
  352. // The out parameter seed is h1(key), while the out parameter
  353. // incr is h2(key, hashSize). Callers of this function should
  354. // add incr each time through a loop.
  355. private uint InitHash(object key, int hashsize, out uint seed, out uint incr)
  356. {
  357. // Hashcode must be positive. Also, we must not use the sign bit, since
  358. // that is used for the collision bit.
  359. uint hashcode = (uint)GetHash(key) & 0x7FFFFFFF;
  360. seed = (uint)hashcode;
  361. // Restriction: incr MUST be between 1 and hashsize - 1, inclusive for
  362. // the modular arithmetic to work correctly. This guarantees you'll
  363. // visit every bucket in the table exactly once within hashsize
  364. // iterations. Violate this and it'll cause obscure bugs forever.
  365. // If you change this calculation for h2(key), update putEntry too!
  366. incr = (uint)(1 + ((seed * HashHelpers.HashPrime) % ((uint)hashsize - 1)));
  367. return hashcode;
  368. }
  369. // Adds an entry with the given key and value to this hashtable. An
  370. // ArgumentException is thrown if the key is null or if the key is already
  371. // present in the hashtable.
  372. //
  373. public virtual void Add(object key, object value)
  374. {
  375. Insert(key, value, true);
  376. }
  377. // Removes all entries from this hashtable.
  378. public virtual void Clear()
  379. {
  380. Debug.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.");
  381. if (_count == 0 && _occupancy == 0)
  382. return;
  383. _isWriterInProgress = true;
  384. for (int i = 0; i < _buckets.Length; i++)
  385. {
  386. _buckets[i].hash_coll = 0;
  387. _buckets[i].key = null;
  388. _buckets[i].val = null;
  389. }
  390. _count = 0;
  391. _occupancy = 0;
  392. UpdateVersion();
  393. _isWriterInProgress = false;
  394. }
  395. // Clone returns a virtually identical copy of this hash table. This does
  396. // a shallow copy - the Objects in the table aren't cloned, only the references
  397. // to those Objects.
  398. public virtual object Clone()
  399. {
  400. bucket[] lbuckets = _buckets;
  401. Hashtable ht = new Hashtable(_count, _keycomparer);
  402. ht._version = _version;
  403. ht._loadFactor = _loadFactor;
  404. ht._count = 0;
  405. int bucket = lbuckets.Length;
  406. while (bucket > 0)
  407. {
  408. bucket--;
  409. object keyv = lbuckets[bucket].key;
  410. if ((keyv != null) && (keyv != lbuckets))
  411. {
  412. ht[keyv] = lbuckets[bucket].val;
  413. }
  414. }
  415. return ht;
  416. }
  417. // Checks if this hashtable contains the given key.
  418. public virtual bool Contains(object key)
  419. {
  420. return ContainsKey(key);
  421. }
  422. // Checks if this hashtable contains an entry with the given key. This is
  423. // an O(1) operation.
  424. //
  425. public virtual bool ContainsKey(object key)
  426. {
  427. if (key == null)
  428. {
  429. throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
  430. }
  431. uint seed;
  432. uint incr;
  433. // Take a snapshot of buckets, in case another thread resizes table
  434. bucket[] lbuckets = _buckets;
  435. uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr);
  436. int ntry = 0;
  437. bucket b;
  438. int bucketNumber = (int)(seed % (uint)lbuckets.Length);
  439. do
  440. {
  441. b = lbuckets[bucketNumber];
  442. if (b.key == null)
  443. {
  444. return false;
  445. }
  446. if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
  447. KeyEquals(b.key, key))
  448. return true;
  449. bucketNumber = (int)(((long)bucketNumber + incr) % (uint)lbuckets.Length);
  450. } while (b.hash_coll < 0 && ++ntry < lbuckets.Length);
  451. return false;
  452. }
  453. // Checks if this hashtable contains an entry with the given value. The
  454. // values of the entries of the hashtable are compared to the given value
  455. // using the Object.Equals method. This method performs a linear
  456. // search and is thus be substantially slower than the ContainsKey
  457. // method.
  458. //
  459. public virtual bool ContainsValue(object value)
  460. {
  461. if (value == null)
  462. {
  463. for (int i = _buckets.Length; --i >= 0;)
  464. {
  465. if (_buckets[i].key != null && _buckets[i].key != _buckets && _buckets[i].val == null)
  466. return true;
  467. }
  468. }
  469. else
  470. {
  471. for (int i = _buckets.Length; --i >= 0;)
  472. {
  473. object val = _buckets[i].val;
  474. if (val != null && val.Equals(value))
  475. return true;
  476. }
  477. }
  478. return false;
  479. }
  480. // Copies the keys of this hashtable to a given array starting at a given
  481. // index. This method is used by the implementation of the CopyTo method in
  482. // the KeyCollection class.
  483. private void CopyKeys(Array array, int arrayIndex)
  484. {
  485. Debug.Assert(array != null);
  486. Debug.Assert(array.Rank == 1);
  487. bucket[] lbuckets = _buckets;
  488. for (int i = lbuckets.Length; --i >= 0;)
  489. {
  490. object keyv = lbuckets[i].key;
  491. if ((keyv != null) && (keyv != _buckets))
  492. {
  493. array.SetValue(keyv, arrayIndex++);
  494. }
  495. }
  496. }
  497. // Copies the keys of this hashtable to a given array starting at a given
  498. // index. This method is used by the implementation of the CopyTo method in
  499. // the KeyCollection class.
  500. private void CopyEntries(Array array, int arrayIndex)
  501. {
  502. Debug.Assert(array != null);
  503. Debug.Assert(array.Rank == 1);
  504. bucket[] lbuckets = _buckets;
  505. for (int i = lbuckets.Length; --i >= 0;)
  506. {
  507. object keyv = lbuckets[i].key;
  508. if ((keyv != null) && (keyv != _buckets))
  509. {
  510. DictionaryEntry entry = new DictionaryEntry(keyv, lbuckets[i].val);
  511. array.SetValue(entry, arrayIndex++);
  512. }
  513. }
  514. }
  515. // Copies the values in this hash table to an array at
  516. // a given index. Note that this only copies values, and not keys.
  517. public virtual void CopyTo(Array array, int arrayIndex)
  518. {
  519. if (array == null)
  520. throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Array);
  521. if (array.Rank != 1)
  522. throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
  523. if (arrayIndex < 0)
  524. throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum);
  525. if (array.Length - arrayIndex < Count)
  526. throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
  527. CopyEntries(array, arrayIndex);
  528. }
  529. // Copies the values in this Hashtable to an KeyValuePairs array.
  530. // KeyValuePairs is different from Dictionary Entry in that it has special
  531. // debugger attributes on its fields.
  532. internal virtual KeyValuePairs[] ToKeyValuePairsArray()
  533. {
  534. KeyValuePairs[] array = new KeyValuePairs[_count];
  535. int index = 0;
  536. bucket[] lbuckets = _buckets;
  537. for (int i = lbuckets.Length; --i >= 0;)
  538. {
  539. object keyv = lbuckets[i].key;
  540. if ((keyv != null) && (keyv != _buckets))
  541. {
  542. array[index++] = new KeyValuePairs(keyv, lbuckets[i].val);
  543. }
  544. }
  545. return array;
  546. }
  547. // Copies the values of this hashtable to a given array starting at a given
  548. // index. This method is used by the implementation of the CopyTo method in
  549. // the ValueCollection class.
  550. private void CopyValues(Array array, int arrayIndex)
  551. {
  552. Debug.Assert(array != null);
  553. Debug.Assert(array.Rank == 1);
  554. bucket[] lbuckets = _buckets;
  555. for (int i = lbuckets.Length; --i >= 0;)
  556. {
  557. object keyv = lbuckets[i].key;
  558. if ((keyv != null) && (keyv != _buckets))
  559. {
  560. array.SetValue(lbuckets[i].val, arrayIndex++);
  561. }
  562. }
  563. }
  564. // Returns the value associated with the given key. If an entry with the
  565. // given key is not found, the returned value is null.
  566. //
  567. public virtual object this[object key]
  568. {
  569. get
  570. {
  571. if (key == null)
  572. {
  573. throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
  574. }
  575. uint seed;
  576. uint incr;
  577. // Take a snapshot of buckets, in case another thread does a resize
  578. bucket[] lbuckets = _buckets;
  579. uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr);
  580. int ntry = 0;
  581. bucket b;
  582. int bucketNumber = (int)(seed % (uint)lbuckets.Length);
  583. do
  584. {
  585. int currentversion;
  586. // A read operation on hashtable has three steps:
  587. // (1) calculate the hash and find the slot number.
  588. // (2) compare the hashcode, if equal, go to step 3. Otherwise end.
  589. // (3) compare the key, if equal, go to step 4. Otherwise end.
  590. // (4) return the value contained in the bucket.
  591. // After step 3 and before step 4. A writer can kick in a remove the old item and add a new one
  592. // in the same bucket. So in the reader we need to check if the hash table is modified during above steps.
  593. //
  594. // Writers (Insert, Remove, Clear) will set 'isWriterInProgress' flag before it starts modifying
  595. // the hashtable and will ckear the flag when it is done. When the flag is cleared, the 'version'
  596. // will be increased. We will repeat the reading if a writer is in progress or done with the modification
  597. // during the read.
  598. //
  599. // Our memory model guarantee if we pick up the change in bucket from another processor,
  600. // we will see the 'isWriterProgress' flag to be true or 'version' is changed in the reader.
  601. //
  602. SpinWait spin = new SpinWait();
  603. while (true)
  604. {
  605. // this is volatile read, following memory accesses can not be moved ahead of it.
  606. currentversion = _version;
  607. b = lbuckets[bucketNumber];
  608. if (!_isWriterInProgress && (currentversion == _version))
  609. break;
  610. spin.SpinOnce();
  611. }
  612. if (b.key == null)
  613. {
  614. return null;
  615. }
  616. if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
  617. KeyEquals(b.key, key))
  618. return b.val;
  619. bucketNumber = (int)(((long)bucketNumber + incr) % (uint)lbuckets.Length);
  620. } while (b.hash_coll < 0 && ++ntry < lbuckets.Length);
  621. return null;
  622. }
  623. set
  624. {
  625. Insert(key, value, false);
  626. }
  627. }
  628. // Increases the bucket count of this hashtable. This method is called from
  629. // the Insert method when the actual load factor of the hashtable reaches
  630. // the upper limit specified when the hashtable was constructed. The number
  631. // of buckets in the hashtable is increased to the smallest prime number
  632. // that is larger than twice the current number of buckets, and the entries
  633. // in the hashtable are redistributed into the new buckets using the cached
  634. // hashcodes.
  635. private void expand()
  636. {
  637. int rawsize = HashHelpers.ExpandPrime(_buckets.Length);
  638. rehash(rawsize);
  639. }
  640. // We occasionally need to rehash the table to clean up the collision bits.
  641. private void rehash()
  642. {
  643. rehash(_buckets.Length);
  644. }
  645. private void UpdateVersion()
  646. {
  647. // Version might become negative when version is int.MaxValue, but the oddity will be still be correct.
  648. // So we don't need to special case this.
  649. _version++;
  650. }
  651. private void rehash(int newsize)
  652. {
  653. // reset occupancy
  654. _occupancy = 0;
  655. // Don't replace any internal state until we've finished adding to the
  656. // new bucket[]. This serves two purposes:
  657. // 1) Allow concurrent readers to see valid hashtable contents
  658. // at all times
  659. // 2) Protect against an OutOfMemoryException while allocating this
  660. // new bucket[].
  661. bucket[] newBuckets = new bucket[newsize];
  662. // rehash table into new buckets
  663. int nb;
  664. for (nb = 0; nb < _buckets.Length; nb++)
  665. {
  666. bucket oldb = _buckets[nb];
  667. if ((oldb.key != null) && (oldb.key != _buckets))
  668. {
  669. int hashcode = oldb.hash_coll & 0x7FFFFFFF;
  670. putEntry(newBuckets, oldb.key, oldb.val, hashcode);
  671. }
  672. }
  673. // New bucket[] is good to go - replace buckets and other internal state.
  674. _isWriterInProgress = true;
  675. _buckets = newBuckets;
  676. _loadsize = (int)(_loadFactor * newsize);
  677. UpdateVersion();
  678. _isWriterInProgress = false;
  679. // minimum size of hashtable is 3 now and maximum loadFactor is 0.72 now.
  680. Debug.Assert(_loadsize < newsize, "Our current implementation means this is not possible.");
  681. }
  682. // Returns an enumerator for this hashtable.
  683. // If modifications made to the hashtable while an enumeration is
  684. // in progress, the MoveNext and Current methods of the
  685. // enumerator will throw an exception.
  686. //
  687. IEnumerator IEnumerable.GetEnumerator()
  688. {
  689. return new HashtableEnumerator(this, HashtableEnumerator.DictEntry);
  690. }
  691. // Returns a dictionary enumerator for this hashtable.
  692. // If modifications made to the hashtable while an enumeration is
  693. // in progress, the MoveNext and Current methods of the
  694. // enumerator will throw an exception.
  695. //
  696. public virtual IDictionaryEnumerator GetEnumerator()
  697. {
  698. return new HashtableEnumerator(this, HashtableEnumerator.DictEntry);
  699. }
  700. // Internal method to get the hash code for an Object. This will call
  701. // GetHashCode() on each object if you haven't provided an IHashCodeProvider
  702. // instance. Otherwise, it calls hcp.GetHashCode(obj).
  703. protected virtual int GetHash(object key)
  704. {
  705. if (_keycomparer != null)
  706. return _keycomparer.GetHashCode(key);
  707. return key.GetHashCode();
  708. }
  709. // Is this Hashtable read-only?
  710. public virtual bool IsReadOnly
  711. {
  712. get { return false; }
  713. }
  714. public virtual bool IsFixedSize
  715. {
  716. get { return false; }
  717. }
  718. // Is this Hashtable synchronized? See SyncRoot property
  719. public virtual bool IsSynchronized
  720. {
  721. get { return false; }
  722. }
  723. // Internal method to compare two keys. If you have provided an IComparer
  724. // instance in the constructor, this method will call comparer.Compare(item, key).
  725. // Otherwise, it will call item.Equals(key).
  726. //
  727. protected virtual bool KeyEquals(object item, object key)
  728. {
  729. Debug.Assert(key != null, "key can't be null here!");
  730. if (object.ReferenceEquals(_buckets, item))
  731. {
  732. return false;
  733. }
  734. if (object.ReferenceEquals(item, key))
  735. return true;
  736. if (_keycomparer != null)
  737. return _keycomparer.Equals(item, key);
  738. return item == null ? false : item.Equals(key);
  739. }
  740. // Returns a collection representing the keys of this hashtable. The order
  741. // in which the returned collection represents the keys is unspecified, but
  742. // it is guaranteed to be buckets = newBuckets; the same order in which a collection returned by
  743. // GetValues represents the values of the hashtable.
  744. //
  745. // The returned collection is live in the sense that any changes
  746. // to the hash table are reflected in this collection. It is not
  747. // a static copy of all the keys in the hash table.
  748. //
  749. public virtual ICollection Keys
  750. {
  751. get
  752. {
  753. if (_keys == null)
  754. _keys = new KeyCollection(this);
  755. return _keys;
  756. }
  757. }
  758. // Returns a collection representing the values of this hashtable. The
  759. // order in which the returned collection represents the values is
  760. // unspecified, but it is guaranteed to be the same order in which a
  761. // collection returned by GetKeys represents the keys of the
  762. // hashtable.
  763. //
  764. // The returned collection is live in the sense that any changes
  765. // to the hash table are reflected in this collection. It is not
  766. // a static copy of all the keys in the hash table.
  767. //
  768. public virtual ICollection Values
  769. {
  770. get
  771. {
  772. if (_values == null)
  773. _values = new ValueCollection(this);
  774. return _values;
  775. }
  776. }
  777. // Inserts an entry into this hashtable. This method is called from the Set
  778. // and Add methods. If the add parameter is true and the given key already
  779. // exists in the hashtable, an exception is thrown.
  780. private void Insert(object key, object nvalue, bool add)
  781. {
  782. if (key == null)
  783. {
  784. throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
  785. }
  786. if (_count >= _loadsize)
  787. {
  788. expand();
  789. }
  790. else if (_occupancy > _loadsize && _count > 100)
  791. {
  792. rehash();
  793. }
  794. uint seed;
  795. uint incr;
  796. // Assume we only have one thread writing concurrently. Modify
  797. // buckets to contain new data, as long as we insert in the right order.
  798. uint hashcode = InitHash(key, _buckets.Length, out seed, out incr);
  799. int ntry = 0;
  800. int emptySlotNumber = -1; // We use the empty slot number to cache the first empty slot. We chose to reuse slots
  801. // create by remove that have the collision bit set over using up new slots.
  802. int bucketNumber = (int)(seed % (uint)_buckets.Length);
  803. do
  804. {
  805. // Set emptySlot number to current bucket if it is the first available bucket that we have seen
  806. // that once contained an entry and also has had a collision.
  807. // We need to search this entire collision chain because we have to ensure that there are no
  808. // duplicate entries in the table.
  809. if (emptySlotNumber == -1 && (_buckets[bucketNumber].key == _buckets) && (_buckets[bucketNumber].hash_coll < 0))//(((buckets[bucketNumber].hash_coll & unchecked(0x80000000))!=0)))
  810. emptySlotNumber = bucketNumber;
  811. // Insert the key/value pair into this bucket if this bucket is empty and has never contained an entry
  812. // OR
  813. // This bucket once contained an entry but there has never been a collision
  814. if ((_buckets[bucketNumber].key == null) ||
  815. (_buckets[bucketNumber].key == _buckets && ((_buckets[bucketNumber].hash_coll & unchecked(0x80000000)) == 0)))
  816. {
  817. // If we have found an available bucket that has never had a collision, but we've seen an available
  818. // bucket in the past that has the collision bit set, use the previous bucket instead
  819. if (emptySlotNumber != -1) // Reuse slot
  820. bucketNumber = emptySlotNumber;
  821. // We pretty much have to insert in this order. Don't set hash
  822. // code until the value & key are set appropriately.
  823. _isWriterInProgress = true;
  824. _buckets[bucketNumber].val = nvalue;
  825. _buckets[bucketNumber].key = key;
  826. _buckets[bucketNumber].hash_coll |= (int)hashcode;
  827. _count++;
  828. UpdateVersion();
  829. _isWriterInProgress = false;
  830. return;
  831. }
  832. // The current bucket is in use
  833. // OR
  834. // it is available, but has had the collision bit set and we have already found an available bucket
  835. if (((_buckets[bucketNumber].hash_coll & 0x7FFFFFFF) == hashcode) &&
  836. KeyEquals(_buckets[bucketNumber].key, key))
  837. {
  838. if (add)
  839. {
  840. throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate__, _buckets[bucketNumber].key, key));
  841. }
  842. _isWriterInProgress = true;
  843. _buckets[bucketNumber].val = nvalue;
  844. UpdateVersion();
  845. _isWriterInProgress = false;
  846. return;
  847. }
  848. // The current bucket is full, and we have therefore collided. We need to set the collision bit
  849. // unless we have remembered an available slot previously.
  850. if (emptySlotNumber == -1)
  851. {// We don't need to set the collision bit here since we already have an empty slot
  852. if (_buckets[bucketNumber].hash_coll >= 0)
  853. {
  854. _buckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
  855. _occupancy++;
  856. }
  857. }
  858. bucketNumber = (int)(((long)bucketNumber + incr) % (uint)_buckets.Length);
  859. } while (++ntry < _buckets.Length);
  860. // This code is here if and only if there were no buckets without a collision bit set in the entire table
  861. if (emptySlotNumber != -1)
  862. {
  863. // We pretty much have to insert in this order. Don't set hash
  864. // code until the value & key are set appropriately.
  865. _isWriterInProgress = true;
  866. _buckets[emptySlotNumber].val = nvalue;
  867. _buckets[emptySlotNumber].key = key;
  868. _buckets[emptySlotNumber].hash_coll |= (int)hashcode;
  869. _count++;
  870. UpdateVersion();
  871. _isWriterInProgress = false;
  872. return;
  873. }
  874. // If you see this assert, make sure load factor & count are reasonable.
  875. // Then verify that our double hash function (h2, described at top of file)
  876. // meets the requirements described above. You should never see this assert.
  877. Debug.Fail("hash table insert failed! Load factor too high, or our double hashing function is incorrect.");
  878. throw new InvalidOperationException(SR.InvalidOperation_HashInsertFailed);
  879. }
  880. private void putEntry(bucket[] newBuckets, object key, object nvalue, int hashcode)
  881. {
  882. Debug.Assert(hashcode >= 0, "hashcode >= 0"); // make sure collision bit (sign bit) wasn't set.
  883. uint seed = (uint)hashcode;
  884. uint incr = unchecked((uint)(1 + ((seed * HashHelpers.HashPrime) % ((uint)newBuckets.Length - 1))));
  885. int bucketNumber = (int)(seed % (uint)newBuckets.Length);
  886. do
  887. {
  888. if ((newBuckets[bucketNumber].key == null) || (newBuckets[bucketNumber].key == _buckets))
  889. {
  890. newBuckets[bucketNumber].val = nvalue;
  891. newBuckets[bucketNumber].key = key;
  892. newBuckets[bucketNumber].hash_coll |= hashcode;
  893. return;
  894. }
  895. if (newBuckets[bucketNumber].hash_coll >= 0)
  896. {
  897. newBuckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
  898. _occupancy++;
  899. }
  900. bucketNumber = (int)(((long)bucketNumber + incr) % (uint)newBuckets.Length);
  901. } while (true);
  902. }
  903. // Removes an entry from this hashtable. If an entry with the specified
  904. // key exists in the hashtable, it is removed. An ArgumentException is
  905. // thrown if the key is null.
  906. //
  907. public virtual void Remove(object key)
  908. {
  909. if (key == null)
  910. {
  911. throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
  912. }
  913. Debug.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.");
  914. uint seed;
  915. uint incr;
  916. // Assuming only one concurrent writer, write directly into buckets.
  917. uint hashcode = InitHash(key, _buckets.Length, out seed, out incr);
  918. int ntry = 0;
  919. bucket b;
  920. int bn = (int)(seed % (uint)_buckets.Length); // bucketNumber
  921. do
  922. {
  923. b = _buckets[bn];
  924. if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
  925. KeyEquals(b.key, key))
  926. {
  927. _isWriterInProgress = true;
  928. // Clear hash_coll field, then key, then value
  929. _buckets[bn].hash_coll &= unchecked((int)0x80000000);
  930. if (_buckets[bn].hash_coll != 0)
  931. {
  932. _buckets[bn].key = _buckets;
  933. }
  934. else
  935. {
  936. _buckets[bn].key = null;
  937. }
  938. _buckets[bn].val = null; // Free object references sooner & simplify ContainsValue.
  939. _count--;
  940. UpdateVersion();
  941. _isWriterInProgress = false;
  942. return;
  943. }
  944. bn = (int)(((long)bn + incr) % (uint)_buckets.Length);
  945. } while (b.hash_coll < 0 && ++ntry < _buckets.Length);
  946. }
  947. // Returns the object to synchronize on for this hash table.
  948. public virtual object SyncRoot
  949. {
  950. get
  951. {
  952. if (_syncRoot == null)
  953. {
  954. System.Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null);
  955. }
  956. return _syncRoot;
  957. }
  958. }
  959. // Returns the number of associations in this hashtable.
  960. //
  961. public virtual int Count
  962. {
  963. get { return _count; }
  964. }
  965. // Returns a thread-safe wrapper for a Hashtable.
  966. //
  967. public static Hashtable Synchronized(Hashtable table)
  968. {
  969. if (table == null)
  970. throw new ArgumentNullException(nameof(table));
  971. return new SyncHashtable(table);
  972. }
  973. public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
  974. {
  975. if (info == null)
  976. {
  977. throw new ArgumentNullException(nameof(info));
  978. }
  979. // This is imperfect - it only works well if all other writes are
  980. // also using our synchronized wrapper. But it's still a good idea.
  981. lock (SyncRoot)
  982. {
  983. // This method hasn't been fully tweaked to be safe for a concurrent writer.
  984. int oldVersion = _version;
  985. info.AddValue(LoadFactorName, _loadFactor);
  986. info.AddValue(VersionName, _version);
  987. //
  988. // We need to maintain serialization compatibility with Everett and RTM.
  989. // If the comparer is null or a compatible comparer, serialize Hashtable
  990. // in a format that can be deserialized on Everett and RTM.
  991. //
  992. // Also, if the Hashtable is using randomized hashing, serialize the old
  993. // view of the _keycomparer so perevious frameworks don't see the new types
  994. #pragma warning disable 618
  995. IEqualityComparer keyComparerForSerilization = _keycomparer;
  996. if (keyComparerForSerilization == null)
  997. {
  998. info.AddValue(ComparerName, null, typeof(IComparer));
  999. info.AddValue(HashCodeProviderName, null, typeof(IHashCodeProvider));
  1000. }
  1001. else if (keyComparerForSerilization is CompatibleComparer)
  1002. {
  1003. CompatibleComparer c = keyComparerForSerilization as CompatibleComparer;
  1004. info.AddValue(ComparerName, c.Comparer, typeof(IComparer));
  1005. info.AddValue(HashCodeProviderName, c.HashCodeProvider, typeof(IHashCodeProvider));
  1006. }
  1007. else
  1008. {
  1009. info.AddValue(KeyComparerName, keyComparerForSerilization, typeof(IEqualityComparer));
  1010. }
  1011. #pragma warning restore 618
  1012. info.AddValue(HashSizeName, _buckets.Length); //This is the length of the bucket array.
  1013. object[] serKeys = new object[_count];
  1014. object[] serValues = new object[_count];
  1015. CopyKeys(serKeys, 0);
  1016. CopyValues(serValues, 0);
  1017. info.AddValue(KeysName, serKeys, typeof(object[]));
  1018. info.AddValue(ValuesName, serValues, typeof(object[]));
  1019. // Explicitly check to see if anyone changed the Hashtable while we
  1020. // were serializing it. That's a race in their code.
  1021. if (_version != oldVersion)
  1022. {
  1023. throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
  1024. }
  1025. }
  1026. }
  1027. //
  1028. // DeserializationEvent Listener
  1029. //
  1030. public virtual void OnDeserialization(object sender)
  1031. {
  1032. if (_buckets != null)
  1033. {
  1034. // Somebody had a dependency on this hashtable and fixed us up before the ObjectManager got to it.
  1035. return;
  1036. }
  1037. SerializationInfo siInfo;
  1038. HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo);
  1039. if (siInfo == null)
  1040. {
  1041. throw new SerializationException(SR.Serialization_InvalidOnDeser);
  1042. }
  1043. int hashsize = 0;
  1044. IComparer c = null;
  1045. #pragma warning disable 618
  1046. IHashCodeProvider hcp = null;
  1047. #pragma warning restore 618
  1048. object[] serKeys = null;
  1049. object[] serValues = null;
  1050. SerializationInfoEnumerator enumerator = siInfo.GetEnumerator();
  1051. while (enumerator.MoveNext())
  1052. {
  1053. switch (enumerator.Name)
  1054. {
  1055. case LoadFactorName:
  1056. _loadFactor = siInfo.GetSingle(LoadFactorName);
  1057. break;
  1058. case HashSizeName:
  1059. hashsize = siInfo.GetInt32(HashSizeName);
  1060. break;
  1061. case KeyComparerName:
  1062. _keycomparer = (IEqualityComparer)siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer));
  1063. break;
  1064. case ComparerName:
  1065. c = (IComparer)siInfo.GetValue(ComparerName, typeof(IComparer));
  1066. break;
  1067. case HashCodeProviderName:
  1068. #pragma warning disable 618
  1069. hcp = (IHashCodeProvider)siInfo.GetValue(HashCodeProviderName, typeof(IHashCodeProvider));
  1070. #pragma warning restore 618
  1071. break;
  1072. case KeysName:
  1073. serKeys = (object[])siInfo.GetValue(KeysName, typeof(object[]));
  1074. break;
  1075. case ValuesName:
  1076. serValues = (object[])siInfo.GetValue(ValuesName, typeof(object[]));
  1077. break;
  1078. }
  1079. }
  1080. _loadsize = (int)(_loadFactor * hashsize);
  1081. // V1 object doesn't has _keycomparer field.
  1082. if ((_keycomparer == null) && ((c != null) || (hcp != null)))
  1083. {
  1084. _keycomparer = new CompatibleComparer(hcp, c);
  1085. }
  1086. _buckets = new bucket[hashsize];
  1087. if (serKeys == null)
  1088. {
  1089. throw new SerializationException(SR.Serialization_MissingKeys);
  1090. }
  1091. if (serValues == null)
  1092. {
  1093. throw new SerializationException(SR.Serialization_MissingValues);
  1094. }
  1095. if (serKeys.Length != serValues.Length)
  1096. {
  1097. throw new SerializationException(SR.Serialization_KeyValueDifferentSizes);
  1098. }
  1099. for (int i = 0; i < serKeys.Length; i++)
  1100. {
  1101. if (serKeys[i] == null)
  1102. {
  1103. throw new SerializationException(SR.Serialization_NullKey);
  1104. }
  1105. Insert(serKeys[i], serValues[i], true);
  1106. }
  1107. _version = siInfo.GetInt32(VersionName);
  1108. HashHelpers.SerializationInfoTable.Remove(this);
  1109. }
  1110. // Implements a Collection for the keys of a hashtable. An instance of this
  1111. // class is created by the GetKeys method of a hashtable.
  1112. private class KeyCollection : ICollection
  1113. {
  1114. private Hashtable _hashtable;
  1115. internal KeyCollection(Hashtable hashtable)
  1116. {
  1117. _hashtable = hashtable;
  1118. }
  1119. public virtual void CopyTo(Array array, int arrayIndex)
  1120. {
  1121. if (array == null)
  1122. throw new ArgumentNullException(nameof(array));
  1123. if (array.Rank != 1)
  1124. throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
  1125. if (arrayIndex < 0)
  1126. throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum);
  1127. if (array.Length - arrayIndex < _hashtable._count)
  1128. throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
  1129. _hashtable.CopyKeys(array, arrayIndex);
  1130. }
  1131. public virtual IEnumerator GetEnumerator()
  1132. {
  1133. return new HashtableEnumerator(_hashtable, HashtableEnumerator.Keys);
  1134. }
  1135. public virtual bool IsSynchronized
  1136. {
  1137. get { return _hashtable.IsSynchronized; }
  1138. }
  1139. public virtual object SyncRoot
  1140. {
  1141. get { return _hashtable.SyncRoot; }
  1142. }
  1143. public virtual int Count
  1144. {
  1145. get { return _hashtable._count; }
  1146. }
  1147. }
  1148. // Implements a Collection for the values of a hashtable. An instance of
  1149. // this class is created by the GetValues method of a hashtable.
  1150. private class ValueCollection : ICollection
  1151. {
  1152. private Hashtable _hashtable;
  1153. internal ValueCollection(Hashtable hashtable)
  1154. {
  1155. _hashtable = hashtable;
  1156. }
  1157. public virtual void CopyTo(Array array, int arrayIndex)
  1158. {
  1159. if (array == null)
  1160. throw new ArgumentNullException(nameof(array));
  1161. if (array.Rank != 1)
  1162. throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
  1163. if (arrayIndex < 0)
  1164. throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum);
  1165. if (array.Length - arrayIndex < _hashtable._count)
  1166. throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
  1167. _hashtable.CopyValues(array, arrayIndex);
  1168. }
  1169. public virtual IEnumerator GetEnumerator()
  1170. {
  1171. return new HashtableEnumerator(_hashtable, HashtableEnumerator.Values);
  1172. }
  1173. public virtual bool IsSynchronized
  1174. {
  1175. get { return _hashtable.IsSynchronized; }
  1176. }
  1177. public virtual object SyncRoot
  1178. {
  1179. get { return _hashtable.SyncRoot; }
  1180. }
  1181. public virtual int Count
  1182. {
  1183. get { return _hashtable._count; }
  1184. }
  1185. }
  1186. // Synchronized wrapper for hashtable
  1187. private class SyncHashtable : Hashtable, IEnumerable
  1188. {
  1189. protected Hashtable _table;
  1190. internal SyncHashtable(Hashtable table) : base(false)
  1191. {
  1192. _table = table;
  1193. }
  1194. internal SyncHashtable(SerializationInfo info, StreamingContext context) : base(info, context)
  1195. {
  1196. throw new PlatformNotSupportedException();
  1197. }
  1198. public override void GetObjectData(SerializationInfo info, StreamingContext context)
  1199. {
  1200. throw new PlatformNotSupportedException();
  1201. }
  1202. public override int Count
  1203. {
  1204. get { return _table.Count; }
  1205. }
  1206. public override bool IsReadOnly
  1207. {
  1208. get { return _table.IsReadOnly; }
  1209. }
  1210. public override bool IsFixedSize
  1211. {
  1212. get { return _table.IsFixedSize; }
  1213. }
  1214. public override bool IsSynchronized
  1215. {
  1216. get { return true; }
  1217. }
  1218. public override object this[object key]
  1219. {
  1220. get
  1221. {
  1222. return _table[key];
  1223. }
  1224. set
  1225. {
  1226. lock (_table.SyncRoot)
  1227. {
  1228. _table[key] = value;
  1229. }
  1230. }
  1231. }
  1232. public override object SyncRoot
  1233. {
  1234. get { return _table.SyncRoot; }
  1235. }
  1236. public override void Add(object key, object value)
  1237. {
  1238. lock (_table.SyncRoot)
  1239. {
  1240. _table.Add(key, value);
  1241. }
  1242. }
  1243. public override void Clear()
  1244. {
  1245. lock (_table.SyncRoot)
  1246. {
  1247. _table.Clear();
  1248. }
  1249. }
  1250. public override bool Contains(object key)
  1251. {
  1252. return _table.Contains(key);
  1253. }
  1254. public override bool ContainsKey(object key)
  1255. {
  1256. if (key == null)
  1257. {
  1258. throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
  1259. }
  1260. return _table.ContainsKey(key);
  1261. }
  1262. public override bool ContainsValue(object key)
  1263. {
  1264. lock (_table.SyncRoot)
  1265. {
  1266. return _table.ContainsValue(key);
  1267. }
  1268. }
  1269. public override void CopyTo(Array array, int arrayIndex)
  1270. {
  1271. lock (_table.SyncRoot)
  1272. {
  1273. _table.CopyTo(array, arrayIndex);
  1274. }
  1275. }
  1276. public override object Clone()
  1277. {
  1278. lock (_table.SyncRoot)
  1279. {
  1280. return Hashtable.Synchronized((Hashtable)_table.Clone());
  1281. }
  1282. }
  1283. IEnumerator IEnumerable.GetEnumerator()
  1284. {
  1285. return _table.GetEnumerator();
  1286. }
  1287. public override IDictionaryEnumerator GetEnumerator()
  1288. {
  1289. return _table.GetEnumerator();
  1290. }
  1291. public override ICollection Keys
  1292. {
  1293. get
  1294. {
  1295. lock (_table.SyncRoot)
  1296. {
  1297. return _table.Keys;
  1298. }
  1299. }
  1300. }
  1301. public override ICollection Values
  1302. {
  1303. get
  1304. {
  1305. lock (_table.SyncRoot)
  1306. {
  1307. return _table.Values;
  1308. }
  1309. }
  1310. }
  1311. public override void Remove(object key)
  1312. {
  1313. lock (_table.SyncRoot)
  1314. {
  1315. _table.Remove(key);
  1316. }
  1317. }
  1318. public override void OnDeserialization(object sender)
  1319. {
  1320. // Does nothing. We have to implement this because our parent HT implements it,
  1321. // but it doesn't do anything meaningful. The real work will be done when we
  1322. // call OnDeserialization on our parent table.
  1323. }
  1324. internal override KeyValuePairs[] ToKeyValuePairsArray()
  1325. {
  1326. return _table.ToKeyValuePairsArray();
  1327. }
  1328. }
  1329. // Implements an enumerator for a hashtable. The enumerator uses the
  1330. // internal version number of the hashtable to ensure that no modifications
  1331. // are made to the hashtable while an enumeration is in progress.
  1332. private class HashtableEnumerator : IDictionaryEnumerator, ICloneable
  1333. {
  1334. private Hashtable _hashtable;
  1335. private int _bucket;
  1336. private int _version;
  1337. private bool _current;
  1338. private int _getObjectRetType; // What should GetObject return?
  1339. private object _currentKey;
  1340. private object _currentValue;
  1341. internal const int Keys = 1;
  1342. internal const int Values = 2;
  1343. internal const int DictEntry = 3;
  1344. internal HashtableEnumerator(Hashtable hashtable, int getObjRetType)
  1345. {
  1346. _hashtable = hashtable;
  1347. _bucket = hashtable._buckets.Length;
  1348. _version = hashtable._version;
  1349. _current = false;
  1350. _getObjectRetType = getObjRetType;
  1351. }
  1352. public object Clone() => MemberwiseClone();
  1353. public virtual object Key
  1354. {
  1355. get
  1356. {
  1357. if (_current == false)
  1358. throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
  1359. return _currentKey;
  1360. }
  1361. }
  1362. public virtual bool MoveNext()
  1363. {
  1364. if (_version != _hashtable._version)
  1365. throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
  1366. while (_bucket > 0)
  1367. {
  1368. _bucket--;
  1369. object keyv = _hashtable._buckets[_bucket].key;
  1370. if ((keyv != null) && (keyv != _hashtable._buckets))
  1371. {
  1372. _currentKey = keyv;
  1373. _currentValue = _hashtable._buckets[_bucket].val;
  1374. _current = true;
  1375. return true;
  1376. }
  1377. }
  1378. _current = false;
  1379. return false;
  1380. }
  1381. public virtual DictionaryEntry Entry
  1382. {
  1383. get
  1384. {
  1385. if (_current == false)
  1386. throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
  1387. return new DictionaryEntry(_currentKey, _currentValue);
  1388. }
  1389. }
  1390. public virtual object Current
  1391. {
  1392. get
  1393. {
  1394. if (_current == false)
  1395. throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
  1396. if (_getObjectRetType == Keys)
  1397. return _currentKey;
  1398. else if (_getObjectRetType == Values)
  1399. return _currentValue;
  1400. else
  1401. return new DictionaryEntry(_currentKey, _currentValue);
  1402. }
  1403. }
  1404. public virtual object Value
  1405. {
  1406. get
  1407. {
  1408. if (_current == false)
  1409. throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
  1410. return _currentValue;
  1411. }
  1412. }
  1413. public virtual void Reset()
  1414. {
  1415. if (_version != _hashtable._version)
  1416. throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
  1417. _current = false;
  1418. _bucket = _hashtable._buckets.Length;
  1419. _currentKey = null;
  1420. _currentValue = null;
  1421. }
  1422. }
  1423. // internal debug view class for hashtable
  1424. internal class HashtableDebugView
  1425. {
  1426. private Hashtable _hashtable;
  1427. public HashtableDebugView(Hashtable hashtable)
  1428. {
  1429. if (hashtable == null)
  1430. {
  1431. throw new ArgumentNullException(nameof(hashtable));
  1432. }
  1433. _hashtable = hashtable;
  1434. }
  1435. [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
  1436. public KeyValuePairs[] Items
  1437. {
  1438. get
  1439. {
  1440. return _hashtable.ToKeyValuePairsArray();
  1441. }
  1442. }
  1443. }
  1444. }
  1445. }