2
0

BaseDictionary.h 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #pragma once
  6. //////////////////////////////////////////////////////////////////////////
  7. // Template implementation of dictionary based on .NET BCL implementation.
  8. //
  9. // Buckets and entries are allocated as contiguous arrays to maintain good locality of reference.
  10. //
  11. // COLLISION STRATEGY
  12. // This dictionary uses a chaining collision resolution strategy. Chains are implemented using indexes to the 'buckets' array.
  13. //
  14. // STORAGE (TAllocator)
  15. // This dictionary works for both arena and recycler based allocation using TAllocator template parameter.
  16. // It supports storing of both value and pointer types. Using template specialization, value types (built-in fundamental
  17. // types and structs) are stored as leaf nodes by default.
  18. //
  19. // INITIAL SIZE and BUCKET MAPPING (SizePolicy)
  20. // This can be specified using TSizePolicy template parameter. There are 2 implementations:
  21. // - PrimeSizePolicy (Better distribution): Initial size is a prime number. Mapping to bucket is done using modulus operation (costlier).
  22. // - PowerOf2SizePolicy (faster): Initial size is a power of 2. Mapping to bucket is done by a fast truncating the MSB bits up to the size of the table.
  23. //
  24. // COMPARISONS AND HASHCODE (Comparer)
  25. // Enables custom comparisons for TKey and TValue. For example, for strings we use string comparison instead of comparing pointers.
  26. //
  27. #if PROFILE_DICTIONARY
  28. #include "DictionaryStats.h"
  29. #endif
  30. namespace Js
  31. {
  32. template <class TDictionary>
  33. class RemoteDictionary;
  34. }
  35. namespace JsDiag
  36. {
  37. template <class TDictionary>
  38. struct RemoteDictionary;
  39. }
  40. namespace JsUtil
  41. {
  42. class NoResizeLock
  43. {
  44. public:
  45. void BeginResize() {}
  46. void EndResize() {}
  47. };
  48. class AsymetricResizeLock
  49. {
  50. public:
  51. void BeginResize() { cs.Enter(); }
  52. void EndResize() { cs.Leave(); }
  53. void LockResize() { cs.Enter(); }
  54. void UnlockResize() { cs.Leave(); }
  55. private:
  56. CriticalSection cs;
  57. };
  58. template <class TKey, class TValue> class SimpleDictionaryEntry;
  59. template <
  60. class TKey,
  61. class TValue,
  62. class TAllocator,
  63. class SizePolicy = PowerOf2SizePolicy,
  64. template <typename ValueOrKey> class Comparer = DefaultComparer,
  65. template <typename K, typename V> class Entry = SimpleDictionaryEntry,
  66. typename Lock = NoResizeLock
  67. >
  68. class BaseDictionary : protected Lock
  69. {
  70. public:
  71. typedef TKey KeyType;
  72. typedef TValue ValueType;
  73. typedef typename AllocatorInfo<TAllocator, TValue>::AllocatorType AllocatorType;
  74. typedef SizePolicy CurrentSizePolicy;
  75. typedef Entry<TKey, TValue> EntryType;
  76. template<class TDictionary> class EntryIterator;
  77. template<class TDictionary> class BucketEntryIterator;
  78. protected:
  79. typedef typename AllocatorInfo<TAllocator, TValue>::AllocatorFunc EntryAllocatorFuncType;
  80. friend class Js::RemoteDictionary<BaseDictionary>;
  81. template <typename ValueOrKey> struct ComparerType { typedef Comparer<ValueOrKey> Type; }; // Used by diagnostics to access Comparer type
  82. int* buckets;
  83. EntryType* entries;
  84. AllocatorType* alloc;
  85. int size;
  86. uint bucketCount;
  87. int count;
  88. int freeList;
  89. int freeCount;
  90. #if PROFILE_DICTIONARY
  91. DictionaryStats *stats;
  92. #endif
  93. enum InsertOperations
  94. {
  95. Insert_Add , // FatalInternalError if the item already exist in debug build
  96. Insert_AddNew, // Ignore add if the item already exist
  97. Insert_Item // Replace the item if it already exist
  98. };
  99. class AutoDoResize
  100. {
  101. public:
  102. AutoDoResize(Lock& lock) : lock(lock) { lock.BeginResize(); };
  103. ~AutoDoResize() { lock.EndResize(); };
  104. private:
  105. Lock& lock;
  106. };
  107. public:
  108. BaseDictionary(AllocatorType* allocator, int capacity = 0)
  109. : buckets (nullptr),
  110. size(0),
  111. bucketCount(0),
  112. entries(nullptr),
  113. count(0),
  114. freeCount(0),
  115. alloc(allocator)
  116. {
  117. Assert(allocator);
  118. #if PROFILE_DICTIONARY
  119. stats = nullptr;
  120. #endif
  121. // If initial capacity is negative or 0, lazy initialization on
  122. // the first insert operation is performed.
  123. if (capacity > 0)
  124. {
  125. Initialize(capacity);
  126. }
  127. }
  128. BaseDictionary(const BaseDictionary &other) : alloc(other.alloc)
  129. {
  130. if(other.Count() == 0)
  131. {
  132. size = 0;
  133. bucketCount = 0;
  134. buckets = nullptr;
  135. entries = nullptr;
  136. count = 0;
  137. freeCount = 0;
  138. #if PROFILE_DICTIONARY
  139. stats = nullptr;
  140. #endif
  141. return;
  142. }
  143. Assert(other.bucketCount != 0);
  144. Assert(other.size != 0);
  145. buckets = AllocateBuckets(other.bucketCount);
  146. Assert(buckets); // no-throw allocators are currently not supported
  147. try
  148. {
  149. entries = AllocateEntries(other.size, false /* zeroAllocate */);
  150. Assert(entries); // no-throw allocators are currently not supported
  151. }
  152. catch(...)
  153. {
  154. DeleteBuckets(buckets, other.bucketCount);
  155. throw;
  156. }
  157. size = other.size;
  158. bucketCount = other.bucketCount;
  159. count = other.count;
  160. freeList = other.freeList;
  161. freeCount = other.freeCount;
  162. size_t copySize = bucketCount * sizeof(buckets[0]);
  163. js_memcpy_s(buckets, copySize, other.buckets, copySize);
  164. copySize = size * sizeof(entries[0]);
  165. js_memcpy_s(entries, copySize, other.entries, copySize);
  166. #if PROFILE_DICTIONARY
  167. stats = DictionaryStats::Create(typeid(this).name(), size);
  168. #endif
  169. }
  170. ~BaseDictionary()
  171. {
  172. if (buckets)
  173. {
  174. DeleteBuckets(buckets, bucketCount);
  175. }
  176. if (entries)
  177. {
  178. DeleteEntries(entries, size);
  179. }
  180. }
  181. AllocatorType *GetAllocator() const
  182. {
  183. return alloc;
  184. }
  185. inline int Capacity() const
  186. {
  187. return size;
  188. }
  189. inline int Count() const
  190. {
  191. return count - freeCount;
  192. }
  193. TValue Item(const TKey& key)
  194. {
  195. int i = FindEntry(key);
  196. Assert(i >= 0);
  197. return entries[i].Value();
  198. }
  199. int Add(const TKey& key, const TValue& value)
  200. {
  201. return Insert<Insert_Add>(key, value);
  202. }
  203. int AddNew(const TKey& key, const TValue& value)
  204. {
  205. return Insert<Insert_AddNew>(key, value);
  206. }
  207. int Item(const TKey& key, const TValue& value)
  208. {
  209. return Insert<Insert_Item>(key, value);
  210. }
  211. bool Contains(KeyValuePair<TKey, TValue> keyValuePair)
  212. {
  213. int i = FindEntry(keyValuePair.Key());
  214. if( i >= 0 && Comparer<TValue>::Equals(entries[i].Value(), keyValuePair.Value()))
  215. {
  216. return true;
  217. }
  218. return false;
  219. }
  220. bool Remove(KeyValuePair<TKey, TValue> keyValuePair)
  221. {
  222. int i, last;
  223. uint targetBucket;
  224. if(FindEntryWithKey(keyValuePair.Key(), &i, &last, &targetBucket))
  225. {
  226. const TValue &value = entries[i].Value();
  227. if(Comparer<TValue>::Equals(value, keyValuePair.Value()))
  228. {
  229. RemoveAt(i, last, targetBucket);
  230. return true;
  231. }
  232. }
  233. return false;
  234. }
  235. void Clear()
  236. {
  237. if (count > 0)
  238. {
  239. memset(buckets, -1, bucketCount * sizeof(buckets[0]));
  240. memset(entries, 0, sizeof(EntryType) * size);
  241. count = 0;
  242. freeCount = 0;
  243. #if PROFILE_DICTIONARY
  244. // To not loose previously collected data, we will treat cleared dictionary as a separate instance for stats tracking purpose
  245. stats = DictionaryStats::Create(typeid(this).name(), size);
  246. #endif
  247. }
  248. }
  249. void ResetNoDelete()
  250. {
  251. this->size = 0;
  252. this->bucketCount = 0;
  253. this->buckets = nullptr;
  254. this->entries = nullptr;
  255. this->count = 0;
  256. this->freeCount = 0;
  257. }
  258. void Reset()
  259. {
  260. if(bucketCount != 0)
  261. {
  262. DeleteBuckets(buckets, bucketCount);
  263. buckets = nullptr;
  264. bucketCount = 0;
  265. }
  266. else
  267. {
  268. Assert(!buckets);
  269. }
  270. if(size != 0)
  271. {
  272. DeleteEntries(entries, size);
  273. entries = nullptr;
  274. freeCount = count = size = 0;
  275. }
  276. else
  277. {
  278. Assert(!entries);
  279. Assert(count == 0);
  280. Assert(freeCount == 0);
  281. }
  282. }
  283. bool ContainsKey(const TKey& key) const
  284. {
  285. return FindEntry(key) >= 0;
  286. }
  287. template <typename TLookup>
  288. inline const TValue& LookupWithKey(const TLookup& key, const TValue& defaultValue) const
  289. {
  290. int i = FindEntryWithKey(key);
  291. if (i >= 0)
  292. {
  293. return entries[i].Value();
  294. }
  295. return defaultValue;
  296. }
  297. inline const TValue& Lookup(const TKey& key, const TValue& defaultValue)
  298. {
  299. return LookupWithKey<TKey>(key, defaultValue);
  300. }
  301. template <typename TLookup>
  302. bool TryGetValue(const TLookup& key, TValue* value) const
  303. {
  304. int i = FindEntryWithKey(key);
  305. if (i >= 0)
  306. {
  307. *value = entries[i].Value();
  308. return true;
  309. }
  310. return false;
  311. }
  312. bool TryGetValueAndRemove(const TKey& key, TValue* value)
  313. {
  314. int i, last;
  315. uint targetBucket;
  316. if (FindEntryWithKey(key, &i, &last, &targetBucket))
  317. {
  318. *value = entries[i].Value();
  319. RemoveAt(i, last, targetBucket);
  320. return true;
  321. }
  322. return false;
  323. }
  324. template <typename TLookup>
  325. bool TryGetReference(const TLookup& key, const TValue** value) const
  326. {
  327. int i;
  328. return TryGetReference(key, value, &i);
  329. }
  330. template <typename TLookup>
  331. bool TryGetReference(const TLookup& key, TValue** value) const
  332. {
  333. return TryGetReference(key, const_cast<const TValue **>(value));
  334. }
  335. template <typename TLookup>
  336. bool TryGetReference(const TLookup& key, const TValue** value, int* index) const
  337. {
  338. int i = FindEntryWithKey(key);
  339. if (i >= 0)
  340. {
  341. *value = &entries[i].Value();
  342. *index = i;
  343. return true;
  344. }
  345. return false;
  346. }
  347. template <typename TLookup>
  348. bool TryGetReference(const TLookup& key, TValue** value, int* index) const
  349. {
  350. return TryGetReference(key, const_cast<const TValue **>(value), index);
  351. }
  352. const TValue& GetValueAt(const int index) const
  353. {
  354. Assert(index >= 0);
  355. Assert(index < count);
  356. return entries[index].Value();
  357. }
  358. TValue* GetReferenceAt(const int index) const
  359. {
  360. Assert(index >= 0);
  361. Assert(index < count);
  362. return &entries[index].Value();
  363. }
  364. TKey const& GetKeyAt(const int index) const
  365. {
  366. Assert(index >= 0);
  367. Assert(index < count);
  368. return entries[index].Key();
  369. }
  370. bool TryGetValueAt(const int index, TValue const ** value) const
  371. {
  372. if (index >= 0 && index < count)
  373. {
  374. *value = &entries[index].Value();
  375. return true;
  376. }
  377. return false;
  378. }
  379. bool TryGetValueAt(int index, TValue * value) const
  380. {
  381. if (index >= 0 && index < count)
  382. {
  383. *value = entries[index].Value();
  384. return true;
  385. }
  386. return false;
  387. }
  388. bool Remove(const TKey& key)
  389. {
  390. int i, last;
  391. uint targetBucket;
  392. if(FindEntryWithKey(key, &i, &last, &targetBucket))
  393. {
  394. RemoveAt(i, last, targetBucket);
  395. return true;
  396. }
  397. return false;
  398. }
  399. EntryIterator<const BaseDictionary> GetIterator() const
  400. {
  401. return EntryIterator<const BaseDictionary>(*this);
  402. }
  403. EntryIterator<BaseDictionary> GetIterator()
  404. {
  405. return EntryIterator<BaseDictionary>(*this);
  406. }
  407. BucketEntryIterator<BaseDictionary> GetIteratorWithRemovalSupport()
  408. {
  409. return BucketEntryIterator<BaseDictionary>(*this);
  410. }
  411. template<class Fn>
  412. bool AnyValue(Fn fn) const
  413. {
  414. for (uint i = 0; i < bucketCount; i++)
  415. {
  416. if(buckets[i] != -1)
  417. {
  418. for (int currentIndex = buckets[i] ; currentIndex != -1 ; currentIndex = entries[currentIndex].next)
  419. {
  420. if (fn(entries[currentIndex].Value()))
  421. {
  422. return true;
  423. }
  424. }
  425. }
  426. }
  427. return false;
  428. }
  429. template<class Fn>
  430. void EachValue(Fn fn) const
  431. {
  432. for (uint i = 0; i < bucketCount; i++)
  433. {
  434. if(buckets[i] != -1)
  435. {
  436. for (int currentIndex = buckets[i] ; currentIndex != -1 ; currentIndex = entries[currentIndex].next)
  437. {
  438. fn(entries[currentIndex].Value());
  439. }
  440. }
  441. }
  442. }
  443. template<class Fn>
  444. void MapReference(Fn fn)
  445. {
  446. MapUntilReference([fn](TKey const& key, TValue& value)
  447. {
  448. fn(key, value);
  449. return false;
  450. });
  451. }
  452. template<class Fn>
  453. bool MapUntilReference(Fn fn) const
  454. {
  455. return MapEntryUntil([fn](EntryType &entry) -> bool
  456. {
  457. return fn(entry.Key(), entry.Value());
  458. });
  459. }
  460. template<class Fn>
  461. void MapAddress(Fn fn) const
  462. {
  463. MapUntilAddress([fn](TKey const& key, TValue * value) -> bool
  464. {
  465. fn(key, value);
  466. return false;
  467. });
  468. }
  469. template<class Fn>
  470. bool MapUntilAddress(Fn fn) const
  471. {
  472. return MapEntryUntil([fn](EntryType &entry) -> bool
  473. {
  474. return fn(entry.Key(), &entry.Value());
  475. });
  476. }
  477. template<class Fn>
  478. void Map(Fn fn) const
  479. {
  480. MapUntil([fn](TKey const& key, TValue const& value) -> bool
  481. {
  482. fn(key, value);
  483. return false;
  484. });
  485. }
  486. template<class Fn>
  487. bool MapUntil(Fn fn) const
  488. {
  489. return MapEntryUntil([fn](EntryType const& entry) -> bool
  490. {
  491. return fn(entry.Key(), entry.Value());
  492. });
  493. }
  494. template<class Fn>
  495. void MapAndRemoveIf(Fn fn)
  496. {
  497. for (uint i = 0; i < bucketCount; i++)
  498. {
  499. if (buckets[i] != -1)
  500. {
  501. for (int currentIndex = buckets[i], lastIndex = -1; currentIndex != -1;)
  502. {
  503. // If the predicate says we should remove this item
  504. if (fn(entries[currentIndex]) == true)
  505. {
  506. const int nextIndex = entries[currentIndex].next;
  507. RemoveAt(currentIndex, lastIndex, i);
  508. currentIndex = nextIndex;
  509. }
  510. else
  511. {
  512. lastIndex = currentIndex;
  513. currentIndex = entries[currentIndex].next;
  514. }
  515. }
  516. }
  517. }
  518. }
  519. template <class Fn>
  520. bool RemoveIf(TKey const& key, Fn fn)
  521. {
  522. return RemoveIfWithKey<TKey>(key, fn);
  523. }
  524. template <typename LookupType, class Fn>
  525. bool RemoveIfWithKey(LookupType const& lookupKey, Fn fn)
  526. {
  527. int i, last;
  528. uint targetBucket;
  529. if (FindEntryWithKey<LookupType>(lookupKey, &i, &last, &targetBucket))
  530. {
  531. if (fn(entries[i].Key(), entries[i].Value()))
  532. {
  533. RemoveAt(i, last, targetBucket);
  534. return true;
  535. }
  536. }
  537. return false;
  538. }
  539. // Returns whether the dictionary was resized or not
  540. bool EnsureCapacity()
  541. {
  542. if (freeCount == 0 && count == size)
  543. {
  544. Resize();
  545. return true;
  546. }
  547. return false;
  548. }
  549. int GetNextIndex()
  550. {
  551. if (freeCount != 0)
  552. {
  553. Assert(freeCount > 0);
  554. Assert(freeList >= 0);
  555. Assert(freeList < count);
  556. return freeList;
  557. }
  558. return count;
  559. }
  560. int GetLastIndex()
  561. {
  562. return count - 1;
  563. }
  564. BaseDictionary *Clone()
  565. {
  566. return AllocatorNew(AllocatorType, alloc, BaseDictionary, *this);
  567. }
  568. void Copy(const BaseDictionary *const other)
  569. {
  570. DoCopy(other);
  571. }
  572. void LockResize()
  573. {
  574. __super::LockResize();
  575. }
  576. void UnlockResize()
  577. {
  578. __super::UnlockResize();
  579. }
  580. protected:
  581. template<class T>
  582. void DoCopy(const T *const other)
  583. {
  584. Assert(size == 0);
  585. Assert(bucketCount == 0);
  586. Assert(!buckets);
  587. Assert(!entries);
  588. Assert(count == 0);
  589. Assert(freeCount == 0);
  590. #if PROFILE_DICTIONARY
  591. Assert(!stats);
  592. #endif
  593. if(other->Count() == 0)
  594. {
  595. return;
  596. }
  597. Assert(other->bucketCount != 0);
  598. Assert(other->size != 0);
  599. buckets = AllocateBuckets(other->bucketCount);
  600. Assert(buckets); // no-throw allocators are currently not supported
  601. try
  602. {
  603. entries = AllocateEntries(other->size, false /* zeroAllocate */);
  604. Assert(entries); // no-throw allocators are currently not supported
  605. }
  606. catch(...)
  607. {
  608. DeleteBuckets(buckets, other->bucketCount);
  609. buckets = nullptr;
  610. throw;
  611. }
  612. size = other->size;
  613. bucketCount = other->bucketCount;
  614. count = other->count;
  615. freeList = other->freeList;
  616. freeCount = other->freeCount;
  617. size_t copySize = bucketCount * sizeof(buckets[0]);
  618. js_memcpy_s(buckets, copySize, other->buckets, copySize);
  619. copySize = size * sizeof(entries[0]);
  620. js_memcpy_s(entries, copySize, other->entries, copySize);
  621. #if PROFILE_DICTIONARY
  622. stats = DictionaryStats::Create(typeid(this).name(), size);
  623. #endif
  624. }
  625. protected:
  626. template<class Fn>
  627. bool MapEntryUntil(Fn fn) const
  628. {
  629. for (uint i = 0; i < bucketCount; i++)
  630. {
  631. if(buckets[i] != -1)
  632. {
  633. for (int currentIndex = buckets[i] ; currentIndex != -1 ; currentIndex = entries[currentIndex].next)
  634. {
  635. if (fn(entries[currentIndex]))
  636. {
  637. return true; // fn condition succeeds
  638. }
  639. }
  640. }
  641. }
  642. return false;
  643. }
  644. private:
  645. template <typename TLookup>
  646. static hash_t GetHashCodeWithKey(const TLookup& key)
  647. {
  648. // set last bit to 1 to avoid false positive to make hash appears to be an valid recycler address.
  649. // In the same line, 0 should be use to indicate a non-existing entry.
  650. return TAGHASH(Comparer<TLookup>::GetHashCode(key));
  651. }
  652. static hash_t GetHashCode(const TKey& key)
  653. {
  654. return GetHashCodeWithKey<TKey>(key);
  655. }
  656. static uint GetBucket(hash_t hashCode, int bucketCount)
  657. {
  658. return SizePolicy::GetBucket(UNTAGHASH(hashCode), bucketCount);
  659. }
  660. uint GetBucket(uint hashCode) const
  661. {
  662. return GetBucket(hashCode, this->bucketCount);
  663. }
  664. static bool IsFreeEntry(const EntryType &entry)
  665. {
  666. // A free entry's next index will be (-2 - nextIndex), such that it is always <= -2, for fast entry iteration
  667. // allowing for skipping over free entries. -1 is reserved for the end-of-chain marker for a used entry.
  668. return entry.next <= -2;
  669. }
  670. void SetNextFreeEntryIndex(EntryType &freeEntry, const int nextFreeEntryIndex)
  671. {
  672. Assert(!IsFreeEntry(freeEntry));
  673. Assert(nextFreeEntryIndex >= -1);
  674. Assert(nextFreeEntryIndex < count);
  675. // The last entry in the free list chain will have a next of -2 to indicate that it is a free entry. The end of the
  676. // free list chain is identified using freeCount.
  677. freeEntry.next = nextFreeEntryIndex >= 0 ? -2 - nextFreeEntryIndex : -2;
  678. }
  679. static int GetNextFreeEntryIndex(const EntryType &freeEntry)
  680. {
  681. Assert(IsFreeEntry(freeEntry));
  682. return -2 - freeEntry.next;
  683. }
  684. template <typename LookupType>
  685. __inline int FindEntryWithKey(const LookupType& key) const
  686. {
  687. #if PROFILE_DICTIONARY
  688. uint depth = 0;
  689. #endif
  690. int * localBuckets = buckets;
  691. if (localBuckets != nullptr)
  692. {
  693. hash_t hashCode = GetHashCodeWithKey<LookupType>(key);
  694. uint targetBucket = this->GetBucket(hashCode);
  695. EntryType * localEntries = entries;
  696. for (int i = localBuckets[targetBucket]; i >= 0; i = localEntries[i].next)
  697. {
  698. if (localEntries[i].KeyEquals<Comparer<TKey>>(key, hashCode))
  699. {
  700. #if PROFILE_DICTIONARY
  701. if (stats)
  702. stats->Lookup(depth);
  703. #endif
  704. return i;
  705. }
  706. #if PROFILE_DICTIONARY
  707. depth += 1;
  708. #endif
  709. }
  710. }
  711. #if PROFILE_DICTIONARY
  712. if (stats)
  713. stats->Lookup(depth);
  714. #endif
  715. return -1;
  716. }
  717. inline int FindEntry(const TKey& key) const
  718. {
  719. return FindEntryWithKey<TKey>(key);
  720. }
  721. template <typename LookupType>
  722. __inline bool FindEntryWithKey(const LookupType& key, int *const i, int *const last, uint *const targetBucket)
  723. {
  724. #if PROFILE_DICTIONARY
  725. uint depth = 0;
  726. #endif
  727. int * localBuckets = buckets;
  728. if (localBuckets != nullptr)
  729. {
  730. uint hashCode = GetHashCodeWithKey<LookupType>(key);
  731. *targetBucket = this->GetBucket(hashCode);
  732. *last = -1;
  733. EntryType * localEntries = entries;
  734. for (*i = localBuckets[*targetBucket]; *i >= 0; *last = *i, *i = localEntries[*i].next)
  735. {
  736. if (localEntries[*i].KeyEquals<Comparer<TKey>>(key, hashCode))
  737. {
  738. #if PROFILE_DICTIONARY
  739. if (stats)
  740. stats->Lookup(depth);
  741. #endif
  742. return true;
  743. }
  744. #if PROFILE_DICTIONARY
  745. depth += 1;
  746. #endif
  747. }
  748. }
  749. #if PROFILE_DICTIONARY
  750. if (stats)
  751. stats->Lookup(depth);
  752. #endif
  753. return false;
  754. }
  755. void Initialize(int capacity)
  756. {
  757. // minimum capacity is 4
  758. int initSize = max(capacity, 4);
  759. uint initBucketCount = SizePolicy::GetBucketSize(initSize);
  760. AssertMsg(initBucketCount > 0, "Size returned by policy should be greater than 0");
  761. Allocate(&buckets, &entries, initBucketCount, initSize);
  762. // Allocation can throw - assign the size only after allocation has succeeded.
  763. this->bucketCount = initBucketCount;
  764. this->size = initSize;
  765. Assert(this->freeCount == 0);
  766. #if PROFILE_DICTIONARY
  767. stats = DictionaryStats::Create(typeid(this).name(), size);
  768. #endif
  769. }
  770. template <InsertOperations op>
  771. int Insert(TKey key, TValue value)
  772. {
  773. int * localBuckets = buckets;
  774. if (localBuckets == nullptr)
  775. {
  776. Initialize(0);
  777. localBuckets = buckets;
  778. }
  779. #if DBG || PROFILE_DICTIONARY
  780. // Always search and verify
  781. const bool needSearch = true;
  782. #else
  783. const bool needSearch = (op != Insert_Add);
  784. #endif
  785. hash_t hashCode = GetHashCode(key);
  786. uint targetBucket = this->GetBucket(hashCode);
  787. if (needSearch)
  788. {
  789. #if PROFILE_DICTIONARY
  790. uint depth = 0;
  791. #endif
  792. EntryType * localEntries = entries;
  793. for (int i = localBuckets[targetBucket]; i >= 0; i = localEntries[i].next)
  794. {
  795. if (localEntries[i].KeyEquals<Comparer<TKey>>(key, hashCode))
  796. {
  797. #if PROFILE_DICTIONARY
  798. if (stats)
  799. stats->Lookup(depth);
  800. #endif
  801. Assert(op != Insert_Add);
  802. if (op == Insert_Item)
  803. {
  804. localEntries[i].SetValue(value);
  805. return i;
  806. }
  807. return -1;
  808. }
  809. #if PROFILE_DICTIONARY
  810. depth += 1;
  811. #endif
  812. }
  813. #if PROFILE_DICTIONARY
  814. if (stats)
  815. stats->Lookup(depth);
  816. #endif
  817. }
  818. // Ideally we'd do cleanup only if weak references have been collected since the last resize
  819. // but that would require us to use an additional field to store the last recycler cleanup id
  820. // that we saw
  821. // We can add that optimization later if we have to.
  822. if (EntryType::SupportsCleanup() && freeCount == 0 && count == size)
  823. {
  824. this->MapAndRemoveIf([](EntryType& entry)
  825. {
  826. return EntryType::NeedsCleanup(entry);
  827. });
  828. }
  829. int index;
  830. if (freeCount != 0)
  831. {
  832. Assert(freeCount > 0);
  833. Assert(freeList >= 0);
  834. Assert(freeList < count);
  835. index = freeList;
  836. freeCount--;
  837. if(freeCount != 0)
  838. {
  839. freeList = GetNextFreeEntryIndex(entries[index]);
  840. }
  841. }
  842. else
  843. {
  844. // If there's nothing free, then in general, we set index to count, and increment count
  845. // If we resize, we also need to recalculate the target
  846. // However, if cleanup is supported, then before resize, we should try and clean up and see
  847. // if something got freed, and if it did, reuse that index
  848. if (count == size)
  849. {
  850. Resize();
  851. targetBucket = this->GetBucket(hashCode);
  852. index = count;
  853. count++;
  854. }
  855. else
  856. {
  857. index = count;
  858. count++;
  859. }
  860. Assert(count <= size);
  861. Assert(index < size);
  862. }
  863. entries[index].Set(key, value, hashCode);
  864. entries[index].next = buckets[targetBucket];
  865. buckets[targetBucket] = index;
  866. #if PROFILE_DICTIONARY
  867. int profileIndex = index;
  868. uint depth = 1; // need to recalculate depth in case there was a resize (also 1-based for stats->Insert)
  869. while(entries[profileIndex].next != -1)
  870. {
  871. profileIndex = entries[profileIndex].next;
  872. ++depth;
  873. }
  874. if (stats)
  875. stats->Insert(depth);
  876. #endif
  877. return index;
  878. }
  879. void Resize()
  880. {
  881. AutoDoResize autoDoResize(*this);
  882. int newSize = SizePolicy::GetNextSize(count);
  883. uint newBucketCount = SizePolicy::GetBucketSize(newSize);
  884. __analysis_assume(newSize > count);
  885. int* newBuckets = nullptr;
  886. EntryType* newEntries = nullptr;
  887. if (newBucketCount == bucketCount)
  888. {
  889. // no need to rehash
  890. newEntries = AllocateEntries(newSize);
  891. js_memcpy_s(newEntries, sizeof(EntryType) * newSize, entries, sizeof(EntryType) * count);
  892. DeleteEntries(entries, size);
  893. this->entries = newEntries;
  894. this->size = newSize;
  895. return;
  896. }
  897. Allocate(&newBuckets, &newEntries, newBucketCount, newSize);
  898. js_memcpy_s(newEntries, sizeof(EntryType) * newSize, entries, sizeof(EntryType) * count);
  899. // When TAllocator is of type Recycler, it is possible that the Allocate above causes a collection, which
  900. // in turn can cause entries in the dictionary to be removed - i.e. the dictionary contains weak references
  901. // that remove themselves when no longer valid. This means the free list might not be empty anymore.
  902. for (int i = 0; i < count; i++)
  903. {
  904. __analysis_assume(i < newSize);
  905. if (!IsFreeEntry(newEntries[i]))
  906. {
  907. uint hashCode = newEntries[i].GetHashCode<Comparer<TKey>>();
  908. int bucket = GetBucket(hashCode, newBucketCount);
  909. newEntries[i].next = newBuckets[bucket];
  910. newBuckets[bucket] = i;
  911. }
  912. }
  913. DeleteBuckets(buckets, bucketCount);
  914. DeleteEntries(entries, size);
  915. #if PROFILE_DICTIONARY
  916. if (stats)
  917. stats->Resize(newSize, /*emptyBuckets=*/ newSize - size);
  918. #endif
  919. buckets = newBuckets;
  920. bucketCount = newBucketCount;
  921. size = newSize;
  922. entries = newEntries;
  923. }
  924. __ecount(bucketCount) int *AllocateBuckets(const uint bucketCount)
  925. {
  926. return
  927. AllocateArray<AllocatorType, int, false>(
  928. TRACK_ALLOC_INFO(alloc, int, AllocatorType, 0, bucketCount),
  929. TypeAllocatorFunc<AllocatorType, int>::GetAllocFunc(),
  930. bucketCount);
  931. }
  932. __ecount(size) EntryType * AllocateEntries(int size, const bool zeroAllocate = true)
  933. {
  934. // Note that the choice of leaf/non-leaf node is decided for the EntryType on the basis of TValue. By default, if
  935. // TValue is a pointer, a non-leaf allocation is done. This behavior can be overridden by specializing
  936. // TypeAllocatorFunc for TValue.
  937. return
  938. AllocateArray<AllocatorType, EntryType, false>(
  939. TRACK_ALLOC_INFO(alloc, EntryType, AllocatorType, 0, size),
  940. zeroAllocate ? EntryAllocatorFuncType::GetAllocZeroFunc() : EntryAllocatorFuncType::GetAllocFunc(),
  941. size);
  942. }
  943. void DeleteBuckets(__in_ecount(bucketCount) int *const buckets, const uint bucketCount)
  944. {
  945. Assert(buckets);
  946. Assert(bucketCount != 0);
  947. AllocatorFree(alloc, (TypeAllocatorFunc<AllocatorType, int>::GetFreeFunc()), buckets, bucketCount * sizeof(int));
  948. }
  949. void DeleteEntries(__in_ecount(size) EntryType *const entries, const int size)
  950. {
  951. Assert(entries);
  952. Assert(size != 0);
  953. AllocatorFree(alloc, EntryAllocatorFuncType::GetFreeFunc(), entries, size * sizeof(EntryType));
  954. }
  955. void Allocate(__deref_out_ecount(bucketCount) int** ppBuckets, __deref_out_ecount(size) EntryType** ppEntries, uint bucketCount, int size)
  956. {
  957. int *const buckets = AllocateBuckets(bucketCount);
  958. Assert(buckets); // no-throw allocators are currently not supported
  959. EntryType *entries;
  960. try
  961. {
  962. entries = AllocateEntries(size);
  963. Assert(entries); // no-throw allocators are currently not supported
  964. }
  965. catch(...)
  966. {
  967. DeleteBuckets(buckets, bucketCount);
  968. throw;
  969. }
  970. memset(buckets, -1, bucketCount * sizeof(buckets[0]));
  971. *ppBuckets = buckets;
  972. *ppEntries = entries;
  973. }
  974. __inline void RemoveAt(const int i, const int last, const uint targetBucket)
  975. {
  976. if (last < 0)
  977. {
  978. buckets[targetBucket] = entries[i].next;
  979. }
  980. else
  981. {
  982. entries[last].next = entries[i].next;
  983. }
  984. entries[i].Clear();
  985. SetNextFreeEntryIndex(entries[i], freeCount == 0 ? -1 : freeList);
  986. freeList = i;
  987. freeCount++;
  988. #if PROFILE_DICTIONARY
  989. if (stats)
  990. stats->Remove(buckets[targetBucket] == -1);
  991. #endif
  992. }
  993. #if DBG_DUMP
  994. public:
  995. void Dump()
  996. {
  997. printf("Dumping Dictionary\n");
  998. printf("-------------------\n");
  999. for (uint i = 0; i < bucketCount; i++)
  1000. {
  1001. printf("Bucket value: %d\n", buckets[i]);
  1002. for (int j = buckets[i]; j >= 0; j = entries[j].next)
  1003. {
  1004. printf("%d => %d Next: %d\n", entries[j].Key(), entries[j].Value(), entries[j].next);
  1005. }
  1006. }
  1007. }
  1008. #endif
  1009. protected:
  1010. template<class TDictionary, class Leaf>
  1011. class IteratorBase abstract
  1012. {
  1013. protected:
  1014. EntryType *const entries;
  1015. int entryIndex;
  1016. #if DBG
  1017. protected:
  1018. TDictionary &dictionary;
  1019. private:
  1020. int usedEntryCount;
  1021. #endif
  1022. protected:
  1023. IteratorBase(TDictionary &dictionary, const int entryIndex)
  1024. : entries(dictionary.entries),
  1025. entryIndex(entryIndex)
  1026. #if DBG
  1027. ,
  1028. dictionary(dictionary),
  1029. usedEntryCount(dictionary.Count())
  1030. #endif
  1031. {
  1032. }
  1033. protected:
  1034. void OnEntryRemoved()
  1035. {
  1036. DebugOnly(--usedEntryCount);
  1037. }
  1038. private:
  1039. bool IsValid_Virtual() const
  1040. {
  1041. return static_cast<const Leaf *>(this)->IsValid();
  1042. }
  1043. protected:
  1044. bool IsValid() const
  1045. {
  1046. Assert(dictionary.entries == entries);
  1047. Assert(dictionary.Count() == usedEntryCount);
  1048. return true;
  1049. }
  1050. public:
  1051. EntryType &Current() const
  1052. {
  1053. Assert(IsValid_Virtual());
  1054. Assert(!IsFreeEntry(entries[entryIndex]));
  1055. return entries[entryIndex];
  1056. }
  1057. TKey CurrentKey() const
  1058. {
  1059. return Current().Key();
  1060. }
  1061. const TValue &CurrentValue() const
  1062. {
  1063. return Current().Value();
  1064. }
  1065. TValue &CurrentValueReference() const
  1066. {
  1067. return Current().Value();
  1068. }
  1069. void SetCurrentValue(const TValue &value) const
  1070. {
  1071. #if DBG
  1072. // For BaseHashSet, save the key before changing the value to verify that the key does not change
  1073. const TKey previousKey = CurrentKey();
  1074. const hash_t previousHashCode = GetHashCode(previousKey);
  1075. #endif
  1076. Current().SetValue(value);
  1077. Assert(Current().KeyEquals<Comparer<TKey>>(previousKey, previousHashCode));
  1078. }
  1079. };
  1080. public:
  1081. template<class TDictionary>
  1082. class EntryIterator sealed : public IteratorBase<TDictionary, EntryIterator<TDictionary>>
  1083. {
  1084. private:
  1085. typedef IteratorBase<TDictionary, EntryIterator<TDictionary>> Base;
  1086. private:
  1087. const int entryCount;
  1088. public:
  1089. EntryIterator(TDictionary &dictionary) : Base(dictionary, 0), entryCount(dictionary.count)
  1090. {
  1091. if(IsValid() && IsFreeEntry(entries[entryIndex]))
  1092. {
  1093. MoveNext();
  1094. }
  1095. }
  1096. public:
  1097. bool IsValid() const
  1098. {
  1099. Assert(dictionary.count == entryCount);
  1100. Assert(entryIndex >= 0);
  1101. Assert(entryIndex <= entryCount);
  1102. return Base::IsValid() && entryIndex < entryCount;
  1103. }
  1104. public:
  1105. void MoveNext()
  1106. {
  1107. Assert(IsValid());
  1108. do
  1109. {
  1110. ++entryIndex;
  1111. } while(IsValid() && IsFreeEntry(entries[entryIndex]));
  1112. }
  1113. };
  1114. public:
  1115. template<class TDictionary>
  1116. class BucketEntryIterator sealed : public IteratorBase<TDictionary, BucketEntryIterator<TDictionary>>
  1117. {
  1118. private:
  1119. typedef IteratorBase<TDictionary, BucketEntryIterator<TDictionary>> Base;
  1120. private:
  1121. TDictionary &dictionary;
  1122. int *const buckets;
  1123. const uint bucketCount;
  1124. uint bucketIndex;
  1125. int previousEntryIndexInBucket;
  1126. int indexOfEntryAfterRemovedEntry;
  1127. public:
  1128. BucketEntryIterator(TDictionary &dictionary)
  1129. : Base(dictionary, -1),
  1130. dictionary(dictionary),
  1131. buckets(dictionary.buckets),
  1132. bucketCount(dictionary.bucketCount),
  1133. bucketIndex(0u - 1)
  1134. #if DBG
  1135. ,
  1136. previousEntryIndexInBucket(-2),
  1137. indexOfEntryAfterRemovedEntry(-2)
  1138. #endif
  1139. {
  1140. if(dictionary.Count() != 0)
  1141. {
  1142. MoveNextBucket();
  1143. }
  1144. }
  1145. public:
  1146. bool IsValid() const
  1147. {
  1148. Assert(dictionary.buckets == buckets);
  1149. Assert(dictionary.bucketCount == bucketCount);
  1150. Assert(entryIndex >= -1);
  1151. Assert(entryIndex < dictionary.count);
  1152. Assert(bucketIndex == 0u - 1 || bucketIndex <= bucketCount);
  1153. Assert(previousEntryIndexInBucket >= -2);
  1154. Assert(previousEntryIndexInBucket < dictionary.count);
  1155. Assert(indexOfEntryAfterRemovedEntry >= -2);
  1156. Assert(indexOfEntryAfterRemovedEntry < dictionary.count);
  1157. return Base::IsValid() && entryIndex >= 0;
  1158. }
  1159. public:
  1160. void MoveNext()
  1161. {
  1162. if(IsValid())
  1163. {
  1164. previousEntryIndexInBucket = entryIndex;
  1165. entryIndex = Current().next;
  1166. }
  1167. else
  1168. {
  1169. Assert(indexOfEntryAfterRemovedEntry >= -1);
  1170. entryIndex = indexOfEntryAfterRemovedEntry;
  1171. }
  1172. if(!IsValid())
  1173. {
  1174. MoveNextBucket();
  1175. }
  1176. }
  1177. private:
  1178. void MoveNextBucket()
  1179. {
  1180. Assert(!IsValid());
  1181. while(++bucketIndex < bucketCount)
  1182. {
  1183. entryIndex = buckets[bucketIndex];
  1184. if(IsValid())
  1185. {
  1186. previousEntryIndexInBucket = -1;
  1187. break;
  1188. }
  1189. }
  1190. }
  1191. public:
  1192. void RemoveCurrent()
  1193. {
  1194. Assert(previousEntryIndexInBucket >= -1);
  1195. indexOfEntryAfterRemovedEntry = Current().next;
  1196. dictionary.RemoveAt(entryIndex, previousEntryIndexInBucket, bucketIndex);
  1197. OnEntryRemoved();
  1198. entryIndex = -1;
  1199. }
  1200. };
  1201. template<class TDictionary, class Leaf> friend class IteratorBase;
  1202. template<class TDictionary> friend class EntryIterator;
  1203. template<class TDictionary> friend class BucketEntryIterator;
  1204. PREVENT_ASSIGN(BaseDictionary);
  1205. };
  1206. template <class TKey, class TValue> class SimpleHashedEntry;
  1207. template <
  1208. class TElement,
  1209. class TAllocator,
  1210. class SizePolicy = PowerOf2SizePolicy,
  1211. class TKey = TElement,
  1212. template <typename ValueOrKey> class Comparer = DefaultComparer,
  1213. template <typename, typename> class Entry = SimpleHashedEntry,
  1214. typename Lock = NoResizeLock
  1215. >
  1216. class BaseHashSet : protected BaseDictionary<TKey, TElement, TAllocator, SizePolicy, Comparer, Entry, Lock>
  1217. {
  1218. typedef BaseDictionary<TKey, TElement, TAllocator, SizePolicy, Comparer, Entry, Lock> Base;
  1219. typedef Entry<TKey, TElement> EntryType;
  1220. friend struct JsDiag::RemoteDictionary<BaseHashSet<TElement, TAllocator, SizePolicy, TKey, Comparer, Entry, Lock>>;
  1221. public:
  1222. BaseHashSet(AllocatorType * allocator, int capacity = 0) : BaseDictionary(allocator, capacity) {}
  1223. using Base::GetAllocator;
  1224. int Count() const
  1225. {
  1226. return __super::Count();
  1227. }
  1228. int Add(TElement const& element)
  1229. {
  1230. return __super::Add(ValueToKey<TKey, TElement>::ToKey(element), element);
  1231. }
  1232. // Add only if there isn't an existing element
  1233. int AddNew(TElement const& element)
  1234. {
  1235. return __super::AddNew(ValueToKey<TKey, TElement>::ToKey(element), element);
  1236. }
  1237. int Item(TElement const& element)
  1238. {
  1239. return __super::Item(ValueToKey<TKey, TElement>::ToKey(element), element);
  1240. }
  1241. void Clear()
  1242. {
  1243. __super::Clear();
  1244. }
  1245. using Base::Reset;
  1246. TElement const& Lookup(TKey const& key)
  1247. {
  1248. // Use a static to pass the null default value, since the
  1249. // default value may get returned out of the current scope by ref.
  1250. static const TElement nullElement = nullptr;
  1251. return __super::Lookup(key, nullElement);
  1252. }
  1253. template <typename KeyType>
  1254. TElement const& LookupWithKey(KeyType const& key)
  1255. {
  1256. static const TElement nullElement = nullptr;
  1257. return __super::LookupWithKey(key, nullElement);
  1258. }
  1259. bool Contains(TElement const& element) const
  1260. {
  1261. return ContainsKey(ValueToKey<TKey, TElement>::ToKey(element));
  1262. }
  1263. using Base::ContainsKey;
  1264. using Base::TryGetValue;
  1265. using Base::TryGetReference;
  1266. bool RemoveKey(const TKey &key)
  1267. {
  1268. return Base::Remove(key);
  1269. }
  1270. bool Remove(TElement const& element)
  1271. {
  1272. return __super::Remove(ValueToKey<TKey, TElement>::ToKey(element));
  1273. }
  1274. EntryIterator<const BaseHashSet> GetIterator() const
  1275. {
  1276. return EntryIterator<const BaseHashSet>(*this);
  1277. }
  1278. EntryIterator<BaseHashSet> GetIterator()
  1279. {
  1280. return EntryIterator<BaseHashSet>(*this);
  1281. }
  1282. BucketEntryIterator<BaseHashSet> GetIteratorWithRemovalSupport()
  1283. {
  1284. return BucketEntryIterator<BaseHashSet>(*this);
  1285. }
  1286. template<class Fn>
  1287. void Map(Fn fn)
  1288. {
  1289. MapUntil([fn](TElement const& value) -> bool
  1290. {
  1291. fn(value);
  1292. return false;
  1293. });
  1294. }
  1295. template<class Fn>
  1296. void MapAndRemoveIf(Fn fn)
  1297. {
  1298. __super::MapAndRemoveIf([fn](EntryType const& entry) -> bool
  1299. {
  1300. return fn(entry.Value());
  1301. });
  1302. }
  1303. template<class Fn>
  1304. bool MapUntil(Fn fn)
  1305. {
  1306. return __super::MapEntryUntil([fn](EntryType const& entry) -> bool
  1307. {
  1308. return fn(entry.Value());
  1309. });
  1310. }
  1311. bool EnsureCapacity()
  1312. {
  1313. return __super::EnsureCapacity();
  1314. }
  1315. int GetNextIndex()
  1316. {
  1317. return __super::GetNextIndex();
  1318. }
  1319. int GetLastIndex()
  1320. {
  1321. return __super::GetLastIndex();
  1322. }
  1323. using Base::GetValueAt;
  1324. bool TryGetValueAt(int index, TElement * value) const
  1325. {
  1326. return __super::TryGetValueAt(index, value);
  1327. }
  1328. BaseHashSet *Clone()
  1329. {
  1330. return AllocatorNew(AllocatorType, alloc, BaseHashSet, *this);
  1331. }
  1332. void Copy(const BaseHashSet *const other)
  1333. {
  1334. DoCopy(other);
  1335. }
  1336. void LockResize()
  1337. {
  1338. __super::LockResize();
  1339. }
  1340. void UnlockResize()
  1341. {
  1342. __super::UnlockResize();
  1343. }
  1344. public:
  1345. using Base::EntryIterator;
  1346. using Base::BucketEntryIterator;
  1347. friend class Base;
  1348. // The following syntax works in BaseDictionary (where the classes are defined), but not in derived
  1349. // classes such as BaseHashSet
  1350. // template<class TDictionary, class Leaf> friend class IteratorBase;
  1351. // template<class TDictionary> friend class EntryIterator;
  1352. // template<class TDictionary> friend class BucketEntryIterator;
  1353. friend class Base::IteratorBase<const BaseHashSet, EntryIterator<const BaseHashSet>>;
  1354. friend class Base::IteratorBase<const BaseHashSet, BucketEntryIterator<const BaseHashSet>>;
  1355. friend class Base::IteratorBase<BaseHashSet, EntryIterator<BaseHashSet>>;
  1356. friend class Base::IteratorBase<BaseHashSet, BucketEntryIterator<BaseHashSet>>;
  1357. friend class EntryIterator<const BaseHashSet>;
  1358. friend class EntryIterator<BaseHashSet>;
  1359. friend class BucketEntryIterator<const BaseHashSet>;
  1360. friend class BucketEntryIterator<BaseHashSet>;
  1361. PREVENT_ASSIGN(BaseHashSet);
  1362. };
  1363. template <
  1364. class TKey,
  1365. class TValue,
  1366. class TAllocator,
  1367. class SizePolicy = PowerOf2SizePolicy,
  1368. template <typename ValueOrKey> class Comparer = DefaultComparer,
  1369. template <typename K, typename V> class Entry = SimpleDictionaryEntry,
  1370. class LockPolicy = Js::DefaultListLockPolicy, // Controls lock policy for read/map/write/add/remove items
  1371. class SyncObject = CriticalSection
  1372. >
  1373. class SynchronizedDictionary: protected BaseDictionary<TKey, TValue, TAllocator, SizePolicy, Comparer, Entry>
  1374. {
  1375. private:
  1376. SyncObject* syncObj;
  1377. public:
  1378. typedef TKey KeyType;
  1379. typedef TValue ValueType;
  1380. typedef BaseDictionary<TKey, TValue, TAllocator, SizePolicy, Comparer, Entry>::EntryType EntryType;
  1381. typedef SynchronizedDictionary<TKey, TValue, TAllocator, SizePolicy, Comparer, Entry, LockPolicy, SyncObject> DictionaryType;
  1382. private:
  1383. friend class Js::RemoteDictionary<DictionaryType>;
  1384. public:
  1385. SynchronizedDictionary(AllocatorType * allocator, int capacity, SyncObject* syncObject):
  1386. BaseDictionary(allocator, capacity),
  1387. syncObj(syncObject)
  1388. {}
  1389. #ifdef DBG
  1390. void Dump()
  1391. {
  1392. LockPolicy::ReadLock autoLock(syncObj);
  1393. __super::Dump();
  1394. }
  1395. #endif
  1396. TAllocator *GetAllocator() const
  1397. {
  1398. LockPolicy::ReadLock autoLock(syncObj);
  1399. return __super::GetAllocator();
  1400. }
  1401. inline int Count() const
  1402. {
  1403. LockPolicy::ReadLock autoLock(syncObj);
  1404. return __super::Count();
  1405. }
  1406. inline int Capacity() const
  1407. {
  1408. LockPolicy::ReadLock autoLock(syncObj);
  1409. return __super::Capacity();
  1410. }
  1411. TValue Item(const TKey& key)
  1412. {
  1413. LockPolicy::ReadLock autoLock(syncObj);
  1414. return __super::Item(key);
  1415. }
  1416. bool IsInAdd()
  1417. {
  1418. LockPolicy::ReadLock autoLock(syncObj);
  1419. return __super::IsInAdd();
  1420. }
  1421. int Add(const TKey& key, const TValue& value)
  1422. {
  1423. LockPolicy::AddRemoveLock autoLock(syncObj);
  1424. return __super::Add(key, value);
  1425. }
  1426. int AddNew(const TKey& key, const TValue& value)
  1427. {
  1428. LockPolicy::AddRemoveLock autoLock(syncObj);
  1429. return __super::AddNew(key, value);
  1430. }
  1431. int Item(const TKey& key, const TValue& value)
  1432. {
  1433. LockPolicy::AddRemoveLock autoLock(syncObj);
  1434. return __super::Item(key, value);
  1435. }
  1436. bool Contains(KeyValuePair<TKey, TValue> keyValuePair)
  1437. {
  1438. LockPolicy::ReadLock autoLock(syncObj);
  1439. return __super::Contains(keyValuePair);
  1440. }
  1441. bool Remove(KeyValuePair<TKey, TValue> keyValuePair)
  1442. {
  1443. LockPolicy::AddRemoveLock autoLock(syncObj);
  1444. return __super::Remove(keyValuePair);
  1445. }
  1446. void Clear()
  1447. {
  1448. LockPolicy::AddRemoveLock autoLock(syncObj);
  1449. return __super::Clear();
  1450. }
  1451. void Reset()
  1452. {
  1453. LockPolicy::AddRemoveLock autoLock(syncObj);
  1454. return __super::Reset();
  1455. }
  1456. bool ContainsKey(const TKey& key)
  1457. {
  1458. LockPolicy::ReadLock autoLock(syncObj);
  1459. return __super::ContainsKey(key);
  1460. }
  1461. template <typename TLookup>
  1462. inline const TValue& LookupWithKey(const TLookup& key, const TValue& defaultValue)
  1463. {
  1464. LockPolicy::ReadLock autoLock(syncObj);
  1465. return __super::LookupWithKey(key, defaultValue);
  1466. }
  1467. inline const TValue& Lookup(const TKey& key, const TValue& defaultValue)
  1468. {
  1469. LockPolicy::ReadLock autoLock(syncObj);
  1470. return __super::Lookup(key, defaultValue);
  1471. }
  1472. template <typename TLookup>
  1473. bool TryGetValue(const TLookup& key, TValue* value)
  1474. {
  1475. LockPolicy::ReadLock autoLock(syncObj);
  1476. return __super::TryGetValue(key, value);
  1477. }
  1478. bool TryGetValueAndRemove(const TKey& key, TValue* value)
  1479. {
  1480. LockPolicy::AddRemoveLock autoLock(syncObj);
  1481. return __super::TryGetValueAndRemove(key, value);
  1482. }
  1483. template <typename TLookup>
  1484. __inline bool TryGetReference(const TLookup& key, TValue** value)
  1485. {
  1486. LockPolicy::ReadLock autoLock(syncObj);
  1487. return __super::TryGetReference(key, value);
  1488. }
  1489. template <typename TLookup>
  1490. __inline bool TryGetReference(const TLookup& key, TValue** value, int* index)
  1491. {
  1492. LockPolicy::ReadLock autoLock(syncObj);
  1493. return __super::TryGetReference(key, value, index);
  1494. }
  1495. const TValue& GetValueAt(const int& index) const
  1496. {
  1497. LockPolicy::ReadLock autoLock(syncObj);
  1498. return __super::GetValueAt(index);
  1499. }
  1500. TValue* GetReferenceAt(const int& index)
  1501. {
  1502. LockPolicy::ReadLock autoLock(syncObj);
  1503. return __super::GetReferenceAt(index);
  1504. }
  1505. TKey const& GetKeyAt(const int& index)
  1506. {
  1507. LockPolicy::ReadLock autoLock(syncObj);
  1508. return __super::GetKeyAt(index);
  1509. }
  1510. bool Remove(const TKey& key)
  1511. {
  1512. LockPolicy::ReadLock autoLock(syncObj);
  1513. return __super::Remove(key);
  1514. }
  1515. template<class Fn>
  1516. void MapReference(Fn fn)
  1517. {
  1518. // TODO: Verify that Map doesn't actually modify the list
  1519. LockPolicy::ReadLock autoLock(syncObj);
  1520. return __super::MapReference(fn);
  1521. }
  1522. template<class Fn>
  1523. bool MapUntilReference(Fn fn) const
  1524. {
  1525. LockPolicy::ReadLock autoLock(syncObj);
  1526. return __super::MapUntilReference(fn);
  1527. }
  1528. template<class Fn>
  1529. void MapAddress(Fn fn) const
  1530. {
  1531. LockPolicy::ReadLock autoLock(syncObj);
  1532. return __super::MapAddress(fn);
  1533. }
  1534. template<class Fn>
  1535. bool MapUntilAddress(Fn fn) const
  1536. {
  1537. LockPolicy::ReadLock autoLock(syncObj);
  1538. return __super::MapUntilAddress(fn);
  1539. }
  1540. template<class Fn>
  1541. void Map(Fn fn) const
  1542. {
  1543. LockPolicy::ReadLock autoLock(syncObj);
  1544. return __super::Map(fn);
  1545. }
  1546. template<class Fn>
  1547. bool MapUntil(Fn fn) const
  1548. {
  1549. LockPolicy::ReadLock autoLock(syncObj);
  1550. return __super::MapUntil(fn);
  1551. }
  1552. template<class Fn>
  1553. void MapAndRemoveIf(Fn fn)
  1554. {
  1555. LockPolicy::AddRemoveLock autoLock(syncObj);
  1556. return __super::MapAndRemoveIf(fn);
  1557. }
  1558. PREVENT_COPY(SynchronizedDictionary);
  1559. };
  1560. }