BaseDictionary.h 55 KB

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