BaseDictionary.h 55 KB

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