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. const int HASH_FLAG = -2147483648;
  44. struct Link {
  45. public int HashCode;
  46. public int Next;
  47. }
  48. // The hash table contains indices into the "links" array
  49. int [] table;
  50. Link [] links;
  51. T [] slots;
  52. // The number of slots in "links" and "slots" that
  53. // are in use (i.e. filled with data) or have been used and marked as
  54. // "empty" later on.
  55. int touched;
  56. // The index of the first slot in the "empty slots chain".
  57. // "Remove ()" prepends the cleared slots to the empty chain.
  58. // "Add ()" fills the first slot in the empty slots chain with the
  59. // added item (or increases "touched" if the chain itself is empty).
  60. int empty_slot;
  61. // The number of items in this set.
  62. int count;
  63. // The number of items the set can hold without
  64. // resizing the hash table and the slots arrays.
  65. int threshold;
  66. IEqualityComparer<T> comparer;
  67. SerializationInfo si;
  68. // The number of changes made to this set. Used by enumerators
  69. // to detect changes and invalidate themselves.
  70. int generation;
  71. public int Count {
  72. get { return count; }
  73. }
  74. public HashSet ()
  75. {
  76. Init (INITIAL_SIZE, null);
  77. }
  78. public HashSet (IEqualityComparer<T> comparer)
  79. {
  80. Init (INITIAL_SIZE, comparer);
  81. }
  82. public HashSet (IEnumerable<T> collection) : this (collection, null)
  83. {
  84. }
  85. public HashSet (IEnumerable<T> collection, IEqualityComparer<T> comparer)
  86. {
  87. if (collection == null)
  88. throw new ArgumentNullException ("collection");
  89. int capacity = 0;
  90. var col = collection as ICollection<T>;
  91. if (col != null)
  92. capacity = col.Count;
  93. Init (capacity, comparer);
  94. foreach (var item in collection)
  95. Add (item);
  96. }
  97. protected HashSet (SerializationInfo info, StreamingContext context)
  98. {
  99. si = info;
  100. }
  101. void Init (int capacity, IEqualityComparer<T> comparer)
  102. {
  103. if (capacity < 0)
  104. throw new ArgumentOutOfRangeException ("capacity");
  105. this.comparer = comparer ?? EqualityComparer<T>.Default;
  106. if (capacity == 0)
  107. capacity = INITIAL_SIZE;
  108. /* Modify capacity so 'capacity' elements can be added without resizing */
  109. capacity = (int) (capacity / DEFAULT_LOAD_FACTOR) + 1;
  110. InitArrays (capacity);
  111. generation = 0;
  112. }
  113. void InitArrays (int size)
  114. {
  115. table = new int [size];
  116. links = new Link [size];
  117. empty_slot = NO_SLOT;
  118. slots = new T [size];
  119. touched = 0;
  120. threshold = (int) (table.Length * DEFAULT_LOAD_FACTOR);
  121. if (threshold == 0 && table.Length > 0)
  122. threshold = 1;
  123. }
  124. bool SlotsContainsAt (int index, int hash, T item)
  125. {
  126. int current = table [index] - 1;
  127. while (current != NO_SLOT) {
  128. Link link = links [current];
  129. if (link.HashCode == hash && comparer.Equals (item, slots [current]))
  130. return true;
  131. current = link.Next;
  132. }
  133. return false;
  134. }
  135. public void CopyTo (T [] array)
  136. {
  137. CopyTo (array, 0, count);
  138. }
  139. public void CopyTo (T [] array, int index)
  140. {
  141. CopyTo (array, index, count);
  142. }
  143. public void CopyTo (T [] array, int index, int count)
  144. {
  145. if (array == null)
  146. throw new ArgumentNullException ("array");
  147. if (index < 0)
  148. throw new ArgumentOutOfRangeException ("index");
  149. if (index > array.Length)
  150. throw new ArgumentException ("index larger than largest valid index of array");
  151. if (array.Length - index < count)
  152. throw new ArgumentException ("Destination array cannot hold the requested elements!");
  153. for (int i = 0, items = 0; i < touched && items < count; i++) {
  154. if (GetLinkHashCode (i) != 0)
  155. array [index++] = slots [i];
  156. }
  157. }
  158. void Resize ()
  159. {
  160. int newSize = PrimeHelper.ToPrime ((table.Length << 1) | 1);
  161. // allocate new hash table and link slots array
  162. var newTable = new int [newSize];
  163. var newLinks = new Link [newSize];
  164. for (int i = 0; i < table.Length; i++) {
  165. int current = table [i] - 1;
  166. while (current != NO_SLOT) {
  167. int hashCode = newLinks [current].HashCode = GetItemHashCode (slots [current]);
  168. int index = (hashCode & int.MaxValue) % newSize;
  169. newLinks [current].Next = newTable [index] - 1;
  170. newTable [index] = current + 1;
  171. current = links [current].Next;
  172. }
  173. }
  174. table = newTable;
  175. links = newLinks;
  176. // allocate new data slots, copy data
  177. var newSlots = new T [newSize];
  178. Array.Copy (slots, 0, newSlots, 0, touched);
  179. slots = newSlots;
  180. threshold = (int) (newSize * DEFAULT_LOAD_FACTOR);
  181. }
  182. int GetLinkHashCode (int index)
  183. {
  184. return links [index].HashCode & HASH_FLAG;
  185. }
  186. int GetItemHashCode (T item)
  187. {
  188. return comparer.GetHashCode (item) | HASH_FLAG;
  189. }
  190. public bool Add (T item)
  191. {
  192. int hashCode = GetItemHashCode (item);
  193. int index = (hashCode & int.MaxValue) % table.Length;
  194. if (SlotsContainsAt (index, hashCode, item))
  195. return false;
  196. if (++count > threshold) {
  197. Resize ();
  198. index = (hashCode & int.MaxValue) % table.Length;
  199. }
  200. // find an empty slot
  201. int current = empty_slot;
  202. if (current == NO_SLOT)
  203. current = touched++;
  204. else
  205. empty_slot = links [current].Next;
  206. // store the hash code of the added item,
  207. // prepend the added item to its linked list,
  208. // update the hash table
  209. links [current].HashCode = hashCode;
  210. links [current].Next = table [index] - 1;
  211. table [index] = current + 1;
  212. // store item
  213. slots [current] = item;
  214. generation++;
  215. return true;
  216. }
  217. public IEqualityComparer<T> Comparer {
  218. get { return comparer; }
  219. }
  220. public void Clear ()
  221. {
  222. count = 0;
  223. Array.Clear (table, 0, table.Length);
  224. Array.Clear (slots, 0, slots.Length);
  225. Array.Clear (links, 0, links.Length);
  226. // empty the "empty slots chain"
  227. empty_slot = NO_SLOT;
  228. touched = 0;
  229. generation++;
  230. }
  231. public bool Contains (T item)
  232. {
  233. int hashCode = GetItemHashCode (item);
  234. int index = (hashCode & int.MaxValue) % table.Length;
  235. return SlotsContainsAt (index, hashCode, item);
  236. }
  237. public bool Remove (T item)
  238. {
  239. // get first item of linked list corresponding to given key
  240. int hashCode = GetItemHashCode (item);
  241. int index = (hashCode & int.MaxValue) % table.Length;
  242. int current = table [index] - 1;
  243. // if there is no linked list, return false
  244. if (current == NO_SLOT)
  245. return false;
  246. // walk linked list until right slot (and its predecessor) is
  247. // found or end is reached
  248. int prev = NO_SLOT;
  249. do {
  250. Link link = links [current];
  251. if (link.HashCode == hashCode && comparer.Equals (slots [current], item))
  252. break;
  253. prev = current;
  254. current = link.Next;
  255. } while (current != NO_SLOT);
  256. // if we reached the end of the chain, return false
  257. if (current == NO_SLOT)
  258. return false;
  259. count--;
  260. // remove slot from linked list
  261. // is slot at beginning of linked list?
  262. if (prev == NO_SLOT)
  263. table [index] = links [current].Next + 1;
  264. else
  265. links [prev].Next = links [current].Next;
  266. // mark slot as empty and prepend it to "empty slots chain"
  267. links [current].Next = empty_slot;
  268. empty_slot = current;
  269. // clear slot
  270. links [current].HashCode = 0;
  271. slots [current] = default (T);
  272. generation++;
  273. return true;
  274. }
  275. public int RemoveWhere (Predicate<T> predicate)
  276. {
  277. if (predicate == null)
  278. throw new ArgumentNullException ("predicate");
  279. int counter = 0;
  280. var copy = new T [count];
  281. CopyTo (copy, 0);
  282. foreach (var item in copy) {
  283. if (predicate (item)) {
  284. Remove (item);
  285. counter++;
  286. }
  287. }
  288. return counter;
  289. }
  290. public void TrimExcess ()
  291. {
  292. Resize ();
  293. }
  294. // set operations
  295. public void IntersectWith (IEnumerable<T> other)
  296. {
  297. if (other == null)
  298. throw new ArgumentNullException ("other");
  299. var copy = new T [count];
  300. CopyTo (copy, 0);
  301. foreach (var item in copy)
  302. if (!other.Contains (item))
  303. Remove (item);
  304. foreach (var item in other)
  305. if (!Contains (item))
  306. Remove (item);
  307. }
  308. public void ExceptWith (IEnumerable<T> other)
  309. {
  310. if (other == null)
  311. throw new ArgumentNullException ("other");
  312. foreach (var item in other)
  313. Remove (item);
  314. }
  315. public bool Overlaps (IEnumerable<T> other)
  316. {
  317. if (other == null)
  318. throw new ArgumentNullException ("other");
  319. foreach (var item in other)
  320. if (Contains (item))
  321. return true;
  322. return false;
  323. }
  324. public bool SetEquals (IEnumerable<T> other)
  325. {
  326. if (other == null)
  327. throw new ArgumentNullException ("other");
  328. if (count != other.Count ())
  329. return false;
  330. foreach (var item in this)
  331. if (!other.Contains (item))
  332. return false;
  333. return true;
  334. }
  335. public void SymmetricExceptWith (IEnumerable<T> other)
  336. {
  337. if (other == null)
  338. throw new ArgumentNullException ("other");
  339. foreach (var item in other) {
  340. if (Contains (item))
  341. Remove (item);
  342. else
  343. Add (item);
  344. }
  345. }
  346. public void UnionWith (IEnumerable<T> other)
  347. {
  348. if (other == null)
  349. throw new ArgumentNullException ("other");
  350. foreach (var item in other)
  351. Add (item);
  352. }
  353. bool CheckIsSubsetOf (IEnumerable<T> other)
  354. {
  355. if (other == null)
  356. throw new ArgumentNullException ("other");
  357. foreach (var item in this)
  358. if (!other.Contains (item))
  359. return false;
  360. return true;
  361. }
  362. public bool IsSubsetOf (IEnumerable<T> other)
  363. {
  364. if (other == null)
  365. throw new ArgumentNullException ("other");
  366. if (count == 0)
  367. return true;
  368. if (count > other.Count ())
  369. return false;
  370. return CheckIsSubsetOf (other);
  371. }
  372. public bool IsProperSubsetOf (IEnumerable<T> other)
  373. {
  374. if (other == null)
  375. throw new ArgumentNullException ("other");
  376. if (count == 0)
  377. return true;
  378. if (count >= other.Count ())
  379. return false;
  380. return CheckIsSubsetOf (other);
  381. }
  382. bool CheckIsSupersetOf (IEnumerable<T> other)
  383. {
  384. if (other == null)
  385. throw new ArgumentNullException ("other");
  386. foreach (var item in other)
  387. if (!Contains (item))
  388. return false;
  389. return true;
  390. }
  391. public bool IsSupersetOf (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. public bool IsProperSupersetOf (IEnumerable<T> other)
  400. {
  401. if (other == null)
  402. throw new ArgumentNullException ("other");
  403. if (count <= other.Count ())
  404. return false;
  405. return CheckIsSupersetOf (other);
  406. }
  407. [MonoTODO]
  408. public static IEqualityComparer<HashSet<T>> CreateSetComparer ()
  409. {
  410. throw new NotImplementedException ();
  411. }
  412. [MonoTODO]
  413. [SecurityPermission (SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
  414. public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
  415. {
  416. throw new NotImplementedException ();
  417. }
  418. [MonoTODO]
  419. public virtual void OnDeserialization (object sender)
  420. {
  421. if (si == null)
  422. return;
  423. throw new NotImplementedException ();
  424. }
  425. IEnumerator<T> IEnumerable<T>.GetEnumerator ()
  426. {
  427. return new Enumerator (this);
  428. }
  429. bool ICollection<T>.IsReadOnly {
  430. get { return false; }
  431. }
  432. void ICollection<T>.CopyTo (T [] array, int index)
  433. {
  434. CopyTo (array, index);
  435. }
  436. void ICollection<T>.Add (T item)
  437. {
  438. if (!Add (item))
  439. throw new ArgumentException ();
  440. }
  441. IEnumerator IEnumerable.GetEnumerator ()
  442. {
  443. return new Enumerator (this);
  444. }
  445. public Enumerator GetEnumerator ()
  446. {
  447. return new Enumerator (this);
  448. }
  449. [Serializable]
  450. public struct Enumerator : IEnumerator<T>, IDisposable {
  451. HashSet<T> hashset;
  452. int current;
  453. int stamp;
  454. internal Enumerator (HashSet<T> hashset)
  455. {
  456. this.hashset = hashset;
  457. this.stamp = hashset.generation;
  458. current = NO_SLOT;
  459. }
  460. public bool MoveNext ()
  461. {
  462. CheckState ();
  463. while (current < hashset.touched)
  464. if (hashset.GetLinkHashCode (++current) != 0)
  465. return true;
  466. return false;
  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. 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 || current >= hashset.touched)
  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. }