HashSet.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. //
  2. // HashSet.cs
  3. //
  4. // Authors:
  5. // Jb Evain <[email protected]>
  6. //
  7. // Copyright (C) 2007 Novell, Inc (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Linq;
  32. using System.Runtime.Serialization;
  33. using System.Runtime.InteropServices;
  34. using System.Security;
  35. using System.Security.Permissions;
  36. // HashSet is basically implemented as a reduction of Dictionary<K, V>
  37. namespace System.Collections.Generic {
  38. [Serializable, HostProtection (SecurityAction.LinkDemand, MayLeakOnAbort = true)]
  39. public class HashSet<T> : ICollection<T>, ISerializable, IDeserializationCallback {
  40. const int INITIAL_SIZE = 10;
  41. const float DEFAULT_LOAD_FACTOR = (90f / 100);
  42. const int NO_SLOT = -1;
  43. struct Link {
  44. public int HashCode;
  45. public int Next;
  46. }
  47. // The hash table contains indices into the "links" array
  48. int [] table;
  49. Link [] links;
  50. T [] slots;
  51. // The number of slots in "links" and "slots" that
  52. // are in use (i.e. filled with data) or have been used and marked as
  53. // "empty" later on.
  54. int touched;
  55. // The index of the first slot in the "empty slots chain".
  56. // "Remove ()" prepends the cleared slots to the empty chain.
  57. // "Add ()" fills the first slot in the empty slots chain with the
  58. // added item (or increases "touched" if the chain itself is empty).
  59. int empty_slot;
  60. // The number of items in this set.
  61. int count;
  62. // The number of items the set can hold without
  63. // resizing the hash table and the slots arrays.
  64. int threshold;
  65. IEqualityComparer<T> comparer;
  66. SerializationInfo si;
  67. // The number of changes made to this set. Used by enumerators
  68. // to detect changes and invalidate themselves.
  69. int generation;
  70. public int Count {
  71. get { return count; }
  72. }
  73. public HashSet ()
  74. {
  75. Init (INITIAL_SIZE, null);
  76. }
  77. public HashSet (IEqualityComparer<T> comparer)
  78. {
  79. Init (INITIAL_SIZE, comparer);
  80. }
  81. public HashSet (IEnumerable<T> collection) : this (collection, null)
  82. {
  83. }
  84. public HashSet (IEnumerable<T> collection, IEqualityComparer<T> comparer)
  85. {
  86. if (collection == null)
  87. throw new ArgumentNullException ("collection");
  88. int capacity = collection.Count ();
  89. Init (capacity, comparer);
  90. foreach (var item in collection)
  91. Add (item);
  92. }
  93. protected HashSet (SerializationInfo info, StreamingContext context)
  94. {
  95. si = info;
  96. }
  97. void Init (int capacity, IEqualityComparer<T> comparer)
  98. {
  99. if (capacity < 0)
  100. throw new ArgumentOutOfRangeException ("capacity");
  101. this.comparer = comparer ?? EqualityComparer<T>.Default;
  102. if (capacity == 0)
  103. capacity = INITIAL_SIZE;
  104. /* Modify capacity so 'capacity' elements can be added without resizing */
  105. capacity = (int) (capacity / DEFAULT_LOAD_FACTOR) + 1;
  106. InitArrays (capacity);
  107. generation = 0;
  108. }
  109. void InitArrays (int size) {
  110. table = new int [size];
  111. links = new Link [size];
  112. empty_slot = NO_SLOT;
  113. slots = new T [size];
  114. touched = 0;
  115. threshold = (int) (table.Length * DEFAULT_LOAD_FACTOR);
  116. if (threshold == 0 && table.Length > 0)
  117. threshold = 1;
  118. }
  119. bool SlotsContainsAt (int index, int hash, T item)
  120. {
  121. int current = table [index] - 1;
  122. while (current != NO_SLOT) {
  123. Link link = links [current];
  124. if (link.HashCode == hash && comparer.Equals (item, slots [current]))
  125. return true;
  126. current = link.Next;
  127. }
  128. return false;
  129. }
  130. public void CopyTo (T [] array)
  131. {
  132. CopyTo (array, 0, count);
  133. }
  134. public void CopyTo (T [] array, int index)
  135. {
  136. CopyTo (array, index, count);
  137. }
  138. public void CopyTo (T [] array, int index, int count)
  139. {
  140. if (array == null)
  141. throw new ArgumentNullException ("array");
  142. if (index < 0)
  143. throw new ArgumentOutOfRangeException ("index");
  144. if (index > array.Length)
  145. throw new ArgumentException ("index larger than largest valid index of array");
  146. if (array.Length - index < count)
  147. throw new ArgumentException ("Destination array cannot hold the requested elements!");
  148. for (int i = 0; i < table.Length && index < count; i++) {
  149. int current = table [i] - 1;
  150. while (current != NO_SLOT) {
  151. array [index++] = slots [current];
  152. current = links [current].Next;
  153. }
  154. }
  155. }
  156. void Resize ()
  157. {
  158. int newSize = PrimeHelper.ToPrime ((table.Length << 1) | 1);
  159. // allocate new hash table and link slots array
  160. var newTable = new int [newSize];
  161. var newLinks = new Link [newSize];
  162. for (int i = 0; i < table.Length; i++) {
  163. int current = table [i] - 1;
  164. while (current != NO_SLOT) {
  165. int hashCode = newLinks [current].HashCode = comparer.GetHashCode (slots [current]);
  166. int index = (hashCode & int.MaxValue) % newSize;
  167. newLinks [current].Next = newTable [index] - 1;
  168. newTable [index] = current + 1;
  169. current = links [current].Next;
  170. }
  171. }
  172. table = newTable;
  173. links = newLinks;
  174. // allocate new data slots, copy data
  175. var newSlots = new T [newSize];
  176. Array.Copy (slots, 0, newSlots, 0, touched);
  177. slots = newSlots;
  178. threshold = (int) (newSize * DEFAULT_LOAD_FACTOR);
  179. }
  180. public bool Add (T item)
  181. {
  182. int hashCode = comparer.GetHashCode (item);
  183. int index = (hashCode & int.MaxValue) % table.Length;
  184. if (SlotsContainsAt (index, hashCode, item))
  185. return false;
  186. if (++count > threshold) {
  187. Resize ();
  188. index = (hashCode & int.MaxValue) % table.Length;
  189. }
  190. // find an empty slot
  191. int current = empty_slot;
  192. if (current == NO_SLOT)
  193. current = touched++;
  194. else
  195. empty_slot = links [current].Next;
  196. // store the hash code of the added item,
  197. // prepend the added item to its linked list,
  198. // update the hash table
  199. links [current].HashCode = hashCode;
  200. links [current].Next = table [index] - 1;
  201. table [index] = current + 1;
  202. // store item
  203. slots [current] = item;
  204. generation++;
  205. return true;
  206. }
  207. public IEqualityComparer<T> Comparer {
  208. get { return comparer; }
  209. }
  210. public void Clear ()
  211. {
  212. count = 0;
  213. // clear the hash table
  214. Array.Clear (table, 0, table.Length);
  215. // empty the "empty slots chain"
  216. empty_slot = NO_SLOT;
  217. touched = 0;
  218. generation++;
  219. }
  220. public bool Contains (T item)
  221. {
  222. int hashCode = comparer.GetHashCode (item);
  223. int index = (hashCode & int.MaxValue) % table.Length;
  224. return SlotsContainsAt (index, hashCode, item);
  225. }
  226. public bool Remove (T item)
  227. {
  228. // get first item of linked list corresponding to given key
  229. int hashCode = comparer.GetHashCode (item);
  230. int index = (hashCode & int.MaxValue) % table.Length;
  231. int current = table [index] - 1;
  232. // if there is no linked list, return false
  233. if (current == NO_SLOT)
  234. return false;
  235. // walk linked list until right slot (and its predecessor) is
  236. // found or end is reached
  237. int prev = NO_SLOT;
  238. do {
  239. Link link = links [current];
  240. if (link.HashCode == hashCode && comparer.Equals (slots [current], item))
  241. break;
  242. prev = current;
  243. current = link.Next;
  244. } while (current != NO_SLOT);
  245. // if we reached the end of the chain, return false
  246. if (current == NO_SLOT)
  247. return false;
  248. count--;
  249. // remove slot from linked list
  250. // is slot at beginning of linked list?
  251. if (prev == NO_SLOT)
  252. table [index] = links [current].Next + 1;
  253. else
  254. links [prev].Next = links [current].Next;
  255. // mark slot as empty and prepend it to "empty slots chain"
  256. links [current].Next = empty_slot;
  257. empty_slot = current;
  258. generation++;
  259. return true;
  260. }
  261. public int RemoveWhere (Predicate<T> predicate)
  262. {
  263. if (predicate == null)
  264. throw new ArgumentNullException ("predicate");
  265. int counter = 0;
  266. var copy = new T [count];
  267. CopyTo (copy, 0);
  268. foreach (var item in copy) {
  269. if (predicate (item)) {
  270. Remove (item);
  271. counter++;
  272. }
  273. }
  274. return counter;
  275. }
  276. public void TrimExcess ()
  277. {
  278. Resize ();
  279. }
  280. // set operations
  281. public void IntersectWith (IEnumerable<T> other)
  282. {
  283. if (other == null)
  284. throw new ArgumentNullException ("other");
  285. var copy = new T [count];
  286. CopyTo (copy, 0);
  287. foreach (var item in copy)
  288. if (!other.Contains (item))
  289. Remove (item);
  290. foreach (var item in other)
  291. if (!Contains (item))
  292. Remove (item);
  293. }
  294. public void ExceptWith (IEnumerable<T> other)
  295. {
  296. if (other == null)
  297. throw new ArgumentNullException ("other");
  298. foreach (var item in other)
  299. Remove (item);
  300. }
  301. public bool Overlaps (IEnumerable<T> other)
  302. {
  303. if (other == null)
  304. throw new ArgumentNullException ("other");
  305. foreach (var item in other)
  306. if (Contains (item))
  307. return true;
  308. return false;
  309. }
  310. public bool SetEquals (IEnumerable<T> other)
  311. {
  312. if (other == null)
  313. throw new ArgumentNullException ("other");
  314. if (count != other.Count ())
  315. return false;
  316. foreach (var item in this)
  317. if (!other.Contains (item))
  318. return false;
  319. return true;
  320. }
  321. public void SymmetricExceptWith (IEnumerable<T> other)
  322. {
  323. if (other == null)
  324. throw new ArgumentNullException ("other");
  325. foreach (var item in other) {
  326. if (Contains (item))
  327. Remove (item);
  328. else
  329. Add (item);
  330. }
  331. }
  332. public void UnionWith (IEnumerable<T> other)
  333. {
  334. if (other == null)
  335. throw new ArgumentNullException ("other");
  336. foreach (var item in other)
  337. Add (item);
  338. }
  339. bool CheckIsSubsetOf (IEnumerable<T> other)
  340. {
  341. if (other == null)
  342. throw new ArgumentNullException ("other");
  343. foreach (var item in this)
  344. if (!other.Contains (item))
  345. return false;
  346. return true;
  347. }
  348. public bool IsSubsetOf (IEnumerable<T> other)
  349. {
  350. if (other == null)
  351. throw new ArgumentNullException ("other");
  352. if (count == 0)
  353. return true;
  354. if (count > other.Count ())
  355. return false;
  356. return CheckIsSubsetOf (other);
  357. }
  358. public bool IsProperSubsetOf (IEnumerable<T> other)
  359. {
  360. if (other == null)
  361. throw new ArgumentNullException ("other");
  362. if (count == 0)
  363. return true;
  364. if (count >= other.Count ())
  365. return false;
  366. return CheckIsSubsetOf (other);
  367. }
  368. bool CheckIsSupersetOf (IEnumerable<T> other)
  369. {
  370. if (other == null)
  371. throw new ArgumentNullException ("other");
  372. foreach (var item in other)
  373. if (!Contains (item))
  374. return false;
  375. return true;
  376. }
  377. public bool IsSupersetOf (IEnumerable<T> other)
  378. {
  379. if (other == null)
  380. throw new ArgumentNullException ("other");
  381. if (count < other.Count ())
  382. return false;
  383. return CheckIsSupersetOf (other);
  384. }
  385. public bool IsProperSupersetOf (IEnumerable<T> other)
  386. {
  387. if (other == null)
  388. throw new ArgumentNullException ("other");
  389. if (count <= other.Count ())
  390. return false;
  391. return CheckIsSupersetOf (other);
  392. }
  393. [MonoTODO]
  394. public static IEqualityComparer<HashSet<T>> CreateSetComparer ()
  395. {
  396. throw new NotImplementedException ();
  397. }
  398. [MonoTODO]
  399. [SecurityPermission (SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
  400. public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
  401. {
  402. throw new NotImplementedException ();
  403. }
  404. [MonoTODO]
  405. public virtual void OnDeserialization (object sender)
  406. {
  407. if (si == null)
  408. return;
  409. throw new NotImplementedException ();
  410. }
  411. IEnumerator<T> IEnumerable<T>.GetEnumerator ()
  412. {
  413. return new Enumerator (this);
  414. }
  415. bool ICollection<T>.IsReadOnly {
  416. get { return false; }
  417. }
  418. void ICollection<T>.CopyTo (T [] array, int index)
  419. {
  420. CopyTo (array, index);
  421. }
  422. void ICollection<T>.Add (T item)
  423. {
  424. if (!Add (item))
  425. throw new ArgumentException ();
  426. }
  427. IEnumerator IEnumerable.GetEnumerator ()
  428. {
  429. return new Enumerator (this);
  430. }
  431. public Enumerator GetEnumerator ()
  432. {
  433. return new Enumerator (this);
  434. }
  435. [Serializable]
  436. public struct Enumerator : IEnumerator<T>, IDisposable {
  437. HashSet<T> hashset;
  438. int index, current;
  439. int stamp;
  440. internal Enumerator (HashSet<T> hashset)
  441. {
  442. this.hashset = hashset;
  443. this.stamp = hashset.generation;
  444. index = -1;
  445. current = NO_SLOT;
  446. }
  447. public bool MoveNext ()
  448. {
  449. CheckState ();
  450. do {
  451. if (current != NO_SLOT) {
  452. current = hashset.links [current].Next;
  453. continue;
  454. }
  455. if (index + 1 >= hashset.table.Length)
  456. return false;
  457. current = hashset.table [++index] - 1;;
  458. } while (current == NO_SLOT);
  459. return true;
  460. }
  461. public T Current {
  462. get {
  463. CheckCurrent ();
  464. return hashset.slots [current];
  465. }
  466. }
  467. object IEnumerator.Current {
  468. get { return this.Current; }
  469. }
  470. void IEnumerator.Reset ()
  471. {
  472. index = -1;
  473. current = NO_SLOT;
  474. }
  475. public void Dispose ()
  476. {
  477. hashset = null;
  478. }
  479. void CheckState ()
  480. {
  481. if (hashset == null)
  482. throw new ObjectDisposedException (null);
  483. if (hashset.generation != stamp)
  484. throw new InvalidOperationException ("HashSet have been modified while it was iterated over");
  485. }
  486. void CheckCurrent ()
  487. {
  488. CheckState ();
  489. if (current == NO_SLOT)
  490. throw new InvalidOperationException ("Current is not valid");
  491. }
  492. }
  493. // borrowed from System.Collections.HashTable
  494. static class PrimeHelper {
  495. static readonly int [] primes_table = {
  496. 11,
  497. 19,
  498. 37,
  499. 73,
  500. 109,
  501. 163,
  502. 251,
  503. 367,
  504. 557,
  505. 823,
  506. 1237,
  507. 1861,
  508. 2777,
  509. 4177,
  510. 6247,
  511. 9371,
  512. 14057,
  513. 21089,
  514. 31627,
  515. 47431,
  516. 71143,
  517. 106721,
  518. 160073,
  519. 240101,
  520. 360163,
  521. 540217,
  522. 810343,
  523. 1215497,
  524. 1823231,
  525. 2734867,
  526. 4102283,
  527. 6153409,
  528. 9230113,
  529. 13845163
  530. };
  531. static bool TestPrime (int x)
  532. {
  533. if ((x & 1) != 0) {
  534. int top = (int) Math.Sqrt (x);
  535. for (int n = 3; n < top; n += 2) {
  536. if ((x % n) == 0)
  537. return false;
  538. }
  539. return true;
  540. }
  541. // There is only one even prime - 2.
  542. return x == 2;
  543. }
  544. static int CalcPrime (int x)
  545. {
  546. for (int i = (x & (~1)) - 1; i < Int32.MaxValue; i += 2)
  547. if (TestPrime (i))
  548. return i;
  549. return x;
  550. }
  551. public static int ToPrime (int x)
  552. {
  553. for (int i = 0; i < primes_table.Length; i++)
  554. if (x <= primes_table [i])
  555. return primes_table [i];
  556. return CalcPrime (x);
  557. }
  558. }
  559. }
  560. }