HashSet.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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. var copy = new T [count];
  274. CopyTo (copy, 0);
  275. foreach (var item in copy)
  276. if (!other.Contains (item))
  277. Remove (item);
  278. foreach (var item in other)
  279. if (!Contains (item))
  280. Remove (item);
  281. }
  282. public void ExceptWith (IEnumerable<T> other)
  283. {
  284. foreach (var item in other)
  285. Remove (item);
  286. }
  287. public bool Overlaps (IEnumerable<T> other)
  288. {
  289. foreach (var item in other)
  290. if (Contains (item))
  291. return true;
  292. return false;
  293. }
  294. public bool SetEquals (IEnumerable<T> other)
  295. {
  296. if (count != other.Count ())
  297. return false;
  298. foreach (var item in this)
  299. if (!other.Contains (item))
  300. return false;
  301. return true;
  302. }
  303. public void SymmetricExceptWith (IEnumerable<T> other)
  304. {
  305. foreach (var item in other) {
  306. if (Contains (item))
  307. Remove (item);
  308. else
  309. Add (item);
  310. }
  311. }
  312. public void UnionWith (IEnumerable<T> other)
  313. {
  314. foreach (var item in other)
  315. Add (item);
  316. }
  317. bool CheckIsSubsetOf (IEnumerable<T> other)
  318. {
  319. foreach (var item in this)
  320. if (!other.Contains (item))
  321. return false;
  322. return true;
  323. }
  324. public bool IsSubsetOf (IEnumerable<T> other)
  325. {
  326. if (count == 0)
  327. return true;
  328. if (count > other.Count ())
  329. return false;
  330. return CheckIsSubsetOf (other);
  331. }
  332. public bool IsProperSubsetOf (IEnumerable<T> other)
  333. {
  334. if (count == 0)
  335. return true;
  336. if (count >= other.Count ())
  337. return false;
  338. return CheckIsSubsetOf (other);
  339. }
  340. bool CheckIsSupersetOf (IEnumerable<T> other)
  341. {
  342. foreach (var item in other)
  343. if (!Contains (item))
  344. return false;
  345. return true;
  346. }
  347. public bool IsSupersetOf (IEnumerable<T> other)
  348. {
  349. if (count < other.Count ())
  350. return false;
  351. return CheckIsSupersetOf (other);
  352. }
  353. public bool IsProperSupersetOf (IEnumerable<T> other)
  354. {
  355. if (count <= other.Count ())
  356. return false;
  357. return CheckIsSupersetOf (other);
  358. }
  359. [MonoTODO]
  360. public static IEqualityComparer<HashSet<T>> CreateSetComparer ()
  361. {
  362. throw new NotImplementedException ();
  363. }
  364. [MonoTODO]
  365. [SecurityPermission (SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
  366. public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
  367. {
  368. throw new NotImplementedException ();
  369. }
  370. [MonoTODO]
  371. public virtual void OnDeserialization (object sender)
  372. {
  373. if (si == null)
  374. return;
  375. throw new NotImplementedException ();
  376. }
  377. public IEnumerator<T> GetEnumerator ()
  378. {
  379. return new Enumerator (this);
  380. }
  381. IEnumerator<T> IEnumerable<T>.GetEnumerator ()
  382. {
  383. return new Enumerator (this);
  384. }
  385. bool ICollection<T>.IsReadOnly {
  386. get { return false; }
  387. }
  388. void ICollection<T>.CopyTo (T [] array, int index)
  389. {
  390. CopyTo (array, index);
  391. }
  392. void ICollection<T>.Add (T item)
  393. {
  394. if (!Add (item))
  395. throw new ArgumentException ();
  396. }
  397. IEnumerator IEnumerable.GetEnumerator ()
  398. {
  399. return new Enumerator (this);
  400. }
  401. struct Enumerator : IEnumerator<T>, IDisposable {
  402. HashSet<T> hashset;
  403. int index, current;
  404. int stamp;
  405. public Enumerator (HashSet<T> hashset)
  406. {
  407. this.hashset = hashset;
  408. this.stamp = hashset.generation;
  409. index = -1;
  410. current = NO_SLOT;
  411. }
  412. public bool MoveNext ()
  413. {
  414. CheckState ();
  415. do {
  416. if (current != NO_SLOT) {
  417. current = hashset.links [current].Next;
  418. continue;
  419. }
  420. if (index + 1 >= hashset.table.Length)
  421. return false;
  422. current = hashset.table [++index] - 1;;
  423. } while (current == NO_SLOT);
  424. return true;
  425. }
  426. public T Current {
  427. get {
  428. CheckCurrent ();
  429. return hashset.slots [current];
  430. }
  431. }
  432. object IEnumerator.Current {
  433. get { return this.Current; }
  434. }
  435. void IEnumerator.Reset ()
  436. {
  437. index = -1;
  438. current = NO_SLOT;
  439. }
  440. void IDisposable.Dispose ()
  441. {
  442. hashset = null;
  443. }
  444. void CheckState ()
  445. {
  446. if (hashset == null)
  447. throw new ObjectDisposedException (null);
  448. if (hashset.generation != stamp)
  449. throw new InvalidOperationException ("HashSet have been modified while it was iterated over");
  450. }
  451. void CheckCurrent ()
  452. {
  453. CheckState ();
  454. if (current == NO_SLOT)
  455. throw new InvalidOperationException ("Current is not valid");
  456. }
  457. }
  458. // borrowed from System.Collections.HashTable
  459. static class PrimeHelper {
  460. static readonly int [] primes_table = {
  461. 11,
  462. 19,
  463. 37,
  464. 73,
  465. 109,
  466. 163,
  467. 251,
  468. 367,
  469. 557,
  470. 823,
  471. 1237,
  472. 1861,
  473. 2777,
  474. 4177,
  475. 6247,
  476. 9371,
  477. 14057,
  478. 21089,
  479. 31627,
  480. 47431,
  481. 71143,
  482. 106721,
  483. 160073,
  484. 240101,
  485. 360163,
  486. 540217,
  487. 810343,
  488. 1215497,
  489. 1823231,
  490. 2734867,
  491. 4102283,
  492. 6153409,
  493. 9230113,
  494. 13845163
  495. };
  496. static bool TestPrime (int x)
  497. {
  498. if ((x & 1) != 0) {
  499. int top = (int) Math.Sqrt (x);
  500. for (int n = 3; n < top; n += 2) {
  501. if ((x % n) == 0)
  502. return false;
  503. }
  504. return true;
  505. }
  506. // There is only one even prime - 2.
  507. return x == 2;
  508. }
  509. static int CalcPrime (int x)
  510. {
  511. for (int i = (x & (~1)) - 1; i < Int32.MaxValue; i += 2)
  512. if (TestPrime (i))
  513. return i;
  514. return x;
  515. }
  516. public static int ToPrime (int x)
  517. {
  518. for (int i = 0; i < primes_table.Length; i++)
  519. if (x <= primes_table [i])
  520. return primes_table [i];
  521. return CalcPrime (x);
  522. }
  523. }
  524. }
  525. }