compact_hash.h 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660
  1. #pragma once
  2. #include <yql/essentials/utils/hash.h>
  3. #include "aligned_page_pool.h"
  4. #include "primes.h"
  5. #include <util/generic/vector.h>
  6. #include <util/generic/ptr.h>
  7. #include <util/generic/hash.h>
  8. #include <util/generic/algorithm.h>
  9. #include <util/generic/bitops.h>
  10. #include <util/generic/utility.h>
  11. #include <util/generic/strbuf.h>
  12. #include <util/generic/mem_copy.h>
  13. #include <util/generic/scope.h>
  14. #include <util/system/defaults.h>
  15. #include <util/system/unaligned_mem.h>
  16. #include <util/system/align.h>
  17. #include <util/stream/output.h>
  18. #include <type_traits>
  19. #include <cmath>
  20. #include <array>
  21. // TODO: Allow only PODs in key/value. Use runtime key/value sizes instead of compile time type instantiation. Use Read/WriteUnaligned
  22. namespace NKikimr {
  23. namespace NCHash {
  24. class TListPoolBase {
  25. public:
  26. enum {
  27. SMALL_MARK = 1,
  28. MEDIUM_MARK,
  29. LARGE_MARK,
  30. };
  31. static const size_t MAX_SMALL_LIST_SIZE = 16;
  32. static const size_t MAX_MEDIUM_LIST_INDEX = 10;
  33. public:
  34. struct TPageListItem: public TIntrusiveListItem<TPageListItem> {
  35. template <class T>
  36. T* As() {
  37. return static_cast<T*>(TAlignedPagePool::GetPageStart(this));
  38. }
  39. template <class T>
  40. const T* As() const {
  41. return static_cast<const T*>(TAlignedPagePool::GetPageStart(this));
  42. }
  43. };
  44. struct TListHeader {
  45. ui16 Mark;
  46. ui16 ListSize;
  47. ui16 FreeLists;
  48. ui16 FreeListOffset;
  49. TPageListItem ListItem;
  50. TListHeader(ui16 mark, ui16 listSize, ui16 listCount)
  51. : Mark(mark)
  52. , ListSize(listSize)
  53. , FreeLists(listCount)
  54. , FreeListOffset(0u)
  55. {
  56. Y_ASSERT(ListItem.As<TListHeader>() == this);
  57. *reinterpret_cast<ui16*>(this + 1) = 0u; // Mark first list for initial usage
  58. }
  59. ~TListHeader() {
  60. Mark = 0u; // Reset mark
  61. }
  62. };
  63. struct TLargeListHeader {
  64. ui16 Mark;
  65. ui32 Capacity;
  66. ui32 Size;
  67. TPageListItem ListItem;
  68. TLargeListHeader(ui32 capacity)
  69. : Mark(LARGE_MARK)
  70. , Capacity(capacity)
  71. , Size(0u)
  72. {
  73. Y_ASSERT(ListItem.As<TLargeListHeader>() == this);
  74. }
  75. ~TLargeListHeader() {
  76. Mark = 0u; // Reset mark
  77. }
  78. template <typename T>
  79. T* GetList() {
  80. return reinterpret_cast<T*>(this + 1);
  81. }
  82. template <typename T>
  83. const T* GetList() const {
  84. return reinterpret_cast<const T*>(this + 1);
  85. }
  86. TLargeListHeader* Next() {
  87. return ListItem.Next()->Node()->As<TLargeListHeader>();
  88. }
  89. const TLargeListHeader* Next() const {
  90. return ListItem.Next()->Node()->As<TLargeListHeader>();
  91. }
  92. void Append(TLargeListHeader* header) {
  93. header->ListItem.LinkAfter(ListItem);
  94. }
  95. };
  96. template <typename T, class THeader>
  97. class TListIterator {
  98. using TRawByte = std::conditional_t<std::is_const<T>::value, const ui8*, ui8*>;
  99. public:
  100. using TRaw = std::conditional_t<std::is_const<T>::value, const void*, void*>;
  101. TListIterator() {
  102. }
  103. TListIterator(T* list) {
  104. if (LARGE_MARK == GetMark(list)) {
  105. CurrentPage = EndPage = GetLargeListHeader(list)->Next();
  106. Current = CurrentPage->template GetList<T>();
  107. End = (TRawByte)Current + CurrentPage->Size * sizeof(T);
  108. } else {
  109. Current = list;
  110. End = (TRawByte)Current + GetPartListSize(list) * sizeof(T);
  111. }
  112. }
  113. TListIterator(TRaw start, TRaw end)
  114. : Current(start)
  115. , End(end)
  116. {
  117. }
  118. TListIterator& operator++() {
  119. Y_ASSERT(Ok());
  120. Current = (TRawByte)Current + sizeof(T);
  121. if (Current == End) {
  122. if (CurrentPage) {
  123. CurrentPage = CurrentPage->Next();
  124. if (CurrentPage != EndPage) {
  125. Current = (TRaw)CurrentPage->template GetList<T>();
  126. End = (TRawByte)Current + CurrentPage->Size * sizeof(T);
  127. } else {
  128. CurrentPage = EndPage = nullptr;
  129. Current = End = nullptr;
  130. }
  131. } else {
  132. Current = End = nullptr;
  133. }
  134. }
  135. return *this;
  136. }
  137. bool operator ==(const TListIterator& it) const {
  138. return Current == it.Current && CurrentPage == it.CurrentPage;
  139. }
  140. bool operator !=(const TListIterator& it) const {
  141. return !operator ==(it);
  142. }
  143. T Get() const {
  144. using TClean = typename std::remove_cv<T>::type;
  145. return ::ReadUnaligned<TClean>(Current);
  146. }
  147. void Set(T val) const {
  148. ::WriteUnaligned<T>(Current, val);
  149. }
  150. TRaw GetRaw() const {
  151. return Current;
  152. }
  153. bool Ok() const {
  154. return Current != nullptr;
  155. }
  156. private:
  157. TRaw Current = nullptr;
  158. TRaw End = nullptr;
  159. THeader* CurrentPage = nullptr;
  160. THeader* EndPage = nullptr;
  161. };
  162. public:
  163. static inline TListHeader* GetListHeader(void* addr) {
  164. TListHeader* header = reinterpret_cast<TListHeader*>(TAlignedPagePool::GetPageStart(addr));
  165. Y_ASSERT(SMALL_MARK == header->Mark || MEDIUM_MARK == header->Mark);
  166. return header;
  167. }
  168. static inline const TListHeader* GetListHeader(const void* addr) {
  169. const TListHeader* header = reinterpret_cast<const TListHeader*>(TAlignedPagePool::GetPageStart(addr));
  170. Y_ASSERT(SMALL_MARK == header->Mark || MEDIUM_MARK == header->Mark);
  171. return header;
  172. }
  173. static inline TLargeListHeader* GetLargeListHeader(void* addr) {
  174. TLargeListHeader* header = reinterpret_cast<TLargeListHeader*>(TAlignedPagePool::GetPageStart(addr));
  175. Y_ASSERT(LARGE_MARK == header->Mark);
  176. return header;
  177. }
  178. static inline const TLargeListHeader* GetLargeListHeader(const void* addr) {
  179. const TLargeListHeader* header = reinterpret_cast<const TLargeListHeader*>(TAlignedPagePool::GetPageStart(addr));
  180. Y_ASSERT(LARGE_MARK == header->Mark);
  181. return header;
  182. }
  183. template <typename T>
  184. static inline constexpr ui16 GetSmallPageCapacity(size_t listSize) {
  185. // Always keep at least ui16 per list in order to track collection free lists
  186. return static_cast<ui16>((TAlignedPagePool::POOL_PAGE_SIZE - sizeof(TListHeader)) / (AlignUp<size_t>(listSize * sizeof(T), sizeof(ui16)))) & 0x7FFF;
  187. }
  188. template <typename T>
  189. static inline constexpr ui16 GetMediumPageCapacity(size_t listSize) {
  190. return static_cast<ui16>((TAlignedPagePool::POOL_PAGE_SIZE - sizeof(TListHeader)) / (FastClp2(listSize) * sizeof(T) + sizeof(ui16))) & 0x7FFF;
  191. }
  192. template <typename T>
  193. static inline constexpr ui32 GetLargePageCapacity() {
  194. return static_cast<ui32>((TAlignedPagePool::POOL_PAGE_SIZE - sizeof(TLargeListHeader)) / sizeof(T));
  195. }
  196. template <typename T>
  197. static inline constexpr size_t GetMaxListSize() {
  198. #define NCHASH_RAW_SIZE ((((TAlignedPagePool::POOL_PAGE_SIZE - sizeof(TListHeader)) / 2) - sizeof(ui16)) / sizeof(T))
  199. // For medium lists get downward pow2 num
  200. return NCHASH_RAW_SIZE > 16 ? 1ULL << MostSignificantBitCT(NCHASH_RAW_SIZE) : NCHASH_RAW_SIZE;
  201. #undef NCHASH_RAW_SIZE
  202. }
  203. protected:
  204. using TListType = TIntrusiveList<TPageListItem>;
  205. struct TUsedPages {
  206. TUsedPages() = default;
  207. TUsedPages(const TUsedPages&) = delete;
  208. TUsedPages(TUsedPages&& other)
  209. : SmallPages(std::move(other.SmallPages))
  210. , MediumPages(std::move(other.MediumPages))
  211. , FullPages(std::move(other.FullPages))
  212. {
  213. }
  214. TUsedPages& operator =(const TUsedPages& other) = delete;
  215. TUsedPages& operator =(TUsedPages&& other) {
  216. TUsedPages(std::move(other)).Swap(*this);
  217. return *this;
  218. }
  219. void Swap(TUsedPages& other) {
  220. DoSwap(SmallPages, other.SmallPages);
  221. DoSwap(MediumPages, other.MediumPages);
  222. DoSwap(FullPages, other.FullPages);
  223. }
  224. // Returns count of used pages
  225. size_t PrintStat(const TStringBuf& header, IOutputStream& out) const;
  226. TString DebugInfo() const;
  227. std::array<TListType, MAX_SMALL_LIST_SIZE - 1> SmallPages; // 2-16 sizes
  228. std::array<TListType, MAX_MEDIUM_LIST_INDEX> MediumPages; // 32,64,128,...,16384. Indexed by pow2
  229. TListType FullPages;
  230. };
  231. public:
  232. TListPoolBase(TAlignedPagePool& pagePool)
  233. : PagePool_(pagePool)
  234. {}
  235. TListPoolBase(const TListPoolBase&) = delete;
  236. TListPoolBase(TListPoolBase&& other)
  237. : PagePool_(other.PagePool_)
  238. {
  239. }
  240. TListPoolBase& operator =(const TListPoolBase& other) = delete;
  241. TListPoolBase& operator =(TListPoolBase&& other) {
  242. PagePool_.Swap(other.PagePool_);
  243. return *this;
  244. }
  245. void Swap(TListPoolBase& other) {
  246. PagePool_.Swap(other.PagePool_);
  247. }
  248. TAlignedPagePool& GetPagePool() const {
  249. return PagePool_;
  250. }
  251. // Returns full list size for short and medium lists. Returns size of last page for a large list
  252. static size_t GetPartListSize(const void* list) {
  253. switch (GetMark(list)) {
  254. case SMALL_MARK:
  255. return GetListHeader(list)->ListSize;
  256. case MEDIUM_MARK:
  257. return *(reinterpret_cast<const ui16*>(list) - 1);
  258. case LARGE_MARK:
  259. return GetLargeListHeader(list)->Size;
  260. default:
  261. Y_ABORT("Bad list address");
  262. }
  263. return 0;
  264. }
  265. static size_t GetFullListSize(const void* list) {
  266. switch (GetMark(list)) {
  267. case SMALL_MARK:
  268. return GetListHeader(list)->ListSize;
  269. case MEDIUM_MARK:
  270. return *(reinterpret_cast<const ui16*>(list) - 1);
  271. case LARGE_MARK:
  272. {
  273. const TLargeListHeader* start = GetLargeListHeader(list);
  274. const TLargeListHeader* next = start;
  275. size_t size = 0;
  276. do {
  277. size += next->Size;
  278. next = next->Next();
  279. } while (next != start);
  280. return size;
  281. }
  282. default:
  283. Y_ABORT("Bad list address");
  284. }
  285. return 0;
  286. }
  287. static size_t GetListCapacity(const void* list) {
  288. switch (GetMark(list)) {
  289. case SMALL_MARK:
  290. case MEDIUM_MARK:
  291. return GetListHeader(list)->ListSize;
  292. case LARGE_MARK:
  293. return GetLargeListHeader(list)->Capacity;
  294. default:
  295. Y_ABORT("Bad list address");
  296. }
  297. return 0;
  298. }
  299. static void SetPartListSize(void* list, size_t size) {
  300. switch (GetMark(list)) {
  301. case MEDIUM_MARK:
  302. *(reinterpret_cast<ui16*>(list) - 1) = size;
  303. break;
  304. case LARGE_MARK:
  305. GetLargeListHeader(list)->Size = size;
  306. break;
  307. default:
  308. Y_ABORT("Bad list address");
  309. }
  310. }
  311. static inline ui16 GetMark(const void* addr) {
  312. return *reinterpret_cast<const ui16*>(TAlignedPagePool::GetPageStart(addr));
  313. }
  314. protected:
  315. void FreeListPage(TListHeader* p);
  316. private:
  317. TAlignedPagePool& PagePool_;
  318. };
  319. template <typename TPrimary, typename TSecondary = TPrimary>
  320. class TListPool: public TListPoolBase {
  321. private:
  322. static constexpr size_t PoolCount = 1 + !std::is_same<TPrimary, TSecondary>::value;
  323. public:
  324. TListPool(TAlignedPagePool& pagePool)
  325. : TListPoolBase(pagePool)
  326. {}
  327. TListPool(const TListPool&) = delete;
  328. TListPool(TListPool&& other)
  329. : TListPoolBase(std::move(other))
  330. , Pools(std::move(other.Pools))
  331. {
  332. }
  333. ~TListPool() {
  334. for (auto& p: Pools) {
  335. for (auto& list: p.SmallPages) {
  336. Y_ABORT_UNLESS(list.Empty(), "%s", DebugInfo().data());
  337. }
  338. for (auto& list: p.MediumPages) {
  339. Y_ABORT_UNLESS(list.Empty(), "%s", DebugInfo().data());
  340. }
  341. Y_ABORT_UNLESS(p.FullPages.Empty(), "%s", DebugInfo().data());
  342. }
  343. }
  344. TListPool& operator =(const TListPool& other) = delete;
  345. TListPool& operator =(TListPool&& other) {
  346. TListPool(std::move(other)).Swap(*this);
  347. return *this;
  348. }
  349. template <typename T>
  350. T* GetList(size_t size) {
  351. static_assert(std::is_same<TPrimary, T>::value || std::is_same<TSecondary, T>::value, "Bad requested list type");
  352. static constexpr size_t PoolNdx = static_cast<size_t>(!std::is_same<TPrimary, T>::value);
  353. Y_ABORT_UNLESS(size >= 2);
  354. T* res = nullptr;
  355. if (Y_LIKELY(size <= TListPoolBase::GetMaxListSize<T>())) {
  356. if (Y_LIKELY(size <= MAX_SMALL_LIST_SIZE)) {
  357. res = GetSmallList<PoolNdx, T>(GetSmallListPage<PoolNdx, T>(size));
  358. } else {
  359. res = GetMediumList<PoolNdx, T>(GetMediumListPage<PoolNdx, T>(size), size);
  360. }
  361. }
  362. return res;
  363. }
  364. // Returns pointer to the new element
  365. template <typename T>
  366. T* IncrementList(T*& list) {
  367. size_t oldSize = TListPoolBase::GetPartListSize(list);
  368. if (oldSize + 1 <= TListPoolBase::GetListCapacity(list)) {
  369. TListPoolBase::SetPartListSize(list, oldSize + 1);
  370. return list + oldSize;
  371. }
  372. TLargeListHeader* header = nullptr;
  373. T* oldList = list;
  374. if (Y_LIKELY(LARGE_MARK != GetMark(oldList))) {
  375. list = GetList<T>(oldSize + 1);
  376. if (nullptr == list) {
  377. // Convert to large list
  378. header = GetLargeListPage<T>();
  379. list = header->GetList<T>();
  380. Y_ABORT_UNLESS(header->Capacity >= oldSize);
  381. header->Size = oldSize;
  382. }
  383. if (std::is_trivially_copyable<T>::value) {
  384. memcpy(list, oldList, sizeof(T) * oldSize);
  385. } else {
  386. for (size_t i = 0; i < oldSize; ++i) {
  387. ::WriteUnaligned<T>(list + i, ::ReadUnaligned<T>(oldList + i));
  388. }
  389. }
  390. ReturnList(oldList);
  391. if (nullptr == header) {
  392. return list + oldSize;
  393. } else if (header->Size < header->Capacity) {
  394. return header->GetList<T>() + header->Size++;
  395. }
  396. } else {
  397. header = GetLargeListHeader(list);
  398. }
  399. // Add new page to large list
  400. TLargeListHeader* newPage = GetLargeListPage<T>();
  401. ++newPage->Size;
  402. list = newPage->GetList<T>();
  403. header->Append(newPage);
  404. return list;
  405. }
  406. template <typename T>
  407. T* CloneList(const T* list) {
  408. if (Y_LIKELY(LARGE_MARK != GetMark(list))) {
  409. const size_t size = TListPoolBase::GetPartListSize(list);
  410. T* clonedList = GetList<T>(size);
  411. for (size_t i = 0; i < size; ++i) {
  412. new (clonedList + i) T(list[i]);
  413. }
  414. return clonedList;
  415. } else {
  416. TLargeListHeader* lastListHeader = nullptr;
  417. const TLargeListHeader* start = GetLargeListHeader(list)->Next();
  418. const TLargeListHeader* header = start;
  419. do {
  420. TLargeListHeader* newHeader = GetLargeListPage<T>();
  421. newHeader->Size = header->Size;
  422. T* newList = newHeader->GetList<T>();
  423. const T* list = header->GetList<T>();
  424. for (size_t i = 0; i < header->Size; ++i) {
  425. new (newList + i) T(list[i]);
  426. }
  427. if (lastListHeader) {
  428. lastListHeader->Append(newHeader);
  429. }
  430. lastListHeader = newHeader;
  431. header = header->Next();
  432. } while (header != start);
  433. return lastListHeader->GetList<T>();
  434. }
  435. }
  436. template <typename T>
  437. void ReturnList(T* list) {
  438. static_assert(std::is_same<TPrimary, T>::value || std::is_same<TSecondary, T>::value, "Bad returned list type");
  439. static constexpr size_t PoolNdx = static_cast<size_t>(!std::is_same<TPrimary, T>::value);
  440. switch (GetMark(list)) {
  441. case SMALL_MARK:
  442. ReturnSmallList<PoolNdx, T>(GetListHeader(list), list);
  443. break;
  444. case MEDIUM_MARK:
  445. ReturnMediumList<PoolNdx, T>(GetListHeader(list), list);
  446. break;
  447. case LARGE_MARK:
  448. ReturnLargeList<T>(list);
  449. break;
  450. default:
  451. Y_ABORT("Bad list address");
  452. }
  453. }
  454. void Swap(TListPool& other) {
  455. TListPoolBase::Swap(other);
  456. DoSwap(Pools, other.Pools);
  457. }
  458. void PrintStat(IOutputStream& out) const {
  459. size_t usedPages = 0;
  460. if (std::is_same<TPrimary, TSecondary>::value) {
  461. usedPages = Pools[0].PrintStat(TStringBuf(""), out);
  462. } else {
  463. usedPages = Pools[0].PrintStat(TStringBuf("Primary: "), out) + Pools[1].PrintStat(TStringBuf("Secondary: "), out);
  464. }
  465. GetPagePool().PrintStat(usedPages, out);
  466. }
  467. TString DebugInfo() const {
  468. if (std::is_same<TPrimary, TSecondary>::value) {
  469. return Pools[0].DebugInfo();
  470. } else {
  471. return TString().append("Primary:\n").append(Pools[0].DebugInfo()).append("Secondary:\n").append(Pools[1].DebugInfo());
  472. }
  473. }
  474. private:
  475. template <typename T>
  476. static void DestroyRange(T* s, T* e) {
  477. if (!std::is_trivially_destructible<T>::value) {
  478. while (s != e) {
  479. --e;
  480. e->~T();
  481. }
  482. }
  483. }
  484. template <size_t PoolNdx, typename T>
  485. TListHeader* GetSmallListPage(size_t size) {
  486. Y_ASSERT(size > 1 && size <= MAX_SMALL_LIST_SIZE);
  487. TListType& pages = Pools[PoolNdx].SmallPages[size - 2];
  488. if (!pages.Empty()) {
  489. return pages.Front()->As<TListHeader>();
  490. }
  491. ui16 listCount = GetSmallPageCapacity<T>(size);
  492. Y_ASSERT(listCount >= 2);
  493. TListHeader* header = new (GetPagePool().GetPage()) TListHeader(SMALL_MARK, size, listCount);
  494. pages.PushFront(&header->ListItem);
  495. return header;
  496. }
  497. template <size_t PoolNdx, typename T>
  498. TListHeader* GetMediumListPage(size_t size) {
  499. Y_ASSERT(size > MAX_SMALL_LIST_SIZE && size <= TListPoolBase::GetMaxListSize<T>());
  500. size_t index = MostSignificantBit((size - 1) >> MostSignificantBitCT(MAX_SMALL_LIST_SIZE));
  501. Y_ASSERT(index < Pools[PoolNdx].MediumPages.size());
  502. TListType& pages = Pools[PoolNdx].MediumPages[index];
  503. if (!pages.Empty()) {
  504. return pages.Front()->As<TListHeader>();
  505. }
  506. ui16 listCapacity = FastClp2(size);
  507. ui16 listCount = GetMediumPageCapacity<T>(listCapacity);
  508. Y_ASSERT(listCount >= 2);
  509. TListHeader* header = new (GetPagePool().GetPage()) TListHeader(MEDIUM_MARK, listCapacity, listCount);
  510. pages.PushFront(&header->ListItem);
  511. return header;
  512. }
  513. template <typename T>
  514. TLargeListHeader* GetLargeListPage() {
  515. TLargeListHeader* const header = new (GetPagePool().GetPage()) TLargeListHeader(GetLargePageCapacity<T>());
  516. return header;
  517. }
  518. template <size_t PoolNdx, typename T>
  519. T* GetSmallList(TListHeader* listHeader) {
  520. if (0 == listHeader->FreeLists) {
  521. return nullptr;
  522. }
  523. const bool last = (0 == --listHeader->FreeLists);
  524. // Always keep at least ui16 per list in order to track collection of free lists
  525. const size_t byteListSize = AlignUp<size_t>(sizeof(T) * listHeader->ListSize, sizeof(ui16));
  526. ui16* l = reinterpret_cast<ui16*>(reinterpret_cast<ui8*>(listHeader + 1) + byteListSize * listHeader->FreeListOffset);
  527. // Distinguish first (0) and repeatedly (0x8000u) used lists
  528. if ((*l) & 0x8000u) {
  529. listHeader->FreeListOffset = ((*l) & 0x7FFF);
  530. } else {
  531. ++listHeader->FreeListOffset;
  532. if (!last) {
  533. // Mark next free list as first used
  534. *reinterpret_cast<ui16*>(reinterpret_cast<ui8*>(listHeader + 1) + byteListSize * listHeader->FreeListOffset) = 0u;
  535. }
  536. }
  537. if (last) {
  538. listHeader->ListItem.Unlink();
  539. Pools[PoolNdx].FullPages.PushBack(&listHeader->ListItem);
  540. }
  541. return reinterpret_cast<T*>(l);
  542. }
  543. template <size_t PoolNdx, typename T>
  544. T* GetMediumList(TListHeader* listHeader, size_t size) {
  545. if (0 == listHeader->FreeLists) {
  546. return nullptr;
  547. }
  548. const bool last = (0 == --listHeader->FreeLists);
  549. const size_t byteListSize = sizeof(T) * listHeader->ListSize + sizeof(ui16);
  550. ui16* l = reinterpret_cast<ui16*>(reinterpret_cast<ui8*>(listHeader + 1) + byteListSize * listHeader->FreeListOffset);
  551. // Distinguish first (0) and repeatedly (0x8000u) used lists
  552. if ((*l) & 0x8000u) {
  553. listHeader->FreeListOffset = ((*l) & 0x7FFF);
  554. } else {
  555. ++listHeader->FreeListOffset;
  556. if (!last) {
  557. // Mark next free list as first used
  558. *reinterpret_cast<ui16*>(reinterpret_cast<ui8*>(listHeader + 1) + byteListSize * listHeader->FreeListOffset) = 0u;
  559. }
  560. }
  561. if (last) {
  562. listHeader->ListItem.Unlink();
  563. Pools[PoolNdx].FullPages.PushBack(&listHeader->ListItem);
  564. }
  565. // For medium pages store the list size ahead
  566. *l = size;
  567. ++l;
  568. return reinterpret_cast<T*>(l);
  569. }
  570. template <size_t PoolNdx, typename T>
  571. void ReturnSmallList(TListHeader* listHeader, T* list) {
  572. DestroyRange(list, list + listHeader->ListSize);
  573. const size_t byteListSize = AlignUp<size_t>(sizeof(T) * listHeader->ListSize, sizeof(ui16));
  574. Y_ASSERT((reinterpret_cast<ui8*>(list) - reinterpret_cast<ui8*>(listHeader + 1)) % byteListSize == 0);
  575. const ui64 offset = (reinterpret_cast<ui8*>(list) - reinterpret_cast<ui8*>(listHeader + 1)) / byteListSize;
  576. Y_ASSERT(offset < TAlignedPagePool::POOL_PAGE_SIZE);
  577. *reinterpret_cast<ui16*>(list) = listHeader->FreeListOffset | 0x8000u;
  578. listHeader->FreeListOffset = offset;
  579. ++listHeader->FreeLists;
  580. if (1 == listHeader->FreeLists) {
  581. listHeader->ListItem.Unlink(); // Remove from full list
  582. Pools[PoolNdx].SmallPages[listHeader->ListSize - 2].PushFront(&listHeader->ListItem); // Add to partially used
  583. } else if (GetSmallPageCapacity<T>(listHeader->ListSize) == listHeader->FreeLists) {
  584. listHeader->ListItem.Unlink(); // Remove from partially used
  585. FreeListPage(listHeader);
  586. }
  587. }
  588. template <size_t PoolNdx, typename T>
  589. void ReturnMediumList(TListHeader* listHeader, T* list) {
  590. ui16* l = reinterpret_cast<ui16*>(list) - 1;
  591. DestroyRange(list, list + *l);
  592. Y_ASSERT((reinterpret_cast<ui8*>(l) - reinterpret_cast<ui8*>(listHeader + 1)) % (listHeader->ListSize * sizeof(T) + sizeof(ui16)) == 0);
  593. ui64 offset = (reinterpret_cast<ui8*>(l) - reinterpret_cast<ui8*>(listHeader + 1)) / (listHeader->ListSize * sizeof(T) + sizeof(ui16));
  594. Y_ASSERT(offset < TAlignedPagePool::POOL_PAGE_SIZE);
  595. *l = listHeader->FreeListOffset | 0x8000u;
  596. listHeader->FreeListOffset = offset;
  597. ++listHeader->FreeLists;
  598. if (1 == listHeader->FreeLists) {
  599. listHeader->ListItem.Unlink(); // Remove from full list
  600. const size_t index = MostSignificantBit((listHeader->ListSize - 1) >> MostSignificantBitCT(MAX_SMALL_LIST_SIZE));
  601. Y_ASSERT(index < Pools[PoolNdx].MediumPages.size());
  602. Pools[PoolNdx].MediumPages[index].PushFront(&listHeader->ListItem); // Add to partially used
  603. } else if (GetMediumPageCapacity<T>(listHeader->ListSize) == listHeader->FreeLists) {
  604. listHeader->ListItem.Unlink(); // Remove from partially used
  605. FreeListPage(listHeader);
  606. }
  607. }
  608. template <typename T>
  609. void ReturnLargeList(T* list) {
  610. TLargeListHeader* header = GetLargeListHeader(list);
  611. while (!header->ListItem.Empty()) {
  612. TLargeListHeader* next = header->Next();
  613. DestroyRange(next->GetList<T>(), next->GetList<T>() + next->Size);
  614. next->ListItem.Unlink();
  615. next->~TLargeListHeader();
  616. GetPagePool().ReturnPage(next);
  617. }
  618. DestroyRange(header->GetList<T>(), header->GetList<T>() + header->Size);
  619. header->~TLargeListHeader();
  620. GetPagePool().ReturnPage(header);
  621. }
  622. protected:
  623. std::array<TUsedPages, PoolCount> Pools;
  624. };
  625. #pragma pack(push, 1)
  626. template <typename T>
  627. struct TNode {
  628. enum {
  629. FlagEmpty = 0,
  630. FlagSingle = 1,
  631. FlagList = 2,
  632. };
  633. ui8 Flag;
  634. union {
  635. ui8 D1;
  636. ui8 D2[Max<size_t>(sizeof(T), sizeof(T*))];
  637. } Storage;
  638. TNode()
  639. : Flag(FlagEmpty)
  640. {
  641. }
  642. TNode(const TNode& n)
  643. : Flag(n.Flag)
  644. {
  645. MemCopy(Storage.D2, n.Storage.D2, sizeof(Storage.D2));
  646. }
  647. TNode(TNode&& n)
  648. : Flag(n.Flag)
  649. {
  650. MemCopy(Storage.D2, n.Storage.D2, sizeof(Storage.D2));
  651. n.Flag = FlagEmpty;
  652. }
  653. TNode& operator=(const TNode& n) {
  654. Flag = n.Flag;
  655. MemCopy(Storage.D2, n.Storage.D2, sizeof(Storage.D2));
  656. return *this;
  657. }
  658. TListPoolBase::TListIterator<T, TListPoolBase::TLargeListHeader> Iter() {
  659. if (FlagSingle == Flag) {
  660. return TListPoolBase::TListIterator<T, TListPoolBase::TLargeListHeader>(reinterpret_cast<T*>(&Storage), reinterpret_cast<T*>(&Storage) + 1);
  661. } else if (FlagList == Flag) {
  662. return TListPoolBase::TListIterator<T, TListPoolBase::TLargeListHeader>(*reinterpret_cast<T**>(&Storage));
  663. }
  664. return TListPoolBase::TListIterator<T, TListPoolBase::TLargeListHeader>();
  665. }
  666. TListPoolBase::TListIterator<const T, const TListPoolBase::TLargeListHeader> Iter() const {
  667. if (FlagSingle == Flag) {
  668. return TListPoolBase::TListIterator<const T, const TListPoolBase::TLargeListHeader>(reinterpret_cast<const T*>(&Storage), reinterpret_cast<const T*>(&Storage) + 1);
  669. } else if (FlagList == Flag) {
  670. return TListPoolBase::TListIterator<const T, const TListPoolBase::TLargeListHeader>(*reinterpret_cast<const T* const*>(&Storage));
  671. }
  672. return TListPoolBase::TListIterator<const T, const TListPoolBase::TLargeListHeader>();
  673. }
  674. void Set(T val) {
  675. Flag = FlagSingle;
  676. ::WriteUnaligned<T>(&Storage, val);
  677. }
  678. void SetList(T* list) {
  679. Flag = FlagList;
  680. ::WriteUnaligned<T*>(&Storage, list);
  681. }
  682. T Get() const {
  683. Y_ABORT_UNLESS(FlagSingle == Flag);
  684. return ::ReadUnaligned<T>(&Storage);
  685. }
  686. T* GetList() {
  687. Y_ABORT_UNLESS(FlagList == Flag);
  688. return *reinterpret_cast<T**>(&Storage);
  689. }
  690. const T* GetList() const {
  691. Y_ABORT_UNLESS(FlagList == Flag);
  692. return *reinterpret_cast<const T* const*>(&Storage);
  693. }
  694. size_t Size() const {
  695. if (FlagEmpty == Flag) {
  696. return 0;
  697. } else if (FlagSingle == Flag) {
  698. return 1;
  699. } else {
  700. return TListPoolBase::GetFullListSize(GetList());
  701. }
  702. }
  703. void Clear() {
  704. if (FlagSingle == Flag) {
  705. reinterpret_cast<T*>(&Storage)->~T();
  706. }
  707. Flag = FlagEmpty;
  708. }
  709. };
  710. template <typename TKey, typename TValue>
  711. struct TKeyValuePair {
  712. using first_type = TKey;
  713. using second_type = TValue;
  714. TKeyValuePair() = default;
  715. TKeyValuePair(const TKeyValuePair&) = default;
  716. TKeyValuePair(TKeyValuePair&&) = default;
  717. TKeyValuePair(const std::pair<TKey, TValue>& p)
  718. : first(p.first)
  719. , second(p.second)
  720. {
  721. }
  722. TKeyValuePair(const TKey& k, const TValue& v)
  723. : first(k)
  724. , second(v)
  725. {
  726. }
  727. TKeyValuePair(TKey&& k, const TValue& v)
  728. : first(std::move(k))
  729. , second(v)
  730. {
  731. }
  732. TKeyValuePair(const TKey& k, TValue&& v)
  733. : first(k)
  734. , second(std::move(v))
  735. {
  736. }
  737. TKeyValuePair(TKey&& k, TValue&& v)
  738. : first(std::move(k))
  739. , second(std::move(v))
  740. {
  741. }
  742. TKeyValuePair& operator =(const TKeyValuePair&) = default;
  743. TKeyValuePair& operator =(TKeyValuePair&&) = default;
  744. TKey first;
  745. TValue second;
  746. };
  747. template <typename TKey, typename TValue>
  748. using TKeyNodePair = TKeyValuePair<TKey, TNode<TValue>>;
  749. #pragma pack(pop)
  750. template <typename TItemType,
  751. typename TKeyType,
  752. typename TKeyExtractor,
  753. typename TKeyHash,
  754. typename TKeyEqual,
  755. typename TSubItemType = TItemType
  756. >
  757. class TCompactHashBase {
  758. protected:
  759. using TItemNode = TNode<TItemType>;
  760. static_assert(sizeof(TItemNode) == 1 + Max<size_t>(sizeof(TItemType), sizeof(void*)), "Unexpected size");
  761. public:
  762. template <typename T>
  763. class TIteratorImpl {
  764. friend class TCompactHashBase;
  765. using TBucketIter = TListPoolBase::TListIterator<const T, const TListPoolBase::TLargeListHeader>;
  766. // Full scan iterator
  767. TIteratorImpl(const TCompactHashBase* hash)
  768. : Hash(hash)
  769. , Bucket(0)
  770. , EndBucket(Hash->BucketsCount_)
  771. , Pos()
  772. {
  773. for (; Bucket < EndBucket; ++Bucket) {
  774. if (!Hash->IsEmptyBucket(Bucket)) {
  775. Pos = Hash->GetBucketIter(Bucket);
  776. break;
  777. }
  778. }
  779. }
  780. // Key iterator
  781. TIteratorImpl(const TCompactHashBase* hash, size_t bucket, const TBucketIter& pos)
  782. : Hash(hash)
  783. , Bucket(bucket)
  784. , EndBucket(bucket + 1)
  785. , Pos(pos)
  786. {
  787. }
  788. // Empty iterator
  789. TIteratorImpl() {
  790. }
  791. public:
  792. TIteratorImpl& operator=(const TIteratorImpl& rhs) {
  793. Hash = rhs.Hash;
  794. Bucket = rhs.Bucket;
  795. EndBucket = rhs.EndBucket;
  796. Pos = rhs.Pos;
  797. return *this;
  798. }
  799. bool Ok() const {
  800. return Bucket < EndBucket && Pos.Ok();
  801. }
  802. TIteratorImpl& operator++() {
  803. if (Bucket < EndBucket) {
  804. if ((++Pos).Ok()) {
  805. return *this;
  806. }
  807. for (++Bucket; Bucket < EndBucket; ++Bucket) {
  808. if (!Hash->IsEmptyBucket(Bucket)) {
  809. Pos = Hash->GetBucketIter(Bucket);
  810. break;
  811. }
  812. }
  813. }
  814. return *this;
  815. }
  816. T operator*() const {
  817. Y_ASSERT(Ok());
  818. return Pos.Get();
  819. }
  820. T Get() const {
  821. Y_ASSERT(Ok());
  822. return Pos.Get();
  823. }
  824. TIteratorImpl MakeCurrentKeyIter() const {
  825. Y_ASSERT(Ok());
  826. return TIteratorImpl(Hash, Bucket, TBucketIter(Pos.GetRaw(), Pos.GetRaw() + sizeof(T)));
  827. }
  828. private:
  829. const TCompactHashBase* Hash = nullptr;
  830. size_t Bucket = 0;
  831. size_t EndBucket = 0;
  832. TBucketIter Pos;
  833. };
  834. template <typename T>
  835. class TIteratorImpl<TKeyNodePair<TKeyType, T>> {
  836. friend class TCompactHashBase;
  837. using TBucketIter = TListPoolBase::TListIterator<const TKeyNodePair<TKeyType, T>, const TListPoolBase::TLargeListHeader>;
  838. using TValueIter = TListPoolBase::TListIterator<const T, const TListPoolBase::TLargeListHeader>;
  839. // Full scan iterator
  840. TIteratorImpl(const TCompactHashBase* hash)
  841. : Hash(hash)
  842. , Bucket(0)
  843. , EndBucket(Hash->BucketsCount_)
  844. {
  845. for (; Bucket < EndBucket; ++Bucket) {
  846. if (!Hash->IsEmptyBucket(Bucket)) {
  847. Pos = Hash->GetBucketIter(Bucket);
  848. SubPos = static_cast<const TKeyNodePair<TKeyType, T>*>(Pos.GetRaw())->second.Iter();
  849. break;
  850. }
  851. }
  852. }
  853. // Key iterator
  854. TIteratorImpl(const TCompactHashBase* hash, size_t bucket, const TBucketIter& pos)
  855. : Hash(hash)
  856. , Bucket(bucket)
  857. , EndBucket(bucket + 1)
  858. , Pos(pos)
  859. , SubPos(static_cast<const TKeyNodePair<TKeyType, T>*>(Pos.GetRaw())->second.Iter())
  860. {
  861. }
  862. // Empty iterator
  863. TIteratorImpl() {
  864. }
  865. public:
  866. bool Ok() const {
  867. return Bucket < EndBucket;
  868. }
  869. TIteratorImpl& operator++() {
  870. return Shift(false);
  871. }
  872. TIteratorImpl& NextKey() {
  873. return Shift(true);
  874. }
  875. TKeyType GetKey() const {
  876. Y_ASSERT(Ok());
  877. return Pos.Get().first;
  878. }
  879. T GetValue() const {
  880. Y_ASSERT(Ok());
  881. return SubPos.Get();
  882. }
  883. T operator*() const {
  884. return GetValue();
  885. }
  886. TIteratorImpl MakeCurrentKeyIter() const {
  887. Y_ASSERT(Ok());
  888. return TIteratorImpl(Hash, Bucket, TBucketIter(Pos.GetRaw(), static_cast<const ui8*>(Pos.GetRaw()) + sizeof(TKeyNodePair<TKeyType, T>)));
  889. }
  890. private:
  891. TIteratorImpl& Shift(bool nextKey) {
  892. Y_ASSERT(Bucket < EndBucket);
  893. Y_ASSERT(SubPos.Ok());
  894. if (!nextKey && (++SubPos).Ok()) {
  895. return *this;
  896. }
  897. Y_ASSERT(Pos.Ok());
  898. if ((++Pos).Ok()) {
  899. SubPos = static_cast<const TKeyNodePair<TKeyType, T>*>(Pos.GetRaw())->second.Iter();
  900. return *this;
  901. } else {
  902. SubPos = TValueIter();
  903. }
  904. for (++Bucket; Bucket < EndBucket; ++Bucket) {
  905. if (!Hash->IsEmptyBucket(Bucket)) {
  906. Pos = Hash->GetBucketIter(Bucket);
  907. SubPos = static_cast<const TKeyNodePair<TKeyType, T>*>(Pos.GetRaw())->second.Iter();
  908. break;
  909. }
  910. }
  911. return *this;
  912. }
  913. private:
  914. const TCompactHashBase* Hash = nullptr;
  915. size_t Bucket = 0;
  916. size_t EndBucket = 0;
  917. TBucketIter Pos;
  918. TValueIter SubPos;
  919. };
  920. public:
  921. using TIterator = TIteratorImpl<TItemType>;
  922. using TBucketIterator = TListPoolBase::TListIterator<TItemType, TListPoolBase::TLargeListHeader>;
  923. using TConstBucketIterator = TListPoolBase::TListIterator<const TItemType, const TListPoolBase::TLargeListHeader>;
  924. TCompactHashBase(TAlignedPagePool& pagePool, size_t size = 0, const TKeyExtractor& keyExtractor = TKeyExtractor(),
  925. const TKeyHash& keyHash = TKeyHash(), const TKeyEqual& keyEqual = TKeyEqual())
  926. : ListPool_(pagePool)
  927. , KeyExtractor_(keyExtractor)
  928. , KeyHash_(keyHash)
  929. , KeyEqual_(keyEqual)
  930. {
  931. AllocateBuckets(FindNearestPrime(size));
  932. }
  933. TCompactHashBase(const TCompactHashBase& other)
  934. : Size_(other.Size_)
  935. , UniqSize_(other.UniqSize_)
  936. , MaxLoadFactor_(other.MaxLoadFactor_)
  937. , ListPool_(other.ListPool_.GetPagePool())
  938. , KeyExtractor_(other.KeyExtractor_)
  939. , KeyHash_(other.KeyHash_)
  940. , KeyEqual_(other.KeyEqual_)
  941. {
  942. AllocateBuckets(other.BucketsCount_);
  943. for (size_t i = 0; i < other.BucketsCount_; ++i) {
  944. auto& b = other.Buckets_[i];
  945. if (TItemNode::FlagSingle == b.Flag) {
  946. TItemType item = b.Get();
  947. UnconditionalInsert(KeyExtractor_(item)).Set(CloneItem(item));
  948. } else if (TItemNode::FlagList == b.Flag) {
  949. for (auto it = b.Iter(); it.Ok(); ++it) {
  950. UnconditionalInsert(KeyExtractor_(it.Get())).Set(CloneItem(it.Get()));
  951. }
  952. }
  953. }
  954. }
  955. TCompactHashBase(TCompactHashBase&& other)
  956. : Size_(std::move(other.Size_))
  957. , UniqSize_(std::move(other.UniqSize_))
  958. , MaxLoadFactor_(std::move(other.MaxLoadFactor_))
  959. , Buckets_(std::move(other.Buckets_))
  960. , BucketsCount_(std::move(other.BucketsCount_))
  961. , BucketsMemory_(std::move(other.BucketsMemory_))
  962. , ListPool_(std::move(other.ListPool_))
  963. , KeyExtractor_(std::move(other.KeyExtractor_))
  964. , KeyHash_(std::move(other.KeyHash_))
  965. , KeyEqual_(std::move(other.KeyEqual_))
  966. {
  967. other.Buckets_ = nullptr;
  968. other.BucketsMemory_ = 0;
  969. other.BucketsCount_ = 0;
  970. other.Size_ = 0;
  971. other.UniqSize_ = 0;
  972. other.MaxLoadFactor_ = 1.f;
  973. }
  974. ~TCompactHashBase() {
  975. ClearImpl(true);
  976. }
  977. TCompactHashBase& operator= (const TCompactHashBase& other) {
  978. TCompactHashBase(other).Swap(*this);
  979. return *this;
  980. }
  981. TCompactHashBase& operator= (TCompactHashBase&& other) {
  982. TCompactHashBase(std::move(other)).Swap(*this);
  983. return *this;
  984. }
  985. void Clear() {
  986. ClearImpl(false);
  987. }
  988. bool Has(const TKeyType& key) const {
  989. auto& b = Buckets_[GetBucket(key)];
  990. auto res = FindPos(b, key);
  991. return res.Ok();
  992. }
  993. bool Empty() const {
  994. return Size_ == 0;
  995. }
  996. size_t Size() const {
  997. return Size_;
  998. }
  999. size_t UniqSize() const {
  1000. return UniqSize_;
  1001. }
  1002. const TKeyExtractor& GetKeyExtractor() const {
  1003. return KeyExtractor_;
  1004. }
  1005. const TKeyHash& GetKeyHash() const {
  1006. return KeyHash_;
  1007. }
  1008. const TKeyEqual& GetKeyEqual() const {
  1009. return KeyEqual_;
  1010. }
  1011. float GetMaxLoadFactor() const {
  1012. return MaxLoadFactor_;
  1013. }
  1014. void SetMaxLoadFactor(float factor) {
  1015. Y_ABORT_UNLESS(factor > 0);
  1016. MaxLoadFactor_ = factor;
  1017. }
  1018. float GetLoadFactor() const {
  1019. return float(UniqSize_) / float(BucketsCount_);
  1020. }
  1021. TAlignedPagePool& GetPagePool() const {
  1022. return ListPool_.GetPagePool();
  1023. }
  1024. void Swap(TCompactHashBase& other) {
  1025. DoSwap(Size_, other.Size_);
  1026. DoSwap(UniqSize_, other.UniqSize_);
  1027. DoSwap(MaxLoadFactor_, other.MaxLoadFactor_);
  1028. DoSwap(Buckets_, other.Buckets_);
  1029. DoSwap(BucketsCount_, other.BucketsCount_);
  1030. DoSwap(BucketsMemory_, other.BucketsMemory_);
  1031. DoSwap(ListPool_, other.ListPool_);
  1032. DoSwap(KeyExtractor_, other.KeyExtractor_);
  1033. DoSwap(KeyHash_, other.KeyHash_);
  1034. DoSwap(KeyEqual_, other.KeyEqual_);
  1035. }
  1036. // Full scan
  1037. TIterator Iterate() const {
  1038. return TIterator(this);
  1039. }
  1040. // Key scan
  1041. TIterator Find(const TKeyType& key) const {
  1042. size_t bucket = GetBucket(key);
  1043. auto& b = Buckets_[bucket];
  1044. auto pos = FindPos(b, key);
  1045. if (pos.Ok()) {
  1046. return TIterator(this, bucket, pos);
  1047. }
  1048. return TIterator();
  1049. }
  1050. size_t Count(const TKeyType& key) const {
  1051. size_t bucket = GetBucket(key);
  1052. auto& b = Buckets_[bucket];
  1053. auto pos = FindPos(b, key);
  1054. if (pos.Ok()) {
  1055. return ValueCount(pos.Get());
  1056. }
  1057. return 0;
  1058. }
  1059. size_t GetBucketCount() const {
  1060. return BucketsCount_;
  1061. }
  1062. size_t GetBucket(const TKeyType& key) const {
  1063. return NYql::VaryingHash(KeyHash_(key)) % BucketsCount_;
  1064. }
  1065. bool IsEmptyBucket(size_t bucket) const {
  1066. Y_ASSERT(bucket < BucketsCount_);
  1067. return TItemNode::FlagEmpty == Buckets_[bucket].Flag;
  1068. }
  1069. size_t GetBucketSize(size_t bucket) const {
  1070. Y_ASSERT(bucket < BucketsCount_);
  1071. return Buckets_[bucket].Size();
  1072. }
  1073. TConstBucketIterator GetBucketIter(size_t bucket) const {
  1074. Y_ASSERT(bucket < BucketsCount_);
  1075. const TItemNode& b = Buckets_[bucket];
  1076. return b.Iter();
  1077. }
  1078. bool Rehash(size_t size) {
  1079. if (double(size) / BucketsCount_ <= MaxLoadFactor_) {
  1080. return false;
  1081. }
  1082. TItemNode* oldBuckets = Buckets_;
  1083. size_t oldBucketsCount = BucketsCount_;
  1084. size_t oldBucketsMemory = BucketsMemory_;
  1085. AllocateBuckets(FindNearestPrime(ceil(double(size) / MaxLoadFactor_)));
  1086. Y_DEFER {
  1087. for (size_t i = 0; i < oldBucketsCount; ++i) {
  1088. auto& b = oldBuckets[i];
  1089. if (TItemNode::FlagList == b.Flag) {
  1090. ListPool_.ReturnList(b.GetList());
  1091. }
  1092. b.Clear();
  1093. }
  1094. FreeBuckets(oldBuckets, oldBucketsMemory);
  1095. };
  1096. try {
  1097. for (size_t i = 0; i < oldBucketsCount; ++i) {
  1098. auto& b = oldBuckets[i];
  1099. if (TItemNode::FlagSingle == b.Flag) {
  1100. TItemType item = b.Get();
  1101. UnconditionalInsert(KeyExtractor_(item)).Set(item);
  1102. } else if (TItemNode::FlagList == b.Flag) {
  1103. for (TBucketIterator it = b.Iter(); it.Ok(); ++it) {
  1104. UnconditionalInsert(KeyExtractor_(it.Get())).Set(it.Get());
  1105. }
  1106. }
  1107. }
  1108. } catch (...) {
  1109. DoSwap(oldBuckets, Buckets_);
  1110. DoSwap(oldBucketsCount, BucketsCount_);
  1111. DoSwap(oldBucketsMemory, BucketsMemory_);
  1112. throw;
  1113. }
  1114. return true;
  1115. }
  1116. void PrintStat(IOutputStream& out) const {
  1117. size_t empty = 0;
  1118. size_t single = 0;
  1119. size_t list = 0;
  1120. for (size_t i = 0; i < BucketsCount_; ++i) {
  1121. auto& b = Buckets_[i];
  1122. if (TItemNode::FlagEmpty == b.Flag) {
  1123. ++empty;
  1124. } else if (TItemNode::FlagSingle == b.Flag) {
  1125. ++single;
  1126. } else {
  1127. ++list;
  1128. }
  1129. }
  1130. out << "Empty buckets: " << empty << Endl;
  1131. out << "Single buckets: " << single << Endl;
  1132. out << "List buckets: " << list << Endl;
  1133. ListPool_.PrintStat(out);
  1134. }
  1135. protected:
  1136. void ClearImpl(bool fromDtor) {
  1137. for (size_t i = 0; i < BucketsCount_; ++i) {
  1138. ClearNode(Buckets_[i]);
  1139. }
  1140. FreeBuckets(Buckets_, BucketsMemory_);
  1141. Buckets_ = nullptr;
  1142. BucketsCount_ = 0;
  1143. BucketsMemory_ = 0;
  1144. if (!fromDtor) {
  1145. AllocateBuckets(FindNearestPrime(0));
  1146. }
  1147. Size_ = 0;
  1148. UniqSize_ = 0;
  1149. }
  1150. void AllocateBuckets(size_t count) {
  1151. auto bucketsMemory = Max(sizeof(TItemNode) * count, (size_t)TAlignedPagePool::POOL_PAGE_SIZE);
  1152. Buckets_ = (TItemNode*)GetPagePool().GetBlock(bucketsMemory);
  1153. BucketsCount_ = count;
  1154. BucketsMemory_ = bucketsMemory;
  1155. for (size_t i = 0; i < count; ++i) {
  1156. new (&Buckets_[i]) TItemNode();
  1157. }
  1158. }
  1159. void FreeBuckets(TItemNode* buckets, size_t memory) {
  1160. if (!buckets) {
  1161. return;
  1162. }
  1163. GetPagePool().ReturnBlock(buckets, memory);
  1164. }
  1165. TConstBucketIterator FindPos(const TNode<TItemType>& b, const TKeyType& key) const {
  1166. if (TItemNode::FlagEmpty != b.Flag) {
  1167. for (TConstBucketIterator it = b.Iter(); it.Ok(); ++it) {
  1168. if (KeyEqual_(key, KeyExtractor_(it.Get()))) {
  1169. return TConstBucketIterator(it.GetRaw(), static_cast<const TItemType*>(it.GetRaw()) + 1); // Limit iterator by current key only
  1170. }
  1171. }
  1172. }
  1173. return TConstBucketIterator();
  1174. }
  1175. TBucketIterator FindPos(TNode<TItemType>& b, const TKeyType& key) {
  1176. if (TItemNode::FlagEmpty != b.Flag) {
  1177. for (TBucketIterator it = b.Iter(); it.Ok(); ++it) {
  1178. if (KeyEqual_(key, KeyExtractor_(it.Get()))) {
  1179. return TBucketIterator(it.GetRaw(), static_cast<TItemType*>(it.GetRaw()) + 1); // Limit iterator by current key only
  1180. }
  1181. }
  1182. }
  1183. return TBucketIterator();
  1184. }
  1185. template <typename T>
  1186. static size_t ValueCount(const TKeyNodePair<TKeyType, T>& item) {
  1187. return item.second.Size();
  1188. }
  1189. template <typename T>
  1190. static size_t ValueCount(const T& /*item*/) {
  1191. return 1;
  1192. }
  1193. template <typename T>
  1194. T CloneItem(const T& src) {
  1195. return src;
  1196. }
  1197. template <typename T>
  1198. TKeyNodePair<TKeyType, T> CloneItem(const TKeyNodePair<TKeyType, T>& src) {
  1199. if (TNode<T>::FlagList == src.second.Flag) {
  1200. TKeyNodePair<TKeyType, T> res(src.first, TNode<T>());
  1201. res.second.SetList(ListPool_.template CloneList<T>(src.second.GetList()));
  1202. return res;
  1203. } else {
  1204. return TKeyNodePair<TKeyType, T>(src.first, src.second);
  1205. }
  1206. }
  1207. template <typename T>
  1208. struct THasNodeValue : public std::false_type {};
  1209. template <typename T>
  1210. struct THasNodeValue<TKeyNodePair<TKeyType, T>> : public std::true_type {};
  1211. template <typename T>
  1212. void ClearNode(TNode<T>& b) {
  1213. if (THasNodeValue<T>::value) {
  1214. for (auto it = b.Iter(); it.Ok(); ++it) {
  1215. ClearItem(*reinterpret_cast<T*>(it.GetRaw()));
  1216. }
  1217. }
  1218. if (TNode<T>::FlagList == b.Flag) {
  1219. ListPool_.ReturnList(b.GetList());
  1220. }
  1221. b.Clear();
  1222. }
  1223. template <typename T>
  1224. void ClearItem(T& /*item*/) {
  1225. }
  1226. template <typename T>
  1227. void ClearItem(TKeyNodePair<TKeyType, T>& item) {
  1228. ClearNode(item.second);
  1229. }
  1230. std::pair<TBucketIterator, bool> InsertOrReplace(TKeyType key) {
  1231. auto b = &Buckets_[GetBucket(key)];
  1232. auto res = FindPos(*b, key);
  1233. if (res.Ok()) {
  1234. return {res, false};
  1235. }
  1236. if (Rehash(UniqSize_ + 1)) {
  1237. // Update bucket after rehashing
  1238. b = &Buckets_[GetBucket(key)];
  1239. }
  1240. TBucketIterator iter = ExpandBucket<TItemType>(*b);
  1241. ++UniqSize_;
  1242. ++Size_;
  1243. return {iter, true};
  1244. }
  1245. TBucketIterator UnconditionalInsert(TKeyType key) {
  1246. return ExpandBucket<TItemType>(Buckets_[GetBucket(key)]);
  1247. }
  1248. template <typename T>
  1249. TListPoolBase::TListIterator<T, TListPoolBase::TLargeListHeader> ExpandBucket(TNode<T>& b) {
  1250. if (TNode<T>::FlagEmpty == b.Flag) {
  1251. b.Flag = TNode<T>::FlagSingle;
  1252. return b.Iter();
  1253. } else if (TNode<T>::FlagSingle == b.Flag) {
  1254. T* list = ListPool_.template GetList<T>(2);
  1255. *list = b.Get();
  1256. b.SetList(list);
  1257. return TListPoolBase::TListIterator<T, TListPoolBase::TLargeListHeader>(reinterpret_cast<ui8*>(list + 1), reinterpret_cast<ui8*>(list + 2));
  1258. } else {
  1259. T* list = b.GetList();
  1260. T* pos = ListPool_.template IncrementList<T>(list);
  1261. b.SetList(list);
  1262. return TListPoolBase::TListIterator<T, TListPoolBase::TLargeListHeader>(reinterpret_cast<ui8*>(pos), reinterpret_cast<ui8*>(pos + 1));
  1263. }
  1264. }
  1265. protected:
  1266. size_t Size_ = 0;
  1267. size_t UniqSize_ = 0;
  1268. float MaxLoadFactor_ = 1.f;
  1269. TItemNode* Buckets_ = nullptr;
  1270. size_t BucketsCount_ = 0;
  1271. size_t BucketsMemory_ = 0;
  1272. TListPool<TItemType, TSubItemType> ListPool_;
  1273. TKeyExtractor KeyExtractor_;
  1274. TKeyHash KeyHash_;
  1275. TKeyEqual KeyEqual_;
  1276. };
  1277. template <typename TKey,
  1278. typename TValue,
  1279. typename TKeyHash = THash<TKey>,
  1280. typename TKeyEqual = TEqualTo<TKey>>
  1281. class TCompactHash: public TCompactHashBase<TKeyValuePair<TKey, TValue>, TKey, TSelect1st, TKeyHash, TKeyEqual> {
  1282. private:
  1283. static_assert(std::is_trivially_destructible<TKey>::value
  1284. && std::is_trivially_copy_assignable<TKey>::value
  1285. && std::is_trivially_move_assignable<TKey>::value
  1286. && std::is_trivially_copy_constructible<TKey>::value
  1287. && std::is_trivially_move_constructible<TKey>::value
  1288. , "Expected POD key type");
  1289. static_assert(std::is_trivially_destructible<TValue>::value
  1290. && std::is_trivially_copy_assignable<TValue>::value
  1291. && std::is_trivially_move_assignable<TValue>::value
  1292. && std::is_trivially_copy_constructible<TValue>::value
  1293. && std::is_trivially_move_constructible<TValue>::value
  1294. , "Expected POD value type");
  1295. using TItem = TKeyValuePair<TKey, TValue>;
  1296. using TBase = TCompactHashBase<TItem, TKey, TSelect1st, TKeyHash, TKeyEqual>;
  1297. public:
  1298. TCompactHash(TAlignedPagePool& pagePool, size_t size = 0, const TKeyHash& keyHash = TKeyHash(), const TKeyEqual& keyEqual = TKeyEqual())
  1299. : TBase(pagePool, size, TSelect1st(), keyHash, keyEqual)
  1300. {
  1301. }
  1302. TCompactHash(const TCompactHash& other)
  1303. : TBase(other)
  1304. {
  1305. }
  1306. TCompactHash(TCompactHash&& other)
  1307. : TBase(std::move(other))
  1308. {
  1309. }
  1310. TCompactHash& operator= (const TCompactHash& rhs) {
  1311. TBase::operator =(rhs);
  1312. return *this;
  1313. }
  1314. TCompactHash& operator= (TCompactHash&& rhs) {
  1315. TBase::operator =(std::move(rhs));
  1316. return *this;
  1317. }
  1318. bool Insert(TItem item) {
  1319. auto res = TBase::InsertOrReplace(TBase::KeyExtractor_(item));
  1320. res.first.Set(item);
  1321. return res.second;
  1322. }
  1323. bool Insert(TKey key, TValue value) {
  1324. auto res = TBase::InsertOrReplace(key);
  1325. res.first.Set(TItem(key, value));
  1326. return res.second;
  1327. }
  1328. bool InsertNew(TItem item) {
  1329. auto res = TBase::InsertOrReplace(TBase::KeyExtractor_(item));
  1330. if (res.second) {
  1331. res.first.Set(item);
  1332. }
  1333. return res.second;
  1334. }
  1335. bool InsertNew(TKey key, TValue value) {
  1336. auto res = TBase::InsertOrReplace(key);
  1337. if (res.second) {
  1338. res.first.Set(TItem(key, value));
  1339. }
  1340. return res.second;
  1341. }
  1342. };
  1343. template <typename TKey,
  1344. typename TValue,
  1345. typename TKeyHash = THash<TKey>,
  1346. typename TKeyEqual = TEqualTo<TKey>>
  1347. class TCompactMultiHash: public TCompactHashBase<TKeyNodePair<TKey, TValue>, TKey, TSelect1st, TKeyHash, TKeyEqual, TValue> {
  1348. private:
  1349. static_assert(std::is_trivially_destructible<TKey>::value
  1350. && std::is_trivially_copy_assignable<TKey>::value
  1351. && std::is_trivially_move_assignable<TKey>::value
  1352. && std::is_trivially_copy_constructible<TKey>::value
  1353. && std::is_trivially_move_constructible<TKey>::value
  1354. , "Expected POD key type");
  1355. static_assert(std::is_trivially_destructible<TValue>::value
  1356. && std::is_trivially_copy_assignable<TValue>::value
  1357. && std::is_trivially_move_assignable<TValue>::value
  1358. && std::is_trivially_copy_constructible<TValue>::value
  1359. && std::is_trivially_move_constructible<TValue>::value
  1360. , "Expected POD value type");
  1361. using TUserItem = std::pair<TKey, TValue>;
  1362. using TStoreItem = TKeyNodePair<TKey, TValue>;
  1363. using TBase = TCompactHashBase<TStoreItem, TKey, TSelect1st, TKeyHash, TKeyEqual, TValue>;
  1364. static_assert(sizeof(TStoreItem) == sizeof(TKey) + sizeof(TNode<TValue>), "Unexpected size");
  1365. public:
  1366. TCompactMultiHash(TAlignedPagePool& pagePool, size_t size = 0, const TKeyHash& keyHash = TKeyHash(), const TKeyEqual& keyEqual = TKeyEqual())
  1367. : TBase(pagePool, size, TSelect1st(), keyHash, keyEqual)
  1368. {
  1369. }
  1370. TCompactMultiHash(const TCompactMultiHash& other)
  1371. : TBase(other)
  1372. {
  1373. }
  1374. TCompactMultiHash(TCompactMultiHash&& other)
  1375. : TBase(std::move(other))
  1376. {
  1377. }
  1378. TCompactMultiHash& operator= (const TCompactMultiHash& rhs) {
  1379. TBase::operator =(rhs);
  1380. return *this;
  1381. }
  1382. TCompactMultiHash& operator= (TCompactMultiHash&& rhs) {
  1383. TBase::operator =(std::move(rhs));
  1384. return *this;
  1385. }
  1386. void Insert(const TUserItem& item) {
  1387. GetOrInsert(item.first).Set(item.second);
  1388. }
  1389. void Insert(TKey key, TValue value) {
  1390. GetOrInsert(key).Set(value);
  1391. }
  1392. protected:
  1393. template <typename TKeyType>
  1394. TListPoolBase::TListIterator<TValue, TListPoolBase::TLargeListHeader> GetOrInsert(TKeyType key) {
  1395. auto res = TBase::InsertOrReplace(key);
  1396. if (res.second) {
  1397. res.first.Set(TStoreItem(key, TNode<TValue>()));
  1398. }
  1399. auto valueIter = TBase::template ExpandBucket<TValue>(reinterpret_cast<TStoreItem*>(res.first.GetRaw())->second);
  1400. if (!res.second) {
  1401. ++TBase::Size_;
  1402. }
  1403. return valueIter;
  1404. }
  1405. };
  1406. template <typename TKey,
  1407. typename TKeyHash = THash<TKey>,
  1408. typename TKeyEqual = TEqualTo<TKey>>
  1409. class TCompactHashSet: public TCompactHashBase<TKey, TKey, TIdentity, TKeyHash, TKeyEqual> {
  1410. private:
  1411. static_assert(std::is_trivially_destructible<TKey>::value
  1412. && std::is_trivially_copy_assignable<TKey>::value
  1413. && std::is_trivially_move_assignable<TKey>::value
  1414. && std::is_trivially_copy_constructible<TKey>::value
  1415. && std::is_trivially_move_constructible<TKey>::value
  1416. , "Expected POD key type");
  1417. using TBase = TCompactHashBase<TKey, TKey, TIdentity, TKeyHash, TKeyEqual>;
  1418. public:
  1419. TCompactHashSet(TAlignedPagePool& pagePool, size_t size = 0, const TKeyHash& keyHash = TKeyHash(), const TKeyEqual& keyEqual = TKeyEqual())
  1420. : TBase(pagePool, size, TIdentity(), keyHash, keyEqual)
  1421. {
  1422. }
  1423. TCompactHashSet(const TCompactHashSet& other)
  1424. : TBase(other)
  1425. {
  1426. }
  1427. TCompactHashSet(TCompactHashSet&& other)
  1428. : TBase(std::move(other))
  1429. {
  1430. }
  1431. TCompactHashSet& operator= (const TCompactHashSet& rhs) {
  1432. TBase::operator =(rhs);
  1433. return *this;
  1434. }
  1435. TCompactHashSet& operator= (TCompactHashSet&& rhs) {
  1436. TBase::operator =(std::move(rhs));
  1437. return *this;
  1438. }
  1439. bool Insert(TKey key) {
  1440. auto res = TBase::InsertOrReplace(key);
  1441. if (res.second) {
  1442. res.first.Set(key);
  1443. }
  1444. return res.second;
  1445. }
  1446. };
  1447. } // NCHash
  1448. } // NKikimr