-
Notifications
You must be signed in to change notification settings - Fork 49
/
unordered_dense.h
1936 lines (1624 loc) · 74.3 KB
/
unordered_dense.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///////////////////////// ankerl::unordered_dense::{map, set} /////////////////////////
// A fast & densely stored hashmap and hashset based on robin-hood backward shift deletion.
// Version 4.1.2
// https://github.com/martinus/unordered_dense
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
// SPDX-License-Identifier: MIT
// Copyright (c) 2022-2023 Martin Leitner-Ankerl <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef ANKERL_UNORDERED_DENSE_H
#define ANKERL_UNORDERED_DENSE_H
// see https://semver.org/spec/v2.0.0.html
#define ANKERL_UNORDERED_DENSE_VERSION_MAJOR 4 // NOLINT(cppcoreguidelines-macro-usage) incompatible API changes
#define ANKERL_UNORDERED_DENSE_VERSION_MINOR 1 // NOLINT(cppcoreguidelines-macro-usage) backwards compatible functionality
#define ANKERL_UNORDERED_DENSE_VERSION_PATCH 2 // NOLINT(cppcoreguidelines-macro-usage) backwards compatible bug fixes
// API versioning with inline namespace, see https://www.foonathan.net/2018/11/inline-namespaces/
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define ANKERL_UNORDERED_DENSE_VERSION_CONCAT1(major, minor, patch) v##major##_##minor##_##patch
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define ANKERL_UNORDERED_DENSE_VERSION_CONCAT(major, minor, patch) ANKERL_UNORDERED_DENSE_VERSION_CONCAT1(major, minor, patch)
#define ANKERL_UNORDERED_DENSE_NAMESPACE \
ANKERL_UNORDERED_DENSE_VERSION_CONCAT( \
ANKERL_UNORDERED_DENSE_VERSION_MAJOR, ANKERL_UNORDERED_DENSE_VERSION_MINOR, ANKERL_UNORDERED_DENSE_VERSION_PATCH)
#if defined(_MSVC_LANG)
# define ANKERL_UNORDERED_DENSE_CPP_VERSION _MSVC_LANG
#else
# define ANKERL_UNORDERED_DENSE_CPP_VERSION __cplusplus
#endif
#if defined(__GNUC__)
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
# define ANKERL_UNORDERED_DENSE_PACK(decl) decl __attribute__((__packed__))
#elif defined(_MSC_VER)
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
# define ANKERL_UNORDERED_DENSE_PACK(decl) __pragma(pack(push, 1)) decl __pragma(pack(pop))
#endif
// exceptions
#if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)
# define ANKERL_UNORDERED_DENSE_HAS_EXCEPTIONS() 1 // NOLINT(cppcoreguidelines-macro-usage)
#else
# define ANKERL_UNORDERED_DENSE_HAS_EXCEPTIONS() 0 // NOLINT(cppcoreguidelines-macro-usage)
#endif
#ifdef _MSC_VER
# define ANKERL_UNORDERED_DENSE_NOINLINE __declspec(noinline)
#else
# define ANKERL_UNORDERED_DENSE_NOINLINE __attribute__((noinline))
#endif
// defined in unordered_dense.cpp
#if !defined(ANKERL_UNORDERED_DENSE_EXPORT)
# define ANKERL_UNORDERED_DENSE_EXPORT
#endif
#if ANKERL_UNORDERED_DENSE_CPP_VERSION < 201703L
# error ankerl::unordered_dense requires C++17 or higher
#else
# include <array> // for array
# include <cstdint> // for uint64_t, uint32_t, uint8_t, UINT64_C
# include <cstring> // for size_t, memcpy, memset
# include <functional> // for equal_to, hash
# include <initializer_list> // for initializer_list
# include <iterator> // for pair, distance
# include <limits> // for numeric_limits
# include <memory> // for allocator, allocator_traits, shared_ptr
# include <stdexcept> // for out_of_range
# include <string> // for basic_string
# include <string_view> // for basic_string_view, hash
# include <tuple> // for forward_as_tuple
# include <type_traits> // for enable_if_t, declval, conditional_t, ena...
# include <utility> // for forward, exchange, pair, as_const, piece...
# include <vector> // for vector
# if ANKERL_UNORDERED_DENSE_HAS_EXCEPTIONS() == 0
# include <cstdlib> // for abort
# endif
# if defined(__has_include)
# if __has_include(<memory_resource>)
# define ANKERL_UNORDERED_DENSE_PMR std::pmr // NOLINT(cppcoreguidelines-macro-usage)
# include <memory_resource> // for polymorphic_allocator
# elif __has_include(<experimental/memory_resource>)
# define ANKERL_UNORDERED_DENSE_PMR std::experimental::pmr // NOLINT(cppcoreguidelines-macro-usage)
# include <experimental/memory_resource> // for polymorphic_allocator
# endif
# endif
# if defined(_MSC_VER) && defined(_M_X64)
# include <intrin.h>
# pragma intrinsic(_umul128)
# endif
# if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__clang__)
# define ANKERL_UNORDERED_DENSE_LIKELY(x) __builtin_expect(x, 1) // NOLINT(cppcoreguidelines-macro-usage)
# define ANKERL_UNORDERED_DENSE_UNLIKELY(x) __builtin_expect(x, 0) // NOLINT(cppcoreguidelines-macro-usage)
# else
# define ANKERL_UNORDERED_DENSE_LIKELY(x) (x) // NOLINT(cppcoreguidelines-macro-usage)
# define ANKERL_UNORDERED_DENSE_UNLIKELY(x) (x) // NOLINT(cppcoreguidelines-macro-usage)
# endif
namespace ankerl::unordered_dense {
inline namespace ANKERL_UNORDERED_DENSE_NAMESPACE {
namespace detail {
# if ANKERL_UNORDERED_DENSE_HAS_EXCEPTIONS()
// make sure this is not inlined as it is slow and dramatically enlarges code, thus making other
// inlinings more difficult. Throws are also generally the slow path.
[[noreturn]] inline ANKERL_UNORDERED_DENSE_NOINLINE void on_error_key_not_found() {
throw std::out_of_range("ankerl::unordered_dense::map::at(): key not found");
}
[[noreturn]] inline ANKERL_UNORDERED_DENSE_NOINLINE void on_error_bucket_overflow() {
throw std::overflow_error("ankerl::unordered_dense: reached max bucket size, cannot increase size");
}
[[noreturn]] inline ANKERL_UNORDERED_DENSE_NOINLINE void on_error_too_many_elements() {
throw std::out_of_range("ankerl::unordered_dense::map::replace(): too many elements");
}
# else
[[noreturn]] inline void on_error_key_not_found() {
abort();
}
[[noreturn]] inline void on_error_bucket_overflow() {
abort();
}
[[noreturn]] inline void on_error_too_many_elements() {
abort();
}
# endif
} // namespace detail
// hash ///////////////////////////////////////////////////////////////////////
// This is a stripped-down implementation of wyhash: https://github.com/wangyi-fudan/wyhash
// No big-endian support (because different values on different machines don't matter),
// hardcodes seed and the secret, reformats the code, and clang-tidy fixes.
namespace detail::wyhash {
inline void mum(uint64_t* a, uint64_t* b) {
# if defined(__SIZEOF_INT128__)
__uint128_t r = *a;
r *= *b;
*a = static_cast<uint64_t>(r);
*b = static_cast<uint64_t>(r >> 64U);
# elif defined(_MSC_VER) && defined(_M_X64)
*a = _umul128(*a, *b, b);
# else
uint64_t ha = *a >> 32U;
uint64_t hb = *b >> 32U;
uint64_t la = static_cast<uint32_t>(*a);
uint64_t lb = static_cast<uint32_t>(*b);
uint64_t hi{};
uint64_t lo{};
uint64_t rh = ha * hb;
uint64_t rm0 = ha * lb;
uint64_t rm1 = hb * la;
uint64_t rl = la * lb;
uint64_t t = rl + (rm0 << 32U);
auto c = static_cast<uint64_t>(t < rl);
lo = t + (rm1 << 32U);
c += static_cast<uint64_t>(lo < t);
hi = rh + (rm0 >> 32U) + (rm1 >> 32U) + c;
*a = lo;
*b = hi;
# endif
}
// multiply and xor mix function, aka MUM
[[nodiscard]] inline auto mix(uint64_t a, uint64_t b) -> uint64_t {
mum(&a, &b);
return a ^ b;
}
// read functions. WARNING: we don't care about endianness, so results are different on big endian!
[[nodiscard]] inline auto r8(const uint8_t* p) -> uint64_t {
uint64_t v{};
std::memcpy(&v, p, 8U);
return v;
}
[[nodiscard]] inline auto r4(const uint8_t* p) -> uint64_t {
uint32_t v{};
std::memcpy(&v, p, 4);
return v;
}
// reads 1, 2, or 3 bytes
[[nodiscard]] inline auto r3(const uint8_t* p, size_t k) -> uint64_t {
return (static_cast<uint64_t>(p[0]) << 16U) | (static_cast<uint64_t>(p[k >> 1U]) << 8U) | p[k - 1];
}
[[maybe_unused]] [[nodiscard]] inline auto hash(void const* key, size_t len) -> uint64_t {
static constexpr auto secret = std::array{UINT64_C(0xa0761d6478bd642f),
UINT64_C(0xe7037ed1a0b428db),
UINT64_C(0x8ebc6af09c88c6e3),
UINT64_C(0x589965cc75374cc3)};
auto const* p = static_cast<uint8_t const*>(key);
uint64_t seed = secret[0];
uint64_t a{};
uint64_t b{};
if (ANKERL_UNORDERED_DENSE_LIKELY(len <= 16)) {
if (ANKERL_UNORDERED_DENSE_LIKELY(len >= 4)) {
a = (r4(p) << 32U) | r4(p + ((len >> 3U) << 2U));
b = (r4(p + len - 4) << 32U) | r4(p + len - 4 - ((len >> 3U) << 2U));
} else if (ANKERL_UNORDERED_DENSE_LIKELY(len > 0)) {
a = r3(p, len);
b = 0;
} else {
a = 0;
b = 0;
}
} else {
size_t i = len;
if (ANKERL_UNORDERED_DENSE_UNLIKELY(i > 48)) {
uint64_t see1 = seed;
uint64_t see2 = seed;
do {
seed = mix(r8(p) ^ secret[1], r8(p + 8) ^ seed);
see1 = mix(r8(p + 16) ^ secret[2], r8(p + 24) ^ see1);
see2 = mix(r8(p + 32) ^ secret[3], r8(p + 40) ^ see2);
p += 48;
i -= 48;
} while (ANKERL_UNORDERED_DENSE_LIKELY(i > 48));
seed ^= see1 ^ see2;
}
while (ANKERL_UNORDERED_DENSE_UNLIKELY(i > 16)) {
seed = mix(r8(p) ^ secret[1], r8(p + 8) ^ seed);
i -= 16;
p += 16;
}
a = r8(p + i - 16);
b = r8(p + i - 8);
}
return mix(secret[1] ^ len, mix(a ^ secret[1], b ^ seed));
}
[[nodiscard]] inline auto hash(uint64_t x) -> uint64_t {
return detail::wyhash::mix(x, UINT64_C(0x9E3779B97F4A7C15));
}
} // namespace detail::wyhash
ANKERL_UNORDERED_DENSE_EXPORT template <typename T, typename Enable = void>
struct hash {
auto operator()(T const& obj) const noexcept(noexcept(std::declval<std::hash<T>>().operator()(std::declval<T const&>())))
-> uint64_t {
return std::hash<T>{}(obj);
}
};
template <typename CharT>
struct hash<std::basic_string<CharT>> {
using is_avalanching = void;
auto operator()(std::basic_string<CharT> const& str) const noexcept -> uint64_t {
return detail::wyhash::hash(str.data(), sizeof(CharT) * str.size());
}
};
template <typename CharT>
struct hash<std::basic_string_view<CharT>> {
using is_avalanching = void;
auto operator()(std::basic_string_view<CharT> const& sv) const noexcept -> uint64_t {
return detail::wyhash::hash(sv.data(), sizeof(CharT) * sv.size());
}
};
template <class T>
struct hash<T*> {
using is_avalanching = void;
auto operator()(T* ptr) const noexcept -> uint64_t {
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
return detail::wyhash::hash(reinterpret_cast<uintptr_t>(ptr));
}
};
template <class T>
struct hash<std::unique_ptr<T>> {
using is_avalanching = void;
auto operator()(std::unique_ptr<T> const& ptr) const noexcept -> uint64_t {
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
return detail::wyhash::hash(reinterpret_cast<uintptr_t>(ptr.get()));
}
};
template <class T>
struct hash<std::shared_ptr<T>> {
using is_avalanching = void;
auto operator()(std::shared_ptr<T> const& ptr) const noexcept -> uint64_t {
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
return detail::wyhash::hash(reinterpret_cast<uintptr_t>(ptr.get()));
}
};
template <typename Enum>
struct hash<Enum, typename std::enable_if<std::is_enum<Enum>::value>::type> {
using is_avalanching = void;
auto operator()(Enum e) const noexcept -> uint64_t {
using underlying = typename std::underlying_type_t<Enum>;
return detail::wyhash::hash(static_cast<underlying>(e));
}
};
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
# define ANKERL_UNORDERED_DENSE_HASH_STATICCAST(T) \
template <> \
struct hash<T> { \
using is_avalanching = void; \
auto operator()(T const& obj) const noexcept -> uint64_t { \
return detail::wyhash::hash(static_cast<uint64_t>(obj)); \
} \
}
# if defined(__GNUC__) && !defined(__clang__)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wuseless-cast"
# endif
// see https://en.cppreference.com/w/cpp/utility/hash
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(bool);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(char);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(signed char);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(unsigned char);
# if ANKERL_UNORDERED_DENSE_CPP_VERSION >= 202002L && defined(__cpp_char8_t)
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(char8_t);
# endif
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(char16_t);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(char32_t);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(wchar_t);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(short);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(unsigned short);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(int);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(unsigned int);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(long);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(long long);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(unsigned long);
ANKERL_UNORDERED_DENSE_HASH_STATICCAST(unsigned long long);
# if defined(__GNUC__) && !defined(__clang__)
# pragma GCC diagnostic pop
# endif
// bucket_type //////////////////////////////////////////////////////////
namespace bucket_type {
struct standard {
static constexpr uint32_t dist_inc = 1U << 8U; // skip 1 byte fingerprint
static constexpr uint32_t fingerprint_mask = dist_inc - 1; // mask for 1 byte of fingerprint
uint32_t m_dist_and_fingerprint; // upper 3 byte: distance to original bucket. lower byte: fingerprint from hash
uint32_t m_value_idx; // index into the m_values vector.
};
ANKERL_UNORDERED_DENSE_PACK(struct big {
static constexpr uint32_t dist_inc = 1U << 8U; // skip 1 byte fingerprint
static constexpr uint32_t fingerprint_mask = dist_inc - 1; // mask for 1 byte of fingerprint
uint32_t m_dist_and_fingerprint; // upper 3 byte: distance to original bucket. lower byte: fingerprint from hash
size_t m_value_idx; // index into the m_values vector.
});
} // namespace bucket_type
namespace detail {
struct nonesuch {};
template <class Default, class AlwaysVoid, template <class...> class Op, class... Args>
struct detector {
using value_t = std::false_type;
using type = Default;
};
template <class Default, template <class...> class Op, class... Args>
struct detector<Default, std::void_t<Op<Args...>>, Op, Args...> {
using value_t = std::true_type;
using type = Op<Args...>;
};
template <template <class...> class Op, class... Args>
using is_detected = typename detail::detector<detail::nonesuch, void, Op, Args...>::value_t;
template <template <class...> class Op, class... Args>
constexpr bool is_detected_v = is_detected<Op, Args...>::value;
template <typename T>
using detect_avalanching = typename T::is_avalanching;
template <typename T>
using detect_is_transparent = typename T::is_transparent;
template <typename T>
using detect_iterator = typename T::iterator;
template <typename T>
using detect_reserve = decltype(std::declval<T&>().reserve(size_t{}));
// enable_if helpers
template <typename Mapped>
constexpr bool is_map_v = !std::is_void_v<Mapped>;
// clang-format off
template <typename Hash, typename KeyEqual>
constexpr bool is_transparent_v = is_detected_v<detect_is_transparent, Hash> && is_detected_v<detect_is_transparent, KeyEqual>;
// clang-format on
template <typename From, typename To1, typename To2>
constexpr bool is_neither_convertible_v = !std::is_convertible_v<From, To1> && !std::is_convertible_v<From, To2>;
template <typename T>
constexpr bool has_reserve = is_detected_v<detect_reserve, T>;
// base type for map has mapped_type
template <class T>
struct base_table_type_map {
using mapped_type = T;
};
// base type for set doesn't have mapped_type
struct base_table_type_set {};
} // namespace detail
// Very much like std::deque, but faster for indexing (in most cases). As of now this doesn't implement the full std::vector
// API, but merely what's necessary to work as an underlying container for ankerl::unordered_dense::{map, set}.
// It allocates blocks of equal size and puts them into the m_blocks vector. That means it can grow simply by adding a new
// block to the back of m_blocks, and doesn't double its size like an std::vector. The disadvantage is that memory is not
// linear and thus there is one more indirection necessary for indexing.
template <typename T, typename Allocator = std::allocator<T>, size_t MaxSegmentSizeBytes = 4096>
class segmented_vector {
template <bool IsConst>
class iter_t;
public:
using allocator_type = Allocator;
using pointer = typename std::allocator_traits<allocator_type>::pointer;
using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
using difference_type = typename std::allocator_traits<allocator_type>::difference_type;
using value_type = T;
using size_type = std::size_t;
using reference = T&;
using const_reference = T const&;
using iterator = iter_t<false>;
using const_iterator = iter_t<true>;
private:
using vec_alloc = typename std::allocator_traits<Allocator>::template rebind_alloc<pointer>;
std::vector<pointer, vec_alloc> m_blocks{};
size_t m_size{};
// Calculates the maximum number for x in (s << x) <= max_val
static constexpr auto num_bits_closest(size_t max_val, size_t s) -> size_t {
auto f = size_t{0};
while (s << (f + 1) <= max_val) {
++f;
}
return f;
}
using self_t = segmented_vector<T, Allocator, MaxSegmentSizeBytes>;
static constexpr auto num_bits = num_bits_closest(MaxSegmentSizeBytes, sizeof(T));
static constexpr auto num_elements_in_block = 1U << num_bits;
static constexpr auto mask = num_elements_in_block - 1U;
/**
* Iterator class doubles as const_iterator and iterator
*/
template <bool IsConst>
class iter_t {
using ptr_t = typename std::conditional_t<IsConst, segmented_vector::const_pointer const*, segmented_vector::pointer*>;
ptr_t m_data{};
size_t m_idx{};
template <bool B>
friend class iter_t;
public:
using difference_type = segmented_vector::difference_type;
using value_type = T;
using reference = typename std::conditional_t<IsConst, value_type const&, value_type&>;
using pointer = typename std::conditional_t<IsConst, segmented_vector::const_pointer, segmented_vector::pointer>;
using iterator_category = std::forward_iterator_tag;
iter_t() noexcept = default;
template <bool OtherIsConst, typename = typename std::enable_if<IsConst && !OtherIsConst>::type>
// NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions)
constexpr iter_t(iter_t<OtherIsConst> const& other) noexcept
: m_data(other.m_data)
, m_idx(other.m_idx) {}
constexpr iter_t(ptr_t data, size_t idx) noexcept
: m_data(data)
, m_idx(idx) {}
template <bool OtherIsConst, typename = typename std::enable_if<IsConst && !OtherIsConst>::type>
constexpr auto operator=(iter_t<OtherIsConst> const& other) noexcept -> iter_t& {
m_data = other.m_data;
m_idx = other.m_idx;
return *this;
}
constexpr auto operator++() noexcept -> iter_t& {
++m_idx;
return *this;
}
constexpr auto operator+(difference_type diff) noexcept -> iter_t {
return {m_data, static_cast<size_t>(static_cast<difference_type>(m_idx) + diff)};
}
template <bool OtherIsConst>
constexpr auto operator-(iter_t<OtherIsConst> const& other) noexcept -> difference_type {
return static_cast<difference_type>(m_idx) - static_cast<difference_type>(other.m_idx);
}
constexpr auto operator*() const noexcept -> reference {
return m_data[m_idx >> num_bits][m_idx & mask];
}
constexpr auto operator->() const noexcept -> pointer {
return &m_data[m_idx >> num_bits][m_idx & mask];
}
template <bool O>
constexpr auto operator==(iter_t<O> const& o) const noexcept -> bool {
return m_idx == o.m_idx;
}
template <bool O>
constexpr auto operator!=(iter_t<O> const& o) const noexcept -> bool {
return !(*this == o);
}
};
// slow path: need to allocate a new segment every once in a while
void increase_capacity() {
auto ba = Allocator(m_blocks.get_allocator());
pointer block = std::allocator_traits<Allocator>::allocate(ba, num_elements_in_block);
m_blocks.push_back(block);
}
// Moves everything from other
void append_everything_from(segmented_vector&& other) {
reserve(size() + other.size());
for (auto&& o : other) {
emplace_back(std::move(o));
}
}
// Copies everything from other
void append_everything_from(segmented_vector const& other) {
reserve(size() + other.size());
for (auto const& o : other) {
emplace_back(o);
}
}
void dealloc() {
auto ba = Allocator(m_blocks.get_allocator());
for (auto ptr : m_blocks) {
std::allocator_traits<Allocator>::deallocate(ba, ptr, num_elements_in_block);
}
}
[[nodiscard]] static constexpr auto calc_num_blocks_for_capacity(size_t capacity) {
return (capacity + num_elements_in_block - 1U) / num_elements_in_block;
}
public:
segmented_vector() = default;
// NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions)
segmented_vector(Allocator alloc)
: m_blocks(vec_alloc(alloc)) {}
segmented_vector(segmented_vector&& other, Allocator alloc)
: segmented_vector(alloc) {
*this = std::move(other);
}
segmented_vector(segmented_vector const& other, Allocator alloc)
: m_blocks(vec_alloc(alloc)) {
append_everything_from(other);
}
segmented_vector(segmented_vector&& other) noexcept
: segmented_vector(std::move(other), get_allocator()) {}
segmented_vector(segmented_vector const& other) {
append_everything_from(other);
}
auto operator=(segmented_vector const& other) -> segmented_vector& {
if (this == &other) {
return *this;
}
clear();
append_everything_from(other);
return *this;
}
auto operator=(segmented_vector&& other) noexcept -> segmented_vector& {
clear();
dealloc();
if (other.get_allocator() == get_allocator()) {
m_blocks = std::move(other.m_blocks);
m_size = std::exchange(other.m_size, {});
} else {
// make sure to construct with other's allocator!
m_blocks = std::vector<pointer, vec_alloc>(vec_alloc(other.get_allocator()));
append_everything_from(std::move(other));
}
return *this;
}
~segmented_vector() {
clear();
dealloc();
}
[[nodiscard]] constexpr auto size() const -> size_t {
return m_size;
}
[[nodiscard]] constexpr auto capacity() const -> size_t {
return m_blocks.size() * num_elements_in_block;
}
// Indexing is highly performance critical
[[nodiscard]] constexpr auto operator[](size_t i) const noexcept -> T const& {
return m_blocks[i >> num_bits][i & mask];
}
[[nodiscard]] constexpr auto operator[](size_t i) noexcept -> T& {
return m_blocks[i >> num_bits][i & mask];
}
[[nodiscard]] constexpr auto begin() -> iterator {
return {m_blocks.data(), 0U};
}
[[nodiscard]] constexpr auto begin() const -> const_iterator {
return {m_blocks.data(), 0U};
}
[[nodiscard]] constexpr auto cbegin() const -> const_iterator {
return {m_blocks.data(), 0U};
}
[[nodiscard]] constexpr auto end() -> iterator {
return {m_blocks.data(), m_size};
}
[[nodiscard]] constexpr auto end() const -> const_iterator {
return {m_blocks.data(), m_size};
}
[[nodiscard]] constexpr auto cend() const -> const_iterator {
return {m_blocks.data(), m_size};
}
[[nodiscard]] constexpr auto back() -> reference {
return operator[](m_size - 1);
}
[[nodiscard]] constexpr auto back() const -> const_reference {
return operator[](m_size - 1);
}
void pop_back() {
back().~T();
--m_size;
}
[[nodiscard]] auto empty() const {
return 0 == m_size;
}
void reserve(size_t new_capacity) {
m_blocks.reserve(calc_num_blocks_for_capacity(new_capacity));
while (new_capacity > capacity()) {
increase_capacity();
}
}
[[nodiscard]] auto get_allocator() const -> allocator_type {
return allocator_type{m_blocks.get_allocator()};
}
template <class... Args>
auto emplace_back(Args&&... args) -> reference {
if (m_size == capacity()) {
increase_capacity();
}
auto* ptr = static_cast<void*>(&operator[](m_size));
auto& ref = *new (ptr) T(std::forward<Args>(args)...);
++m_size;
return ref;
}
void clear() {
if constexpr (!std::is_trivially_destructible_v<T>) {
for (size_t i = 0, s = size(); i < s; ++i) {
operator[](i).~T();
}
}
m_size = 0;
}
void shrink_to_fit() {
auto ba = Allocator(m_blocks.get_allocator());
auto num_blocks_required = calc_num_blocks_for_capacity(m_size);
while (m_blocks.size() > num_blocks_required) {
std::allocator_traits<Allocator>::deallocate(ba, m_blocks.back(), num_elements_in_block);
m_blocks.pop_back();
}
m_blocks.shrink_to_fit();
}
};
namespace detail {
// This is it, the table. Doubles as map and set, and uses `void` for T when its used as a set.
template <class Key,
class T, // when void, treat it as a set.
class Hash,
class KeyEqual,
class AllocatorOrContainer,
class Bucket,
bool IsSegmented>
class table : public std::conditional_t<is_map_v<T>, base_table_type_map<T>, base_table_type_set> {
using underlying_value_type = typename std::conditional_t<is_map_v<T>, std::pair<Key, T>, Key>;
using underlying_container_type = std::conditional_t<IsSegmented,
segmented_vector<underlying_value_type, AllocatorOrContainer>,
std::vector<underlying_value_type, AllocatorOrContainer>>;
public:
using value_container_type = std::
conditional_t<is_detected_v<detect_iterator, AllocatorOrContainer>, AllocatorOrContainer, underlying_container_type>;
private:
using bucket_alloc =
typename std::allocator_traits<typename value_container_type::allocator_type>::template rebind_alloc<Bucket>;
using bucket_alloc_traits = std::allocator_traits<bucket_alloc>;
static constexpr uint8_t initial_shifts = 64 - 3; // 2^(64-m_shift) number of buckets
static constexpr float default_max_load_factor = 0.8F;
public:
using key_type = Key;
using value_type = typename value_container_type::value_type;
using size_type = typename value_container_type::size_type;
using difference_type = typename value_container_type::difference_type;
using hasher = Hash;
using key_equal = KeyEqual;
using allocator_type = typename value_container_type::allocator_type;
using reference = typename value_container_type::reference;
using const_reference = typename value_container_type::const_reference;
using pointer = typename value_container_type::pointer;
using const_pointer = typename value_container_type::const_pointer;
using const_iterator = typename value_container_type::const_iterator;
using iterator = std::conditional_t<is_map_v<T>, typename value_container_type::iterator, const_iterator>;
using bucket_type = Bucket;
private:
using value_idx_type = decltype(Bucket::m_value_idx);
using dist_and_fingerprint_type = decltype(Bucket::m_dist_and_fingerprint);
static_assert(std::is_trivially_destructible_v<Bucket>, "assert there's no need to call destructor / std::destroy");
static_assert(std::is_trivially_copyable_v<Bucket>, "assert we can just memset / memcpy");
value_container_type m_values{}; // Contains all the key-value pairs in one densely stored container. No holes.
using bucket_pointer = typename std::allocator_traits<bucket_alloc>::pointer;
bucket_pointer m_buckets{};
size_t m_num_buckets = 0;
size_t m_max_bucket_capacity = 0;
float m_max_load_factor = default_max_load_factor;
Hash m_hash{};
KeyEqual m_equal{};
uint8_t m_shifts = initial_shifts;
[[nodiscard]] auto next(value_idx_type bucket_idx) const -> value_idx_type {
return ANKERL_UNORDERED_DENSE_UNLIKELY(bucket_idx + 1U == m_num_buckets)
? 0
: static_cast<value_idx_type>(bucket_idx + 1U);
}
// Helper to access bucket through pointer types
[[nodiscard]] static constexpr auto at(bucket_pointer bucket_ptr, size_t offset) -> Bucket& {
return *(bucket_ptr + static_cast<typename std::allocator_traits<bucket_alloc>::difference_type>(offset));
}
// use the dist_inc and dist_dec functions so that uint16_t types work without warning
[[nodiscard]] static constexpr auto dist_inc(dist_and_fingerprint_type x) -> dist_and_fingerprint_type {
return static_cast<dist_and_fingerprint_type>(x + Bucket::dist_inc);
}
[[nodiscard]] static constexpr auto dist_dec(dist_and_fingerprint_type x) -> dist_and_fingerprint_type {
return static_cast<dist_and_fingerprint_type>(x - Bucket::dist_inc);
}
// The goal of mixed_hash is to always produce a high quality 64bit hash.
template <typename K>
[[nodiscard]] constexpr auto mixed_hash(K const& key) const -> uint64_t {
if constexpr (is_detected_v<detect_avalanching, Hash>) {
// we know that the hash is good because is_avalanching.
if constexpr (sizeof(decltype(m_hash(key))) < sizeof(uint64_t)) {
// 32bit hash and is_avalanching => multiply with a constant to avalanche bits upwards
return m_hash(key) * UINT64_C(0x9ddfea08eb382d69);
} else {
// 64bit and is_avalanching => only use the hash itself.
return m_hash(key);
}
} else {
// not is_avalanching => apply wyhash
return wyhash::hash(m_hash(key));
}
}
[[nodiscard]] constexpr auto dist_and_fingerprint_from_hash(uint64_t hash) const -> dist_and_fingerprint_type {
return Bucket::dist_inc | (static_cast<dist_and_fingerprint_type>(hash) & Bucket::fingerprint_mask);
}
[[nodiscard]] constexpr auto bucket_idx_from_hash(uint64_t hash) const -> value_idx_type {
return static_cast<value_idx_type>(hash >> m_shifts);
}
[[nodiscard]] static constexpr auto get_key(value_type const& vt) -> key_type const& {
if constexpr (is_map_v<T>) {
return vt.first;
} else {
return vt;
}
}
template <typename K>
[[nodiscard]] auto next_while_less(K const& key) const -> Bucket {
auto hash = mixed_hash(key);
auto dist_and_fingerprint = dist_and_fingerprint_from_hash(hash);
auto bucket_idx = bucket_idx_from_hash(hash);
while (dist_and_fingerprint < at(m_buckets, bucket_idx).m_dist_and_fingerprint) {
dist_and_fingerprint = dist_inc(dist_and_fingerprint);
bucket_idx = next(bucket_idx);
}
return {dist_and_fingerprint, bucket_idx};
}
void place_and_shift_up(Bucket bucket, value_idx_type place) {
while (0 != at(m_buckets, place).m_dist_and_fingerprint) {
bucket = std::exchange(at(m_buckets, place), bucket);
bucket.m_dist_and_fingerprint = dist_inc(bucket.m_dist_and_fingerprint);
place = next(place);
}
at(m_buckets, place) = bucket;
}
[[nodiscard]] static constexpr auto calc_num_buckets(uint8_t shifts) -> size_t {
return (std::min)(max_bucket_count(), size_t{1} << (64U - shifts));
}
[[nodiscard]] constexpr auto calc_shifts_for_size(size_t s) const -> uint8_t {
auto shifts = initial_shifts;
while (shifts > 0 && static_cast<size_t>(static_cast<float>(calc_num_buckets(shifts)) * max_load_factor()) < s) {
--shifts;
}
return shifts;
}
// assumes m_values has data, m_buckets=m_buckets_end=nullptr, m_shifts is INITIAL_SHIFTS
void copy_buckets(table const& other) {
if (!empty()) {
m_shifts = other.m_shifts;
allocate_buckets_from_shift();
std::memcpy(m_buckets, other.m_buckets, sizeof(Bucket) * bucket_count());
}
}
/**
* True when no element can be added any more without increasing the size
*/
[[nodiscard]] auto is_full() const -> bool {
return size() >= m_max_bucket_capacity;
}
void deallocate_buckets() {
auto ba = bucket_alloc(m_values.get_allocator());
if (nullptr != m_buckets) {
bucket_alloc_traits::deallocate(ba, m_buckets, bucket_count());
m_buckets = nullptr;
}
m_num_buckets = 0;
m_max_bucket_capacity = 0;
}
void allocate_buckets_from_shift() {
auto ba = bucket_alloc(m_values.get_allocator());
m_num_buckets = calc_num_buckets(m_shifts);
m_buckets = bucket_alloc_traits::allocate(ba, m_num_buckets);
if (m_num_buckets == max_bucket_count()) {
// reached the maximum, make sure we can use each bucket
m_max_bucket_capacity = max_bucket_count();
} else {
m_max_bucket_capacity = static_cast<value_idx_type>(static_cast<float>(m_num_buckets) * max_load_factor());
}
}
void clear_buckets() {
if (m_buckets != nullptr) {
std::memset(&*m_buckets, 0, sizeof(Bucket) * bucket_count());
}
}
void clear_and_fill_buckets_from_values() {
clear_buckets();
for (value_idx_type value_idx = 0, end_idx = static_cast<value_idx_type>(m_values.size()); value_idx < end_idx;
++value_idx) {
auto const& key = get_key(m_values[value_idx]);
auto [dist_and_fingerprint, bucket] = next_while_less(key);
// we know for certain that key has not yet been inserted, so no need to check it.
place_and_shift_up({dist_and_fingerprint, value_idx}, bucket);
}
}
void increase_size() {
if (ANKERL_UNORDERED_DENSE_UNLIKELY(m_max_bucket_capacity == max_bucket_count())) {
on_error_bucket_overflow();
}
--m_shifts;
deallocate_buckets();
allocate_buckets_from_shift();
clear_and_fill_buckets_from_values();
}
void do_erase(value_idx_type bucket_idx) {
auto const value_idx_to_remove = at(m_buckets, bucket_idx).m_value_idx;
// shift down until either empty or an element with correct spot is found
auto next_bucket_idx = next(bucket_idx);
while (at(m_buckets, next_bucket_idx).m_dist_and_fingerprint >= Bucket::dist_inc * 2) {
at(m_buckets, bucket_idx) = {dist_dec(at(m_buckets, next_bucket_idx).m_dist_and_fingerprint),
at(m_buckets, next_bucket_idx).m_value_idx};
bucket_idx = std::exchange(next_bucket_idx, next(next_bucket_idx));
}
at(m_buckets, bucket_idx) = {};
// update m_values
if (value_idx_to_remove != m_values.size() - 1) {
// no luck, we'll have to replace the value with the last one and update the index accordingly
auto& val = m_values[value_idx_to_remove];
val = std::move(m_values.back());
// update the values_idx of the moved entry. No need to play the info game, just look until we find the values_idx
auto mh = mixed_hash(get_key(val));
bucket_idx = bucket_idx_from_hash(mh);
auto const values_idx_back = static_cast<value_idx_type>(m_values.size() - 1);
while (values_idx_back != at(m_buckets, bucket_idx).m_value_idx) {
bucket_idx = next(bucket_idx);
}
at(m_buckets, bucket_idx).m_value_idx = value_idx_to_remove;
}
m_values.pop_back();
}
template <typename K>
auto do_erase_key(K&& key) -> size_t {
if (empty()) {
return 0;
}
auto [dist_and_fingerprint, bucket_idx] = next_while_less(key);
while (dist_and_fingerprint == at(m_buckets, bucket_idx).m_dist_and_fingerprint &&
!m_equal(key, get_key(m_values[at(m_buckets, bucket_idx).m_value_idx]))) {