Hashtable.cs 63 KB

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