HashSet.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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, int index)
  131. {
  132. if (array == null)
  133. throw new ArgumentNullException ("array");
  134. if (index < 0)
  135. throw new ArgumentOutOfRangeException ("index");
  136. if (index > array.Length)
  137. throw new ArgumentException ("index larger than largest valid index of array");
  138. if (array.Length - index < count)
  139. throw new ArgumentException ("Destination array cannot hold the requested elements!");
  140. for (int i = 0; i < table.Length; i++) {
  141. int current = table [i] - 1;
  142. while (current != NO_SLOT) {
  143. array [index++] = slots [current];
  144. current = links [current].Next;
  145. }
  146. }
  147. }
  148. void Resize ()
  149. {
  150. int newSize = PrimeHelper.ToPrime ((table.Length << 1) | 1);
  151. // allocate new hash table and link slots array
  152. var newTable = new int [newSize];
  153. var newLinks = new Link [newSize];
  154. for (int i = 0; i < table.Length; i++) {
  155. int current = table [i] - 1;
  156. while (current != NO_SLOT) {
  157. int hashCode = newLinks [current].HashCode = comparer.GetHashCode (slots [current]);
  158. int index = (hashCode & int.MaxValue) % newSize;
  159. newLinks [current].Next = newTable [index] - 1;
  160. newTable [index] = current + 1;
  161. current = links [current].Next;
  162. }
  163. }
  164. table = newTable;
  165. links = newLinks;
  166. // allocate new data slots, copy data
  167. var newSlots = new T [newSize];
  168. Array.Copy (slots, 0, newSlots, 0, touched);
  169. slots = newSlots;
  170. threshold = (int) (newSize * DEFAULT_LOAD_FACTOR);
  171. }
  172. public bool Add (T item)
  173. {
  174. int hashCode = comparer.GetHashCode (item);
  175. int index = (hashCode & int.MaxValue) % table.Length;
  176. if (SlotsContainsAt (index, hashCode, item))
  177. return false;
  178. if (++count > threshold) {
  179. Resize ();
  180. index = (hashCode & int.MaxValue) % table.Length;
  181. }
  182. // find an empty slot
  183. int current = empty_slot;
  184. if (current == NO_SLOT)
  185. current = touched++;
  186. else
  187. empty_slot = links [current].Next;
  188. // store the hash code of the added item,
  189. // prepend the added item to its linked list,
  190. // update the hash table
  191. links [current].HashCode = hashCode;
  192. links [current].Next = table [index] - 1;
  193. table [index] = current + 1;
  194. // store item
  195. slots [current] = item;
  196. generation++;
  197. return true;
  198. }
  199. public IEqualityComparer<T> Comparer {
  200. get { return comparer; }
  201. }
  202. public void Clear ()
  203. {
  204. count = 0;
  205. // clear the hash table
  206. Array.Clear (table, 0, table.Length);
  207. // empty the "empty slots chain"
  208. empty_slot = NO_SLOT;
  209. touched = 0;
  210. generation++;
  211. }
  212. public bool Contains (T item)
  213. {
  214. int hashCode = comparer.GetHashCode (item);
  215. int index = (hashCode & int.MaxValue) % table.Length;
  216. return SlotsContainsAt (index, hashCode, item);
  217. }
  218. public bool Remove (T item)
  219. {
  220. // get first item of linked list corresponding to given key
  221. int hashCode = comparer.GetHashCode (item);
  222. int index = (hashCode & int.MaxValue) % table.Length;
  223. int current = table [index] - 1;
  224. // if there is no linked list, return false
  225. if (current == NO_SLOT)
  226. return false;
  227. // walk linked list until right slot (and its predecessor) is
  228. // found or end is reached
  229. int prev = NO_SLOT;
  230. do {
  231. Link link = links [current];
  232. if (link.HashCode == hashCode && comparer.Equals (slots [current], item))
  233. break;
  234. prev = current;
  235. current = link.Next;
  236. } while (current != NO_SLOT);
  237. // if we reached the end of the chain, return false
  238. if (current == NO_SLOT)
  239. return false;
  240. count--;
  241. // remove slot from linked list
  242. // is slot at beginning of linked list?
  243. if (prev == NO_SLOT)
  244. table [index] = links [current].Next + 1;
  245. else
  246. links [prev].Next = links [current].Next;
  247. // mark slot as empty and prepend it to "empty slots chain"
  248. links [current].Next = empty_slot;
  249. empty_slot = current;
  250. generation++;
  251. return true;
  252. }
  253. public int RemoveWhere (Predicate<T> predicate)
  254. {
  255. int counter = 0;
  256. var copy = new T [count];
  257. CopyTo (copy, 0);
  258. foreach (var item in copy) {
  259. if (predicate (item)) {
  260. Remove (item);
  261. counter++;
  262. }
  263. }
  264. return counter;
  265. }
  266. public void TrimExcess ()
  267. {
  268. Resize ();
  269. }
  270. // set operations
  271. public void IntersectWith (IEnumerable<T> other)
  272. {
  273. if (other == null)
  274. throw new ArgumentNullException ("other");
  275. var copy = new T [count];
  276. CopyTo (copy, 0);
  277. foreach (var item in copy)
  278. if (!other.Contains (item))
  279. Remove (item);
  280. foreach (var item in other)
  281. if (!Contains (item))
  282. Remove (item);
  283. }
  284. public void ExceptWith (IEnumerable<T> other)
  285. {
  286. if (other == null)
  287. throw new ArgumentNullException ("other");
  288. foreach (var item in other)
  289. Remove (item);
  290. }
  291. public bool Overlaps (IEnumerable<T> other)
  292. {
  293. if (other == null)
  294. throw new ArgumentNullException ("other");
  295. foreach (var item in other)
  296. if (Contains (item))
  297. return true;
  298. return false;
  299. }
  300. public bool SetEquals (IEnumerable<T> other)
  301. {
  302. if (other == null)
  303. throw new ArgumentNullException ("other");
  304. if (count != other.Count ())
  305. return false;
  306. foreach (var item in this)
  307. if (!other.Contains (item))
  308. return false;
  309. return true;
  310. }
  311. public void SymmetricExceptWith (IEnumerable<T> other)
  312. {
  313. if (other == null)
  314. throw new ArgumentNullException ("other");
  315. foreach (var item in other) {
  316. if (Contains (item))
  317. Remove (item);
  318. else
  319. Add (item);
  320. }
  321. }
  322. public void UnionWith (IEnumerable<T> other)
  323. {
  324. if (other == null)
  325. throw new ArgumentNullException ("other");
  326. foreach (var item in other)
  327. Add (item);
  328. }
  329. bool CheckIsSubsetOf (IEnumerable<T> other)
  330. {
  331. if (other == null)
  332. throw new ArgumentNullException ("other");
  333. foreach (var item in this)
  334. if (!other.Contains (item))
  335. return false;
  336. return true;
  337. }
  338. public bool IsSubsetOf (IEnumerable<T> other)
  339. {
  340. if (other == null)
  341. throw new ArgumentNullException ("other");
  342. if (count == 0)
  343. return true;
  344. if (count > other.Count ())
  345. return false;
  346. return CheckIsSubsetOf (other);
  347. }
  348. public bool IsProperSubsetOf (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. bool CheckIsSupersetOf (IEnumerable<T> other)
  359. {
  360. if (other == null)
  361. throw new ArgumentNullException ("other");
  362. foreach (var item in other)
  363. if (!Contains (item))
  364. return false;
  365. return true;
  366. }
  367. public bool IsSupersetOf (IEnumerable<T> other)
  368. {
  369. if (other == null)
  370. throw new ArgumentNullException ("other");
  371. if (count < other.Count ())
  372. return false;
  373. return CheckIsSupersetOf (other);
  374. }
  375. public bool IsProperSupersetOf (IEnumerable<T> other)
  376. {
  377. if (other == null)
  378. throw new ArgumentNullException ("other");
  379. if (count <= other.Count ())
  380. return false;
  381. return CheckIsSupersetOf (other);
  382. }
  383. [MonoTODO]
  384. public static IEqualityComparer<HashSet<T>> CreateSetComparer ()
  385. {
  386. throw new NotImplementedException ();
  387. }
  388. [MonoTODO]
  389. [SecurityPermission (SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
  390. public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
  391. {
  392. throw new NotImplementedException ();
  393. }
  394. [MonoTODO]
  395. public virtual void OnDeserialization (object sender)
  396. {
  397. if (si == null)
  398. return;
  399. throw new NotImplementedException ();
  400. }
  401. public IEnumerator<T> GetEnumerator ()
  402. {
  403. return new Enumerator (this);
  404. }
  405. IEnumerator<T> IEnumerable<T>.GetEnumerator ()
  406. {
  407. return new Enumerator (this);
  408. }
  409. bool ICollection<T>.IsReadOnly {
  410. get { return false; }
  411. }
  412. void ICollection<T>.CopyTo (T [] array, int index)
  413. {
  414. CopyTo (array, index);
  415. }
  416. void ICollection<T>.Add (T item)
  417. {
  418. if (!Add (item))
  419. throw new ArgumentException ();
  420. }
  421. IEnumerator IEnumerable.GetEnumerator ()
  422. {
  423. return new Enumerator (this);
  424. }
  425. struct Enumerator : IEnumerator<T>, IDisposable {
  426. HashSet<T> hashset;
  427. int index, current;
  428. int stamp;
  429. public Enumerator (HashSet<T> hashset)
  430. {
  431. this.hashset = hashset;
  432. this.stamp = hashset.generation;
  433. index = -1;
  434. current = NO_SLOT;
  435. }
  436. public bool MoveNext ()
  437. {
  438. CheckState ();
  439. do {
  440. if (current != NO_SLOT) {
  441. current = hashset.links [current].Next;
  442. continue;
  443. }
  444. if (index + 1 >= hashset.table.Length)
  445. return false;
  446. current = hashset.table [++index] - 1;;
  447. } while (current == NO_SLOT);
  448. return true;
  449. }
  450. public T Current {
  451. get {
  452. CheckCurrent ();
  453. return hashset.slots [current];
  454. }
  455. }
  456. object IEnumerator.Current {
  457. get { return this.Current; }
  458. }
  459. void IEnumerator.Reset ()
  460. {
  461. index = -1;
  462. current = NO_SLOT;
  463. }
  464. void IDisposable.Dispose ()
  465. {
  466. hashset = null;
  467. }
  468. void CheckState ()
  469. {
  470. if (hashset == null)
  471. throw new ObjectDisposedException (null);
  472. if (hashset.generation != stamp)
  473. throw new InvalidOperationException ("HashSet have been modified while it was iterated over");
  474. }
  475. void CheckCurrent ()
  476. {
  477. CheckState ();
  478. if (current == NO_SLOT)
  479. throw new InvalidOperationException ("Current is not valid");
  480. }
  481. }
  482. // borrowed from System.Collections.HashTable
  483. static class PrimeHelper {
  484. static readonly int [] primes_table = {
  485. 11,
  486. 19,
  487. 37,
  488. 73,
  489. 109,
  490. 163,
  491. 251,
  492. 367,
  493. 557,
  494. 823,
  495. 1237,
  496. 1861,
  497. 2777,
  498. 4177,
  499. 6247,
  500. 9371,
  501. 14057,
  502. 21089,
  503. 31627,
  504. 47431,
  505. 71143,
  506. 106721,
  507. 160073,
  508. 240101,
  509. 360163,
  510. 540217,
  511. 810343,
  512. 1215497,
  513. 1823231,
  514. 2734867,
  515. 4102283,
  516. 6153409,
  517. 9230113,
  518. 13845163
  519. };
  520. static bool TestPrime (int x)
  521. {
  522. if ((x & 1) != 0) {
  523. int top = (int) Math.Sqrt (x);
  524. for (int n = 3; n < top; n += 2) {
  525. if ((x % n) == 0)
  526. return false;
  527. }
  528. return true;
  529. }
  530. // There is only one even prime - 2.
  531. return x == 2;
  532. }
  533. static int CalcPrime (int x)
  534. {
  535. for (int i = (x & (~1)) - 1; i < Int32.MaxValue; i += 2)
  536. if (TestPrime (i))
  537. return i;
  538. return x;
  539. }
  540. public static int ToPrime (int x)
  541. {
  542. for (int i = 0; i < primes_table.Length; i++)
  543. if (x <= primes_table [i])
  544. return primes_table [i];
  545. return CalcPrime (x);
  546. }
  547. }
  548. }
  549. }