HashSet.cs 15 KB

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