HashSet.cs 15 KB

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