HashSet.cs 15 KB

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