2
0

Hashtable.cs 64 KB

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