diff --git a/.clang-format b/.clang-format index 5d7b58d..96fe708 100644 --- a/.clang-format +++ b/.clang-format @@ -26,24 +26,24 @@ AlwaysBreakTemplateDeclarations: Yes BinPackArguments: false BinPackParameters: false BraceWrapping: - AfterCaseLabel: true - AfterClass: true - AfterControlStatement: MultiLine - AfterEnum: true - AfterFunction: true + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: false AfterNamespace: false AfterObjCDeclaration: false - AfterStruct: true - AfterUnion: true + AfterStruct: false + AfterUnion: false AfterExternBlock: true - BeforeCatch: true - BeforeElse: true + BeforeCatch: false + BeforeElse: false IndentBraces: false SplitEmptyFunction: false SplitEmptyRecord: false - SplitEmptyNamespace: true + SplitEmptyNamespace: false BreakBeforeBinaryOperators: None -BreakBeforeBraces: Mozilla +BreakBeforeBraces: Custom BreakBeforeInheritanceComma: false BreakInheritanceList: BeforeComma BreakBeforeTernaryOperators: true diff --git a/examples/btree/btree.cpp b/examples/btree/btree.cpp index 87b37e7..7cfaaff 100644 --- a/examples/btree/btree.cpp +++ b/examples/btree/btree.cpp @@ -2,8 +2,7 @@ #include #include -int main() -{ +int main() { // initialise map with some values using an initializer_list gtl::btree_map map = { {"John", 35}, @@ -26,8 +25,7 @@ int main() IntString map2; // IntString is declared in btree_fwd.hpp - map2.emplace( - std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple(10, 'c')); + map2.emplace(std::piecewise_construct, std::forward_as_tuple(0), std::forward_as_tuple(10, 'c')); map2.try_emplace(1, 10, 'a'); // gtl::btree_map supports c++17 API for (auto& p : map2) diff --git a/examples/hmap/allmaps.cpp b/examples/hmap/allmaps.cpp index 7646a75..c7f9089 100644 --- a/examples/hmap/allmaps.cpp +++ b/examples/hmap/allmaps.cpp @@ -4,8 +4,7 @@ #include template -void test_set(const F& f) -{ +void test_set(const F& f) { Set s; typename Set::iterator it; for (int i = 0; i < 100; ++i) @@ -21,8 +20,7 @@ void test_set(const F& f) it = s.begin(); } -int main(int, char**) -{ +int main(int, char**) { using namespace std; auto make_int = [](int i) { return i; }; diff --git a/examples/hmap/basic.cpp b/examples/hmap/basic.cpp index 5802802..6e433a9 100644 --- a/examples/hmap/basic.cpp +++ b/examples/hmap/basic.cpp @@ -4,8 +4,7 @@ using gtl::flat_hash_map; -int main() -{ +int main() { // Create an unordered_map of three strings (that map to strings) flat_hash_map email = { {"tom", "tom@gmail.com" }, diff --git a/examples/hmap/bench.cpp b/examples/hmap/bench.cpp index 60f10c2..a86991a 100644 --- a/examples/hmap/bench.cpp +++ b/examples/hmap/bench.cpp @@ -29,8 +29,7 @@ #endif #elif 1 #include -class srwlock -{ +class srwlock { SRWLOCK _lock; public: @@ -42,13 +41,11 @@ class srwlock #else // spinlocks - slow! #include -class spinlock -{ +class spinlock { std::atomic_flag flag = ATOMIC_FLAG_INIT; public: - void lock() - { + void lock() { while (flag.test_and_set(std::memory_order_acquire)) ; } @@ -113,21 +110,18 @@ int64_t _abs(int64_t x) { return (x < 0) ? -x : x; } #endif // _MSC_VER // -------------------------------------------------------------------------- -class Timer -{ +class Timer { typedef std::chrono::high_resolution_clock high_resolution_clock; typedef std::chrono::milliseconds milliseconds; public: - explicit Timer(bool run = false) - { + explicit Timer(bool run = false) { if (run) reset(); } void reset() { _start = high_resolution_clock::now(); } - milliseconds elapsed() const - { + milliseconds elapsed() const { return std::chrono::duration_cast(high_resolution_clock::now() - _start); } @@ -138,14 +132,12 @@ class Timer // -------------------------------------------------------------------------- // from: https://github.com/preshing/RandomSequence // -------------------------------------------------------------------------- -class RSU -{ +class RSU { private: unsigned int m_index; unsigned int m_intermediateOffset; - static unsigned int permuteQPR(unsigned int x) - { + static unsigned int permuteQPR(unsigned int x) { static const unsigned int prime = 4294967291u; if (x >= prime) return x; // The 5 integers out of range are mapped to themselves. @@ -154,8 +146,7 @@ class RSU } public: - RSU(unsigned int seedBase, unsigned int seedOffset) - { + RSU(unsigned int seedBase, unsigned int seedOffset) { m_index = permuteQPR(permuteQPR(seedBase) + 0x682f0161); m_intermediateOffset = permuteQPR(permuteQPR(seedOffset) + 0x46790905); } @@ -165,8 +156,7 @@ class RSU // -------------------------------------------------------------------------- template -void _fill(vector& v) -{ +void _fill(vector& v) { srand(1); // for a fair/deterministic comparison for (size_t i = 0, sz = v.size(); i < sz; ++i) v[i] = (T)(i * 10 + rand() % 10); @@ -174,16 +164,14 @@ void _fill(vector& v) // -------------------------------------------------------------------------- template -void _shuffle(vector& v) -{ +void _shuffle(vector& v) { for (size_t n = v.size(); n >= 2; --n) std::swap(v[n - 1], v[static_cast(rand()) % n]); } // -------------------------------------------------------------------------- template -Timer _fill_random(vector& v, HT& hash) -{ +Timer _fill_random(vector& v, HT& hash) { _fill(v); _shuffle(v); @@ -195,14 +183,12 @@ Timer _fill_random(vector& v, HT& hash) } // -------------------------------------------------------------------------- -void out(const char* test, uint64_t cnt, const Timer& t, bool = false) -{ +void out(const char* test, uint64_t cnt, const Timer& t, bool = false) { printf("%s,time,%" PRIu64 ",%s,%f\n", test, cnt, program_slug, ((double)t.elapsed().count() / 1000)); } // -------------------------------------------------------------------------- -void outmem(const char*, uint64_t cnt, uint64_t mem, bool final = false) -{ +void outmem(const char*, uint64_t cnt, uint64_t mem, bool final = false) { static uint64_t max_mem = 0; static uint64_t max_keys = 0; if (final) @@ -223,8 +209,7 @@ static const char* test = "random"; // -------------------------------------------------------------------------- template -void _fill_random_inner(int64_t cnt, HT& hash, RSU& rsu) -{ +void _fill_random_inner(int64_t cnt, HT& hash, RSU& rsu) { for (int64_t i = 0; i < cnt; ++i) { hash.insert(typename HT::value_type(rsu.next(), 0)); ++s_num_keys[0]; @@ -233,8 +218,7 @@ void _fill_random_inner(int64_t cnt, HT& hash, RSU& rsu) // -------------------------------------------------------------------------- template -void _fill_random_inner_mt(int64_t cnt, HT& hash, RSU& rsu) -{ +void _fill_random_inner_mt(int64_t cnt, HT& hash, RSU& rsu) { constexpr int64_t num_threads = 8; // has to be a power of two std::unique_ptr threads[num_threads]; @@ -278,8 +262,7 @@ void _fill_random_inner_mt(int64_t cnt, HT& hash, RSU& rsu) } // -------------------------------------------------------------------------- -uint64_t total_num_keys() -{ +uint64_t total_num_keys() { uint64_t n = 0; for (int i = 0; i < 16; ++i) n += s_num_keys[i]; @@ -288,8 +271,7 @@ uint64_t total_num_keys() // -------------------------------------------------------------------------- template -Timer _fill_random2(int64_t cnt, HT& hash) -{ +Timer _fill_random2(int64_t cnt, HT& hash) { test = "random"; unsigned int seed = 76687; RSU rsu(seed, seed + 1); @@ -317,8 +299,7 @@ Timer _fill_random2(int64_t cnt, HT& hash) // -------------------------------------------------------------------------- template -Timer _lookup(vector& v, HT& hash, size_t& num_present) -{ +Timer _lookup(vector& v, HT& hash, size_t& num_present) { _fill_random(v, hash); num_present = 0; @@ -334,8 +315,7 @@ Timer _lookup(vector& v, HT& hash, size_t& num_present) // -------------------------------------------------------------------------- template -Timer _delete(vector& v, HT& hash) -{ +Timer _delete(vector& v, HT& hash) { _fill_random(v, hash); _shuffle(v); // don't delete in insertion order @@ -347,8 +327,7 @@ Timer _delete(vector& v, HT& hash) } // -------------------------------------------------------------------------- -void memlog() -{ +void memlog() { std::this_thread::sleep_for(std::chrono::milliseconds(10)); uint64_t nbytes_old_out = gtl::GetProcessMemoryUsed(); uint64_t nbytes_old = gtl::GetProcessMemoryUsed(); // last non outputted mem measurement @@ -359,7 +338,8 @@ void memlog() uint64_t nbytes = gtl::GetProcessMemoryUsed(); if ((double)_abs(nbytes - nbytes_old_out) / nbytes_old_out > 0.03 || - (double)_abs(nbytes - nbytes_old) / nbytes_old > 0.01) { + (double)_abs(nbytes - nbytes_old) / nbytes_old > 0.01) + { if ((double)(nbytes - nbytes_old) / nbytes_old > 0.03) outmem(test, total_num_keys() - 1, nbytes_old); outmem(test, total_num_keys(), nbytes); @@ -377,8 +357,7 @@ void memlog() } // -------------------------------------------------------------------------- -int main(int argc, char** argv) -{ +int main(int argc, char** argv) { int64_t num_keys = 100000000; const char* bench_name = "random"; int64_t i, value = 0; @@ -414,7 +393,8 @@ int main(int argc, char** argv) out("random", num_keys, timer); } #endif - else if (!strcmp(bench_name, "random")) { + else if (!strcmp(bench_name, "random")) + { fprintf(stderr, "size = %zu\n", sizeof(hash)); timer = _fill_random2(num_keys, hash); } else if (!strcmp(bench_name, "lookup")) { diff --git a/examples/hmap/dump_load.cpp b/examples/hmap/dump_load.cpp index 8cc2cc3..0b1912c 100644 --- a/examples/hmap/dump_load.cpp +++ b/examples/hmap/dump_load.cpp @@ -1,8 +1,7 @@ #include #include -void dump_load_uint64_uint32() -{ +void dump_load_uint64_uint32() { gtl::flat_hash_map mp1 = { {100, 99 }, { 300, 299} @@ -26,8 +25,7 @@ void dump_load_uint64_uint32() std::cout << n.first << "'s value is: " << n.second << "\n"; } -void dump_load_parallel_flat_hash_map() -{ +void dump_load_parallel_flat_hash_map() { gtl::parallel_flat_hash_map mp1 = { {100, 99 }, { 300, 299}, @@ -52,8 +50,7 @@ void dump_load_parallel_flat_hash_map() std::cout << "key: " << n.first << ", value: " << n.second << "\n"; } -int main() -{ +int main() { dump_load_uint64_uint32(); dump_load_parallel_flat_hash_map(); return 0; diff --git a/examples/hmap/dump_nested.cpp b/examples/hmap/dump_nested.cpp index 39b0258..f290b36 100644 --- a/examples/hmap/dump_nested.cpp +++ b/examples/hmap/dump_nested.cpp @@ -9,13 +9,11 @@ #include template -class MyMap : public gtl::flat_hash_map> -{ +class MyMap : public gtl::flat_hash_map> { public: using Set = gtl::flat_hash_set; - void dump(const std::string& filename) - { + void dump(const std::string& filename) { gtl::BinaryOutputArchive ar_out(filename.c_str()); ar_out.saveBinary(this->size()); @@ -25,8 +23,7 @@ class MyMap : public gtl::flat_hash_map> } } - void load(const std::string& filename) - { + void load(const std::string& filename) { gtl::BinaryInputArchive ar_in(filename.c_str()); size_t size; @@ -44,14 +41,12 @@ class MyMap : public gtl::flat_hash_map> } } - void insert(K k, V v) - { + void insert(K k, V v) { Set& set = (*this)[k]; set.insert(v); } - friend std::ostream& operator<<(std::ostream& os, const MyMap& map) - { + friend std::ostream& operator<<(std::ostream& os, const MyMap& map) { for (const auto& [k, m] : map) { os << k << ": ["; for (const auto& x : m) @@ -62,8 +57,7 @@ class MyMap : public gtl::flat_hash_map> } }; -int main() -{ +int main() { MyMap m; m.insert(1, 5); m.insert(1, 8); diff --git a/examples/hmap/emplace.cpp b/examples/hmap/emplace.cpp index c964644..2418001 100644 --- a/examples/hmap/emplace.cpp +++ b/examples/hmap/emplace.cpp @@ -13,10 +13,9 @@ using milliseconds = std::chrono::duration; // type containing std::string. Seems to take a long time to construct (and maybe move) // ------------------------------------------------------------------------------------ -class custom_type -{ - std::string one = "one"; - std::string two = "two"; +class custom_type { + std::string one = "one"; + std::string two = "two"; [[maybe_unused]] std::uint32_t three = 3; [[maybe_unused]] std::uint64_t four = 4; [[maybe_unused]] std::uint64_t five = 5; @@ -36,8 +35,7 @@ class custom_type // type containing only integrals. should be faster to create. // ----------------------------------------------------------- -class custom_type_2 -{ +class custom_type_2 { [[maybe_unused]] std::uint32_t three = 3; [[maybe_unused]] std::uint64_t four = 4; [[maybe_unused]] std::uint64_t five = 5; @@ -59,16 +57,13 @@ class custom_type_2 // convert std::size_t to appropriate key // -------------------------------------- template -struct GenKey -{ +struct GenKey { K operator()(std::size_t j); }; template<> -struct GenKey -{ - std::string operator()(std::size_t j) - { +struct GenKey { + std::string operator()(std::size_t j) { std::ostringstream stm; stm << j; return stm.str(); @@ -76,38 +71,33 @@ struct GenKey }; template<> -struct GenKey -{ +struct GenKey { int operator()(std::size_t j) { return (int)j; } }; // emplace key + large struct // -------------------------- template -struct _emplace -{ +struct _emplace { void operator()(Map& m, std::size_t j); }; // "void" template parameter -> use emplace template -struct _emplace -{ +struct _emplace { void operator()(Map& m, std::size_t j) { m.emplace(GenKey()(j), V()); } }; // "int" template parameter -> use emplace_back for std::vector template -struct _emplace -{ +struct _emplace { void operator()(Map& m, std::size_t j) { m.emplace_back(GenKey()(j), V()); } }; // The test itself // --------------- template class INSERT> -void _test(std::size_t iterations, std::size_t container_size, const char* map_name) -{ +void _test(std::size_t iterations, std::size_t container_size, const char* map_name) { std::size_t count = 0; auto t1 = std::chrono::high_resolution_clock::now(); INSERT insert; @@ -125,24 +115,17 @@ void _test(std::size_t iterations, std::size_t container_size, const char* map_n } template class INSERT> -void test(std::size_t iterations, std::size_t container_size) -{ - std::clog << "bench: iterations: " << iterations << " / container_size: " << container_size - << "\n"; - - _test, K, V, void, INSERT>( - iterations, container_size, " std::map: "); - _test, K, V, void, INSERT>( - iterations, container_size, " std::unordered_map: "); - _test, K, V, void, INSERT>( - iterations, container_size, " gtl::flat_hash_map: "); - _test>, K, V, int, INSERT>( - iterations, container_size, " std::vector: "); +void test(std::size_t iterations, std::size_t container_size) { + std::clog << "bench: iterations: " << iterations << " / container_size: " << container_size << "\n"; + + _test, K, V, void, INSERT>(iterations, container_size, " std::map: "); + _test, K, V, void, INSERT>(iterations, container_size, " std::unordered_map: "); + _test, K, V, void, INSERT>(iterations, container_size, " gtl::flat_hash_map: "); + _test>, K, V, int, INSERT>(iterations, container_size, " std::vector: "); std::clog << "\n"; } -int main() -{ +int main() { std::size_t iterations = 100000; // test with custom_type_2 (int key + 32 byte value). This is representative diff --git a/examples/hmap/f1.cpp b/examples/hmap/f1.cpp index bf76cb0..f8964ba 100644 --- a/examples/hmap/f1.cpp +++ b/examples/hmap/f1.cpp @@ -7,8 +7,7 @@ using gtl::flat_hash_map; -int main() -{ +int main() { // Create an unordered_map of three strings (that map to strings) using Map = flat_hash_map; Map email = { diff --git a/examples/hmap/f2.cpp b/examples/hmap/f2.cpp index a62af48..fe94f67 100644 --- a/examples/hmap/f2.cpp +++ b/examples/hmap/f2.cpp @@ -9,8 +9,7 @@ using gtl::flat_hash_map; using Map = flat_hash_map; -void f2(Map& email) -{ +void f2(Map& email) { // Iterate and print keys and values for (const auto& n : email) std::cout << n.first << "'s email is: " << n.second << "\n"; diff --git a/examples/hmap/hash.cpp b/examples/hmap/hash.cpp index afe4db8..c0d5591 100644 --- a/examples/hmap/hash.cpp +++ b/examples/hmap/hash.cpp @@ -4,7 +4,7 @@ #include #include #include -//#include +// #include #include using std::pair; @@ -15,17 +15,14 @@ using groupid_t = std::array; namespace std { template<> -struct hash -{ - std::size_t operator()(groupid_t const& g) const - { +struct hash { + std::size_t operator()(groupid_t const& g) const { return gtl::Hash()(std::tuple_cat(g)); } }; } -int main() -{ +int main() { std::vector groups = { {17, 75, 82, 66}, { 22, 88, 54, 42}, diff --git a/examples/hmap/hash_std.cpp b/examples/hmap/hash_std.cpp index 2275279..b993eed 100644 --- a/examples/hmap/hash_std.cpp +++ b/examples/hmap/hash_std.cpp @@ -3,8 +3,7 @@ #include #include -int main() -{ +int main() { // As we have defined a specialization of std::hash() for Person, // we can now create sparse_hash_set or sparse_hash_map of Persons // ---------------------------------------------------------------- diff --git a/examples/hmap/hash_std.hpp b/examples/hmap/hash_std.hpp index 1adde0d..abfb631 100644 --- a/examples/hmap/hash_std.hpp +++ b/examples/hmap/hash_std.hpp @@ -5,12 +5,8 @@ #include using std::string; -struct Person -{ - bool operator==(const Person& o) const - { - return _first == o._first && _last == o._last && _age == o._age; - } +struct Person { + bool operator==(const Person& o) const { return _first == o._first && _last == o._last && _age == o._age; } string _first; string _last; @@ -22,12 +18,8 @@ namespace std { // An alternative is to provide a hash_value() friend function (see hash_value.hpp) // ------------------------------------------------------------------------------ template<> -struct hash -{ - std::size_t operator()(Person const& p) const - { - return gtl::HashState().combine(0, p._first, p._last, p._age); - } +struct hash { + std::size_t operator()(Person const& p) const { return gtl::HashState().combine(0, p._first, p._last, p._age); } }; } diff --git a/examples/hmap/hash_value.cpp b/examples/hmap/hash_value.cpp index 454c680..128a0ed 100644 --- a/examples/hmap/hash_value.cpp +++ b/examples/hmap/hash_value.cpp @@ -3,8 +3,7 @@ #include #include -int main() -{ +int main() { // As we have defined a specialization of std::hash() for Person, // we can now create sparse_hash_set or sparse_hash_map of Persons // ---------------------------------------------------------------- diff --git a/examples/hmap/hash_value.hpp b/examples/hmap/hash_value.hpp index b41859f..f5e8fb8 100644 --- a/examples/hmap/hash_value.hpp +++ b/examples/hmap/hash_value.hpp @@ -5,20 +5,13 @@ #include using std::string; -struct Person -{ - bool operator==(const Person& o) const - { - return _first == o._first && _last == o._last && _age == o._age; - } +struct Person { + bool operator==(const Person& o) const { return _first == o._first && _last == o._last && _age == o._age; } // Demonstrates how to provide the hash function as a friend member function of the class // This can be used as an alternative to providing a std::hash specialization // -------------------------------------------------------------------------------------- - friend size_t hash_value(const Person& p) - { - return gtl::HashState().combine(0, p._first, p._last, p._age); - } + friend size_t hash_value(const Person& p) { return gtl::HashState().combine(0, p._first, p._last, p._age); } string _first; string _last; diff --git a/examples/hmap/knucleotide.cpp b/examples/hmap/knucleotide.cpp index bf7724c..3bc856a 100644 --- a/examples/hmap/knucleotide.cpp +++ b/examples/hmap/knucleotide.cpp @@ -49,14 +49,12 @@ // ------------------------------------------------------------------ constexpr size_t thread_count = 4; -struct Cfg -{ +struct Cfg { unsigned char* to_char; unsigned char to_num[128]; using Data = std::vector; - Cfg() - { + Cfg() { static unsigned char __tochar[] = { 'A', 'C', 'T', 'G' }; to_char = __tochar; to_num[static_cast('A')] = to_num[static_cast('a')] = 0; @@ -68,24 +66,19 @@ struct Cfg // ------------------------------------------------------------------ template -struct Key -{ +struct Key { // select type to use for 'data', if hash key can fit on 32-bit integer // then use uint32_t else use uint64_t. using Data = typename std::conditional::type; - struct Hash - { + struct Hash { Data operator()(const Key& t) const { return t._data; } }; Key() - : _data(0) - { - } + : _data(0) {} - Key(const char* str) - { + Key(const char* str) { _data = 0; for (unsigned i = 0; i < size; ++i) { _data <<= 2; @@ -94,8 +87,7 @@ struct Key } // initialize hash from input data - void InitKey(const unsigned char* data) - { + void InitKey(const unsigned char* data) { for (unsigned i = 0; i < size; ++i) { _data <<= 2; _data |= data[i]; @@ -103,8 +95,7 @@ struct Key } // updates the key with 1 byte - void UpdateKey(const unsigned char data) - { + void UpdateKey(const unsigned char data) { _data <<= 2; _data |= data; } @@ -113,8 +104,7 @@ struct Key void MaskKey() { _data &= _mask; } // implicit casting operator to string - operator std::string() const - { + operator std::string() const { std::string tmp; Data data = _data; for (size_t i = 0; i != size; ++i, data >>= 2) @@ -136,8 +126,7 @@ using HashTable = gtl::flat_hash_map; // ------------------------------------------------------------------ template -void Calculate(const Cfg::Data& input, size_t begin, HashTable& table) -{ +void Calculate(const Cfg::Data& input, size_t begin, HashTable& table) { // original implementation fully recomputes the hash key for each // insert to the hash table. This implementation only partially // updates the hash, this is the same with C GCC, Rust #6 and Rust #4 @@ -165,8 +154,7 @@ void Calculate(const Cfg::Data& input, size_t begin, HashTable& table) // ------------------------------------------------------------------ template -HashTable CalculateInThreads(const Cfg::Data& input) -{ +HashTable CalculateInThreads(const Cfg::Data& input) { HashTable hash_tables[thread_count]; std::thread threads[thread_count]; @@ -189,10 +177,9 @@ HashTable CalculateInThreads(const Cfg::Data& input) // ------------------------------------------------------------------ template -void WriteFrequencies(const Cfg::Data& input) -{ +void WriteFrequencies(const Cfg::Data& input) { // we "receive" the returned object by move instead of copy. - auto&& frequencies = CalculateInThreads(input); + auto&& frequencies = CalculateInThreads(input); std::map> freq; for (const auto& i : frequencies) freq.insert({ i.second, i.first }); @@ -205,21 +192,18 @@ void WriteFrequencies(const Cfg::Data& input) // ------------------------------------------------------------------ template -void WriteCount(const Cfg::Data& input, const char* text) -{ +void WriteCount(const Cfg::Data& input, const char* text) { // we "receive" the returned object by move instead of copy. auto&& frequencies = CalculateInThreads(input); std::cout << frequencies[Key(text)] << '\t' << text << '\n'; } // ------------------------------------------------------------------ -int main() -{ +int main() { Cfg::Data data; std::array buf; - while (fgets(buf.data(), static_cast(buf.size()), stdin) && - memcmp(">THREE", buf.data(), 6)) + while (fgets(buf.data(), static_cast(buf.size()), stdin) && memcmp(">THREE", buf.data(), 6)) ; while (fgets(buf.data(), static_cast(buf.size()), stdin) && buf.front() != '>') { if (buf.front() != ';') { @@ -227,8 +211,7 @@ int main() data.insert(data.end(), buf.begin(), i); } } - std::transform( - data.begin(), data.end(), data.begin(), [](unsigned char c) { return cfg.to_num[c]; }); + std::transform(data.begin(), data.end(), data.begin(), [](unsigned char c) { return cfg.to_num[c]; }); std::cout << std::setprecision(3) << std::setiosflags(std::ios::fixed); WriteFrequencies<1>(data); diff --git a/examples/hmap/matt.cpp b/examples/hmap/matt.cpp index 39a6ed1..a1b7f3d 100644 --- a/examples/hmap/matt.cpp +++ b/examples/hmap/matt.cpp @@ -11,17 +11,13 @@ // ------------------------------------------------------------------- // ------------------------------------------------------------------- -class Timer -{ +class Timer { public: Timer(const std::string& name) : _name(name) - , _start(std::chrono::high_resolution_clock::now()) - { - } + , _start(std::chrono::high_resolution_clock::now()) {} - ~Timer() - { + ~Timer() { std::chrono::duration elapsed_seconds = std::chrono::high_resolution_clock::now() - _start; printf("%s: %.3fs\n", _name.c_str(), elapsed_seconds.count()); } @@ -34,14 +30,12 @@ class Timer // -------------------------------------------------------------------------- // from: https://github.com/preshing/RandomSequence // -------------------------------------------------------------------------- -class RSU -{ +class RSU { private: uint32_t m_index; uint32_t m_intermediateOffset; - static uint32_t permuteQPR(uint32_t x) - { + static uint32_t permuteQPR(uint32_t x) { static const uint32_t prime = 4294967291u; if (x >= prime) return x; // The 5 integers out of range are mapped to themselves. @@ -50,8 +44,7 @@ class RSU } public: - RSU(uint32_t seedBase, uint32_t seedOffset) - { + RSU(uint32_t seedBase, uint32_t seedOffset) { m_index = permuteQPR(permuteQPR(seedBase) + 0x682f0161); m_intermediateOffset = permuteQPR(permuteQPR(seedOffset) + 0x46790905); } @@ -64,8 +57,7 @@ using Perturb = std::function&)>; // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- template -void test(const char* name, const Perturb& perturb1, const Perturb& /* perturb2 */) -{ +void test(const char* name, const Perturb& perturb1, const Perturb& /* perturb2 */) { // gtl::btree_set s; Set s; @@ -79,7 +71,7 @@ void test(const char* name, const Perturb& perturb1, const Perturb& /* perturb2 s.end()); // contains sorted, randomly generated keys (when using gtl::btree_set) // or keys in the final order of a Set (when using Set). - perturb1(order); // either keep them in same order, or shuffle them + perturb1(order); // either keep them in same order, or shuffle them #if 0 order.resize(N/4); @@ -105,8 +97,7 @@ using pset = gtl::parallel_flat_hash_set& order) { std::random_device rd; std::mt19937 g(rd()); diff --git a/examples/hmap/serialize.cpp b/examples/hmap/serialize.cpp index f28d46f..18faecc 100644 --- a/examples/hmap/serialize.cpp +++ b/examples/hmap/serialize.cpp @@ -26,14 +26,12 @@ using milliseconds = std::chrono::duration; // -------------------------------------------------------------------------- // from: https://github.com/preshing/RandomSequence // -------------------------------------------------------------------------- -class RSU -{ +class RSU { private: unsigned int m_index; unsigned int m_intermediateOffset; - static unsigned int permuteQPR(unsigned int x) - { + static unsigned int permuteQPR(unsigned int x) { static const unsigned int prime = 4294967291u; if (x >= prime) return x; // The 5 integers out of range are mapped to themselves. @@ -42,8 +40,7 @@ class RSU } public: - RSU(unsigned int seedBase, unsigned int seedOffset) - { + RSU(unsigned int seedBase, unsigned int seedOffset) { m_index = permuteQPR(permuteQPR(seedBase) + 0x682f0161); m_intermediateOffset = permuteQPR(permuteQPR(seedOffset) + 0x46790905); } @@ -53,8 +50,7 @@ class RSU // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- -void showtime(const char* name, const std::function& doit) -{ +void showtime(const char* name, const std::function& doit) { auto t1 = std::chrono::high_resolution_clock::now(); doit(); auto t2 = std::chrono::high_resolution_clock::now(); @@ -65,8 +61,7 @@ void showtime(const char* name, const std::function& doit) // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- template -void testMapSerialization(const char* maptype, const char* fname) -{ +void testMapSerialization(const char* maptype, const char* fname) { MapType table; const int num_items = 100000000; @@ -125,8 +120,7 @@ void testMapSerialization(const char* maptype, const char* fname) // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- template -void testSetSerialization(const char* settype, const char* fname) -{ +void testSetSerialization(const char* settype, const char* fname) { SetType table; const int num_items = 100000000; @@ -184,8 +178,7 @@ void testSetSerialization(const char* settype, const char* fname) // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- -int main() -{ +int main() { testSetSerialization>("flat_hash_set", "dump1.bin"); #if 0 testSetSerialization>("parallel_flat_hash_set", "dump1.bin"); diff --git a/examples/memoize/memoize_fib.cpp b/examples/memoize/memoize_fib.cpp index d5876f3..2460420 100644 --- a/examples/memoize/memoize_fib.cpp +++ b/examples/memoize/memoize_fib.cpp @@ -19,8 +19,7 @@ uint64_t fib(uint64_t n) // cached fibonacci #else -uint64_t fib(uint64_t n) -{ +uint64_t fib(uint64_t n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); @@ -28,16 +27,12 @@ uint64_t fib(uint64_t n) #endif -int main() -{ +int main() { stopwatch sw; constexpr uint64_t val = 42; uint64_t x = fib(val); sw.snap(); - printf("fib(%" PRIu64 "): => %" PRIu64 " in %10.3f seconds\n", - val, - x, - sw.since_start() / 1000); + printf("fib(%" PRIu64 "): => %" PRIu64 " in %10.3f seconds\n", val, x, sw.since_start() / 1000); return 0; } diff --git a/examples/memoize/memoize_primes.cpp b/examples/memoize/memoize_primes.cpp index 6378e3d..6a4a8c1 100644 --- a/examples/memoize/memoize_primes.cpp +++ b/examples/memoize/memoize_primes.cpp @@ -41,8 +41,7 @@ auto cached_twin_primes = gtl::memoize(&twin_primes); // returns f(end), but avoid recursing one by one // --------------------------------------------------------- template -void avoid_deep_recursion(F& f, uint64_t end) -{ +void avoid_deep_recursion(F& f, uint64_t end) { constexpr uint64_t incr = 512; if (end > incr && f.contains(end - incr)) return; @@ -53,8 +52,7 @@ void avoid_deep_recursion(F& f, uint64_t end) // return the nth element in the infinite list of prime numbers // ------------------------------------------------------------ -uint64_t nth_prime(uint64_t idx) -{ +uint64_t nth_prime(uint64_t idx) { if (idx == 0) return 2; @@ -70,8 +68,7 @@ uint64_t nth_prime(uint64_t idx) // returns the number of prime factors of n // ---------------------------------------- -uint64_t num_factors(uint64_t n) -{ +uint64_t num_factors(uint64_t n) { for (uint64_t i = 0;; ++i) { uint64_t factor = cached_nth_prime(i); if (factor * factor > n) @@ -86,8 +83,7 @@ uint64_t num_factors(uint64_t n) // returns the index, in the infinite list of prime numbers, of the first prime // of the idx'th pair of twin primes. // ---------------------------------------------------------------------------- -uint64_t twin_primes(uint64_t idx) -{ +uint64_t twin_primes(uint64_t idx) { if (idx == 0) return 1; // (3, 5) are the first twin primes @@ -104,8 +100,7 @@ uint64_t twin_primes(uint64_t idx) assert(0); } -int main() -{ +int main() { auto x1 = [](int i) -> int { return i + 1; }; auto y = gtl::memoize(x1); printf("---- %d\n", y(6)); @@ -114,10 +109,7 @@ int main() constexpr uint64_t idx = 10000; auto x = cached_nth_prime(idx); - printf("cached_nth_prime(%" PRIu64 "): => %" PRIu64 " in %10.3f seconds\n", - idx, - x, - sw.since_start() / 1000); + printf("cached_nth_prime(%" PRIu64 "): => %" PRIu64 " in %10.3f seconds\n", idx, x, sw.since_start() / 1000); auto first = cached_twin_primes(idx); printf("cached_twin_primes(%" PRIu64 "): => (%" PRIu64 ", %" PRIu64 ") in %10.3f seconds\n", diff --git a/examples/memoize/mt_memoize.cpp b/examples/memoize/mt_memoize.cpp index a7b66fb..5d324ea 100644 --- a/examples/memoize/mt_memoize.cpp +++ b/examples/memoize/mt_memoize.cpp @@ -15,16 +15,14 @@ using namespace std::chrono_literals; -double complexMathFunction(int a, double b) -{ +double complexMathFunction(int a, double b) { double x = 0; for (int i = a; i < a + 5000; ++i) x += std::sin(double(i) / b) + std::cos((double)i) + tanh(double(i)); return x; } -double simulate() -{ +double simulate() { double res = 0; #if USE_CACHING @@ -41,8 +39,7 @@ double simulate() return res; } -int main() -{ +int main() { double sum = 0; std::vector> threads; gtl::stopwatch sw; diff --git a/examples/memoize/mt_memoize_lru.cpp b/examples/memoize/mt_memoize_lru.cpp index 5a41840..73da97c 100644 --- a/examples/memoize/mt_memoize_lru.cpp +++ b/examples/memoize/mt_memoize_lru.cpp @@ -15,16 +15,14 @@ using namespace std::chrono_literals; -double complexMathFunction(int a, double b) -{ +double complexMathFunction(int a, double b) { double x = 0; for (int i = a; i < a + 5000; ++i) x += std::sin(double(i) / b) + std::cos((double)i) + tanh(double(i)); return x; } -double simulate() -{ +double simulate() { double res = 0; #if USE_CACHING @@ -43,8 +41,7 @@ double simulate() return res; } -int main() -{ +int main() { double sum = 0; std::vector> threads; gtl::stopwatch sw; diff --git a/examples/misc/adv_utils.cpp b/examples/misc/adv_utils.cpp index 2920793..6c1f841 100644 --- a/examples/misc/adv_utils.cpp +++ b/examples/misc/adv_utils.cpp @@ -2,8 +2,7 @@ #include #include -int main() -{ +int main() { { // For example, we can use gtl::binary_search to take an integer square root: auto x = gtl::binary_search( diff --git a/examples/misc/bit_vector.cpp b/examples/misc/bit_vector.cpp index 2c206d6..12ab78a 100644 --- a/examples/misc/bit_vector.cpp +++ b/examples/misc/bit_vector.cpp @@ -2,8 +2,7 @@ using std::string; -int main() -{ +int main() { { // allocate small bit_vector on the stack, do very basic operations on it // ---------------------------------------------------------------------- @@ -93,7 +92,7 @@ int main() gtl::bit_vector bv{ 0x0321 }; assert((string)bv == "0x0000000000000321"); - bv.view(0, 4) = 0xf; // create a view on bv, and assign a value to its bits + bv.view(0, 4) = 0xf; // create a view on bv, and assign a value to its bits assert((string)bv == "0x000000000000032f"); // modifies underlying bit_vector bv.view(4, 12) = 0xde; @@ -105,8 +104,7 @@ int main() bv.view(4, 20) >>= 8; // you can bit-shift a view, changing only the "viewed" bits assert((string)bv == "0x70000000000de00f"); - bv.view(4, 12) = - bv.view(12, 20); // or assign a view to another one - they have to be the same size + bv.view(4, 12) = bv.view(12, 20); // or assign a view to another one - they have to be the same size assert((string)bv == "0x70000000000dedef"); assert(bv.view(0, 4).count() == 4); // count set bits in a view @@ -116,8 +114,7 @@ int main() assert((string)bv == "0x77000000000dedef"); // anything you can do on a gtl::bit_vector also works on a gtl::bit_view. - assert((string)bv.view(4, 12) == - "0xde"); // it can also be converted to a string or output on a stream + assert((string)bv.view(4, 12) == "0xde"); // it can also be converted to a string or output on a stream } return 0; diff --git a/examples/misc/intrusive.cpp b/examples/misc/intrusive.cpp index 6d3239e..5d872c3 100644 --- a/examples/misc/intrusive.cpp +++ b/examples/misc/intrusive.cpp @@ -1,26 +1,22 @@ #include #include -struct A : public gtl::intrusive_ref_counter -{ +struct A : public gtl::intrusive_ref_counter { virtual ~A() { std::cout << "A deleted" << std::endl; } int x; }; -struct D : public A -{ +struct D : public A { ~D() { std::cout << "D deleted" << std::endl; } int y; }; -struct B : public gtl::intrusive_ref_counter -{ +struct B : public gtl::intrusive_ref_counter { ~B() { std::cout << "B deleted" << std::endl; } int x; }; -int main() -{ +int main() { { gtl::intrusive_ptr a = new A; diff --git a/examples/misc/soa.cpp b/examples/misc/soa.cpp index a99f9a4..fc42acd 100644 --- a/examples/misc/soa.cpp +++ b/examples/misc/soa.cpp @@ -32,8 +32,7 @@ #include #include -int main() -{ +int main() { // presidents will be a soa representing order, first name, last name constexpr int order = 0; diff --git a/examples/misc/utils.cpp b/examples/misc/utils.cpp index 6c1e238..59c30e3 100644 --- a/examples/misc/utils.cpp +++ b/examples/misc/utils.cpp @@ -1,28 +1,24 @@ #include #include -struct A : public gtl::timestamp -{ +struct A : public gtl::timestamp { bool set_x(int v) { return set_with_ts(x_, v); } int x_{ 0 }; }; -struct B : public gtl::timestamp -{ +struct B : public gtl::timestamp { bool set_y(int v) { return set_with_ts(y_, v); } int y_{ 0 }; }; -struct C : public gtl::provides_timestamp -{ +struct C : public gtl::provides_timestamp { gtl::timestamp get_timestamp() const { return a_ | b_; } A a_; B b_; }; -int main() -{ +int main() { // gtl::timestamp // -------------- A a; diff --git a/examples/misc/vec_utils.cpp b/examples/misc/vec_utils.cpp index 8f6d5dc..6cad3fa 100644 --- a/examples/misc/vec_utils.cpp +++ b/examples/misc/vec_utils.cpp @@ -16,8 +16,7 @@ #include -int main() -{ +int main() { using vec = std::vector; // vector concatenation @@ -50,13 +49,9 @@ int main() // map // --- auto v2 = gtl::map( - [v1](const auto& e) -> std::vector { - return gtl::cat(gtl::slice(v1, 0, 1), std::vector({ e })); - }, - l); + [v1](const auto& e) -> std::vector { return gtl::cat(gtl::slice(v1, 0, 1), std::vector({ e })); }, l); - assert(gtl::map([](int e) { return e + 1; }, std::vector({ 1, 2, 3 })) == - std::vector({ 2, 3, 4 })); + assert(gtl::map([](int e) { return e + 1; }, std::vector({ 1, 2, 3 })) == std::vector({ 2, 3, 4 })); return 0; } diff --git a/examples/phmap/insert_bench.cpp b/examples/phmap/insert_bench.cpp index df265df..6573650 100644 --- a/examples/phmap/insert_bench.cpp +++ b/examples/phmap/insert_bench.cpp @@ -9,8 +9,7 @@ // this is probably the fastest high quality 64bit random number generator that exists. // Implements Small Fast Counting v4 RNG from PractRand. -class sfc64 -{ +class sfc64 { public: using result_type = uint64_t; @@ -25,24 +24,19 @@ class sfc64 : m_a(_state[0]) , m_b(_state[1]) , m_c(_state[2]) - , m_counter(_state[3]) - { - } + , m_counter(_state[3]) {} static constexpr uint64_t(min)() { return (std::numeric_limits::min)(); } static constexpr uint64_t(max)() { return (std::numeric_limits::max)(); } sfc64() - : sfc64(UINT64_C(0x853c49e6748fea9b)) - { - } + : sfc64(UINT64_C(0x853c49e6748fea9b)) {} sfc64(uint64_t _seed) : m_a(_seed) , m_b(_seed) , m_c(_seed) - , m_counter(1) - { + , m_counter(1) { for (int i = 0; i < 12; ++i) { operator()(); } @@ -50,8 +44,7 @@ class sfc64 void seed() { *this = sfc64{ std::random_device{}() }; } - uint64_t operator()() noexcept - { + uint64_t operator()() noexcept { auto const tmp = m_a + m_b + m_counter++; m_a = m_b ^ (m_b >> right_shift); m_b = m_c + (m_c << left_shift); @@ -60,8 +53,7 @@ class sfc64 } // this is a bit biased, but for our use case that's not important. - uint64_t operator()([[maybe_unused]] uint64_t boundExcluded) noexcept - { + uint64_t operator()([[maybe_unused]] uint64_t boundExcluded) noexcept { #ifdef GTL_HAS_UMUL128 uint64_t h; (void)umul128(operator()(), boundExcluded, &h); @@ -71,15 +63,13 @@ class sfc64 #endif } - std::array state() const - { + std::array state() const { return { {m_a, m_b, m_c, m_counter} }; } - void state(std::array const& s) - { + void state(std::array const& s) { m_a = s[0]; m_b = s[1]; m_c = s[2]; @@ -88,8 +78,7 @@ class sfc64 private: template - T rotl(T const x, int k) - { + T rotl(T const x, int k) { return (x << k) | (x >> (8 * sizeof(T) - k)); } @@ -102,8 +91,7 @@ class sfc64 uint64_t m_counter; }; -int main() -{ +int main() { // Create an unordered_map of three strings (that map to strings) using Map = gtl::parallel_node_hash_map; static size_t const n = 50000000; diff --git a/examples/phmap/lazy_emplace_l.cpp b/examples/phmap/lazy_emplace_l.cpp index 449928b..7119b0c 100644 --- a/examples/phmap/lazy_emplace_l.cpp +++ b/examples/phmap/lazy_emplace_l.cpp @@ -9,8 +9,7 @@ #include #include -class srwlock -{ +class srwlock { SRWLOCK _lock; public: @@ -27,20 +26,16 @@ using Map = gtl::parallel_flat_hash_map; -class Dict -{ +class Dict { Map m_stringsMap; public: - int addParallel(std::string&& str, volatile long* curIdx) - { + int addParallel(std::string&& str, volatile long* curIdx) { int newIndex = -1; m_stringsMap.lazy_emplace_l( std::move(str), - [&](Map::value_type& p) { - newIndex = p.second; - }, // called only when key was already present - [&](const Map::constructor& ctor) // construct value_type in place when key not present + [&](Map::value_type& p) { newIndex = p.second; }, // called only when key was already present + [&](const Map::constructor& ctor) // construct value_type in place when key not present { newIndex = InterlockedIncrement(curIdx); ctor(std::move(str), newIndex); @@ -50,8 +45,7 @@ class Dict } }; -int main() -{ +int main() { size_t totalSize = 6000000; std::vector values(totalSize); Dict dict; diff --git a/examples/phmap/mt_word_counter.cpp b/examples/phmap/mt_word_counter.cpp index db7ad92..5def565 100644 --- a/examples/phmap/mt_word_counter.cpp +++ b/examples/phmap/mt_word_counter.cpp @@ -15,8 +15,7 @@ * count the number of occurrences of each word in a large text file using multiple threads */ -int main() -{ +int main() { const std::string filename = "1342-0.txt"; if (!std::filesystem::exists(filename)) { diff --git a/include/gtl/adv_utils.hpp b/include/gtl/adv_utils.hpp index 0e26c92..c414bbe 100644 --- a/include/gtl/adv_utils.hpp +++ b/include/gtl/adv_utils.hpp @@ -58,10 +58,8 @@ std::pair binary_search(Middle&& middle, Pred&& pred, T l, T r) if (!m) return { l, r }; return std::forward(pred)(*m) - ? binary_search( - std::forward(middle), std::forward(pred), l, *m) - : binary_search( - std::forward(middle), std::forward(pred), *m, r); + ? binary_search(std::forward(middle), std::forward(pred), l, *m) + : binary_search(std::forward(middle), std::forward(pred), *m, r); } // --------------------------------------------------------------------------- @@ -74,35 +72,30 @@ concept is_double = std::same_as; // ------------------------------------------ template requires std::integral || is_double -struct middle -{}; +struct middle {}; template -struct middle -{ - std::optional operator()(T l, T r) - { +struct middle { + std::optional operator()(T l, T r) { if (r - l > 1) - return std::optional{ std::midpoint(l, r) }; - return std::optional{}; + return std::midpoint(l, r); + return {}; } }; // Compare doubles using the binary representation // ----------------------------------------------- template -struct middle -{ - std::optional operator()(T l, T r) - { - uint64_t* il = (uint64_t*)&l; - uint64_t* ir = (uint64_t*)&r; +struct middle { + std::optional operator()(T l, T r) { + uint64_t* il = reinterpret_cast(&l); + uint64_t* ir = reinterpret_cast(&r); auto m = middle()(*il, *ir); if (m) { uint64_t med = *m; - return std::optional{ *(T*)&med }; + return *(T*)&med; } - return std::optional{}; + return {}; } }; diff --git a/include/gtl/bit_vector.hpp b/include/gtl/bit_vector.hpp index fac3d27..e435943 100644 --- a/include/gtl/bit_vector.hpp +++ b/include/gtl/bit_vector.hpp @@ -41,8 +41,7 @@ static constexpr uint64_t lowmask(size_t n) { return bitmask(n) - 1; } // a mask for bits higher than n-1 in slot static constexpr uint64_t himask(size_t n) { return ~lowmask(n); } -static constexpr size_t _popcount64(uint64_t y) -{ +static constexpr size_t _popcount64(uint64_t y) { // https://gist.github.com/enjoylife/4091854 y -= ((y >> 1) & 0x5555555555555555ull); y = (y & 0x3333333333333333ull) + (y >> 2 & 0x3333333333333333ull); @@ -50,8 +49,7 @@ static constexpr size_t _popcount64(uint64_t y) } // De Bruijn Multiplication With separated LS1B - author Kim Walisch (2012) -unsigned countr_zero(uint64_t bb) -{ +unsigned countr_zero(uint64_t bb) { const unsigned index64[64] = { 0, 47, 1, 56, 48, 27, 2, 60, 57, 49, 41, 37, 28, 16, 3, 61, 54, 58, 35, 52, 50, 42, 21, 44, 38, 32, 29, 23, 17, 11, 4, 62, 46, 55, 26, 59, 40, 36, 15, 53, 34, 51, 20, 43, 31, 22, 10, 45, @@ -61,15 +59,7 @@ unsigned countr_zero(uint64_t bb) return index64[((bb ^ (bb - 1)) * debruijn64) >> 58]; } -enum class vt -{ - none = 0, - view = 1, - oor_ones = 2, - backward = 4, - true_ = 8, - false_ = 16 -}; // visitor flags +enum class vt { none = 0, view = 1, oor_ones = 2, backward = 4, true_ = 8, false_ = 16 }; // visitor flags using vt_type = std::underlying_type::type; @@ -83,15 +73,13 @@ constexpr vt operator|(vt a, vt b) { return (vt)((vt_type)a | (vt_type)b); } // or like what I did before) // --------------------------------------------------------------------------- template -class storage -{ +class storage { public: storage(size_t num_bits = 0, bool val = false) { resize(num_bits, val); } size_t size() const { return _s.size(); } // size in slots // ------------------------------------------------------------------------------- - void resize(size_t num_bits, bool val = false) - { + void resize(size_t num_bits, bool val = false) { _sz = num_bits; size_t num_slots = slot_cnt(num_bits); _s.resize(num_slots, val ? ones : 0); @@ -101,8 +89,7 @@ class storage } bool operator==(const storage& o) const { return _s == o._s; } - uint64_t operator[](size_t slot) const - { + uint64_t operator[](size_t slot) const { assert(slot < _s.size()); return _s[slot]; } @@ -111,8 +98,7 @@ class storage // bits starting at first, where the first uint64_t returned // contains the first init_lg bits of the sequence, shifted shift bits. // ------------------------------------------------------------------------------- - class bit_sequence - { + class bit_sequence { public: bit_sequence(const storage& s, size_t first, size_t last, size_t as_first) : _s(s) @@ -129,8 +115,7 @@ class storage assert(_init_lg + _shift <= stride); } - uint64_t operator()() - { + uint64_t operator()() { if (_init_lg) { uint64_t res = get_next_bits(_init_lg); _init_lg = 0; @@ -142,8 +127,7 @@ class storage // returns the next std::min(lg, _last - _cur) of the bit sequence // masked appropriately - uint64_t get_next_bits(size_t lg) - { + uint64_t get_next_bits(size_t lg) { lg = std::min(lg, _last - _cur); assert(lg); @@ -176,8 +160,7 @@ class storage // ------------------------------------------------------------------------------------ template - void update_bit(size_t idx, F f) - { + void update_bit(size_t idx, F f) { assert(idx < _sz); const size_t slot_idx = slot(idx); uint64_t& s = _s[slot_idx]; @@ -188,8 +171,7 @@ class storage } template - void update_bit(size_t idx) - { + void update_bit(size_t idx) { assert(idx < _sz); uint64_t& s = _s[slot(idx)]; uint64_t m = bitmask(idx); @@ -204,8 +186,7 @@ class storage } template - constexpr uint64_t oor_bits(uint64_t s, uint64_t m) - { + constexpr uint64_t oor_bits(uint64_t s, uint64_t m) { if constexpr (!(flags & vt::oor_ones)) return (s & ~m); else @@ -218,8 +199,7 @@ class storage // if (flags & vt::view), this fn exits early when the callback returns true. // ------------------------------------------------------------------------------------ template - void visit(const size_t first, const size_t last, F f) - { + void visit(const size_t first, const size_t last, F f) { assert(last <= _sz); if (last <= first) return; @@ -333,8 +313,7 @@ class storage // ----------------------------------------------------------------------- template - void visit_all([[maybe_unused]] F f) - { + void visit_all([[maybe_unused]] F f) { size_t num_slots = slot_cnt(_sz); if constexpr (flags & vt::false_) { // set all bits to 0 @@ -373,15 +352,13 @@ class storage _check_extra_bits(); } - void swap(storage& o) - { + void swap(storage& o) { _s.swap(o._s); std::swap(_sz, o._sz); } private: - void _check_extra_bits() const - { + void _check_extra_bits() const { #ifdef _DEBUG // here we make sure that the bits in the last slot past the bit_vector size() are zeroed if (mod(_sz)) @@ -397,16 +374,14 @@ class storage // implements bit_view class // --------------------------------------------------------------------------- template class BV> -class _view -{ +class _view { public: static constexpr size_t npos = static_cast(-1); // typename std::numeric_limits::max(); using vec_type = BV; explicit _view(vec_type& bv, size_t first = 0, size_t last = npos) : _bv(bv) - , _first(first) - { + , _first(first) { _last = (last == npos) ? _bv.size() : last; assert(_last >= _first); } @@ -416,45 +391,41 @@ class _view // single bit access // ----------------- - _view& set(size_t idx) - { + _view& set(size_t idx) { _bv.set(idx + _first); return *this; } - _view& reset(size_t idx) - { + + _view& reset(size_t idx) { _bv.reset(idx + _first); return *this; } - _view& flip(size_t idx) - { + + _view& flip(size_t idx) { _bv.flip(idx + _first); return *this; } + bool operator[](size_t idx) const { return _bv[idx + _first]; } - _view& set(size_t idx, bool val) - { + _view& set(size_t idx, bool val) { _bv.set(idx + _first, val); return *this; } // change whole view // ----------------- - _view& set() - { + _view& set() { _bv.storage().template visit(_first, _last, [](uint64_t, int) { return ones; }); return *this; } - _view& reset() - { + _view& reset() { _bv.storage().template visit(_first, _last, [](uint64_t, int) { return (uint64_t)0; }); return *this; } - _view& flip() - { + _view& flip() { _bv.storage().template visit(_first, _last, [](uint64_t v, int) { return ~v; }); return *this; } @@ -462,48 +433,41 @@ class _view // compound assignment operators // ----------------------------- template - _view& bin_assign(const _view& o, F&& f) noexcept - { + _view& bin_assign(const _view& o, F&& f) noexcept { assert(size() == o.size()); (void)o; _bv.storage().template visit(_first, _last, std::forward(f)); return *this; } - _view& operator|=(const _view& o) noexcept - { + _view& operator|=(const _view& o) noexcept { typename S::bit_sequence seq(o._bv.storage(), o._first, o._last, _first); return bin_assign(o, [&](uint64_t a, size_t) { return a | seq(); }); } - _view& operator&=(const _view& o) noexcept - { + _view& operator&=(const _view& o) noexcept { typename S::bit_sequence seq(o._bv.storage(), o._first, o._last, _first); return bin_assign(o, [&](uint64_t a, size_t) { return a & seq(); }); } - _view& operator^=(const _view& o) noexcept - { + _view& operator^=(const _view& o) noexcept { typename S::bit_sequence seq(o._bv.storage(), o._first, o._last, _first); return bin_assign(o, [&](uint64_t a, size_t) { return a ^ seq(); }); } - _view& operator-=(const _view& o) noexcept - { + _view& operator-=(const _view& o) noexcept { typename S::bit_sequence seq(o._bv.storage(), o._first, o._last, _first); return bin_assign(o, [&](uint64_t a, size_t) { return a & ~seq(); }); } - _view& or_not(const _view& o) noexcept - { + _view& or_not(const _view& o) noexcept { typename S::bit_sequence seq(o._bv.storage(), o._first, o._last, _first); return bin_assign(o, [&](uint64_t a, size_t) { return a | ~seq(); }); } // shift operators. Zeroes are shifted in. // --------------------------------------- - _view& operator<<=(size_t cnt) noexcept - { + _view& operator<<=(size_t cnt) noexcept { if (cnt >= size()) reset(); else if (cnt) { @@ -532,8 +496,7 @@ class _view return *this; } - _view& operator>>=(size_t cnt) noexcept - { + _view& operator>>=(size_t cnt) noexcept { if (cnt >= size()) reset(); else if (cnt) { @@ -564,8 +527,7 @@ class _view // assignment operators // -------------------- - _view& operator=(uint64_t val) - { + _view& operator=(uint64_t val) { // only works for view width <= 64 bits assert(size() <= stride); _bv.storage().template visit( @@ -573,8 +535,7 @@ class _view return *this; } - _view& operator=(std::initializer_list vals) - { + _view& operator=(std::initializer_list vals) { size_t num_vals = vals.size(); auto v = vals.begin(); size_t start = _first; @@ -586,8 +547,7 @@ class _view return *this; } - _view& operator=(const _view& o) - { + _view& operator=(const _view& o) { assert(size() == o.size()); if ((&_bv != &o._bv) || (_first < o._first) || (_first <= o._last)) { typename S::bit_sequence seq(o._bv.storage(), o._first, o._last, _first); @@ -601,8 +561,7 @@ class _view } // debug version, do not use (instead use operator=() above) - _view& copy_slow(const _view& o) - { + _view& copy_slow(const _view& o) { assert(size() == o.size()); // ------ slow version if (&_bv != &o._bv) { @@ -623,8 +582,7 @@ class _view } template - bool operator==(const View& o) const - { + bool operator==(const View& o) const { if (size() != o.size()) return false; typename S::bit_sequence seq(o._bv.storage(), o._first, o._last, _first); @@ -639,8 +597,7 @@ class _view // unary predicates: any, every, etc... // ------------------------------------ - bool any() const - { + bool any() const { bool res = false; _bv.storage().template visit(_first, _last, [&](uint64_t v, int) { if (v) @@ -650,8 +607,7 @@ class _view return res; } - bool every() const - { + bool every() const { bool res = true; _bv.storage().template visit(_first, _last, [&](uint64_t v, int) { if (v != ones) @@ -666,8 +622,7 @@ class _view // binary predicates: contains, disjoint, ... // ------------------------------------------ template - bool contains(const View& o) const - { + bool contains(const View& o) const { assert(size() >= o.size()); if (size() < o.size()) return false; @@ -683,8 +638,7 @@ class _view } template - bool disjoint(const View& o) const - { + bool disjoint(const View& o) const { bool res = true; if (size() <= o.size()) { typename S::bit_sequence seq(o._bv.storage(), o._first, o._first + size(), _first); @@ -707,15 +661,13 @@ class _view } template - bool intersect(const View& o) const - { + bool intersect(const View& o) const { return !disjoint(o); } // miscellaneous // ------------- - size_t count() const - { // we could use std::popcount in c++20 + size_t count() const { // we could use std::popcount in c++20 size_t cnt = 0; _bv.storage().template visit(_first, _last, [&](uint64_t v, int) { cnt += _popcount64(v); @@ -726,8 +678,7 @@ class _view // find next one bit - returns npos if not found // --------------------------------------------- - size_t find_first() const - { + size_t find_first() const { size_t idx = _first; _bv.storage().template visit(_first, _last, [&](uint64_t v, int shift) { if (v) { @@ -743,8 +694,7 @@ class _view return npos; } - size_t find_next(size_t start) const - { + size_t find_next(size_t start) const { if (_first + start >= _last) return npos; size_t res = _bv.view(_first + start, _last).find_first(); @@ -754,16 +704,14 @@ class _view // print // ----- template> - friend std::basic_ostream& operator<<(std::basic_ostream& s, const _view& v) - { + friend std::basic_ostream& operator<<(std::basic_ostream& s, const _view& v) { return s << static_cast(v); } // conversion to std::string // ------------------------- template, class A = std::allocator> - void append_to_string(std::basic_string& res) const - { + void append_to_string(std::basic_string& res) const { size_t num_bytes = (size() + 7) >> 3; size_t start = res.size(); size_t cur = start + num_bytes * 2; @@ -789,8 +737,7 @@ class _view // make bit_vector convertible to std::string template, class A = std::allocator> - operator std::basic_string() const - { + operator std::basic_string() const { if (size() == 0) return ""; std::basic_string res; @@ -812,8 +759,7 @@ class _view // implements bit_vector class // --------------------------------------------------------------------------- template -class vec -{ +class vec { public: using storage_type = S; using bv_type = _view; @@ -821,36 +767,29 @@ class vec explicit vec(size_t sz = 0, bool val = false) : _sz(sz) - , _s(sz, val) - { - } + , _s(sz, val) {} explicit vec(std::initializer_list vals) - : vec(vals.size() * stride) - { - *this = vals; + : vec(vals.size() * stride) { + *this = vals; } - void resize(size_t sz, bool val = false) - { + void resize(size_t sz, bool val = false) { _sz = sz; _s.resize(_sz, val); } // bit access // ---------- - vec& set(size_t idx) - { + vec& set(size_t idx) { _s.template update_bit(idx); return *this; } - vec& reset(size_t idx) - { + vec& reset(size_t idx) { _s.template update_bit(idx); return *this; } - vec& flip(size_t idx) - { + vec& flip(size_t idx) { _s.update_bit(idx, [](uint64_t v) { return ~v; }); return *this; } @@ -858,8 +797,7 @@ class vec bool operator[](size_t idx) const { return !!(_s[slot(idx)] & bitmask(idx)); } // either sets or resets the bit depending on val - vec& set(size_t idx, bool val) - { + vec& set(size_t idx, bool val) { if (val) _s.template update_bit(idx); else @@ -869,18 +807,15 @@ class vec // change whole bit_vector // ----------------------- - vec& set() - { + vec& set() { _s.template visit_all(nullptr); return *this; } - vec& reset() - { + vec& reset() { _s.template visit_all(nullptr); return *this; } - vec& flip() - { + vec& flip() { _s.template visit_all([](uint64_t v) { return ~v; }); return *this; } @@ -890,44 +825,37 @@ class vec // bitwise operators on full bit_vector // ------------------------------------ - vec operator|(const vec& o) const noexcept - { + vec operator|(const vec& o) const noexcept { vec res(*this); res |= o; return res; } - vec operator&(const vec& o) const noexcept - { + vec operator&(const vec& o) const noexcept { vec res(*this); res &= o; return res; } - vec operator^(const vec& o) const noexcept - { + vec operator^(const vec& o) const noexcept { vec res(*this); res ^= o; return res; } - vec operator-(const vec& o) const noexcept - { + vec operator-(const vec& o) const noexcept { vec res(*this); res -= o; return res; } - vec operator~() const noexcept - { + vec operator~() const noexcept { vec res(*this); res.flip(); return res; } - vec operator<<(size_t cnt) const noexcept - { + vec operator<<(size_t cnt) const noexcept { vec res(*this); res <<= cnt; return res; } - vec operator>>(size_t cnt) const noexcept - { + vec operator>>(size_t cnt) const noexcept { vec res(*this); res >>= cnt; return res; @@ -935,36 +863,30 @@ class vec // compound assignment operators on full bit_vector // ------------------------------------------------ - vec& operator|=(const vec& o) noexcept - { + vec& operator|=(const vec& o) noexcept { view() |= o.view(); return *this; } - vec& operator&=(const vec& o) noexcept - { + vec& operator&=(const vec& o) noexcept { view() &= o.view(); return *this; } - vec& operator^=(const vec& o) noexcept - { + vec& operator^=(const vec& o) noexcept { view() ^= o.view(); return *this; } - vec& operator-=(const vec& o) noexcept - { + vec& operator-=(const vec& o) noexcept { view() -= o.view(); return *this; } - vec& or_not(const vec& o) noexcept - { + vec& or_not(const vec& o) noexcept { view().or_not(o.view()); return *this; } // assignment operators on full bit_vector // --------------------------------------- - vec& operator=(std::initializer_list vals) - { + vec& operator=(std::initializer_list vals) { size_t num_vals = vals.size(); auto v = vals.begin(); for (size_t i = 0; i < num_vals; ++i) @@ -974,21 +896,18 @@ class vec // shift operators. Zeroes are shifted in. // --------------------------------------- - vec& operator<<=(size_t cnt) - { + vec& operator<<=(size_t cnt) { view() <<= cnt; return *this; } - vec& operator>>=(size_t cnt) - { + vec& operator>>=(size_t cnt) { view() >>= cnt; return *this; } // unary predicates any, every, etc... // ----------------------------------- - bool any() const - { // "return view().any();" would work, but this is faster + bool any() const { // "return view().any();" would work, but this is faster bool res = false; const_cast(_s).template visit_all([&](uint64_t v) { if (v) @@ -998,8 +917,7 @@ class vec return res; } - bool every() const - { // "return view().every();" would work, but this is faster + bool every() const { // "return view().every();" would work, but this is faster bool res = true; const_cast(_s).template visit_all([&](uint64_t v) { if (v != ones) @@ -1015,39 +933,33 @@ class vec // support comparing bit_vectors with different storage // ------------------------------------------------------- template - bool operator==(const vec& o) const - { + bool operator==(const vec& o) const { return this == &o || view() == o.view(); } template - bool operator!=(const vec& o) const - { + bool operator!=(const vec& o) const { return !(*this == o); } template - bool contains(const vec& o) const - { + bool contains(const vec& o) const { return view().contains(o.view()); } template - bool disjoint(const vec& o) const - { + bool disjoint(const vec& o) const { return view().disjoint(o.view()); } template - bool intersects(const vec& o) const - { + bool intersects(const vec& o) const { return !disjoint(o); } // miscellaneous // ------------- - size_t count() const - { // "return view().count();" would work, but this is faster + size_t count() const { // "return view().count();" would work, but this is faster size_t cnt = 0; const_cast(_s).template visit_all([&](uint64_t v) { if (v) @@ -1057,8 +969,7 @@ class vec return cnt; } - void swap(vec& o) - { + void swap(vec& o) { std::swap(_sz, o._sz); _s.swap(o._s); } @@ -1079,8 +990,7 @@ class vec // standard bitset conversions // --------------------------- template, class A = std::allocator> - std::basic_string to_string(CharT zero = CharT('0'), CharT one = CharT('1')) const - { + std::basic_string to_string(CharT zero = CharT('0'), CharT one = CharT('1')) const { std::basic_string res(_sz, zero); for (size_t i = 0; i < _sz; ++i) if (test(_sz - i - 1)) @@ -1095,29 +1005,25 @@ class vec // print // ----- template> - friend std::basic_ostream& operator<<(std::basic_ostream& s, const vec& v) - { + friend std::basic_ostream& operator<<(std::basic_ostream& s, const vec& v) { return s << (std::string)v; } template, class A = std::allocator> - void append_to_string(std::basic_string& res) const - { + void append_to_string(std::basic_string& res) const { view().append_to_string(res); } // make bit_vector convertible to std::string template, class A = std::allocator> - operator std::basic_string() const - { + operator std::basic_string() const { return static_cast>(view()); } // access via gtl::bit_view // ------------------------ bv_type view(size_t first = 0, size_t last = npos) { return bv_type(*this, first, last); } - const bv_type view(size_t first = 0, size_t last = npos) const - { + const bv_type view(size_t first = 0, size_t last = npos) const { return bv_type(const_cast(*this), first, last); } @@ -1139,10 +1045,8 @@ namespace std { // inject specialization of std::hash for gtl::bit_vector into namespace std // ------------------------------------------------------------------------- template<> -struct hash -{ - size_t operator()(gtl::bit_vector const& bv) const - { +struct hash { + size_t operator()(gtl::bit_vector const& bv) const { uint64_t h = bv.size(); size_t num_blocks = bv.num_blocks(); for (size_t i = 0; i < num_blocks; ++i) diff --git a/include/gtl/bits.hpp b/include/gtl/bits.hpp index 6115c26..9c03861 100644 --- a/include/gtl/bits.hpp +++ b/include/gtl/bits.hpp @@ -107,22 +107,19 @@ inline void UnalignedStore64(void* p, uint64_t v) { __sanitizer_unaligned_store6 namespace gtl { namespace bits { -inline uint16_t UnalignedLoad16(const void* p) -{ +inline uint16_t UnalignedLoad16(const void* p) { uint16_t t; memcpy(&t, p, sizeof t); return t; } -inline uint32_t UnalignedLoad32(const void* p) -{ +inline uint32_t UnalignedLoad32(const void* p) { uint32_t t; memcpy(&t, p, sizeof t); return t; } -inline uint64_t UnalignedLoad64(const void* p) -{ +inline uint64_t UnalignedLoad64(const void* p) { uint64_t t; memcpy(&t, p, sizeof t); return t; @@ -180,8 +177,7 @@ inline void UnalignedStore64(void* p, uint64_t v) { memcpy(p, &v, sizeof v); } #ifdef GTL_HAVE_INTRINSIC_INT128 __extension__ typedef unsigned __int128 gtl_uint128; -inline uint64_t umul128(uint64_t a, uint64_t b, uint64_t* high) -{ +inline uint64_t umul128(uint64_t a, uint64_t b, uint64_t* high) { auto result = static_cast(a) * static_cast(b); *high = static_cast(result >> 64); return static_cast(result); @@ -260,8 +256,7 @@ inline uint64_t umul128(uint64_t a, uint64_t b, uint64_t* high) { return _umul12 namespace gtl { -GTL_FORCEINLINE uint32_t CountLeadingZeros64Slow(uint64_t n) -{ +GTL_FORCEINLINE uint32_t CountLeadingZeros64Slow(uint64_t n) { uint32_t zeroes = 60; if (n >> 32) zeroes -= 32, n >>= 32; @@ -274,8 +269,7 @@ GTL_FORCEINLINE uint32_t CountLeadingZeros64Slow(uint64_t n) return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[n] + zeroes; } -GTL_FORCEINLINE uint32_t CountLeadingZeros64(uint64_t n) -{ +GTL_FORCEINLINE uint32_t CountLeadingZeros64(uint64_t n) { #if defined(_MSC_VER) && defined(_M_X64) // MSVC does not have __buitin_clzll. Use _BitScanReverse64. unsigned long result = 0; // NOLINT(runtime/int) @@ -311,8 +305,7 @@ GTL_FORCEINLINE uint32_t CountLeadingZeros64(uint64_t n) #endif } -GTL_FORCEINLINE uint32_t CountLeadingZeros32Slow(uint64_t n) -{ +GTL_FORCEINLINE uint32_t CountLeadingZeros32Slow(uint64_t n) { uint32_t zeroes = 28; if (n >> 16) zeroes -= 16, n >>= 16; @@ -323,8 +316,7 @@ GTL_FORCEINLINE uint32_t CountLeadingZeros32Slow(uint64_t n) return "\4\3\2\2\1\1\1\1\0\0\0\0\0\0\0"[n] + zeroes; } -GTL_FORCEINLINE uint32_t CountLeadingZeros32(uint32_t n) -{ +GTL_FORCEINLINE uint32_t CountLeadingZeros32(uint32_t n) { #if defined(_MSC_VER) && !defined(__clang__) unsigned long result = 0; // NOLINT(runtime/int) if (_BitScanReverse(&result, n)) { @@ -348,8 +340,7 @@ GTL_FORCEINLINE uint32_t CountLeadingZeros32(uint32_t n) #endif } -GTL_FORCEINLINE uint32_t CountTrailingZerosNonZero64Slow(uint64_t n) -{ +GTL_FORCEINLINE uint32_t CountTrailingZerosNonZero64Slow(uint64_t n) { uint32_t c = 63; n &= ~n + 1; if (n & 0x00000000FFFFFFFF) @@ -367,8 +358,7 @@ GTL_FORCEINLINE uint32_t CountTrailingZerosNonZero64Slow(uint64_t n) return c; } -GTL_FORCEINLINE uint32_t CountTrailingZerosNonZero64(uint64_t n) -{ +GTL_FORCEINLINE uint32_t CountTrailingZerosNonZero64(uint64_t n) { #if defined(_MSC_VER) && !defined(__clang__) && defined(_M_X64) unsigned long result = 0; // NOLINT(runtime/int) _BitScanForward64(&result, n); @@ -390,8 +380,7 @@ GTL_FORCEINLINE uint32_t CountTrailingZerosNonZero64(uint64_t n) #endif } -GTL_FORCEINLINE uint32_t CountTrailingZerosNonZero32Slow(uint32_t n) -{ +GTL_FORCEINLINE uint32_t CountTrailingZerosNonZero32Slow(uint32_t n) { uint32_t c = 31; n &= ~n + 1; if (n & 0x0000FFFF) @@ -407,8 +396,7 @@ GTL_FORCEINLINE uint32_t CountTrailingZerosNonZero32Slow(uint32_t n) return c; } -GTL_FORCEINLINE uint32_t CountTrailingZerosNonZero32(uint32_t n) -{ +GTL_FORCEINLINE uint32_t CountTrailingZerosNonZero32(uint32_t n) { #if defined(_MSC_VER) && !defined(__clang__) unsigned long result = 0; // NOLINT(runtime/int) _BitScanForward(&result, n); @@ -455,8 +443,7 @@ inline uint16_t gbswap_16(uint16_t host_int) { return OSSwapInt64(host_int); } #else -inline uint64_t gbswap_64(uint64_t host_int) -{ +inline uint64_t gbswap_64(uint64_t host_int) { #if defined(__GNUC__) && defined(__x86_64__) && !defined(__APPLE__) // Adapted from /usr/include/byteswap.h. Not available on Mac. if (__builtin_constant_p(host_int)) { @@ -469,29 +456,27 @@ inline uint64_t gbswap_64(uint64_t host_int) #elif defined(__GLIBC__) return bswap_64(host_int); #else - return (((host_int& uint64_t{ 0xFF }) << 56) | ((host_int& uint64_t{ 0xFF00 }) << 40) | - ((host_int& uint64_t{ 0xFF0000 }) << 24) | ((host_int& uint64_t{ 0xFF000000 }) << 8) | - ((host_int& uint64_t{ 0xFF00000000 }) >> 8) | ((host_int& uint64_t{ 0xFF0000000000 }) >> 24) | - ((host_int& uint64_t{ 0xFF000000000000 }) >> 40) | ((host_int& uint64_t{ 0xFF00000000000000 }) >> 56)); + return (((host_int & uint64_t{ 0xFF }) << 56) | ((host_int & uint64_t{ 0xFF00 }) << 40) | + ((host_int & uint64_t{ 0xFF0000 }) << 24) | ((host_int & uint64_t{ 0xFF000000 }) << 8) | + ((host_int & uint64_t{ 0xFF00000000 }) >> 8) | ((host_int & uint64_t{ 0xFF0000000000 }) >> 24) | + ((host_int & uint64_t{ 0xFF000000000000 }) >> 40) | ((host_int & uint64_t{ 0xFF00000000000000 }) >> 56)); #endif // bswap_64 } -inline uint32_t gbswap_32(uint32_t host_int) -{ +inline uint32_t gbswap_32(uint32_t host_int) { #if defined(__GLIBC__) return bswap_32(host_int); #else - return (((host_int& uint32_t{ 0xFF }) << 24) | ((host_int& uint32_t{ 0xFF00 }) << 8) | - ((host_int& uint32_t{ 0xFF0000 }) >> 8) | ((host_int& uint32_t{ 0xFF000000 }) >> 24)); + return (((host_int & uint32_t{ 0xFF }) << 24) | ((host_int & uint32_t{ 0xFF00 }) << 8) | + ((host_int & uint32_t{ 0xFF0000 }) >> 8) | ((host_int & uint32_t{ 0xFF000000 }) >> 24)); #endif } -inline uint16_t gbswap_16(uint16_t host_int) -{ +inline uint16_t gbswap_16(uint16_t host_int) { #if defined(__GLIBC__) return bswap_16(host_int); #else - return (((host_int& uint16_t{ 0xFF }) << 8) | ((host_int& uint16_t{ 0xFF00 }) >> 8)); + return (((host_int & uint16_t{ 0xFF }) << 8) | ((host_int & uint16_t{ 0xFF00 }) >> 8)); #endif } diff --git a/include/gtl/btree.hpp b/include/gtl/btree.hpp index 8828cf4..f01ac2b 100644 --- a/include/gtl/btree.hpp +++ b/include/gtl/btree.hpp @@ -90,14 +90,12 @@ namespace compare_internal { using value_type = int8_t; template -struct Fail -{ +struct Fail { static_assert(sizeof(T) < 0, "Only literal `0` is allowed."); }; template -struct OnlyLiteralZero -{ +struct OnlyLiteralZero { constexpr OnlyLiteralZero(NullPtrT) noexcept {} // NOLINT template -struct weak_equality_base -{ +struct weak_equality_base { GTL_COMPARE_INLINE_BASECLASS_DECL(equivalent) GTL_COMPARE_INLINE_BASECLASS_DECL(nonequivalent) }; template -struct strong_equality_base -{ +struct strong_equality_base { GTL_COMPARE_INLINE_BASECLASS_DECL(equal) GTL_COMPARE_INLINE_BASECLASS_DECL(nonequal) GTL_COMPARE_INLINE_BASECLASS_DECL(equivalent) @@ -167,8 +155,7 @@ struct strong_equality_base }; template -struct partial_ordering_base -{ +struct partial_ordering_base { GTL_COMPARE_INLINE_BASECLASS_DECL(less) GTL_COMPARE_INLINE_BASECLASS_DECL(equivalent) GTL_COMPARE_INLINE_BASECLASS_DECL(greater) @@ -176,16 +163,14 @@ struct partial_ordering_base }; template -struct weak_ordering_base -{ +struct weak_ordering_base { GTL_COMPARE_INLINE_BASECLASS_DECL(less) GTL_COMPARE_INLINE_BASECLASS_DECL(equivalent) GTL_COMPARE_INLINE_BASECLASS_DECL(greater) }; template -struct strong_ordering_base -{ +struct strong_ordering_base { GTL_COMPARE_INLINE_BASECLASS_DECL(less) GTL_COMPARE_INLINE_BASECLASS_DECL(equal) GTL_COMPARE_INLINE_BASECLASS_DECL(equivalent) @@ -194,12 +179,9 @@ struct strong_ordering_base } // namespace compare_internal -class weak_equality : public compare_internal::weak_equality_base -{ +class weak_equality : public compare_internal::weak_equality_base { explicit constexpr weak_equality(compare_internal::eq v) noexcept - : value_(static_cast(v)) - { - } + : value_(static_cast(v)) {} friend struct compare_internal::weak_equality_base; public: @@ -207,20 +189,16 @@ class weak_equality : public compare_internal::weak_equality_base GTL_COMPARE_INLINE_SUBCLASS_DECL(weak_equality, nonequivalent) // Comparisons - friend constexpr bool operator==(weak_equality v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator==(weak_equality v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ == 0; } - friend constexpr bool operator!=(weak_equality v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator!=(weak_equality v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ != 0; } - friend constexpr bool operator==(compare_internal::OnlyLiteralZero<>, weak_equality v) noexcept - { + friend constexpr bool operator==(compare_internal::OnlyLiteralZero<>, weak_equality v) noexcept { return 0 == v.value_; } - friend constexpr bool operator!=(compare_internal::OnlyLiteralZero<>, weak_equality v) noexcept - { + friend constexpr bool operator!=(compare_internal::OnlyLiteralZero<>, weak_equality v) noexcept { return 0 != v.value_; } @@ -230,12 +208,9 @@ class weak_equality : public compare_internal::weak_equality_base GTL_COMPARE_INLINE_INIT(weak_equality, equivalent, compare_internal::eq::equivalent); GTL_COMPARE_INLINE_INIT(weak_equality, nonequivalent, compare_internal::eq::nonequivalent); -class strong_equality : public compare_internal::strong_equality_base -{ +class strong_equality : public compare_internal::strong_equality_base { explicit constexpr strong_equality(compare_internal::eq v) noexcept - : value_(static_cast(v)) - { - } + : value_(static_cast(v)) {} friend struct compare_internal::strong_equality_base; public: @@ -245,25 +220,20 @@ class strong_equality : public compare_internal::strong_equality_base) noexcept - { + friend constexpr bool operator==(strong_equality v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ == 0; } - friend constexpr bool operator!=(strong_equality v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator!=(strong_equality v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ != 0; } - friend constexpr bool operator==(compare_internal::OnlyLiteralZero<>, strong_equality v) noexcept - { + friend constexpr bool operator==(compare_internal::OnlyLiteralZero<>, strong_equality v) noexcept { return 0 == v.value_; } - friend constexpr bool operator!=(compare_internal::OnlyLiteralZero<>, strong_equality v) noexcept - { + friend constexpr bool operator!=(compare_internal::OnlyLiteralZero<>, strong_equality v) noexcept { return 0 != v.value_; } @@ -276,24 +246,16 @@ GTL_COMPARE_INLINE_INIT(strong_equality, nonequal, compare_internal::eq::nonequa GTL_COMPARE_INLINE_INIT(strong_equality, equivalent, compare_internal::eq::equivalent); GTL_COMPARE_INLINE_INIT(strong_equality, nonequivalent, compare_internal::eq::nonequivalent); -class partial_ordering : public compare_internal::partial_ordering_base -{ +class partial_ordering : public compare_internal::partial_ordering_base { explicit constexpr partial_ordering(compare_internal::eq v) noexcept - : value_(static_cast(v)) - { - } + : value_(static_cast(v)) {} explicit constexpr partial_ordering(compare_internal::ord v) noexcept - : value_(static_cast(v)) - { - } + : value_(static_cast(v)) {} explicit constexpr partial_ordering(compare_internal::ncmp v) noexcept - : value_(static_cast(v)) - { - } + : value_(static_cast(v)) {} friend struct compare_internal::partial_ordering_base; - constexpr bool is_ordered() const noexcept - { + constexpr bool is_ordered() const noexcept { return value_ != compare_internal::value_type(compare_internal::ncmp::unordered); } @@ -304,57 +266,44 @@ class partial_ordering : public compare_internal::partial_ordering_base) noexcept - { + friend constexpr bool operator==(partial_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.is_ordered() && v.value_ == 0; } - friend constexpr bool operator!=(partial_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator!=(partial_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return !v.is_ordered() || v.value_ != 0; } - friend constexpr bool operator<(partial_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator<(partial_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.is_ordered() && v.value_ < 0; } - friend constexpr bool operator<=(partial_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator<=(partial_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.is_ordered() && v.value_ <= 0; } - friend constexpr bool operator>(partial_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator>(partial_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.is_ordered() && v.value_ > 0; } - friend constexpr bool operator>=(partial_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator>=(partial_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.is_ordered() && v.value_ >= 0; } - friend constexpr bool operator==(compare_internal::OnlyLiteralZero<>, partial_ordering v) noexcept - { + friend constexpr bool operator==(compare_internal::OnlyLiteralZero<>, partial_ordering v) noexcept { return v.is_ordered() && 0 == v.value_; } - friend constexpr bool operator!=(compare_internal::OnlyLiteralZero<>, partial_ordering v) noexcept - { + friend constexpr bool operator!=(compare_internal::OnlyLiteralZero<>, partial_ordering v) noexcept { return !v.is_ordered() || 0 != v.value_; } - friend constexpr bool operator<(compare_internal::OnlyLiteralZero<>, partial_ordering v) noexcept - { + friend constexpr bool operator<(compare_internal::OnlyLiteralZero<>, partial_ordering v) noexcept { return v.is_ordered() && 0 < v.value_; } - friend constexpr bool operator<=(compare_internal::OnlyLiteralZero<>, partial_ordering v) noexcept - { + friend constexpr bool operator<=(compare_internal::OnlyLiteralZero<>, partial_ordering v) noexcept { return v.is_ordered() && 0 <= v.value_; } - friend constexpr bool operator>(compare_internal::OnlyLiteralZero<>, partial_ordering v) noexcept - { + friend constexpr bool operator>(compare_internal::OnlyLiteralZero<>, partial_ordering v) noexcept { return v.is_ordered() && 0 > v.value_; } - friend constexpr bool operator>=(compare_internal::OnlyLiteralZero<>, partial_ordering v) noexcept - { + friend constexpr bool operator>=(compare_internal::OnlyLiteralZero<>, partial_ordering v) noexcept { return v.is_ordered() && 0 >= v.value_; } @@ -367,16 +316,11 @@ GTL_COMPARE_INLINE_INIT(partial_ordering, equivalent, compare_internal::eq::equi GTL_COMPARE_INLINE_INIT(partial_ordering, greater, compare_internal::ord::greater); GTL_COMPARE_INLINE_INIT(partial_ordering, unordered, compare_internal::ncmp::unordered); -class weak_ordering : public compare_internal::weak_ordering_base -{ +class weak_ordering : public compare_internal::weak_ordering_base { explicit constexpr weak_ordering(compare_internal::eq v) noexcept - : value_(static_cast(v)) - { - } + : value_(static_cast(v)) {} explicit constexpr weak_ordering(compare_internal::ord v) noexcept - : value_(static_cast(v)) - { - } + : value_(static_cast(v)) {} friend struct compare_internal::weak_ordering_base; public: @@ -385,62 +329,48 @@ class weak_ordering : public compare_internal::weak_ordering_base GTL_COMPARE_INLINE_SUBCLASS_DECL(weak_ordering, greater) // Conversions - constexpr operator weak_equality() const noexcept - { // NOLINT + constexpr operator weak_equality() const noexcept { // NOLINT return value_ == 0 ? weak_equality::equivalent : weak_equality::nonequivalent; } - constexpr operator partial_ordering() const noexcept - { // NOLINT + constexpr operator partial_ordering() const noexcept { // NOLINT return value_ == 0 ? partial_ordering::equivalent : (value_ < 0 ? partial_ordering::less : partial_ordering::greater); } // Comparisons - friend constexpr bool operator==(weak_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator==(weak_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ == 0; } - friend constexpr bool operator!=(weak_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator!=(weak_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ != 0; } - friend constexpr bool operator<(weak_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator<(weak_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ < 0; } - friend constexpr bool operator<=(weak_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator<=(weak_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ <= 0; } - friend constexpr bool operator>(weak_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator>(weak_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ > 0; } - friend constexpr bool operator>=(weak_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator>=(weak_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ >= 0; } - friend constexpr bool operator==(compare_internal::OnlyLiteralZero<>, weak_ordering v) noexcept - { + friend constexpr bool operator==(compare_internal::OnlyLiteralZero<>, weak_ordering v) noexcept { return 0 == v.value_; } - friend constexpr bool operator!=(compare_internal::OnlyLiteralZero<>, weak_ordering v) noexcept - { + friend constexpr bool operator!=(compare_internal::OnlyLiteralZero<>, weak_ordering v) noexcept { return 0 != v.value_; } - friend constexpr bool operator<(compare_internal::OnlyLiteralZero<>, weak_ordering v) noexcept - { + friend constexpr bool operator<(compare_internal::OnlyLiteralZero<>, weak_ordering v) noexcept { return 0 < v.value_; } - friend constexpr bool operator<=(compare_internal::OnlyLiteralZero<>, weak_ordering v) noexcept - { + friend constexpr bool operator<=(compare_internal::OnlyLiteralZero<>, weak_ordering v) noexcept { return 0 <= v.value_; } - friend constexpr bool operator>(compare_internal::OnlyLiteralZero<>, weak_ordering v) noexcept - { + friend constexpr bool operator>(compare_internal::OnlyLiteralZero<>, weak_ordering v) noexcept { return 0 > v.value_; } - friend constexpr bool operator>=(compare_internal::OnlyLiteralZero<>, weak_ordering v) noexcept - { + friend constexpr bool operator>=(compare_internal::OnlyLiteralZero<>, weak_ordering v) noexcept { return 0 >= v.value_; } @@ -452,16 +382,11 @@ GTL_COMPARE_INLINE_INIT(weak_ordering, less, compare_internal::ord::less); GTL_COMPARE_INLINE_INIT(weak_ordering, equivalent, compare_internal::eq::equivalent); GTL_COMPARE_INLINE_INIT(weak_ordering, greater, compare_internal::ord::greater); -class strong_ordering : public compare_internal::strong_ordering_base -{ +class strong_ordering : public compare_internal::strong_ordering_base { explicit constexpr strong_ordering(compare_internal::eq v) noexcept - : value_(static_cast(v)) - { - } + : value_(static_cast(v)) {} explicit constexpr strong_ordering(compare_internal::ord v) noexcept - : value_(static_cast(v)) - { - } + : value_(static_cast(v)) {} friend struct compare_internal::strong_ordering_base; public: @@ -471,70 +396,54 @@ class strong_ordering : public compare_internal::strong_ordering_base) noexcept - { + friend constexpr bool operator==(strong_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ == 0; } - friend constexpr bool operator!=(strong_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator!=(strong_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ != 0; } - friend constexpr bool operator<(strong_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator<(strong_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ < 0; } - friend constexpr bool operator<=(strong_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator<=(strong_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ <= 0; } - friend constexpr bool operator>(strong_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator>(strong_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ > 0; } - friend constexpr bool operator>=(strong_ordering v, compare_internal::OnlyLiteralZero<>) noexcept - { + friend constexpr bool operator>=(strong_ordering v, compare_internal::OnlyLiteralZero<>) noexcept { return v.value_ >= 0; } - friend constexpr bool operator==(compare_internal::OnlyLiteralZero<>, strong_ordering v) noexcept - { + friend constexpr bool operator==(compare_internal::OnlyLiteralZero<>, strong_ordering v) noexcept { return 0 == v.value_; } - friend constexpr bool operator!=(compare_internal::OnlyLiteralZero<>, strong_ordering v) noexcept - { + friend constexpr bool operator!=(compare_internal::OnlyLiteralZero<>, strong_ordering v) noexcept { return 0 != v.value_; } - friend constexpr bool operator<(compare_internal::OnlyLiteralZero<>, strong_ordering v) noexcept - { + friend constexpr bool operator<(compare_internal::OnlyLiteralZero<>, strong_ordering v) noexcept { return 0 < v.value_; } - friend constexpr bool operator<=(compare_internal::OnlyLiteralZero<>, strong_ordering v) noexcept - { + friend constexpr bool operator<=(compare_internal::OnlyLiteralZero<>, strong_ordering v) noexcept { return 0 <= v.value_; } - friend constexpr bool operator>(compare_internal::OnlyLiteralZero<>, strong_ordering v) noexcept - { + friend constexpr bool operator>(compare_internal::OnlyLiteralZero<>, strong_ordering v) noexcept { return 0 > v.value_; } - friend constexpr bool operator>=(compare_internal::OnlyLiteralZero<>, strong_ordering v) noexcept - { + friend constexpr bool operator>=(compare_internal::OnlyLiteralZero<>, strong_ordering v) noexcept { return 0 >= v.value_; } @@ -560,16 +469,14 @@ namespace compare_internal { // SFINAE prevents implicit conversions to bool (such as from int). // ---------------------------------------------------------------------- template, int> = 0> -constexpr bool compare_result_as_less_than(const BoolType r) -{ +constexpr bool compare_result_as_less_than(const BoolType r) { return r; } constexpr bool compare_result_as_less_than(const gtl::weak_ordering r) { return r < 0; } template -constexpr bool do_less_than_comparison(const Compare& compare, const K& x, const LK& y) -{ +constexpr bool do_less_than_comparison(const Compare& compare, const K& x, const LK& y) { return compare_result_as_less_than(compare(x, y)); } @@ -578,8 +485,7 @@ constexpr bool do_less_than_comparison(const Compare& compare, const K& x, const // SFINAE prevents implicit conversions to int (such as from bool). // --------------------------------------------------------------------------- template, int> = 0> -constexpr gtl::weak_ordering compare_result_as_ordering(const Int c) -{ +constexpr gtl::weak_ordering compare_result_as_ordering(const Int c) { return c < 0 ? gtl::weak_ordering::less : c == 0 ? gtl::weak_ordering::equivalent : gtl::weak_ordering::greater; } @@ -589,8 +495,7 @@ template>, int> = 0> -constexpr gtl::weak_ordering do_three_way_comparison(const Compare& compare, const K& x, const LK& y) -{ +constexpr gtl::weak_ordering do_three_way_comparison(const Compare& compare, const K& x, const LK& y) { return compare_result_as_ordering(compare(x, y)); } @@ -598,8 +503,7 @@ template>, int> = 0> -constexpr gtl::weak_ordering do_three_way_comparison(const Compare& cmp, const K& x, const LK& y) -{ +constexpr gtl::weak_ordering do_three_way_comparison(const Compare& cmp, const K& x, const LK& y) { return cmp(x, y) ? gtl::weak_ordering::less : cmp(y, x) ? gtl::weak_ordering::greater : gtl::weak_ordering::equivalent; @@ -616,8 +520,7 @@ template using btree_is_key_compare_to = std::is_convertible, gtl::weak_ordering>; -struct StringBtreeDefaultLess -{ +struct StringBtreeDefaultLess { using is_transparent = void; StringBtreeDefaultLess() = default; @@ -627,14 +530,12 @@ struct StringBtreeDefaultLess StringBtreeDefaultLess(std::less) {} // NOLINT StringBtreeDefaultLess(gtl::Less) {} // NOLINT - gtl::weak_ordering operator()(std::string_view lhs, std::string_view rhs) const - { + gtl::weak_ordering operator()(std::string_view lhs, std::string_view rhs) const { return compare_internal::compare_result_as_ordering(lhs.compare(rhs)); } }; -struct StringBtreeDefaultGreater -{ +struct StringBtreeDefaultGreater { using is_transparent = void; StringBtreeDefaultGreater() = default; @@ -642,8 +543,7 @@ struct StringBtreeDefaultGreater StringBtreeDefaultGreater(std::greater) {} // NOLINT StringBtreeDefaultGreater(std::greater) {} // NOLINT - gtl::weak_ordering operator()(std::string_view lhs, std::string_view rhs) const - { + gtl::weak_ordering operator()(std::string_view lhs, std::string_view rhs) const { return compare_internal::compare_result_as_ordering(rhs.compare(lhs)); } }; @@ -661,50 +561,42 @@ struct StringBtreeDefaultGreater // default. // --------------------------------------------------------------------------- template -struct key_compare_to_adapter -{ +struct key_compare_to_adapter { using type = Compare; }; template<> -struct key_compare_to_adapter> -{ +struct key_compare_to_adapter> { using type = StringBtreeDefaultLess; }; template<> -struct key_compare_to_adapter> -{ +struct key_compare_to_adapter> { using type = StringBtreeDefaultLess; }; template<> -struct key_compare_to_adapter> -{ +struct key_compare_to_adapter> { using type = StringBtreeDefaultGreater; }; template<> -struct key_compare_to_adapter> -{ +struct key_compare_to_adapter> { using type = StringBtreeDefaultLess; }; template<> -struct key_compare_to_adapter> -{ +struct key_compare_to_adapter> { using type = StringBtreeDefaultLess; }; template<> -struct key_compare_to_adapter> -{ +struct key_compare_to_adapter> { using type = StringBtreeDefaultGreater; }; template -struct common_params -{ +struct common_params { // If Compare is a common comparator for a std::string-like type, then we adapt it // to use heterogeneous lookup and to be a key-compare-to comparator. // ------------------------------------------------------------------------------- @@ -732,8 +624,7 @@ struct common_params using reference = value_type&; using const_reference = const value_type&; - enum - { + enum { kTargetNodeSize = TargetNodeSize, // Upper bound for the available space for values. This is largest for leaf @@ -755,24 +646,20 @@ struct common_params static value_type& element(slot_type* slot) { return slot_policy::element(slot); } static const value_type& element(const slot_type* slot) { return slot_policy::element(slot); } template - static void construct(Alloc* alloc, slot_type* slot, Args&&... args) - { + static void construct(Alloc* alloc, slot_type* slot, Args&&... args) { slot_policy::construct(alloc, slot, std::forward(args)...); } - static void construct(Alloc* alloc, slot_type* slot, slot_type* other) - { + static void construct(Alloc* alloc, slot_type* slot, slot_type* other) { slot_policy::construct(alloc, slot, other); } static void destroy(Alloc* alloc, slot_type* slot) { slot_policy::destroy(alloc, slot); } - static void transfer(Alloc* alloc, slot_type* new_slot, slot_type* old_slot) - { + static void transfer(Alloc* alloc, slot_type* new_slot, slot_type* old_slot) { construct(alloc, new_slot, old_slot); destroy(alloc, old_slot); } static void swap(Alloc* alloc, slot_type* a, slot_type* b) { slot_policy::swap(alloc, a, b); } static void move(Alloc* alloc, slot_type* src, slot_type* dest) { slot_policy::move(alloc, src, dest); } - static void move(Alloc* alloc, slot_type* first, slot_type* last, slot_type* result) - { + static void move(Alloc* alloc, slot_type* first, slot_type* last, slot_type* result) { slot_policy::move(alloc, first, last, result); } }; @@ -781,8 +668,7 @@ struct common_params // Compare and Alloc should be nothrow copy-constructible. // ----------------------------------------------------------------------- template -struct map_params : common_params> -{ +struct map_params : common_params> { using super_type = typename map_params::common_params; using mapped_type = Data; // This type allows us to move keys when it is safe to do so. It is safe @@ -795,18 +681,14 @@ struct map_params : common_params auto operator()(const T& left, const U& right) const - -> decltype(std::declval()(left.first, right.first)) - { + -> decltype(std::declval()(left.first, right.first)) { return key_compare::operator()(left.first, right.first); } }; @@ -822,8 +704,7 @@ struct map_params : common_params -struct set_slot_policy -{ +struct set_slot_policy { using slot_type = Key; using value_type = Key; using mutable_value_type = Key; @@ -832,39 +713,33 @@ struct set_slot_policy static const value_type& element(const slot_type* slot) { return *slot; } template - static void construct(Alloc* alloc, slot_type* slot, Args&&... args) - { + static void construct(Alloc* alloc, slot_type* slot, Args&&... args) { std::allocator_traits::construct(*alloc, slot, std::forward(args)...); } template - static void construct(Alloc* alloc, slot_type* slot, slot_type* other) - { + static void construct(Alloc* alloc, slot_type* slot, slot_type* other) { std::allocator_traits::construct(*alloc, slot, std::move(*other)); } template - static void destroy(Alloc* alloc, slot_type* slot) - { + static void destroy(Alloc* alloc, slot_type* slot) { std::allocator_traits::destroy(*alloc, slot); } template - static void swap(Alloc* /*alloc*/, slot_type* a, slot_type* b) - { + static void swap(Alloc* /*alloc*/, slot_type* a, slot_type* b) { using std::swap; swap(*a, *b); } template - static void move(Alloc* /*alloc*/, slot_type* src, slot_type* dest) - { + static void move(Alloc* /*alloc*/, slot_type* src, slot_type* dest) { *dest = std::move(*src); } template - static void move(Alloc* alloc, slot_type* first, slot_type* last, slot_type* result) - { + static void move(Alloc* alloc, slot_type* first, slot_type* last, slot_type* result) { for (slot_type *src = first, *dest = result; src != last; ++src, ++dest) move(alloc, src, dest); } @@ -874,8 +749,7 @@ struct set_slot_policy // Compare and Alloc should be nothrow copy-constructible. // ------------------------------------------------------------------------ template -struct set_params : common_params> -{ +struct set_params : common_params> { using value_type = Key; using slot_type = typename set_params::common_params::slot_type; using value_compare = typename set_params::common_params::key_compare; @@ -891,15 +765,11 @@ struct set_params : common_params -struct upper_bound_adapter -{ +struct upper_bound_adapter { explicit upper_bound_adapter(const Compare& c) - : comp(c) - { - } + : comp(c) {} template - bool operator()(const K& a, const LK& b) const - { + bool operator()(const K& a, const LK& b) const { // Returns true when a is not greater than b. return !gtl::compare_internal::compare_result_as_less_than(comp(b, a)); } @@ -908,15 +778,10 @@ struct upper_bound_adapter Compare comp; }; -enum class MatchKind : uint8_t -{ - kEq, - kNe -}; +enum class MatchKind : uint8_t { kEq, kNe }; template -struct SearchResult -{ +struct SearchResult { V value; MatchKind match; @@ -929,8 +794,7 @@ struct SearchResult // useful information. // ----------------------------------------------------------------------- template -struct SearchResult -{ +struct SearchResult { V value; static constexpr bool HasMatch() { return false; } @@ -942,8 +806,7 @@ struct SearchResult // that the children array is only valid in internal nodes. // ------------------------------------------------------------------------- template -class btree_node -{ +class btree_node { using is_key_compare_to = typename Params::is_key_compare_to; using is_multi_container = typename Params::is_multi_container; using field_type = typename Params::node_count_type; @@ -980,8 +843,7 @@ class btree_node // Public for EmptyNodeType. // ------------------------- - constexpr static size_type Alignment() - { + constexpr static size_type Alignment() { static_assert(LeafLayout(1).Alignment() == InternalLayout().Alignment(), "Alignment of all nodes must be equal."); return (size_type)InternalLayout().Alignment(); @@ -992,8 +854,7 @@ class btree_node private: using layout_type = gtl::priv::Layout; - constexpr static size_type SizeWithNValues(size_type n) - { + constexpr static size_type SizeWithNValues(size_type n) { return (size_type)layout_type(/*parent*/ 1, /*position, start, count, max_count*/ 4, /*values*/ (size_t)n, @@ -1008,16 +869,14 @@ class btree_node // Compute how many values we can fit onto a leaf node taking into account // padding. // ----------------------------------------------------------------------- - constexpr static size_type NodeTargetValues(const int begin, const int end) - { + constexpr static size_type NodeTargetValues(const int begin, const int end) { return begin == end ? begin : SizeWithNValues((begin + end) / 2 + 1) > params_type::kTargetNodeSize ? NodeTargetValues(begin, (begin + end) / 2) : NodeTargetValues((begin + end) / 2 + 1, end); } - enum - { + enum { kTargetNodeSize = params_type::kTargetNodeSize, kNodeTargetValues = NodeTargetValues(0, params_type::kTargetNodeSize), @@ -1035,22 +894,19 @@ class btree_node // Leaves can have less than kNodeValues values. // --------------------------------------------- - constexpr static layout_type LeafLayout(const int max_values = kNodeValues) - { + constexpr static layout_type LeafLayout(const int max_values = kNodeValues) { return layout_type(/*parent*/ 1, /*position, start, count, max_count*/ 4, /*values*/ (size_t)max_values, /*children*/ 0); } - constexpr static layout_type InternalLayout() - { + constexpr static layout_type InternalLayout() { return layout_type(/*parent*/ 1, /*position, start, count, max_count*/ 4, /*values*/ kNodeValues, /*children*/ kNodeValues + 1); } - constexpr static size_type LeafSize(const int max_values = kNodeValues) - { + constexpr static size_type LeafSize(const int max_values = kNodeValues) { return (size_type)LeafLayout(max_values).AllocSize(); } constexpr static size_type InternalSize() { return (size_type)InternalLayout().AllocSize(); } @@ -1059,16 +915,14 @@ class btree_node // ElementType is the Nth type in the Layout definition. // -------------------------------------------------------- template - inline typename layout_type::template ElementType* GetField() - { + inline typename layout_type::template ElementType* GetField() { // We assert that we don't read from values that aren't there. assert(N < 3 || !leaf()); return InternalLayout().template Pointer(reinterpret_cast(this)); } template - inline const typename layout_type::template ElementType* GetField() const - { + inline const typename layout_type::template ElementType* GetField() const { assert(N < 3 || !leaf()); return InternalLayout().template Pointer(reinterpret_cast(this)); } @@ -1099,8 +953,7 @@ class btree_node // Getters for the number of values stored in this node. // ----------------------------------------------------- field_type count() const { return GetField<1>()[2]; } - field_type max_count() const - { + field_type max_count() const { // Internal nodes have max_count==kInternalNodeMaxCount. // Leaf nodes have max_count in [1, kNodeValues]. // ----------------------------------------------------- @@ -1117,8 +970,7 @@ class btree_node // be a leaf. // ------------------------------------------------------------------------ bool is_root() const { return parent()->leaf(); } - void make_root() - { + void make_root() { assert(parent()->is_root()); set_parent(parent()->parent()); } @@ -1138,8 +990,7 @@ class btree_node btree_node* child(size_type i) const { return GetField<3>()[i]; } btree_node*& mutable_child(size_type i) { return GetField<3>()[i]; } void clear_child(size_type i) { SanitizerPoisonObject(&mutable_child(i)); } - void set_child(size_type i, btree_node* c) - { + void set_child(size_type i, btree_node* c) { SanitizerUnpoisonObject(&mutable_child(i)); mutable_child(i) = c; c->set_position((field_type)i); @@ -1147,8 +998,7 @@ class btree_node #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic pop #endif - void init_child(int i, btree_node* c) - { + void init_child(int i, btree_node* c) { set_child(i, c); c->set_parent(this); } @@ -1156,30 +1006,26 @@ class btree_node // Returns the position of the first value whose key is not less than k. // ---------------------------------------------------------------------- template - SearchResult lower_bound(const K& k, const key_compare& comp) const - { + SearchResult lower_bound(const K& k, const key_compare& comp) const { return use_linear_search::value ? linear_search(k, comp) : binary_search(k, comp); } // Returns the position of the first value whose key is greater than k. // -------------------------------------------------------------------- template - int upper_bound(const K& k, const key_compare& comp) const - { + int upper_bound(const K& k, const key_compare& comp) const { auto upper_compare = upper_bound_adapter(comp); return use_linear_search::value ? linear_search(k, upper_compare).value : binary_search(k, upper_compare).value; } template SearchResult::value> linear_search(const K& k, - const Compare& comp) const - { + const Compare& comp) const { return linear_search_impl(k, 0, count(), comp, btree_is_key_compare_to()); } template SearchResult::value> binary_search(const K& k, - const Compare& comp) const - { + const Compare& comp) const { return binary_search_impl(k, 0, count(), comp, btree_is_key_compare_to()); } @@ -1191,8 +1037,7 @@ class btree_node int s, const int e, const Compare& comp, - std::false_type /* IsCompareTo */) const - { + std::false_type /* IsCompareTo */) const { while (s < e) { if (!comp(key(s), k)) { break; @@ -1210,8 +1055,7 @@ class btree_node int s, const int e, const Compare& comp, - std::true_type /* IsCompareTo */) const - { + std::true_type /* IsCompareTo */) const { while (s < e) { const gtl::weak_ordering c = comp(key(s), k); if (c == 0) { @@ -1232,8 +1076,7 @@ class btree_node int s, int e, const Compare& comp, - std::false_type /* IsCompareTo */) const - { + std::false_type /* IsCompareTo */) const { while (s != e) { const int mid = (s + e) >> 1; if (comp(key(mid), k)) { @@ -1253,8 +1096,7 @@ class btree_node int s, int e, const CompareTo& comp, - std::true_type /* IsCompareTo */) const - { + std::true_type /* IsCompareTo */) const { if (is_multi_container::value) { MatchKind exact_match = MatchKind::kNe; while (s != e) { @@ -1326,8 +1168,7 @@ class btree_node // Node allocation/deletion routines. // ---------------------------------- - static btree_node* init_leaf(btree_node* n, btree_node* parent, int max_cnt) - { + static btree_node* init_leaf(btree_node* n, btree_node* parent, int max_cnt) { n->set_parent(parent); n->set_position(0); n->set_start(0); @@ -1337,8 +1178,7 @@ class btree_node return n; } - static btree_node* init_internal(btree_node* n, btree_node* parent) - { + static btree_node* init_internal(btree_node* n, btree_node* parent) { init_leaf(n, parent, kNodeValues); // Set `max_count` to a sentinel value to indicate that this node is // internal. @@ -1347,8 +1187,7 @@ class btree_node return n; } - void destroy(allocator_type* alloc) - { + void destroy(allocator_type* alloc) { for (int i = 0; i < count(); ++i) { value_destroy(i, alloc); } @@ -1361,13 +1200,11 @@ class btree_node private: template - void value_init(const size_type i, allocator_type* alloc, Args&&... args) - { + void value_init(const size_type i, allocator_type* alloc, Args&&... args) { SanitizerUnpoisonObject(slot(i)); params_type::construct(alloc, slot(i), std::forward(args)...); } - void value_destroy(const size_type i, allocator_type* alloc) - { + void value_destroy(const size_type i, allocator_type* alloc) { params_type::destroy(alloc, slot(i)); SanitizerPoisonObject(slot(i)); } @@ -1379,8 +1216,7 @@ class btree_node const size_type i, const size_type j, btree_node* x, - allocator_type* alloc) - { + allocator_type* alloc) { SanitizerUnpoisonMemoryRegion(x->slot(j), n * sizeof(slot_type)); for (slot_type *src = slot(i), *end = src + n, *dest = x->slot(j); src != end; ++src, ++dest) { params_type::construct(alloc, dest, src); @@ -1389,8 +1225,7 @@ class btree_node // Destroys a range of n values, starting at index i. // -------------------------------------------------- - void value_destroy_n(const size_type i, const size_type n, allocator_type* alloc) - { + void value_destroy_n(const size_type i, const size_type n, allocator_type* alloc) { for (size_type j = 0; j < n; ++j) { value_destroy(i + j, alloc); } @@ -1406,8 +1241,7 @@ class btree_node }; template -struct btree_iterator -{ +struct btree_iterator { private: using key_type = typename Node::key_type; using size_type = typename Node::size_type; @@ -1436,14 +1270,10 @@ struct btree_iterator btree_iterator() : node(nullptr) - , position(-1) - { - } + , position(-1) {} btree_iterator(Node* n, int p) : node(n) - , position(p) - { - } + , position(p) {} // NOTE: this SFINAE allows for implicit conversions from iterator to // const_iterator, but it specifically avoids defining copy constructors so @@ -1458,9 +1288,7 @@ struct btree_iterator int> = 0> btree_iterator(const btree_iterator& x) // NOLINT : node(x.node) - , position(x.position) - { - } + , position(x.position) {} private: // This SFINAE allows explicit conversions from const_iterator to @@ -1476,14 +1304,11 @@ struct btree_iterator int> = 0> explicit btree_iterator(const btree_iterator& x) : node(const_cast(x.node)) - , position(x.position) - { - } + , position(x.position) {} // Increment/decrement the iterator. // --------------------------------- - void increment() - { + void increment() { if (node->leaf() && ++position < node->count()) { return; } @@ -1491,8 +1316,7 @@ struct btree_iterator } void increment_slow(); - void decrement() - { + void decrement() { if (node->leaf() && --position >= 0) { return; } @@ -1512,24 +1336,20 @@ struct btree_iterator reference operator*() const { return node->value(position); } pointer operator->() const { return &node->value(position); } - btree_iterator& operator++() - { + btree_iterator& operator++() { increment(); return *this; } - btree_iterator& operator--() - { + btree_iterator& operator--() { decrement(); return *this; } - btree_iterator operator++(int) - { + btree_iterator operator++(int) { btree_iterator tmp = *this; ++*this; return tmp; } - btree_iterator operator--(int) - { + btree_iterator operator--(int) { btree_iterator tmp = *this; --*this; return tmp; @@ -1571,16 +1391,14 @@ struct btree_iterator }; template -class btree -{ +class btree { using node_type = btree_node; using is_key_compare_to = typename Params::is_key_compare_to; // We use a static empty node for the root/leftmost/rightmost of empty btrees // in order to avoid branching in begin()/end(). // -------------------------------------------------------------------------- - struct alignas(node_type::Alignment()) EmptyNodeType : node_type - { + struct alignas(node_type::Alignment()) EmptyNodeType : node_type { using field_type = typename node_type::field_type; node_type* parent; field_type position = 0; @@ -1593,19 +1411,14 @@ class btree #ifdef _MSC_VER // MSVC has constexpr code generations bugs here. EmptyNodeType() - : parent(this) - { - } + : parent(this) {} #else constexpr EmptyNodeType(node_type* p) - : parent(p) - { - } + : parent(p) {} #endif }; - static node_type* EmptyNode() - { + static node_type* EmptyNode() { #ifdef _MSC_VER static EmptyNodeType empty_node; // This assert fails on some other construction methods. @@ -1617,24 +1430,19 @@ class btree #endif } - enum - { + enum { kNodeValues = node_type::kNodeValues, kMinNodeValues = kNodeValues / 2, }; - struct node_stats - { + struct node_stats { using size_type = typename Params::size_type; node_stats(size_type l, size_type i) : leaf_nodes(l) - , internal_nodes(i) - { - } + , internal_nodes(i) {} - node_stats& operator+=(const node_stats& x) - { + node_stats& operator+=(const node_stats& x) { leaf_nodes += x.leaf_nodes; internal_nodes += x.internal_nodes; return *this; @@ -1693,13 +1501,11 @@ class btree btree(btree&& x) noexcept : root_(std::move(x.root_)) , rightmost_(std::exchange(x.rightmost_, EmptyNode())) - , size_(std::exchange(x.size_, 0)) - { + , size_(std::exchange(x.size_, 0)) { x.mutable_root() = EmptyNode(); } - ~btree() - { + ~btree() { // Put static_asserts in destructor to avoid triggering them before the type // is complete. // ------------------------------------------------------------------------- @@ -1724,26 +1530,22 @@ class btree // Finds the first element whose key is not less than key. // ------------------------------------------------------- template - iterator lower_bound(const K& key) - { + iterator lower_bound(const K& key) { return internal_end(internal_lower_bound(key)); } template - const_iterator lower_bound(const K& key) const - { + const_iterator lower_bound(const K& key) const { return internal_end(internal_lower_bound(key)); } // Finds the first element whose key is greater than key. // ------------------------------------------------------ template - iterator upper_bound(const K& key) - { + iterator upper_bound(const K& key) { return internal_end(internal_upper_bound(key)); } template - const_iterator upper_bound(const K& key) const - { + const_iterator upper_bound(const K& key) const { return internal_end(internal_upper_bound(key)); } @@ -1752,13 +1554,11 @@ class btree // the pair is equal to upper_bound(key). // ------------------------------------------------------------------------- template - std::pair equal_range(const K& key) - { + std::pair equal_range(const K& key) { return { lower_bound(key), upper_bound(key) }; } template - std::pair equal_range(const K& key) const - { + std::pair equal_range(const K& key) const { return { lower_bound(key), upper_bound(key) }; } @@ -1793,8 +1593,7 @@ class btree // Inserts a value into the btree. // ------------------------------- template - iterator insert_multi(ValueType&& v) - { + iterator insert_multi(ValueType&& v) { return insert_multi(params_type::key(v), std::forward(v)); } @@ -1839,21 +1638,18 @@ class btree // not present. // ------------------------------------------------------------------------ template - iterator find(const K& key) - { + iterator find(const K& key) { return internal_end(internal_find(key)); } template - const_iterator find(const K& key) const - { + const_iterator find(const K& key) const { return internal_end(internal_find(key)); } // Returns a count of the number of times the key appears in the btree. // -------------------------------------------------------------------- template - size_type count_unique(const K& key) const - { + size_type count_unique(const K& key) const { const iterator beg = internal_find(key); if (beg.node == nullptr) { // The key doesn't exist in the tree. @@ -1865,8 +1661,7 @@ class btree // Returns a count of the number of times the key appears in the btree. // -------------------------------------------------------------------- template - size_type count_multi(const K& key) const - { + size_type count_multi(const K& key) const { const auto range = equal_range(key); return std::distance(range.first, range.second); } @@ -1880,8 +1675,7 @@ class btree const key_compare& key_comp() const noexcept { return std::get<0>(root_); } template - bool compare_keys(const K& x, const LK& y) const - { + bool compare_keys(const K& x, const LK& y) const { return compare_internal::compare_result_as_less_than(key_comp()(x, y)); } @@ -1899,8 +1693,7 @@ class btree // The height of the btree. An empty tree will have height 0. // ---------------------------------------------------------- - size_type height() const - { + size_type height() const { size_type h = 0; if (!empty()) { // Count the length of the chain from the leftmost node up to the @@ -1921,16 +1714,14 @@ class btree // --------------------------------------------------------------- size_type leaf_nodes() const { return internal_stats(root()).leaf_nodes; } size_type internal_nodes() const { return internal_stats(root()).internal_nodes; } - size_type nodes() const - { + size_type nodes() const { node_stats stats = internal_stats(root()); return stats.leaf_nodes + stats.internal_nodes; } // The total number of bytes used by the btree. // -------------------------------------------- - size_type bytes_used() const - { + size_type bytes_used() const { node_stats stats = internal_stats(root()); if (stats.leaf_nodes == 1 && stats.internal_nodes == 0) { return sizeof(*this) + node_type::LeafSize(root()->max_count()); @@ -1942,8 +1733,7 @@ class btree // The average number of bytes used per value stored in the btree. // --------------------------------------------------------------- - static double average_bytes_per_value() - { + static double average_bytes_per_value() { // Returns the number of bytes per value on a leaf node that is 75% // full. Experimentally, this matches up nicely with the computed number of // bytes per value in trees that had their values inserted in random order. @@ -1957,8 +1747,7 @@ class btree // utilization. Smaller values indicate space wastage. // Returns 0 for empty trees. // -------------------------------------------------------------------------- - double fullness() const - { + double fullness() const { if (empty()) return 0.0; return static_cast(size()) / (nodes() * kNodeValues); @@ -1969,8 +1758,7 @@ class btree // storing elements divided by the number of elements. // Returns 0 for empty trees. // -------------------------------------------------------------------------- - double overhead() const - { + double overhead() const { if (empty()) return 0.0; return (bytes_used() - size() * sizeof(value_type)) / static_cast(size()); @@ -2001,25 +1789,21 @@ class btree // Allocates a correctly aligned node of at least size bytes using the // allocator. // ------------------------------------------------------------------- - node_type* allocate(const size_type sz) - { + node_type* allocate(const size_type sz) { return reinterpret_cast(Allocate(mutable_allocator(), (size_t)sz)); } // Node creation/deletion routines. // -------------------------------- - node_type* new_internal_node(node_type* parent) - { + node_type* new_internal_node(node_type* parent) { node_type* p = allocate(node_type::InternalSize()); return node_type::init_internal(p, parent); } - node_type* new_leaf_node(node_type* parent) - { + node_type* new_leaf_node(node_type* parent) { node_type* p = allocate(node_type::LeafSize()); return node_type::init_leaf(p, parent, kNodeValues); } - node_type* new_leaf_root_node(const int max_count) - { + node_type* new_leaf_root_node(const int max_count) { node_type* p = allocate(node_type::LeafSize(max_count)); return node_type::init_leaf(p, p, max_count); } @@ -2032,18 +1816,15 @@ class btree // Deallocates a node of a certain size in bytes using the allocator. // ------------------------------------------------------------------ - void deallocate(const size_type sz, node_type* node) - { + void deallocate(const size_type sz, node_type* node) { Deallocate(mutable_allocator(), node, (size_t)sz); } - void delete_internal_node(node_type* node) - { + void delete_internal_node(node_type* node) { node->destroy(mutable_allocator()); deallocate(node_type::InternalSize(), node); } - void delete_leaf_node(node_type* node) - { + void delete_leaf_node(node_type* node) { node->destroy(mutable_allocator()); deallocate(node_type::LeafSize(node->max_count()), node); } @@ -2127,8 +1908,7 @@ class btree // ------------------------------------ size_type internal_verify(const node_type* node, const key_type* lo, const key_type* hi) const; - node_stats internal_stats(const node_type* node) const - { + node_stats internal_stats(const node_type* node) const { // The root can be a static empty node. // ------------------------------------ if (node == nullptr || (node == root() && empty())) { @@ -2165,8 +1945,7 @@ class btree // ---------------------------------------------------------------------- template template -inline void btree_node

::emplace_value(const size_type i, allocator_type* alloc, Args&&... args) -{ +inline void btree_node

::emplace_value(const size_type i, allocator_type* alloc, Args&&... args) { assert(i <= count()); // Shift old values to create space for new value and then construct it in // place. @@ -2189,8 +1968,7 @@ inline void btree_node

::emplace_value(const size_type i, allocator_type* allo } template -inline void btree_node

::remove_value(const int i, allocator_type* alloc) -{ +inline void btree_node

::remove_value(const int i, allocator_type* alloc) { if (!leaf() && count() > i + 1) { assert(child(i + 1)->count() == 0); for (size_type j = i + 1; j < count(); ++j) { @@ -2203,16 +1981,14 @@ inline void btree_node

::remove_value(const int i, allocator_type* alloc) } template -inline void btree_node

::remove_values_ignore_children(int i, size_type to_erase, allocator_type* alloc) -{ +inline void btree_node

::remove_values_ignore_children(int i, size_type to_erase, allocator_type* alloc) { params_type::move(alloc, slot(i + to_erase), slot(count()), slot(i)); value_destroy_n(count() - to_erase, to_erase, alloc); set_count((field_type)(count() - to_erase)); } template -void btree_node

::rebalance_right_to_left(const int to_move, btree_node* right, allocator_type* alloc) -{ +void btree_node

::rebalance_right_to_left(const int to_move, btree_node* right, allocator_type* alloc) { assert(parent() == right->parent()); assert(position() + 1 == right->position()); assert(right->count() >= count()); @@ -2252,8 +2028,7 @@ void btree_node

::rebalance_right_to_left(const int to_move, btree_node* right } template -void btree_node

::rebalance_left_to_right(const int to_move, btree_node* right, allocator_type* alloc) -{ +void btree_node

::rebalance_left_to_right(const int to_move, btree_node* right, allocator_type* alloc) { assert(parent() == right->parent()); assert(position() + 1 == right->position()); assert(count() >= right->count()); @@ -2279,7 +2054,8 @@ void btree_node

::rebalance_left_to_right(const int to_move, btree_node* right *dest = right->slot(right->count() - 1), *end = right->slot(0); src >= end; - --src, --dest) { + --src, --dest) + { params_type::move(alloc, src, dest); } } @@ -2339,8 +2115,7 @@ void btree_node

::rebalance_left_to_right(const int to_move, btree_node* right } template -void btree_node

::split(const int insert_position, btree_node* dest, allocator_type* alloc) -{ +void btree_node

::split(const int insert_position, btree_node* dest, allocator_type* alloc) { assert(dest->count() == 0); assert(max_count() == kNodeValues); @@ -2384,8 +2159,7 @@ void btree_node

::split(const int insert_position, btree_node* dest, allocator } template -void btree_node

::merge(btree_node* src, allocator_type* alloc) -{ +void btree_node

::merge(btree_node* src, allocator_type* alloc) { assert(parent() == src->parent()); assert(position() + 1 == src->position()); @@ -2421,8 +2195,7 @@ void btree_node

::merge(btree_node* src, allocator_type* alloc) } template -void btree_node

::swap(btree_node* x, allocator_type* alloc) -{ +void btree_node

::swap(btree_node* x, allocator_type* alloc) { using std::swap; assert(leaf() == x->leaf()); @@ -2476,8 +2249,7 @@ void btree_node

::swap(btree_node* x, allocator_type* alloc) // btree_iterator methods // ---------------------------------------------------------------------- template -void btree_iterator::increment_slow() -{ +void btree_iterator::increment_slow() { if (node->leaf()) { assert(position >= node->count()); btree_iterator save(*this); @@ -2500,8 +2272,7 @@ void btree_iterator::increment_slow() } template -void btree_iterator::decrement_slow() -{ +void btree_iterator::decrement_slow() { if (node->leaf()) { assert(position <= -1); btree_iterator save(*this); @@ -2528,8 +2299,7 @@ void btree_iterator::decrement_slow() // ---------------------------------------------------------------------- template template -void btree

::copy_or_move_values_in_order(Btree* x) -{ +void btree

::copy_or_move_values_in_order(Btree* x) { static_assert(std::is_same_v || std::is_same_v, "Btree type must be same or const."); assert(empty()); @@ -2551,8 +2321,7 @@ void btree

::copy_or_move_values_in_order(Btree* x) } template -constexpr bool btree

::static_assert_validation() -{ +constexpr bool btree

::static_assert_validation() { static_assert(std::is_nothrow_copy_constructible_v, "Key comparison must be nothrow copy constructible"); static_assert(std::is_nothrow_copy_constructible_v, "Allocator must be nothrow copy constructible"); @@ -2581,21 +2350,17 @@ template btree

::btree(const key_compare& comp, const allocator_type& alloc) : root_(comp, alloc, EmptyNode()) , rightmost_(EmptyNode()) - , size_(0) -{ -} + , size_(0) {} template btree

::btree(const btree& x) - : btree(x.key_comp(), x.allocator()) -{ + : btree(x.key_comp(), x.allocator()) { copy_or_move_values_in_order(&x); } template template -auto btree

::insert_unique(const key_type& key, Args&&... args) -> std::pair -{ +auto btree

::insert_unique(const key_type& key, Args&&... args) -> std::pair { if (empty()) { mutable_root() = rightmost_ = new_leaf_root_node(1); } @@ -2622,8 +2387,7 @@ auto btree

::insert_unique(const key_type& key, Args&&... args) -> std::pair template inline auto btree

::insert_hint_unique(iterator position, const key_type& key, Args&&... args) - -> std::pair -{ + -> std::pair { if (!empty()) { if (position == end() || compare_keys(key, position.key())) { iterator prev = position; @@ -2650,8 +2414,7 @@ inline auto btree

::insert_hint_unique(iterator position, const key_type& key, template template -void btree

::insert_iterator_unique(InputIterator b, InputIterator e) -{ +void btree

::insert_iterator_unique(InputIterator b, InputIterator e) { for (; b != e; ++b) { insert_hint_unique(end(), params_type::key(*b), *b); } @@ -2659,8 +2422,7 @@ void btree

::insert_iterator_unique(InputIterator b, InputIterator e) template template -auto btree

::insert_multi(const key_type& key, ValueType&& v) -> iterator -{ +auto btree

::insert_multi(const key_type& key, ValueType&& v) -> iterator { if (empty()) { mutable_root() = rightmost_ = new_leaf_root_node(1); } @@ -2674,8 +2436,7 @@ auto btree

::insert_multi(const key_type& key, ValueType&& v) -> iterator template template -auto btree

::insert_hint_multi(iterator position, ValueType&& v) -> iterator -{ +auto btree

::insert_hint_multi(iterator position, ValueType&& v) -> iterator { if (!empty()) { const key_type& key = params_type::key(v); if (position == end() || !compare_keys(position.key(), key)) { @@ -2700,16 +2461,14 @@ auto btree

::insert_hint_multi(iterator position, ValueType&& v) -> iterator template template -void btree

::insert_iterator_multi(InputIterator b, InputIterator e) -{ +void btree

::insert_iterator_multi(InputIterator b, InputIterator e) { for (; b != e; ++b) { insert_hint_multi(end(), *b); } } template -auto btree

::operator=(const btree& x) -> btree& -{ +auto btree

::operator=(const btree& x) -> btree& { if (this != &x) { clear(); @@ -2724,8 +2483,7 @@ auto btree

::operator=(const btree& x) -> btree& } template -auto btree

::operator=(btree&& x) noexcept -> btree& -{ +auto btree

::operator=(btree&& x) noexcept -> btree& { if (this != &x) { clear(); @@ -2756,8 +2514,7 @@ auto btree

::operator=(btree&& x) noexcept -> btree& } template -auto btree

::erase(iterator iter) -> iterator -{ +auto btree

::erase(iterator iter) -> iterator { bool internal_delete = false; if (!iter.node->leaf()) { // Deletion of a value on an internal node. First, move the largest value @@ -2795,8 +2552,7 @@ auto btree

::erase(iterator iter) -> iterator } template -auto btree

::rebalance_after_delete(iterator iter) -> iterator -{ +auto btree

::rebalance_after_delete(iterator iter) -> iterator { // Merge/rebalance as we walk back up the tree. iterator res(iter); bool first_iteration = true; @@ -2838,8 +2594,7 @@ auto btree

::rebalance_after_delete(iterator iter) -> iterator } template -auto btree

::erase(iterator _begin, iterator _end) -> std::pair -{ +auto btree

::erase(iterator _begin, iterator _end) -> std::pair { difference_type count = std::distance(_begin, _end); assert(count >= 0); @@ -2872,8 +2627,7 @@ auto btree

::erase(iterator _begin, iterator _end) -> std::pair -void btree

::erase_same_node(iterator _begin, iterator _end) -{ +void btree

::erase_same_node(iterator _begin, iterator _end) { assert(_begin.node == _end.node); assert(_end.position > _begin.position); @@ -2904,8 +2658,7 @@ void btree

::erase_same_node(iterator _begin, iterator _end) } template -auto btree

::erase_from_leaf_node(iterator _begin, size_type to_erase) -> iterator -{ +auto btree

::erase_from_leaf_node(iterator _begin, size_type to_erase) -> iterator { node_type* node = _begin.node; assert(node->leaf()); assert(node->count() > _begin.position); @@ -2920,8 +2673,7 @@ auto btree

::erase_from_leaf_node(iterator _begin, size_type to_erase) -> iter template template -auto btree

::erase_unique(const K& key) -> size_type -{ +auto btree

::erase_unique(const K& key) -> size_type { const iterator iter = internal_find(key); if (iter.node == nullptr) { // The key doesn't exist in the tree, return nothing done. @@ -2934,8 +2686,7 @@ auto btree

::erase_unique(const K& key) -> size_type template template -auto btree

::erase_multi(const K& key) -> size_type -{ +auto btree

::erase_multi(const K& key) -> size_type { const iterator _begin = internal_lower_bound(key); if (_begin.node == nullptr) { // The key doesn't exist in the tree, return nothing done. @@ -2949,8 +2700,7 @@ auto btree

::erase_multi(const K& key) -> size_type } template -void btree

::clear() -{ +void btree

::clear() { if (!empty()) { internal_clear(root()); } @@ -2960,8 +2710,7 @@ void btree

::clear() } template -void btree

::swap(btree& x) -{ +void btree

::swap(btree& x) { using std::swap; if (std::allocator_traits::propagate_on_container_swap::value) { // Note: `root_` also contains the allocator and the key comparator. @@ -2979,8 +2728,7 @@ void btree

::swap(btree& x) } template -void btree

::verify() const -{ +void btree

::verify() const { assert(root() != nullptr); assert(leftmost() != nullptr); assert(rightmost_ != nullptr); @@ -2992,8 +2740,7 @@ void btree

::verify() const } template -void btree

::rebalance_or_split(iterator* iter) -{ +void btree

::rebalance_or_split(iterator* iter) { node_type*& node = iter->node; int& insert_position = iter->position; assert(node->count() == node->max_count()); @@ -3100,8 +2847,7 @@ void btree

::rebalance_or_split(iterator* iter) } template -void btree

::merge_nodes(node_type* left, node_type* right) -{ +void btree

::merge_nodes(node_type* left, node_type* right) { left->merge(right, mutable_allocator()); if (right->leaf()) { if (rightmost_ == right) @@ -3113,8 +2859,7 @@ void btree

::merge_nodes(node_type* left, node_type* right) } template -bool btree

::try_merge_or_rebalance(iterator* iter) -{ +bool btree

::try_merge_or_rebalance(iterator* iter) { node_type* parent = iter->node->parent(); if (iter->node->position() > 0) { // Try merging with our left sibling. @@ -3156,8 +2901,8 @@ bool btree

::try_merge_or_rebalance(iterator* iter) // from the back of the tree. // ---------------------------------------------------------------------- node_type* left = parent->child(iter->node->position() - 1); - if ((left->count() > kMinNodeValues) && - ((iter->node->count() == 0) || (iter->position < iter->node->count()))) { + if ((left->count() > kMinNodeValues) && ((iter->node->count() == 0) || (iter->position < iter->node->count()))) + { int to_move = (left->count() - iter->node->count()) / 2; to_move = (std::min)(to_move, left->count() - 1); left->rebalance_left_to_right(to_move, iter->node, mutable_allocator()); @@ -3169,8 +2914,7 @@ bool btree

::try_merge_or_rebalance(iterator* iter) } template -void btree

::try_shrink() -{ +void btree

::try_shrink() { if (root()->count() > 0) { return; } @@ -3191,8 +2935,7 @@ void btree

::try_shrink() template template -inline IterType btree

::internal_last(IterType iter) -{ +inline IterType btree

::internal_last(IterType iter) { assert(iter.node != nullptr); while (iter.position == iter.node->count()) { iter.position = iter.node->position(); @@ -3207,8 +2950,7 @@ inline IterType btree

::internal_last(IterType iter) template template -inline auto btree

::internal_emplace(iterator iter, Args&&... args) -> iterator -{ +inline auto btree

::internal_emplace(iterator iter, Args&&... args) -> iterator { if (!iter.node->leaf()) { // We can't insert on an internal node. Instead, we'll insert after the // previous value which is guaranteed to be on a leaf node. @@ -3240,16 +2982,14 @@ inline auto btree

::internal_emplace(iterator iter, Args&&... args) -> iterato template template -inline auto btree

::internal_locate(const K& key) const -> SearchResult -{ +inline auto btree

::internal_locate(const K& key) const -> SearchResult { return internal_locate_impl(key, is_key_compare_to()); } template template inline auto btree

::internal_locate_impl(const K& key, std::false_type /* IsCompareTo */) const - -> SearchResult -{ + -> SearchResult { iterator iter(const_cast(root()), 0); for (;;) { iter.position = iter.node->lower_bound(key, key_comp()).value; @@ -3269,8 +3009,7 @@ inline auto btree

::internal_locate_impl(const K& key, std::false_type /* IsCo template template inline auto btree

::internal_locate_impl(const K& key, std::true_type /* IsCompareTo */) const - -> SearchResult -{ + -> SearchResult { iterator iter(const_cast(root()), 0); for (;;) { SearchResult res = iter.node->lower_bound(key, key_comp()); @@ -3288,8 +3027,7 @@ inline auto btree

::internal_locate_impl(const K& key, std::true_type /* IsCom template template -auto btree

::internal_lower_bound(const K& key) const -> iterator -{ +auto btree

::internal_lower_bound(const K& key) const -> iterator { iterator iter(const_cast(root()), 0); for (;;) { iter.position = iter.node->lower_bound(key, key_comp()).value; @@ -3303,8 +3041,7 @@ auto btree

::internal_lower_bound(const K& key) const -> iterator template template -auto btree

::internal_upper_bound(const K& key) const -> iterator -{ +auto btree

::internal_upper_bound(const K& key) const -> iterator { iterator iter(const_cast(root()), 0); for (;;) { iter.position = iter.node->upper_bound(key, key_comp()); @@ -3318,8 +3055,7 @@ auto btree

::internal_upper_bound(const K& key) const -> iterator template template -auto btree

::internal_find(const K& key) const -> iterator -{ +auto btree

::internal_find(const K& key) const -> iterator { auto res = internal_locate(key); if (res.HasMatch()) { if (res.IsEq()) { @@ -3335,8 +3071,7 @@ auto btree

::internal_find(const K& key) const -> iterator } template -void btree

::internal_clear(node_type* node) -{ +void btree

::internal_clear(node_type* node) { if (!node->leaf()) { for (int i = 0; i <= node->count(); ++i) { internal_clear(node->child(i)); @@ -3350,8 +3085,7 @@ void btree

::internal_clear(node_type* node) template typename btree

::size_type btree

::internal_verify(const node_type* node, const key_type* lo, - const key_type* hi) const -{ + const key_type* hi) const { assert(node->count() > 0); assert(node->count() <= node->max_count()); if (lo) { @@ -3379,8 +3113,7 @@ typename btree

::size_type btree

::internal_verify(const node_type* node, // A common base class for btree_set, btree_map, btree_multiset, and btree_multimap. // --------------------------------------------------------------------------------- template -class btree_container -{ +class btree_container { using params_type = typename Tree::params_type; protected: @@ -3413,13 +3146,9 @@ class btree_container // Constructors/assignments. btree_container() - : tree_(key_compare(), allocator_type()) - { - } + : tree_(key_compare(), allocator_type()) {} explicit btree_container(const key_compare& comp, const allocator_type& alloc = allocator_type()) - : tree_(comp, alloc) - { - } + : tree_(comp, alloc) {} btree_container(const btree_container& x) = default; btree_container(btree_container&& x) noexcept = default; btree_container& operator=(const btree_container& x) = default; @@ -3442,79 +3171,66 @@ class btree_container // Lookup routines. // ---------------- template - size_type count(const key_arg& key) const - { + size_type count(const key_arg& key) const { auto equal_range = this->equal_range(key); return std::distance(equal_range.first, equal_range.second); } template - iterator find(const key_arg& key) - { + iterator find(const key_arg& key) { return tree_.find(key); } template - const_iterator find(const key_arg& key) const - { + const_iterator find(const key_arg& key) const { return tree_.find(key); } template - bool contains(const key_arg& key) const - { + bool contains(const key_arg& key) const { return find(key) != end(); } template - iterator lower_bound(const key_arg& key) - { + iterator lower_bound(const key_arg& key) { return tree_.lower_bound(key); } template - const_iterator lower_bound(const key_arg& key) const - { + const_iterator lower_bound(const key_arg& key) const { return tree_.lower_bound(key); } template - iterator upper_bound(const key_arg& key) - { + iterator upper_bound(const key_arg& key) { return tree_.upper_bound(key); } template - const_iterator upper_bound(const key_arg& key) const - { + const_iterator upper_bound(const key_arg& key) const { return tree_.upper_bound(key); } template - std::pair equal_range(const key_arg& key) - { + std::pair equal_range(const key_arg& key) { return tree_.equal_range(key); } template - std::pair equal_range(const key_arg& key) const - { + std::pair equal_range(const key_arg& key) const { return tree_.equal_range(key); } iterator erase(const_iterator iter) { return tree_.erase(iterator(iter)); } iterator erase(iterator iter) { return tree_.erase(iter); } - iterator erase(const_iterator first, const_iterator last) - { + iterator erase(const_iterator first, const_iterator last) { return tree_.erase(iterator(first), iterator(last)).second; } template - size_type erase(const key_arg& key) - { + size_type erase(const key_arg& key) { auto equal_range = this->equal_range(key); return tree_.erase_range(equal_range.first, equal_range.second).first; } - node_type extract(iterator position) - { + node_type extract(iterator position) { // Use Move instead of Transfer, because the rebalancing code expects to // have a valid object to scribble metadata bits on top of. // --------------------------------------------------------------------- @@ -3534,15 +3250,13 @@ class btree_container size_type max_size() const { return tree_.max_size(); } bool empty() const { return tree_.empty(); } - friend bool operator==(const btree_container& x, const btree_container& y) - { + friend bool operator==(const btree_container& x, const btree_container& y) { return x.size() == y.size() && std::equal(x.begin(), x.end(), y.begin()); } friend bool operator!=(const btree_container& x, const btree_container& y) { return !(x == y); } - friend bool operator<(const btree_container& x, const btree_container& y) - { + friend bool operator<(const btree_container& x, const btree_container& y) { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } @@ -3561,8 +3275,7 @@ class btree_container // Support absl::Hash. template - friend State AbslHashValue(State h, const btree_container& b) - { + friend State AbslHashValue(State h, const btree_container& b) { for (const auto& v : b) { h = State::combine(std::move(h), v); } @@ -3576,8 +3289,7 @@ class btree_container // A common base class for btree_set and btree_map. // ------------------------------------------------ template -class btree_set_container : public btree_container -{ +class btree_set_container : public btree_container { using super_type = btree_container; using params_type = typename Tree::params_type; using init_type = typename params_type::init_type; @@ -3606,70 +3318,57 @@ class btree_set_container : public btree_container InputIterator e, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()) - : super_type(comp, alloc) - { + : super_type(comp, alloc) { insert(b, e); } btree_set_container(std::initializer_list init, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()) - : btree_set_container(init.begin(), init.end(), comp, alloc) - { - } + : btree_set_container(init.begin(), init.end(), comp, alloc) {} btree_set_container(std::initializer_list init, const allocator_type& alloc) - : btree_set_container(init.begin(), init.end(), alloc) - { - } + : btree_set_container(init.begin(), init.end(), alloc) {} // Lookup routines. // ---------------- template - size_type count(const key_arg& key) const - { + size_type count(const key_arg& key) const { return this->tree_.count_unique(key); } // Insertion routines. // ------------------- std::pair insert(const value_type& x) { return this->tree_.insert_unique(params_type::key(x), x); } - std::pair insert(value_type&& x) - { + std::pair insert(value_type&& x) { return this->tree_.insert_unique(params_type::key(x), std::move(x)); } template - std::pair emplace(Args&&... args) - { + std::pair emplace(Args&&... args) { init_type v(std::forward(args)...); return this->tree_.insert_unique(params_type::key(v), std::move(v)); } - iterator insert(const_iterator hint, const value_type& x) - { + iterator insert(const_iterator hint, const value_type& x) { return this->tree_.insert_hint_unique(iterator(hint), params_type::key(x), x).first; } - iterator insert(const_iterator hint, value_type&& x) - { + iterator insert(const_iterator hint, value_type&& x) { return this->tree_.insert_hint_unique(iterator(hint), params_type::key(x), std::move(x)).first; } template - iterator emplace_hint(const_iterator hint, Args&&... args) - { + iterator emplace_hint(const_iterator hint, Args&&... args) { init_type v(std::forward(args)...); return this->tree_.insert_hint_unique(iterator(hint), params_type::key(v), std::move(v)).first; } template - void insert(InputIterator b, InputIterator e) - { + void insert(InputIterator b, InputIterator e) { this->tree_.insert_iterator_unique(b, e); } void insert(std::initializer_list init) { this->tree_.insert_iterator_unique(init.begin(), init.end()); } - insert_return_type insert(node_type&& node) - { + insert_return_type insert(node_type&& node) { if (!node) return { this->end(), false, node_type() }; std::pair res = @@ -3682,8 +3381,7 @@ class btree_set_container : public btree_container } } - iterator insert(const_iterator hint, node_type&& node) - { + iterator insert(const_iterator hint, node_type&& node) { if (!node) return this->end(); std::pair res = this->tree_.insert_hint_unique( @@ -3694,15 +3392,13 @@ class btree_set_container : public btree_container } template - size_type erase(const key_arg& key) - { + size_type erase(const key_arg& key) { return this->tree_.erase_unique(key); } using super_type::erase; template - node_type extract(const key_arg& key) - { + node_type extract(const key_arg& key) { auto it = this->find(key); return it == this->end() ? node_type() : extract(it); } @@ -3719,8 +3415,7 @@ class btree_set_container : public btree_container std::is_same>, int> = 0> - void merge(btree_container& src) - { // NOLINT + void merge(btree_container& src) { // NOLINT for (auto src_it = src.begin(); src_it != src.end();) { if (insert(std::move(*src_it)).second) { src_it = src.erase(src_it); @@ -3736,8 +3431,7 @@ class btree_set_container : public btree_container std::is_same>, int> = 0> - void merge(btree_container&& src) - { + void merge(btree_container&& src) { merge(src); } }; @@ -3745,8 +3439,7 @@ class btree_set_container : public btree_container // Base class for btree_map. // ------------------------- template -class btree_map_container : public btree_set_container -{ +class btree_map_container : public btree_set_container { using super_type = btree_set_container; using params_type = typename Tree::params_type; @@ -3771,14 +3464,12 @@ class btree_map_container : public btree_set_container // Insertion routines. // ------------------- template - std::pair try_emplace(const key_type& k, Args&&... args) - { + std::pair try_emplace(const key_type& k, Args&&... args) { return this->tree_.insert_unique( k, std::piecewise_construct, std::forward_as_tuple(k), std::forward_as_tuple(std::forward(args)...)); } template - std::pair try_emplace(key_type&& k, Args&&... args) - { + std::pair try_emplace(key_type&& k, Args&&... args) { // Note: `key_ref` exists to avoid a ClangTidy warning about moving from `k` // and then using `k` unsequenced. This is safe because the move is into a // forwarding reference and insert_unique guarantees that `key` is never @@ -3791,8 +3482,7 @@ class btree_map_container : public btree_set_container std::forward_as_tuple(std::forward(args)...)); } template - iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args) - { + iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args) { return this->tree_ .insert_hint_unique(iterator(hint), k, @@ -3802,8 +3492,7 @@ class btree_map_container : public btree_set_container .first; } template - iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args) - { + iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args) { // Note: `key_ref` exists to avoid a ClangTidy warning about moving from `k` // and then using `k` unsequenced. This is safe because the move is into a // forwarding reference and insert_hint_unique guarantees that `key` is @@ -3822,16 +3511,14 @@ class btree_map_container : public btree_set_container mapped_type& operator[](key_type&& k) { return try_emplace(std::move(k)).first->second; } template - mapped_type& at(const key_arg& key) - { + mapped_type& at(const key_arg& key) { auto it = this->find(key); if (it == this->end()) ThrowStdOutOfRange("gtl::btree_map::at"); return it->second; } template - const mapped_type& at(const key_arg& key) const - { + const mapped_type& at(const key_arg& key) const { auto it = this->find(key); if (it == this->end()) ThrowStdOutOfRange("gtl::btree_map::at"); @@ -3842,8 +3529,7 @@ class btree_map_container : public btree_set_container // A common base class for btree_multiset and btree_multimap. // ---------------------------------------------------------- template -class btree_multiset_container : public btree_container -{ +class btree_multiset_container : public btree_container { using super_type = btree_container; using params_type = typename Tree::params_type; using init_type = typename params_type::init_type; @@ -3874,8 +3560,7 @@ class btree_multiset_container : public btree_container InputIterator e, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()) - : super_type(comp, alloc) - { + : super_type(comp, alloc) { insert(b, e); } @@ -3884,15 +3569,12 @@ class btree_multiset_container : public btree_container btree_multiset_container(std::initializer_list init, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type()) - : btree_multiset_container(init.begin(), init.end(), comp, alloc) - { - } + : btree_multiset_container(init.begin(), init.end(), comp, alloc) {} // Lookup routines. // ---------------- template - size_type count(const key_arg& key) const - { + size_type count(const key_arg& key) const { return this->tree_.count_multi(key); } @@ -3900,32 +3582,26 @@ class btree_multiset_container : public btree_container // ------------------- iterator insert(const value_type& x) { return this->tree_.insert_multi(x); } iterator insert(value_type&& x) { return this->tree_.insert_multi(std::move(x)); } - iterator insert(const_iterator hint, const value_type& x) - { + iterator insert(const_iterator hint, const value_type& x) { return this->tree_.insert_hint_multi(iterator(hint), x); } - iterator insert(const_iterator hint, value_type&& x) - { + iterator insert(const_iterator hint, value_type&& x) { return this->tree_.insert_hint_multi(iterator(hint), std::move(x)); } template - void insert(InputIterator b, InputIterator e) - { + void insert(InputIterator b, InputIterator e) { this->tree_.insert_iterator_multi(b, e); } void insert(std::initializer_list init) { this->tree_.insert_iterator_multi(init.begin(), init.end()); } template - iterator emplace(Args&&... args) - { + iterator emplace(Args&&... args) { return this->tree_.insert_multi(init_type(std::forward(args)...)); } template - iterator emplace_hint(const_iterator hint, Args&&... args) - { + iterator emplace_hint(const_iterator hint, Args&&... args) { return this->tree_.insert_hint_multi(iterator(hint), init_type(std::forward(args)...)); } - iterator insert(node_type&& node) - { + iterator insert(node_type&& node) { if (!node) return this->end(); iterator res = @@ -3933,8 +3609,7 @@ class btree_multiset_container : public btree_container CommonAccess::Destroy(&node); return res; } - iterator insert(const_iterator hint, node_type&& node) - { + iterator insert(const_iterator hint, node_type&& node) { if (!node) return this->end(); iterator res = @@ -3946,16 +3621,14 @@ class btree_multiset_container : public btree_container // Deletion routines. // ------------------ template - size_type erase(const key_arg& key) - { + size_type erase(const key_arg& key) { return this->tree_.erase_multi(key); } using super_type::erase; // Node extraction routines. template - node_type extract(const key_arg& key) - { + node_type extract(const key_arg& key) { auto it = this->find(key); return it == this->end() ? node_type() : extract(it); } @@ -3970,8 +3643,7 @@ class btree_multiset_container : public btree_container std::is_same>, int> = 0> - void merge(btree_container& src) - { // NOLINT + void merge(btree_container& src) { // NOLINT insert(std::make_move_iterator(src.begin()), std::make_move_iterator(src.end())); src.clear(); } @@ -3982,8 +3654,7 @@ class btree_multiset_container : public btree_container std::is_same>, int> = 0> - void merge(btree_container&& src) - { + void merge(btree_container&& src) { merge(src); } }; @@ -3991,8 +3662,7 @@ class btree_multiset_container : public btree_container // A base class for btree_multimap. // -------------------------------- template -class btree_multimap_container : public btree_multiset_container -{ +class btree_multimap_container : public btree_multiset_container { using super_type = btree_multiset_container; using params_type = typename Tree::params_type; @@ -4012,8 +3682,7 @@ class btree_multimap_container : public btree_multiset_container template class btree_set : public priv::btree_set_container< - priv::btree>> -{ + priv::btree>> { using Base = typename btree_set::btree_set_container; public: @@ -4048,16 +3717,14 @@ class btree_set // Swaps the contents of two `gtl::btree_set` containers. // ------------------------------------------------------- template -void swap(btree_set& x, btree_set& y) -{ +void swap(btree_set& x, btree_set& y) { return x.swap(y); } // Erases all elements that satisfy the predicate pred from the container. // ---------------------------------------------------------------------- template -void erase_if(btree_set& set, Pred pred) -{ +void erase_if(btree_set& set, Pred pred) { for (auto it = set.begin(); it != set.end();) { if (pred(*it)) { it = set.erase(it); @@ -4073,8 +3740,7 @@ void erase_if(btree_set& set, Pred pred) template class btree_multiset : public priv::btree_multiset_container< - priv::btree>> -{ + priv::btree>> { using Base = typename btree_multiset::btree_multiset_container; public: @@ -4109,16 +3775,14 @@ class btree_multiset // Swaps the contents of two `gtl::btree_multiset` containers. // ------------------------------------------------------------ template -void swap(btree_multiset& x, btree_multiset& y) -{ +void swap(btree_multiset& x, btree_multiset& y) { return x.swap(y); } // Erases all elements that satisfy the predicate pred from the container. // ---------------------------------------------------------------------- template -void erase_if(btree_multiset& set, Pred pred) -{ +void erase_if(btree_multiset& set, Pred pred) { for (auto it = set.begin(); it != set.end();) { if (pred(*it)) { it = set.erase(it); @@ -4134,8 +3798,7 @@ void erase_if(btree_multiset& set, Pred pred) template class btree_map : public priv::btree_map_container< - priv::btree>> -{ + priv::btree>> { using Base = typename btree_map::btree_map_container; public: @@ -4173,15 +3836,13 @@ class btree_map // Swaps the contents of two `gtl::btree_map` containers. // ------------------------------------------------------- template -void swap(btree_map& x, btree_map& y) -{ +void swap(btree_map& x, btree_map& y) { return x.swap(y); } // ---------------------------------------------------------------------- template -void erase_if(btree_map& map, Pred pred) -{ +void erase_if(btree_map& map, Pred pred) { for (auto it = map.begin(); it != map.end();) { if (pred(*it)) { it = map.erase(it); @@ -4197,8 +3858,7 @@ void erase_if(btree_map& map, Pred pred) template class btree_multimap : public priv::btree_multimap_container< - priv::btree>> -{ + priv::btree>> { using Base = typename btree_multimap::btree_multimap_container; public: @@ -4233,16 +3893,14 @@ class btree_multimap // Swaps the contents of two `gtl::btree_multimap` containers. // ------------------------------------------------------------ template -void swap(btree_multimap& x, btree_multimap& y) -{ +void swap(btree_multimap& x, btree_multimap& y) { return x.swap(y); } // Erases all elements that satisfy the predicate pred from the container. // ---------------------------------------------------------------------- template -void erase_if(btree_multimap& map, Pred pred) -{ +void erase_if(btree_multimap& map, Pred pred) { for (auto it = map.begin(); it != map.end();) { if (pred(*it)) { it = map.erase(it); diff --git a/include/gtl/combinators.hpp b/include/gtl/combinators.hpp index 16a1e3b..9400c76 100644 --- a/include/gtl/combinators.hpp +++ b/include/gtl/combinators.hpp @@ -4,61 +4,61 @@ pragma once * from https://github.com/codereport/blackbird - Copyright (c) 2022 Conor Hoekstra * * MIT License: https://github.com/codereport/blackbird/blob/main/LICENSE - */ + */ #include -namespace combinators { + namespace combinators { -///////////////// -// combinators // -///////////////// + ///////////////// + // combinators // + ///////////////// -// B (The Bluebird) -auto _b = [](auto f, auto g) { return [=](auto x) { return f(g(x)); }; }; + // B (The Bluebird) + auto _b = [](auto f, auto g) { return [=](auto x) { return f(g(x)); }; }; -// C (The Cardinal) aka `flip` in Haskell -auto _c = [](auto f) { return [=](auto x, auto y) { return f(y, x); }; }; + // C (The Cardinal) aka `flip` in Haskell + auto _c = [](auto f) { return [=](auto x, auto y) { return f(y, x); }; }; -// K (Kestrel) -auto _l_ = [](auto x, auto y) { return x; }; + // K (Kestrel) + auto _l_ = [](auto x, auto y) { return x; }; -// KI -auto _r_ = [](auto x, auto y) { return y; }; + // KI + auto _r_ = [](auto x, auto y) { return y; }; -// Phi (The Phoenix) -auto _phi = [](auto f, auto g, auto h) { return [=](auto x) { return g(f(x), h(x)); }; }; + // Phi (The Phoenix) + auto _phi = [](auto f, auto g, auto h) { return [=](auto x) { return g(f(x), h(x)); }; }; -// Phi1 (The Pheasant) -auto _phi1_ = [](auto f, auto g, auto h) { return [=](auto x, auto y) { return g(f(x, y), h(x, y)); }; }; + // Phi1 (The Pheasant) + auto _phi1_ = [](auto f, auto g, auto h) { return [=](auto x, auto y) { return g(f(x, y), h(x, y)); }; }; -// Psi (The Psi Bird) -auto _psi = [](auto f, auto g) { return [=](auto x, auto y) { return f(g(x), g(y)); }; }; + // Psi (The Psi Bird) + auto _psi = [](auto f, auto g) { return [=](auto x, auto y) { return f(g(x), g(y)); }; }; -///////////////////////////////////////////// -// more convenient binary/unary operations // -///////////////////////////////////////////// + ///////////////////////////////////////////// + // more convenient binary/unary operations // + ///////////////////////////////////////////// -auto _eq = [](auto x) { return [x](auto y) { return x == y; }; }; -auto _eq_ = std::equal_to{}; -auto _neq_ = std::not_equal_to{}; -auto _lt = [](auto x) { return [x](auto y) { return x > y; }; }; -auto lt_ = [](auto x) { return [x](auto y) { return y < x; }; }; -auto _lt_ = std::less{}; -auto _gte = [](auto x) { return [x](auto y) { return x >= y; }; }; -auto _plus = [](auto x) { return [x](auto y) { return x + y; }; }; -auto _plus_ = std::plus{}; -auto _mul = [](auto x) { return [x](auto y) { return x * y; }; }; -auto _mul_ = std::multiplies{}; -auto _sub = [](auto x) { return [x](auto y) { return x - y; }; }; -auto sub_ = [](auto x) { return [x](auto y) { return y - x; }; }; -auto _sub_ = std::minus{}; -auto _or_ = std::logical_or{}; -auto _and_ = std::logical_and{}; -auto _not = std::logical_not{}; -auto _min_ = [](auto a, auto b) { return std::min(a, b); }; -auto _max_ = [](auto a, auto b) { return std::max(a, b); }; -auto _fst = [](auto t) { return std::get<0>(t); }; -auto _snd = [](auto t) { return std::get<1>(t); }; + auto _eq = [](auto x) { return [x](auto y) { return x == y; }; }; + auto _eq_ = std::equal_to{}; + auto _neq_ = std::not_equal_to{}; + auto _lt = [](auto x) { return [x](auto y) { return x > y; }; }; + auto lt_ = [](auto x) { return [x](auto y) { return y < x; }; }; + auto _lt_ = std::less{}; + auto _gte = [](auto x) { return [x](auto y) { return x >= y; }; }; + auto _plus = [](auto x) { return [x](auto y) { return x + y; }; }; + auto _plus_ = std::plus{}; + auto _mul = [](auto x) { return [x](auto y) { return x * y; }; }; + auto _mul_ = std::multiplies{}; + auto _sub = [](auto x) { return [x](auto y) { return x - y; }; }; + auto sub_ = [](auto x) { return [x](auto y) { return y - x; }; }; + auto _sub_ = std::minus{}; + auto _or_ = std::logical_or{}; + auto _and_ = std::logical_and{}; + auto _not = std::logical_not{}; + auto _min_ = [](auto a, auto b) { return std::min(a, b); }; + auto _max_ = [](auto a, auto b) { return std::max(a, b); }; + auto _fst = [](auto t) { return std::get<0>(t); }; + auto _snd = [](auto t) { return std::get<1>(t); }; -} // namespace combinators +} // namespace combinators diff --git a/include/gtl/gtl_base.hpp b/include/gtl/gtl_base.hpp index 01554c2..6710a76 100644 --- a/include/gtl/gtl_base.hpp +++ b/include/gtl/gtl_base.hpp @@ -73,34 +73,29 @@ namespace priv { // type, which is non-portable. // ---------------------------------------------------------------------------- template -struct OffsetOf -{ +struct OffsetOf { static constexpr size_t kFirst = (size_t)-1; static constexpr size_t kSecond = (size_t)-1; }; template -struct OffsetOf::type> -{ +struct OffsetOf::type> { static constexpr size_t kFirst = offsetof(Pair, first); static constexpr size_t kSecond = offsetof(Pair, second); }; // ---------------------------------------------------------------------------- template -struct IsLayoutCompatible -{ +struct IsLayoutCompatible { private: - struct Pair - { + struct Pair { K first; V second; }; // Is P layout-compatible with Pair? template - static constexpr bool LayoutCompatible() - { + static constexpr bool LayoutCompatible() { return std::is_standard_layout

() && sizeof(P) == sizeof(Pair) && alignof(P) == alignof(Pair) && OffsetOf

::kFirst == OffsetOf::kFirst && OffsetOf

::kSecond == OffsetOf::kSecond; } @@ -140,8 +135,7 @@ struct IsLayoutCompatible // https://timsong-cpp.github.io/cppwp/n3337/class.mem#19 (9.2.19) // ---------------------------------------------------------------------------- template -union map_slot_type -{ +union map_slot_type { map_slot_type() {} ~map_slot_type() = delete; map_slot_type(const map_slot_type&) = delete; @@ -158,15 +152,13 @@ union map_slot_type // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- template -struct map_slot_policy -{ +struct map_slot_policy { using slot_type = map_slot_type; using value_type = std::pair; using mutable_value_type = std::pair; private: - static void emplace(slot_type* slot) - { + static void emplace(slot_type* slot) { // The construction of union doesn't do anything at runtime but it allows us // to access its members without violating aliasing rules. new (slot) slot_type; @@ -183,8 +175,7 @@ struct map_slot_policy static const K& key(const slot_type* slot) { return kMutableKeys::value ? slot->key : slot->value.first; } template - static void construct(Allocator* alloc, slot_type* slot, Args&&... args) - { + static void construct(Allocator* alloc, slot_type* slot, Args&&... args) { emplace(slot); if (kMutableKeys::value) { std::allocator_traits::construct(*alloc, &slot->mutable_value, std::forward(args)...); @@ -195,8 +186,7 @@ struct map_slot_policy // Construct this slot by moving from another slot. template - static void construct(Allocator* alloc, slot_type* slot, slot_type* other) - { + static void construct(Allocator* alloc, slot_type* slot, slot_type* other) { emplace(slot); if (kMutableKeys::value) { std::allocator_traits::construct(*alloc, &slot->mutable_value, std::move(other->mutable_value)); @@ -206,8 +196,7 @@ struct map_slot_policy } template - static void destroy(Allocator* alloc, slot_type* slot) - { + static void destroy(Allocator* alloc, slot_type* slot) { if (kMutableKeys::value) { std::allocator_traits::destroy(*alloc, &slot->mutable_value); } else { @@ -216,8 +205,7 @@ struct map_slot_policy } template - static void transfer(Allocator* alloc, slot_type* new_slot, slot_type* old_slot) - { + static void transfer(Allocator* alloc, slot_type* new_slot, slot_type* old_slot) { emplace(new_slot); if (kMutableKeys::value) { std::allocator_traits::construct( @@ -229,8 +217,7 @@ struct map_slot_policy } template - static void swap(Allocator* alloc, slot_type* a, slot_type* b) - { + static void swap(Allocator* alloc, slot_type* a, slot_type* b) { if (kMutableKeys::value) { using std::swap; swap(a->mutable_value, b->mutable_value); @@ -244,8 +231,7 @@ struct map_slot_policy } template - static void move(Allocator* alloc, slot_type* src, slot_type* dest) - { + static void move(Allocator* alloc, slot_type* src, slot_type* dest) { if (kMutableKeys::value) { dest->mutable_value = std::move(src->mutable_value); } else { @@ -255,8 +241,7 @@ struct map_slot_policy } template - static void move(Allocator* alloc, slot_type* first, slot_type* last, slot_type* result) - { + static void move(Allocator* alloc, slot_type* first, slot_type* last, slot_type* result) { for (slot_type *src = first, *dest = result; src != last; ++src, ++dest) move(alloc, src, dest); } @@ -277,13 +262,10 @@ struct Aligned; namespace internal_layout { template -struct NotAligned -{ -}; +struct NotAligned {}; template -struct NotAligned> -{ +struct NotAligned> { static_assert(sizeof(T) == 0, "Aligned cannot be const-qualified"); }; @@ -294,39 +276,31 @@ template using TypeToSize = size_t; template -struct Type : NotAligned -{ +struct Type : NotAligned { using type = T; }; template -struct Type> -{ +struct Type> { using type = T; }; template struct SizeOf : NotAligned - , std::integral_constant -{ -}; + , std::integral_constant {}; template -struct SizeOf> : std::integral_constant -{ -}; +struct SizeOf> : std::integral_constant {}; // Note: workaround for https://gcc.gnu.org/PR88115 template -struct AlignOf : NotAligned -{ +struct AlignOf : NotAligned { static constexpr size_t value = alignof(T); }; template -struct AlignOf> -{ +struct AlignOf> { static_assert(N % alignof(T) == 0, "Custom alignment can't be lower than the type's alignment"); static constexpr size_t value = N; }; @@ -344,15 +318,13 @@ using CopyConst = typename std::conditional_t, const To, T namespace adl_barrier { template -constexpr size_t Find(Needle, Needle, Ts...) -{ +constexpr size_t Find(Needle, Needle, Ts...) { static_assert(!Contains(), "Duplicate element type"); return 0; } template -constexpr size_t Find(Needle, T, Ts...) -{ +constexpr size_t Find(Needle, T, Ts...) { return adl_barrier::Find(Needle(), Ts()...) + 1; } @@ -367,8 +339,7 @@ constexpr size_t Min(size_t a, size_t b) { return b < a ? b : a; } constexpr size_t Max(size_t a) { return a; } template -constexpr size_t Max(size_t a, size_t b, Ts... rest) -{ +constexpr size_t Max(size_t a, size_t b, Ts... rest) { return adl_barrier::Max(b < a ? a : b, rest...); } @@ -403,14 +374,12 @@ class LayoutImpl; // can compute offsets). // --------------------------------------------------------------------------- template -class LayoutImpl, std::index_sequence, std::index_sequence> -{ +class LayoutImpl, std::index_sequence, std::index_sequence> { private: static_assert(sizeof...(Elements) > 0, "At least one field is required"); static_assert(std::conjunction_v...>, "Invalid element type (see IsLegalElementType)"); - enum - { + enum { NumTypes = sizeof...(Elements), NumSizes = sizeof...(SizeSeq), NumOffsets = sizeof...(OffsetSeq), @@ -423,8 +392,7 @@ class LayoutImpl, std::index_sequence, std:: // Returns the index of `T` in `Elements...`. Results in a compilation error // if `Elements...` doesn't contain exactly one instance of `T`. template - static constexpr size_t ElementIndex() - { + static constexpr size_t ElementIndex() { static_assert(Contains, Type::type>...>(), "Type not found"); return adl_barrier::Find(Type(), Type::type>()...); } @@ -441,9 +409,7 @@ class LayoutImpl, std::index_sequence, std:: using ElementType = typename std::tuple_element::type; constexpr explicit LayoutImpl(IntToSize... sizes) - : size_{ sizes... } - { - } + : size_{ sizes... } {} // Alignment of the layout, equal to the strictest alignment of all elements. // All pointers passed to the methods of layout must be aligned to this value. @@ -459,14 +425,12 @@ class LayoutImpl, std::index_sequence, std:: // Requires: `N <= NumSizes && N < sizeof...(Ts)`. // ---------------------------------------------------------------------------- template = 0> - constexpr size_t Offset() const - { + constexpr size_t Offset() const { return 0; } template = 0> - constexpr size_t Offset() const - { + constexpr size_t Offset() const { static_assert(N < NumOffsets, "Index out of bounds"); return adl_barrier::Align(Offset() + SizeOf>::value * size_[N - 1], ElementAlignment::value); @@ -482,8 +446,7 @@ class LayoutImpl, std::index_sequence, std:: // assert(x.Offset() == 16); // The doubles starts from 16. // ---------------------------------------------------------------------------- template - constexpr size_t Offset() const - { + constexpr size_t Offset() const { return Offset()>(); } @@ -501,8 +464,7 @@ class LayoutImpl, std::index_sequence, std:: // Requires: `N < NumSizes`. // ---------------------------------------------------------------------------- template - constexpr size_t Size() const - { + constexpr size_t Size() const { static_assert(N < NumSizes, "Index out of bounds"); return size_[N]; } @@ -517,8 +479,7 @@ class LayoutImpl, std::index_sequence, std:: // assert(x.Size() == 4); // ---------------------------------------------------------------------------- template - constexpr size_t Size() const - { + constexpr size_t Size() const { return Size()>(); } @@ -539,8 +500,7 @@ class LayoutImpl, std::index_sequence, std:: // Requires: `p` is aligned to `Alignment()`. // ---------------------------------------------------------------------------- template - CopyConst>* Pointer(Char* p) const - { + CopyConst>* Pointer(Char* p) const { using C = typename std::remove_const_t; static_assert(std::is_same() || std::is_same() || std::is_same(), "The argument must be a pointer to [const] [signed|unsigned] char"); @@ -565,8 +525,7 @@ class LayoutImpl, std::index_sequence, std:: // Requires: `p` is aligned to `Alignment()`. // ---------------------------------------------------------------------------- template - CopyConst* Pointer(Char* p) const - { + CopyConst* Pointer(Char* p) const { return Pointer()>(p); } @@ -588,8 +547,8 @@ class LayoutImpl, std::index_sequence, std:: // under MSVC. // ---------------------------------------------------------------------------- template - std::tuple::type>*...> Pointers(Char* p) const - { + std::tuple::type>*...> Pointers( + Char* p) const { return std::tuple>*...>(Pointer(p)...); } @@ -601,8 +560,7 @@ class LayoutImpl, std::index_sequence, std:: // // Requires: `NumSizes == sizeof...(Ts)`. // ---------------------------------------------------------------------------- - constexpr size_t AllocSize() const - { + constexpr size_t AllocSize() const { static_assert(NumTypes == NumSizes, "You must specify sizes of all fields"); return Offset() + SizeOf>::value * size_[NumTypes - 1]; } @@ -616,14 +574,12 @@ class LayoutImpl, std::index_sequence, std:: // Requires: `p` is aligned to `Alignment()`. // ---------------------------------------------------------------------------- template = 0> - void PoisonPadding(const Char* p) const - { + void PoisonPadding(const Char* p) const { Pointer<0>(p); // verify the requirements on `Char` and `p` } template = 0> - void PoisonPadding(const Char* p) const - { + void PoisonPadding(const Char* p) const { static_assert(N < NumOffsets, "Index out of bounds"); (void)p; #ifdef ADDRESS_SANITIZER @@ -659,8 +615,7 @@ using LayoutType = LayoutImpl, // by `Layout`. // --------------------------------------------------------------------------- template -class Layout : public internal_layout::LayoutType -{ +class Layout : public internal_layout::LayoutType { public: static_assert(sizeof...(Ts) > 0, "At least one field is required"); static_assert(std::conjunction_v...>, @@ -670,8 +625,7 @@ class Layout : public internal_layout::LayoutType using PartialType = internal_layout::LayoutType; template - static constexpr PartialType Partial(Sizes&&... sizes) - { + static constexpr PartialType Partial(Sizes&&... sizes) { static_assert(sizeof...(Sizes) <= sizeof...(Ts), ""); return PartialType(std::forward(sizes)...); } @@ -685,9 +639,7 @@ class Layout : public internal_layout::LayoutType // Note: The sizes of the arrays must be specified in number of elements, // not in bytes. constexpr explicit Layout(internal_layout::TypeToSize... sizes) - : internal_layout::LayoutType(sizes...) - { - } + : internal_layout::LayoutType(sizes...) {} }; } // priv @@ -695,26 +647,20 @@ class Layout : public internal_layout::LayoutType // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- template -struct IsTransparent : std::false_type -{ -}; +struct IsTransparent : std::false_type {}; template -struct IsTransparent> : std::true_type -{ -}; +struct IsTransparent> : std::true_type {}; template -struct KeyArg -{ +struct KeyArg { // Transparent. Forward `K`. template using type = K; }; template<> -struct KeyArg -{ +struct KeyArg { // Not transparent. Always use `key_type`. template using type = key_type; @@ -723,14 +669,12 @@ struct KeyArg // ----------------------------------------------------------------------- // ----------------------------------------------------------------------- template -struct EqualTo -{ +struct EqualTo { inline bool operator()(const T& a, const T& b) const { return std::equal_to()(a, b); } }; template -struct Less -{ +struct Less { inline bool operator()(const T& a, const T& b) const { return std::less()(a, b); } }; @@ -738,10 +682,8 @@ struct Less // std::aligned_storage and std::aligned_storage_t are deprecated in C++23 // ----------------------------------------------------------------------- template -struct aligned_storage -{ - struct type - { +struct aligned_storage { + struct type { alignas(Align) unsigned char data[Len]; }; }; @@ -755,8 +697,7 @@ using aligned_storage_t = typename aligned_storage::type; // common API of both. // ----------------------------------------------------------------------- template -class node_handle_base -{ +class node_handle_base { protected: using slot_type = typename PolicyTraits::slot_type; @@ -769,8 +710,7 @@ class node_handle_base ~node_handle_base() { destroy(); } - node_handle_base& operator=(node_handle_base&& other) noexcept - { + node_handle_base& operator=(node_handle_base&& other) noexcept { destroy(); if (!other.empty()) { alloc_ = other.alloc_; @@ -787,47 +727,39 @@ class node_handle_base protected: friend struct CommonAccess; - struct transfer_tag_t - {}; + struct transfer_tag_t {}; node_handle_base(transfer_tag_t, const allocator_type& a, slot_type* s) - : alloc_(a) - { + : alloc_(a) { PolicyTraits::transfer(alloc(), slot(), s); } - struct move_tag_t - {}; + struct move_tag_t {}; node_handle_base(move_tag_t, const allocator_type& a, slot_type* s) - : alloc_(a) - { + : alloc_(a) { PolicyTraits::construct(alloc(), slot(), s); } node_handle_base(const allocator_type& a, slot_type* s) - : alloc_(a) - { + : alloc_(a) { PolicyTraits::transfer(alloc(), slot(), s); } // node_handle_base(const node_handle_base&) = delete; // node_handle_base& operator=(const node_handle_base&) = delete; - void destroy() - { + void destroy() { if (!empty()) { PolicyTraits::destroy(alloc(), slot()); reset(); } } - void reset() - { + void reset() { assert(alloc_.has_value()); alloc_ = std::nullopt; } - slot_type* slot() const - { + slot_type* slot() const { assert(!empty()); return reinterpret_cast(std::addressof(slot_space_)); } @@ -842,8 +774,7 @@ class node_handle_base // For sets. // --------- template -class node_handle : public node_handle_base -{ +class node_handle : public node_handle_base { using Base = node_handle_base; public: @@ -865,8 +796,7 @@ class node_handle : public node_handle_base // --------- template class node_handle> - : public node_handle_base -{ + : public node_handle_base { using Base = node_handle_base; public: @@ -887,41 +817,34 @@ class node_handle - static auto GetSlot(const Node& node) -> decltype(node.slot()) - { + static auto GetSlot(const Node& node) -> decltype(node.slot()) { return node.slot(); } template - static void Destroy(Node* node) - { + static void Destroy(Node* node) { node->destroy(); } template - static void Reset(Node* node) - { + static void Reset(Node* node) { node->reset(); } template - static T Make(Args&&... args) - { + static T Make(Args&&... args) { return T(std::forward(args)...); } template - static T Transfer(Args&&... args) - { + static T Transfer(Args&&... args) { return T(typename T::transfer_tag_t{}, std::forward(args)...); } template - static T Move(Args&&... args) - { + static T Move(Args&&... args) { return T(typename T::move_tag_t{}, std::forward(args)...); } }; @@ -929,8 +852,7 @@ struct CommonAccess // Implement the insert_return_type<> concept of C++17. // ---------------------------------------------------- template -struct InsertReturnType -{ +struct InsertReturnType { Iterator position; bool inserted; NodeType node; @@ -945,15 +867,13 @@ struct InsertReturnType // type, which is non-portable. // ---------------------------------------------------------------------------- template -struct OffsetOf -{ +struct OffsetOf { static constexpr size_t kFirst = (size_t)-1; static constexpr size_t kSecond = (size_t)-1; }; template -struct OffsetOf::type> -{ +struct OffsetOf::type> { static constexpr size_t kFirst = offsetof(Pair, first); static constexpr size_t kSecond = offsetof(Pair, second); }; @@ -976,12 +896,10 @@ struct OffsetOf::type> // returns insufficiently alignment pointer, that's what you are going to get. // ---------------------------------------------------------------------------- template -void* Allocate(Alloc* alloc, size_t n) -{ +void* Allocate(Alloc* alloc, size_t n) { static_assert(Alignment > 0, ""); assert(n && "n must be positive"); - struct alignas(Alignment) M - {}; + struct alignas(Alignment) M {}; using A = typename std::allocator_traits::template rebind_alloc; using AT = typename std::allocator_traits::template rebind_traits; A mem_alloc(*alloc); @@ -995,12 +913,10 @@ void* Allocate(Alloc* alloc, size_t n) // Allocate(alloc, n). // ---------------------------------------------------------------------------- template -void Deallocate(Alloc* alloc, void* p, size_t n) -{ +void Deallocate(Alloc* alloc, void* p, size_t n) { static_assert(Alignment > 0, ""); assert(n && "n must be positive"); - struct alignas(Alignment) M - {}; + struct alignas(Alignment) M {}; using A = typename std::allocator_traits::template rebind_alloc; using AT = typename std::allocator_traits::template rebind_traits; A mem_alloc(*alloc); @@ -1017,8 +933,7 @@ void Deallocate(Alloc* alloc, void* p, size_t n) #include #endif -inline void SanitizerPoisonMemoryRegion(const void* m, size_t s) -{ +inline void SanitizerPoisonMemoryRegion(const void* m, size_t s) { #ifdef ADDRESS_SANITIZER ASAN_POISON_MEMORY_REGION(m, s); #endif @@ -1029,8 +944,7 @@ inline void SanitizerPoisonMemoryRegion(const void* m, size_t s) (void)s; } -inline void SanitizerUnpoisonMemoryRegion(const void* m, size_t s) -{ +inline void SanitizerUnpoisonMemoryRegion(const void* m, size_t s) { #ifdef ADDRESS_SANITIZER ASAN_UNPOISON_MEMORY_REGION(m, s); #endif @@ -1042,14 +956,12 @@ inline void SanitizerUnpoisonMemoryRegion(const void* m, size_t s) } template -inline void SanitizerPoisonObject(const T* object) -{ +inline void SanitizerPoisonObject(const T* object) { SanitizerPoisonMemoryRegion(object, sizeof(T)); } template -inline void SanitizerUnpoisonObject(const T* object) -{ +inline void SanitizerUnpoisonObject(const T* object) { SanitizerUnpoisonMemoryRegion(object, sizeof(T)); } diff --git a/include/gtl/intrusive.hpp b/include/gtl/intrusive.hpp index ab18237..1d777a1 100644 --- a/include/gtl/intrusive.hpp +++ b/include/gtl/intrusive.hpp @@ -45,8 +45,7 @@ namespace gtl { // reference counts is 0. // --------------------------------------------------------------------------- template -class intrusive_ptr -{ +class intrusive_ptr { private: using this_type = intrusive_ptr; @@ -57,82 +56,69 @@ class intrusive_ptr friend class intrusive_ptr; constexpr intrusive_ptr() noexcept - : px(nullptr) - { - } + : px(nullptr) {} intrusive_ptr(T* p, bool add_ref = true) noexcept - : px(p) - { + : px(p) { if (px != nullptr && add_ref) intrusive_ptr_add_ref(px); } template //, typename std::enable_if_t, int> = 0> intrusive_ptr(intrusive_ptr const& rhs) noexcept - : px(rhs.get()) - { + : px(rhs.get()) { if (px) intrusive_ptr_add_ref(px); } template, int> = 0> intrusive_ptr(intrusive_ptr&& rhs) - : px(rhs.px) - { + : px(rhs.px) { rhs.px = nullptr; } intrusive_ptr(intrusive_ptr const& rhs) noexcept - : px(rhs.px) - { + : px(rhs.px) { if (px) intrusive_ptr_add_ref(px); } intrusive_ptr(intrusive_ptr&& rhs) noexcept - : px(rhs.px) - { + : px(rhs.px) { rhs.px = nullptr; } - ~intrusive_ptr() - { + ~intrusive_ptr() { if (px) intrusive_ptr_release(px); } - intrusive_ptr& operator=(intrusive_ptr const& rhs) - { + intrusive_ptr& operator=(intrusive_ptr const& rhs) { if (this != &rhs) this_type(rhs).swap(*this); return *this; } template - intrusive_ptr& operator=(intrusive_ptr const& rhs) - { + intrusive_ptr& operator=(intrusive_ptr const& rhs) { if (this != &rhs) this_type(rhs).swap(*this); return *this; } - intrusive_ptr& operator=(intrusive_ptr&& rhs) noexcept - { + intrusive_ptr& operator=(intrusive_ptr&& rhs) noexcept { if (this != &rhs) this_type(std::move(rhs)).swap(*this); return *this; } template - intrusive_ptr& operator=(intrusive_ptr&& rhs) noexcept - { + intrusive_ptr& operator=(intrusive_ptr&& rhs) noexcept { this_type(std::move(rhs)).swap(*this); return *this; } - intrusive_ptr& operator=(T* rhs) - { + intrusive_ptr& operator=(T* rhs) { if (rhs != px) this_type(rhs).swap(*this); return *this; @@ -146,29 +132,25 @@ class intrusive_ptr T* get() const noexcept { return px; } - T* detach() noexcept - { + T* detach() noexcept { T* ret = px; px = nullptr; return ret; } - T& operator*() const - { + T& operator*() const { assert(px); return *px; } - T* operator->() const - { + T* operator->() const { assert(px); return px; } explicit operator bool() const noexcept { return px != nullptr; } - void swap(intrusive_ptr& rhs) noexcept - { + void swap(intrusive_ptr& rhs) noexcept { T* tmp = px; px = rhs.px; rhs.px = tmp; @@ -181,122 +163,103 @@ class intrusive_ptr // comparison operators // -------------------- template -inline bool operator==(intrusive_ptr const& a, intrusive_ptr const& b) noexcept -{ +inline bool operator==(intrusive_ptr const& a, intrusive_ptr const& b) noexcept { return a.get() == b.get(); } template -inline bool operator!=(intrusive_ptr const& a, intrusive_ptr const& b) noexcept -{ +inline bool operator!=(intrusive_ptr const& a, intrusive_ptr const& b) noexcept { return a.get() != b.get(); } template -inline bool operator==(intrusive_ptr const& a, U* b) noexcept -{ +inline bool operator==(intrusive_ptr const& a, U* b) noexcept { return a.get() == b; } template -inline bool operator!=(intrusive_ptr const& a, U* b) noexcept -{ +inline bool operator!=(intrusive_ptr const& a, U* b) noexcept { return a.get() != b; } template -inline bool operator==(T* a, intrusive_ptr const& b) noexcept -{ +inline bool operator==(T* a, intrusive_ptr const& b) noexcept { return a == b.get(); } template -inline bool operator!=(T* a, intrusive_ptr const& b) noexcept -{ +inline bool operator!=(T* a, intrusive_ptr const& b) noexcept { return a != b.get(); } template -inline bool operator==(intrusive_ptr const& p, std::nullptr_t) noexcept -{ +inline bool operator==(intrusive_ptr const& p, std::nullptr_t) noexcept { return p.get() == nullptr; } template -inline bool operator==(std::nullptr_t, intrusive_ptr const& p) noexcept -{ +inline bool operator==(std::nullptr_t, intrusive_ptr const& p) noexcept { return p.get() == nullptr; } template -inline bool operator!=(intrusive_ptr const& p, std::nullptr_t) noexcept -{ +inline bool operator!=(intrusive_ptr const& p, std::nullptr_t) noexcept { return p.get() != nullptr; } template -inline bool operator!=(std::nullptr_t, intrusive_ptr const& p) noexcept -{ +inline bool operator!=(std::nullptr_t, intrusive_ptr const& p) noexcept { return p.get() != nullptr; } template -inline bool operator<(intrusive_ptr const& a, intrusive_ptr const& b) noexcept -{ +inline bool operator<(intrusive_ptr const& a, intrusive_ptr const& b) noexcept { return std::less()(a.get(), b.get()); } // swap // ---- template -void swap(intrusive_ptr& lhs, intrusive_ptr& rhs) noexcept -{ +void swap(intrusive_ptr& lhs, intrusive_ptr& rhs) noexcept { lhs.swap(rhs); } // mem_fn support // -------------- template -T* get_pointer(intrusive_ptr const& p) noexcept -{ +T* get_pointer(intrusive_ptr const& p) noexcept { return p.get(); } // pointer casts // ------------- template -intrusive_ptr static_pointer_cast(intrusive_ptr const& p) -{ +intrusive_ptr static_pointer_cast(intrusive_ptr const& p) { return static_cast(p.get()); } template -intrusive_ptr const_pointer_cast(intrusive_ptr const& p) -{ +intrusive_ptr const_pointer_cast(intrusive_ptr const& p) { return const_cast(p.get()); } template -intrusive_ptr dynamic_pointer_cast(intrusive_ptr const& p) -{ +intrusive_ptr dynamic_pointer_cast(intrusive_ptr const& p) { return dynamic_cast(p.get()); } template -intrusive_ptr static_pointer_cast(intrusive_ptr&& p) noexcept -{ +intrusive_ptr static_pointer_cast(intrusive_ptr&& p) noexcept { return intrusive_ptr(static_cast(p.detach()), false); } template -intrusive_ptr const_pointer_cast(intrusive_ptr&& p) noexcept -{ +intrusive_ptr const_pointer_cast(intrusive_ptr&& p) noexcept { return intrusive_ptr(const_cast(p.detach()), false); } template -intrusive_ptr dynamic_pointer_cast(intrusive_ptr&& p) noexcept -{ +intrusive_ptr dynamic_pointer_cast(intrusive_ptr&& p) noexcept { T* p2 = dynamic_cast(p.get()); intrusive_ptr r(p2, false); @@ -310,8 +273,7 @@ intrusive_ptr dynamic_pointer_cast(intrusive_ptr&& p) noexcept // operator<< // ---------- template -std::ostream& operator<<(std::ostream& os, intrusive_ptr const& p) -{ +std::ostream& operator<<(std::ostream& os, intrusive_ptr const& p) { os << p.get(); return os; } @@ -322,8 +284,7 @@ template struct hash; template -std::size_t hash_value(intrusive_ptr const& p) noexcept -{ +std::size_t hash_value(intrusive_ptr const& p) noexcept { return std::hash()(p.get()); } @@ -334,8 +295,7 @@ std::size_t hash_value(intrusive_ptr const& p) noexcept namespace std { template -struct hash<::gtl::intrusive_ptr> -{ +struct hash<::gtl::intrusive_ptr> { std::size_t operator()(::gtl::intrusive_ptr const& p) const noexcept { return std::hash()(p.get()); } }; @@ -350,8 +310,7 @@ namespace gtl { // a reference counter suitable for single threaded use only. Pointers to the same // object with this kind of reference counter must not be used by different threads. // -------------------------------------------------------------------------------- -struct thread_unsafe_counter -{ +struct thread_unsafe_counter { using type = unsigned int; static unsigned int load(type const& counter) noexcept { return counter; } @@ -367,8 +326,7 @@ struct thread_unsafe_counter // The policy instructs the \c intrusive_ref_counter base class to implement // a thread-safe reference counter, if the target platform supports multithreading. // -------------------------------------------------------------------------------- -struct thread_safe_counter -{ +struct thread_safe_counter { using type = std::atomic; static unsigned int load(type const& counter) noexcept { return counter.load(); } @@ -392,8 +350,7 @@ struct thread_safe_counter // \c intrusive_ref_counter. // -------------------------------------------------------------------------------- template -class intrusive_ref_counter -{ +class intrusive_ref_counter { private: using counter_type = typename CounterPolicyT::type; @@ -401,17 +358,12 @@ class intrusive_ref_counter public: intrusive_ref_counter() noexcept - : _refcount(0) - { - } + : _refcount(0) {} intrusive_ref_counter(intrusive_ref_counter const&) noexcept - : _refcount(0) - { - } + : _refcount(0) {} - intrusive_ref_counter& operator=(intrusive_ref_counter const&) noexcept - { + intrusive_ref_counter& operator=(intrusive_ref_counter const&) noexcept { return *this; // refcount not modified } @@ -422,8 +374,7 @@ class intrusive_ref_counter friend void intrusive_ptr_add_ref(const DerivedT* p) noexcept { CounterPolicyT::increment(p->_refcount); } - friend void intrusive_ptr_release(const DerivedT* p) noexcept - { + friend void intrusive_ptr_release(const DerivedT* p) noexcept { if (CounterPolicyT::decrement(p->_refcount) == 0) delete static_cast(p); } diff --git a/include/gtl/lru_cache.hpp b/include/gtl/lru_cache.hpp index c0c82e6..bf9e4a1 100644 --- a/include/gtl/lru_cache.hpp +++ b/include/gtl/lru_cache.hpp @@ -27,8 +27,7 @@ template, class Eq = std::equal_to, class Mutex = std::mutex> -class lru_cache_impl -{ +class lru_cache_impl { public: using key_type = K; using result_type = V; @@ -51,20 +50,17 @@ class lru_cache_impl // because the cache is sharded (multiple submaps and sublists) // the max_size is an approximation. // ------------------------------------------------------------ - lru_cache_impl(size_t max_size = 65536) - { + lru_cache_impl(size_t max_size = 65536) { reserve(max_size); set_cache_size(max_size); assert(_max_size > 2); } - bool exists(const K& k) - { + bool exists(const K& k) { return _cache.if_contains(k, [&](const auto&, list_type&) {}); } - std::optional get(const K& k) - { + std::optional get(const K& k) { if (result_type res; _cache.if_contains(k, [&](const auto& v, list_type& l) { res = v.second->second; l.splice(l.begin(), l, v.second); @@ -74,8 +70,7 @@ class lru_cache_impl } template - void insert(const K& key, Val&& value) - { + void insert(const K& key, Val&& value) { _cache.lazy_emplace_l( key, [&](typename map_type::value_type& v, list_type& l) { diff --git a/include/gtl/meminfo.hpp b/include/gtl/meminfo.hpp index 18d4d50..68170f0 100644 --- a/include/gtl/meminfo.hpp +++ b/include/gtl/meminfo.hpp @@ -46,8 +46,7 @@ uint64_t GetTotalMemoryUsed(); uint64_t GetProcessMemoryUsed(); uint64_t GetPhysicalMemory(); -uint64_t GetSystemMemory() -{ +uint64_t GetSystemMemory() { #ifdef GTL_WIN MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); @@ -85,8 +84,7 @@ uint64_t GetSystemMemory() #endif } -uint64_t GetTotalMemoryUsed() -{ +uint64_t GetTotalMemoryUsed() { #ifdef GTL_WIN MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); @@ -127,8 +125,7 @@ uint64_t GetTotalMemoryUsed() #endif } -uint64_t GetProcessMemoryUsed() -{ +uint64_t GetProcessMemoryUsed() { #ifdef GTL_WIN PROCESS_MEMORY_COUNTERS_EX pmc; GetProcessMemoryInfo(GetCurrentProcess(), reinterpret_cast(&pmc), sizeof(pmc)); @@ -171,8 +168,7 @@ uint64_t GetProcessMemoryUsed() #endif } -uint64_t GetPhysicalMemory() -{ +uint64_t GetPhysicalMemory() { #ifdef GTL_WIN MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); diff --git a/include/gtl/memoize.hpp b/include/gtl/memoize.hpp index 1b50946..8076f92 100644 --- a/include/gtl/memoize.hpp +++ b/include/gtl/memoize.hpp @@ -25,28 +25,22 @@ namespace gtl { // see https://stackoverflow.com/questions/71630906 for alternate method // ------------------------------------------------------------------------------ template -struct pack -{ -}; +struct pack {}; template struct pack_helper; template -struct pack_helper -{ +struct pack_helper { using args = pack; }; // ---- for lambdas template -struct pack_helper : public pack_helper -{ -}; +struct pack_helper : public pack_helper {}; template -struct pack_helper -{ +struct pack_helper { using args = pack; }; @@ -78,8 +72,7 @@ template -class mt_memoize> -{ +class mt_memoize> { public: using key_type = std::tuple; using result_type = decltype(std::declval()(std::declval()...)); @@ -92,25 +85,19 @@ class mt_memoize> Mutex>; mt_memoize(F&& f) - : _f(std::move(f)) - { - } + : _f(std::move(f)) {} mt_memoize(F& f) - : _f(f) - { - } + : _f(f) {} - std::optional contains(Args... args) - { + std::optional contains(Args... args) { key_type key(args...); if (result_type res; _cache.if_contains(key, [&](const auto& v) { res = v.second; })) return { res }; return {}; } - result_type operator()(Args... args) - { + result_type operator()(Args... args) { key_type key(args...); if constexpr (!std::is_same_v && !recursive) { // because we are using a mutex, we must be in a multithreaded context, @@ -188,8 +175,7 @@ template -class mt_memoize_lru> -{ +class mt_memoize_lru> { public: using key_type = std::tuple; using result_type = decltype(std::declval()(std::declval()...)); @@ -210,31 +196,27 @@ class mt_memoize_lru> static constexpr size_t num_submaps = map_type::subcnt(); mt_memoize_lru(F&& f, size_t max_size = 65536) - : _f(std::move(f)) - { + : _f(std::move(f)) { reserve(max_size); set_cache_size(max_size); assert(_max_size > 2); } mt_memoize_lru(F& f, size_t max_size = 65536) - : _f(f) - { + : _f(f) { reserve(max_size); set_cache_size(max_size); assert(_max_size > 2); } - std::optional contains(Args... args) - { + std::optional contains(Args... args) { key_type key(args...); if (result_type res; _cache.if_contains(key, [&](const auto& v, list_type&) { res = v.second->second; })) return { res }; return {}; } - result_type operator()(Args... args) - { + result_type operator()(Args... args) { key_type key(args...); result_type res; _cache.lazy_emplace_l( @@ -284,27 +266,22 @@ using memoize_lru = mt_memoize_lru; // Attempting to create a lazy list... not ready for prime time :-) // ------------------------------------------------------------------------------ template -class lazy_list -{ +class lazy_list { public: lazy_list(T first, F next) : _first(std::move(first)) - , _next(std::move(next)) - { - } + , _next(std::move(next)) {} #if 1 // wrong implementation, because it calls _next instead of the memoized version - const T& operator[](size_t idx) const - { + const T& operator[](size_t idx) const { if (idx == 0) return _first; return _next(this, idx); } #else // can't get this to build unfortunately - const T& operator[](size_t idx) const - { + const T& operator[](size_t idx) const { auto _memoized_next{ gtl::memoize(_next) }; if (idx == 0) return _first; diff --git a/include/gtl/phmap.hpp b/include/gtl/phmap.hpp index 29c5f70..d8cecf8 100644 --- a/include/gtl/phmap.hpp +++ b/include/gtl/phmap.hpp @@ -139,8 +139,7 @@ namespace gtl { // used as a default template parameters for classes who provide optional // internal locking (like gtl::parallel_flat_hash_map). // ----------------------------------------------------------------------------- -class NullMutex -{ +class NullMutex { public: NullMutex() {} ~NullMutex() {} @@ -156,11 +155,9 @@ namespace priv { // -------------------------------------------------------------------------- template -class probe_seq -{ +class probe_seq { public: - probe_seq(size_t hashval, size_t mask) - { + probe_seq(size_t hashval, size_t mask) { assert(((mask + 1) & mask) == 0 && "not a mask"); mask_ = mask; offset_ = hashval & mask_; @@ -168,8 +165,7 @@ class probe_seq size_t offset() const { return offset_; } size_t offset(size_t i) const { return (offset_ + i) & mask_; } - void next() - { + void next() { index_ += Width; offset_ += index_; offset_ &= mask_; @@ -185,8 +181,7 @@ class probe_seq // -------------------------------------------------------------------------- template -struct RequireUsableKey -{ +struct RequireUsableKey { template std::pair()(std::declval())), decltype(std::declval()(std::declval(), @@ -196,9 +191,7 @@ struct RequireUsableKey // -------------------------------------------------------------------------- template -struct IsDecomposable : std::false_type -{ -}; +struct IsDecomposable : std::false_type {}; template struct IsDecomposable(), @@ -206,14 +199,11 @@ struct IsDecomposable : std::true_type -{ -}; + Ts...> : std::true_type {}; // -------------------------------------------------------------------------- template -uint32_t TrailingZeros(T x) -{ +uint32_t TrailingZeros(T x) { if constexpr (sizeof(T) == 8) return gtl::CountTrailingZerosNonZero64(static_cast(x)); else @@ -222,8 +212,7 @@ uint32_t TrailingZeros(T x) // -------------------------------------------------------------------------- template -uint32_t LeadingZeros(T x) -{ +uint32_t LeadingZeros(T x) { if constexpr (sizeof(T) == 8) return gtl::CountLeadingZeros64(static_cast(x)); else @@ -242,8 +231,7 @@ uint32_t LeadingZeros(T x) // for (int i : BitMask(0x0000000080800000)) -> yields 2, 3 // -------------------------------------------------------------------------- template -class BitMask -{ +class BitMask { static_assert(std::is_unsigned_v, ""); static_assert(Shift == 0 || Shift == 3, ""); @@ -254,11 +242,8 @@ class BitMask using const_iterator = BitMask; explicit BitMask(T mask) - : mask_(mask) - { - } - BitMask& operator++() - { + : mask_(mask) {} + BitMask& operator++() { mask_ &= (mask_ - 1); return *this; } @@ -272,8 +257,7 @@ class BitMask uint32_t TrailingZeros() const { return priv::TrailingZeros(mask_) >> Shift; } - uint32_t LeadingZeros() const - { + uint32_t LeadingZeros() const { constexpr uint32_t total_significant_bits = SignificantBits << Shift; constexpr uint32_t extra_bits = sizeof(T) * 8 - total_significant_bits; return priv::LeadingZeros(mask_ << extra_bits) >> Shift; @@ -294,8 +278,7 @@ using h2_t = uint8_t; // The values here are selected for maximum performance. See the static asserts // below for details. // -------------------------------------------------------------------------- -enum Ctrl : ctrl_t -{ +enum Ctrl : ctrl_t { kEmpty = -128, // 0b10000000 kDeleted = -2, // 0b11111110 kSentinel = -1, // 0b11111111 @@ -324,8 +307,7 @@ static_assert(kDeleted == -2, // A single block of empty control bytes for tables without any slots allocated. // This enables removing a branch in the hot path of find(). // -------------------------------------------------------------------------- -inline ctrl_t* EmptyGroup() -{ +inline ctrl_t* EmptyGroup() { alignas(16) static constexpr ctrl_t empty_group[] = { kSentinel, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty, kEmpty }; @@ -333,8 +315,7 @@ inline ctrl_t* EmptyGroup() } // -------------------------------------------------------------------------- -inline size_t HashSeed(const ctrl_t* ctrl) -{ +inline size_t HashSeed(const ctrl_t* ctrl) { // The low bits of the pointer have little or no entropy because of // alignment. We shift the pointer to try to use higher entropy bits. A // good number seems to be 12 bits, because that aligns with page size. @@ -343,8 +324,7 @@ inline size_t HashSeed(const ctrl_t* ctrl) #ifdef GTL_NON_DETERMINISTIC -inline size_t H1(size_t hashval, const ctrl_t* ctrl) -{ +inline size_t H1(size_t hashval, const ctrl_t* ctrl) { // use ctrl_ pointer to add entropy to ensure // non-deterministic iteration order. return (hashval >> 7) ^ HashSeed(ctrl); @@ -377,8 +357,7 @@ inline bool IsEmptyOrDeleted(ctrl_t c) { return c < kSentinel; } // Work around this by using the portable implementation of Group // when using -funsigned-char under GCC. // -------------------------------------------------------------------------- -inline __m128i _mm_cmpgt_epi8_fixed(__m128i a, __m128i b) -{ +inline __m128i _mm_cmpgt_epi8_fixed(__m128i a, __m128i b) { #if defined(__GNUC__) && !defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverflow" @@ -396,27 +375,21 @@ inline __m128i _mm_cmpgt_epi8_fixed(__m128i a, __m128i b) // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- -struct GroupSse2Impl -{ - enum - { - kWidth = 16 - }; // the number of slots per group +struct GroupSse2Impl { + enum { kWidth = 16 }; // the number of slots per group explicit GroupSse2Impl(const ctrl_t* pos) { ctrl = _mm_loadu_si128(reinterpret_cast(pos)); } // Returns a bitmask representing the positions of slots that match hash. // ---------------------------------------------------------------------- - BitMask Match(h2_t hash) const - { + BitMask Match(h2_t hash) const { auto match = _mm_set1_epi8((char)hash); return BitMask(static_cast(_mm_movemask_epi8(_mm_cmpeq_epi8(match, ctrl)))); } // Returns a bitmask representing the positions of empty slots. // ------------------------------------------------------------ - BitMask MatchEmpty() const - { + BitMask MatchEmpty() const { #if GTL_HAVE_SSSE3 // This only works because kEmpty is -128. return BitMask(static_cast(_mm_movemask_epi8(_mm_sign_epi8(ctrl, ctrl)))); @@ -427,23 +400,20 @@ struct GroupSse2Impl // Returns a bitmask representing the positions of empty or deleted slots. // ----------------------------------------------------------------------- - BitMask MatchEmptyOrDeleted() const - { + BitMask MatchEmptyOrDeleted() const { auto special = _mm_set1_epi8(static_cast(kSentinel)); return BitMask(static_cast(_mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl)))); } // Returns the number of trailing empty or deleted elements in the group. // ---------------------------------------------------------------------- - uint32_t CountLeadingEmptyOrDeleted() const - { + uint32_t CountLeadingEmptyOrDeleted() const { auto special = _mm_set1_epi8(static_cast(kSentinel)); return TrailingZeros(static_cast(_mm_movemask_epi8(_mm_cmpgt_epi8_fixed(special, ctrl)) + 1)); } // ---------------------------------------------------------------------- - void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const - { + void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const { auto msbs = _mm_set1_epi8(static_cast(-128)); auto x126 = _mm_set1_epi8(126); #if GTL_HAVE_SSSE3 @@ -467,20 +437,13 @@ struct GroupSse2Impl // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- -struct GroupPortableImpl -{ - enum - { - kWidth = 8 - }; +struct GroupPortableImpl { + enum { kWidth = 8 }; explicit GroupPortableImpl(const ctrl_t* pos) - : ctrl(gtl::little_endian::Load64(pos)) - { - } + : ctrl(gtl::little_endian::Load64(pos)) {} - BitMask Match(h2_t hash) const - { + BitMask Match(h2_t hash) const { // For the technique, see: // http://graphics.stanford.edu/~seander/bithacks.html##ValueInWord // (Determine if a word has a byte equal to n). @@ -500,26 +463,22 @@ struct GroupPortableImpl return BitMask((x - lsbs) & ~x & msbs); } - BitMask MatchEmpty() const - { + BitMask MatchEmpty() const { constexpr uint64_t msbs = 0x8080808080808080ULL; return BitMask((ctrl & (~ctrl << 6)) & msbs); } - BitMask MatchEmptyOrDeleted() const - { + BitMask MatchEmptyOrDeleted() const { constexpr uint64_t msbs = 0x8080808080808080ULL; return BitMask((ctrl & (~ctrl << 7)) & msbs); } - uint32_t CountLeadingEmptyOrDeleted() const - { + uint32_t CountLeadingEmptyOrDeleted() const { constexpr uint64_t gaps = 0x00FEFEFEFEFEFEFEULL; return (uint32_t)((TrailingZeros(((~ctrl & (ctrl >> 7)) | gaps) + 1) + 7) >> 3); } - void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const - { + void ConvertSpecialToEmptyAndFullToDeleted(ctrl_t* dst) const { constexpr uint64_t msbs = 0x8080808080808080ULL; constexpr uint64_t lsbs = 0x0101010101010101ULL; auto x = ctrl & msbs; @@ -556,8 +515,7 @@ inline bool IsValidCapacity(size_t n) { return ((n + 1) & n) == 0 && n > 0; } // EMPTY -> EMPTY // FULL -> DELETED // -------------------------------------------------------------------------- -inline void ConvertDeletedToEmptyAndFullToDeleted(ctrl_t* ctrl, size_t capacity) -{ +inline void ConvertDeletedToEmptyAndFullToDeleted(ctrl_t* ctrl, size_t capacity) { assert(ctrl[capacity] == kSentinel); assert(IsValidCapacity(capacity)); for (ctrl_t* pos = ctrl; pos != ctrl + capacity + 1; pos += Group::kWidth) { @@ -577,8 +535,7 @@ inline size_t NormalizeCapacity(size_t n) { return n ? ~size_t{} >> LeadingZeros // We use 7/8th as maximum load factor. // For 16-wide groups, that gives an average of two empty slots per group. // -------------------------------------------------------------------------- -inline size_t CapacityToGrowth(size_t capacity) -{ +inline size_t CapacityToGrowth(size_t capacity) { assert(IsValidCapacity(capacity)); // `capacity*7/8` if constexpr (Group::kWidth == 8) { @@ -594,8 +551,7 @@ inline size_t CapacityToGrowth(size_t capacity) // From desired "growth" to a lowerbound of the necessary capacity. // Might not be a valid one and required NormalizeCapacity(). // -------------------------------------------------------------------------- -inline size_t GrowthToLowerboundCapacity(size_t growth) -{ +inline size_t GrowthToLowerboundCapacity(size_t growth) { // `growth*8/7` if constexpr (Group::kWidth == 8) { if (growth == 7) { @@ -611,15 +567,13 @@ namespace hashtable_debug_internal { // If it is a map, call get<0>(). using std::get; template -auto GetKey(const typename T::value_type& pair, int) -> decltype(get<0>(pair)) -{ +auto GetKey(const typename T::value_type& pair, int) -> decltype(get<0>(pair)) { return get<0>(pair); } // If it is not a map, return the value directly. template -const typename T::key_type& GetKey(const typename T::key_type& key, char) -{ +const typename T::key_type& GetKey(const typename T::key_type& key, char) { return key; } @@ -628,8 +582,7 @@ const typename T::key_type& GetKey(const typename T::key_type& key, char) // container. // -------------------------------------------------------------------------- template -struct HashtableDebugAccess -{ +struct HashtableDebugAccess { // Returns the number of probes required to find `key` in `c`. The "number of // probes" is a concept that can vary by container. Implementations should // return 0 when `key` was found in the minimum number of operations and @@ -639,8 +592,7 @@ struct HashtableDebugAccess // The default implementation uses the bucket api from the standard and thus // works for `std::unordered_*` containers. // -------------------------------------------------------------------------- - static size_t GetNumProbes(const Container& c, const typename Container::key_type& key) - { + static size_t GetNumProbes(const Container& c, const typename Container::key_type& key) { if (!c.bucket_count()) return {}; size_t num_probes = 0; @@ -661,32 +613,27 @@ struct HashtableDebugAccess // specified in the tuple. // ---------------------------------------------------------------------------- template -void ConstructFromTupleImpl(Alloc* alloc, T* ptr, Tuple&& t, std::index_sequence) -{ +void ConstructFromTupleImpl(Alloc* alloc, T* ptr, Tuple&& t, std::index_sequence) { std::allocator_traits::construct(*alloc, ptr, std::get(std::forward(t))...); } template -struct WithConstructedImplF -{ +struct WithConstructedImplF { template - decltype(std::declval()(std::declval())) operator()(Args&&... args) const - { + decltype(std::declval()(std::declval())) operator()(Args&&... args) const { return std::forward(f)(T(std::forward(args)...)); } F&& f; }; template -decltype(std::declval()(std::declval())) WithConstructedImpl(Tuple&& t, std::index_sequence, F&& f) -{ +decltype(std::declval()(std::declval())) WithConstructedImpl(Tuple&& t, std::index_sequence, F&& f) { return WithConstructedImplF{ std::forward(f) }(std::get(std::forward(t))...); } template auto TupleRefImpl(T&& t, std::index_sequence) - -> decltype(std::forward_as_tuple(std::get(std::forward(t))...)) -{ + -> decltype(std::forward_as_tuple(std::get(std::forward(t))...)) { return std::forward_as_tuple(std::get(std::forward(t))...); } @@ -695,9 +642,9 @@ auto TupleRefImpl(T&& t, std::index_sequence) // tuple. // ---------------------------------------------------------------------------- template -auto TupleRef(T&& t) -> decltype(TupleRefImpl(std::forward(t), - std::make_index_sequence>>())) -{ +auto TupleRef(T&& t) + -> decltype(TupleRefImpl(std::forward(t), + std::make_index_sequence>>())) { return TupleRefImpl(std::forward(t), std::make_index_sequence>>()); } @@ -706,8 +653,7 @@ decltype(std::declval()(std::declval(), std::piecewise_construct, std::declval>(), std::declval())) -DecomposePairImpl(F&& f, std::pair, V> p) -{ +DecomposePairImpl(F&& f, std::pair, V> p) { const auto& key = std::get<0>(p.first); return std::forward(f)(key, std::piecewise_construct, std::move(p.first), std::move(p.second)); } @@ -717,8 +663,7 @@ DecomposePairImpl(F&& f, std::pair, V> p) // specified in the tuple. // ---------------------------------------------------------------------------- template -void ConstructFromTuple(Alloc* alloc, T* ptr, Tuple&& t) -{ +void ConstructFromTuple(Alloc* alloc, T* ptr, Tuple&& t) { ConstructFromTupleImpl(alloc, ptr, std::forward(t), @@ -730,8 +675,7 @@ void ConstructFromTuple(Alloc* alloc, T* ptr, Tuple&& t) // constructed value. // ---------------------------------------------------------------------------- template -decltype(std::declval()(std::declval())) WithConstructed(Tuple&& t, F&& f) -{ +decltype(std::declval()(std::declval())) WithConstructed(Tuple&& t, F&& f) { return WithConstructedImpl(std::forward(t), std::make_index_sequence>>(), std::forward(f)); @@ -753,29 +697,25 @@ decltype(std::declval()(std::declval())) WithConstructed(Tuple&& t, F&& f) inline std::pair, std::tuple<>> PairArgs() { return {}; } template -std::pair, std::tuple> PairArgs(F&& f, S&& s) -{ +std::pair, std::tuple> PairArgs(F&& f, S&& s) { return { std::piecewise_construct, std::forward_as_tuple(std::forward(f)), std::forward_as_tuple(std::forward(s)) }; } template -std::pair, std::tuple> PairArgs(const std::pair& p) -{ +std::pair, std::tuple> PairArgs(const std::pair& p) { return PairArgs(p.first, p.second); } template -std::pair, std::tuple> PairArgs(std::pair&& p) -{ +std::pair, std::tuple> PairArgs(std::pair&& p) { return PairArgs(std::forward(p.first), std::forward(p.second)); } template auto PairArgs(std::piecewise_construct_t, F&& f, S&& s) - -> decltype(std::make_pair(TupleRef(std::forward(f)), TupleRef(std::forward(s)))) -{ + -> decltype(std::make_pair(TupleRef(std::forward(f)), TupleRef(std::forward(s)))) { return std::make_pair(TupleRef(std::forward(f)), TupleRef(std::forward(s))); } @@ -784,8 +724,7 @@ auto PairArgs(std::piecewise_construct_t, F&& f, S&& s) // ---------------------------------------------------------------------------- template auto DecomposePair(F&& f, Args&&... args) - -> decltype(DecomposePairImpl(std::forward(f), PairArgs(std::forward(args)...))) -{ + -> decltype(DecomposePairImpl(std::forward(f), PairArgs(std::forward(args)...))) { return DecomposePairImpl(std::forward(f), PairArgs(std::forward(args)...)); } @@ -793,8 +732,7 @@ auto DecomposePair(F&& f, Args&&... args) // A helper function for implementing apply() in set policies. // ---------------------------------------------------------------------------- template -decltype(std::declval()(std::declval(), std::declval())) DecomposeValue(F&& f, Arg&& arg) -{ +decltype(std::declval()(std::declval(), std::declval())) DecomposeValue(F&& f, Arg&& arg) { const auto& key = arg; return std::forward(f)(key, std::forward(arg)); } @@ -803,31 +741,24 @@ decltype(std::declval()(std::declval(), std::declval())) Dec // Defines how slots are initialized/destroyed/moved. // ---------------------------------------------------------------------------- template -struct hash_policy_traits -{ +struct hash_policy_traits { private: - struct ReturnKey - { + struct ReturnKey { // We return `Key` here. // When Key=T&, we forward the lvalue reference. // When Key=T, we return by value to avoid a dangling reference. // eg, for string_hash_map. template - Key operator()(Key&& k, const Args&...) const - { + Key operator()(Key&& k, const Args&...) const { return std::forward(k); } }; template - struct ConstantIteratorsImpl : std::false_type - { - }; + struct ConstantIteratorsImpl : std::false_type {}; template - struct ConstantIteratorsImpl> : P::constant_iterators - { - }; + struct ConstantIteratorsImpl> : P::constant_iterators {}; public: using slot_type = typename Policy::slot_type; // The actual object stored in the hash table. @@ -854,8 +785,7 @@ struct hash_policy_traits // POSTCONDITION: `slot` is INITIALIZED // ---------------------------------------------------------------------------- template - static void construct(Alloc* alloc, slot_type* slot, Args&&... args) - { + static void construct(Alloc* alloc, slot_type* slot, Args&&... args) { Policy::construct(alloc, slot, std::forward(args)...); } @@ -863,8 +793,7 @@ struct hash_policy_traits // POSTCONDITION: `slot` is UNINITIALIZED // ---------------------------------------------------------------------------- template - static void destroy(Alloc* alloc, slot_type* slot) - { + static void destroy(Alloc* alloc, slot_type* slot) { Policy::destroy(alloc, slot); } @@ -881,8 +810,7 @@ struct hash_policy_traits // UNINITIALIZED // ---------------------------------------------------------------------------- template - static void transfer(Alloc* alloc, slot_type* new_slot, slot_type* old_slot) - { + static void transfer(Alloc* alloc, slot_type* new_slot, slot_type* old_slot) { transfer_impl(alloc, new_slot, old_slot, 0); } @@ -890,8 +818,7 @@ struct hash_policy_traits // POSTCONDITION: `slot` is INITIALIZED // ---------------------------------------------------------------------------- template - static auto element(slot_type* slot) -> decltype(P::element(slot)) - { + static auto element(slot_type* slot) -> decltype(P::element(slot)) { return P::element(slot); } @@ -903,8 +830,7 @@ struct hash_policy_traits // PRECONDITION: `slot` is INITIALIZED or nullptr // ---------------------------------------------------------------------------- template - static size_t space_used(const slot_type* slot) - { + static size_t space_used(const slot_type* slot) { return P::space_used(slot); } @@ -939,8 +865,7 @@ struct hash_policy_traits // `Policy::apply()` must work. A compile error is not allowed, SFINAE or not. // ---------------------------------------------------------------------------- template - static auto apply(F&& f, Ts&&... ts) -> decltype(P::apply(std::forward(f), std::forward(ts)...)) - { + static auto apply(F&& f, Ts&&... ts) -> decltype(P::apply(std::forward(f), std::forward(ts)...)) { return P::apply(std::forward(f), std::forward(ts)...); } @@ -948,8 +873,7 @@ struct hash_policy_traits // Used for node handle manipulation. // ---------------------------------------------------------------------------- template - static auto key(slot_type* slot) -> decltype(P::apply(ReturnKey(), element(slot))) - { + static auto key(slot_type* slot) -> decltype(P::apply(ReturnKey(), element(slot))) { return P::apply(ReturnKey(), element(slot)); } @@ -957,8 +881,7 @@ struct hash_policy_traits // by maps to implement `operator[]`, `at()` and `insert_or_assign()`. // ---------------------------------------------------------------------------- template - static auto value(T* elem) -> decltype(P::value(elem)) - { + static auto value(T* elem) -> decltype(P::value(elem)) { return P::value(elem); } @@ -967,14 +890,12 @@ struct hash_policy_traits // ---------------------------------------------------------------------------- template static auto transfer_impl(Alloc* alloc, slot_type* new_slot, slot_type* old_slot, int) - -> decltype((void)P::transfer(alloc, new_slot, old_slot)) - { + -> decltype((void)P::transfer(alloc, new_slot, old_slot)) { P::transfer(alloc, new_slot, old_slot); } template - static void transfer_impl(Alloc* alloc, slot_type* new_slot, slot_type* old_slot, char) - { + static void transfer_impl(Alloc* alloc, slot_type* new_slot, slot_type* old_slot, char) { construct(alloc, new_slot, std::move(element(old_slot))); destroy(alloc, old_slot); } @@ -1066,8 +987,7 @@ struct hash_policy_traits // table will be probed exactly once. // ---------------------------------------------------------------------------- template -class raw_hash_set -{ +class raw_hash_set { using PolicyTraits = hash_policy_traits; using KeyArgImpl = KeyArg::value && IsTransparent::value>; @@ -1104,8 +1024,7 @@ class raw_hash_set using Layout = priv::Layout; - static Layout MakeLayout(size_t capacity) - { + static Layout MakeLayout(size_t capacity) { assert(IsValidCapacity(capacity)); return Layout(capacity + Group::kWidth + 1, capacity); } @@ -1119,9 +1038,7 @@ class raw_hash_set template struct SameAsElementReference : std::is_same>, - typename std::remove_cv_t>> - { - }; + typename std::remove_cv_t>> {}; // An enabler for insert(T&&): T must be convertible to init_type or be the // same as [cv] value_type [ref]. @@ -1142,8 +1059,7 @@ class raw_hash_set static_assert(std::is_same_v, "Allocators with custom pointer types are not supported"); - class iterator - { + class iterator { friend class raw_hash_set; public: @@ -1162,16 +1078,14 @@ class raw_hash_set pointer operator->() const { return &operator*(); } // PRECONDITION: not an end() iterator. - iterator& operator++() - { + iterator& operator++() { ++ctrl_; ++slot_; skip_empty_or_deleted(); return *this; } // PRECONDITION: not an end() iterator. - iterator operator++(int) - { + iterator operator++(int) { auto tmp = *this; ++*this; return tmp; @@ -1203,17 +1117,12 @@ class raw_hash_set private: iterator(ctrl_t* ctrl) - : ctrl_(ctrl) - { - } // for end() + : ctrl_(ctrl) {} // for end() iterator(ctrl_t* ctrl, slot_type* slot) : ctrl_(ctrl) - , slot_(slot) - { - } + , slot_(slot) {} - void skip_empty_or_deleted() - { + void skip_empty_or_deleted() { while (IsEmptyOrDeleted(*ctrl_)) { // ctrl is not necessarily aligned to Group::kWidth. It is also likely // to read past the space for ctrl bytes and into slots. This is ok @@ -1230,14 +1139,12 @@ class raw_hash_set // To avoid uninitialized member warnings, put slot_ in an anonymous union. // The member is not initialized on singleton and end iterators. // ------------------------------------------------------------------------ - union - { + union { slot_type* slot_; }; }; - class const_iterator - { + class const_iterator { friend class raw_hash_set; public: @@ -1250,15 +1157,12 @@ class raw_hash_set const_iterator() {} // Implicit construction from iterator. const_iterator(iterator i) - : inner_(std::move(i)) - { - } + : inner_(std::move(i)) {} reference operator*() const { return *inner_; } pointer operator->() const { return inner_.operator->(); } - const_iterator& operator++() - { + const_iterator& operator++() { ++inner_; return *this; } @@ -1269,9 +1173,7 @@ class raw_hash_set private: const_iterator(const ctrl_t* ctrl, const slot_type* slot) - : inner_(const_cast(ctrl), const_cast(slot)) - { - } + : inner_(const_cast(ctrl), const_cast(slot)) {} iterator inner_; }; @@ -1281,17 +1183,14 @@ class raw_hash_set raw_hash_set() noexcept(std::is_nothrow_default_constructible_v && std::is_nothrow_default_constructible_v && - std::is_nothrow_default_constructible_v) - { - } + std::is_nothrow_default_constructible_v) {} explicit raw_hash_set(size_t bucket_cnt, const hasher& hashfn = hasher(), const key_equal& eq = key_equal(), const allocator_type& alloc = allocator_type()) : ctrl_(EmptyGroup()) - , settings_(0, hashfn, eq, alloc) - { + , settings_(0, hashfn, eq, alloc) { if (bucket_cnt) { size_t new_capacity = NormalizeCapacity(bucket_cnt); reset_growth_left(new_capacity); @@ -1301,19 +1200,13 @@ class raw_hash_set } raw_hash_set(size_t bucket_cnt, const hasher& hashfn, const allocator_type& alloc) - : raw_hash_set(bucket_cnt, hashfn, key_equal(), alloc) - { - } + : raw_hash_set(bucket_cnt, hashfn, key_equal(), alloc) {} raw_hash_set(size_t bucket_cnt, const allocator_type& alloc) - : raw_hash_set(bucket_cnt, hasher(), key_equal(), alloc) - { - } + : raw_hash_set(bucket_cnt, hasher(), key_equal(), alloc) {} explicit raw_hash_set(const allocator_type& alloc) - : raw_hash_set(0, hasher(), key_equal(), alloc) - { - } + : raw_hash_set(0, hasher(), key_equal(), alloc) {} template raw_hash_set(InputIter first, @@ -1322,28 +1215,21 @@ class raw_hash_set const hasher& hashfn = hasher(), const key_equal& eq = key_equal(), const allocator_type& alloc = allocator_type()) - : raw_hash_set(bucket_cnt, hashfn, eq, alloc) - { + : raw_hash_set(bucket_cnt, hashfn, eq, alloc) { insert(first, last); } template raw_hash_set(InputIter first, InputIter last, size_t bucket_cnt, const hasher& hashfn, const allocator_type& alloc) - : raw_hash_set(first, last, bucket_cnt, hashfn, key_equal(), alloc) - { - } + : raw_hash_set(first, last, bucket_cnt, hashfn, key_equal(), alloc) {} template raw_hash_set(InputIter first, InputIter last, size_t bucket_cnt, const allocator_type& alloc) - : raw_hash_set(first, last, bucket_cnt, hasher(), key_equal(), alloc) - { - } + : raw_hash_set(first, last, bucket_cnt, hasher(), key_equal(), alloc) {} template raw_hash_set(InputIter first, InputIter last, const allocator_type& alloc) - : raw_hash_set(first, last, 0, hasher(), key_equal(), alloc) - { - } + : raw_hash_set(first, last, 0, hasher(), key_equal(), alloc) {} // ---------------------------------------------------------------------------- // Instead of accepting std::initializer_list as the first @@ -1372,63 +1258,44 @@ class raw_hash_set const hasher& hashfn = hasher(), const key_equal& eq = key_equal(), const allocator_type& alloc = allocator_type()) - : raw_hash_set(init.begin(), init.end(), bucket_cnt, hashfn, eq, alloc) - { - } + : raw_hash_set(init.begin(), init.end(), bucket_cnt, hashfn, eq, alloc) {} raw_hash_set(std::initializer_list init, size_t bucket_cnt = 0, const hasher& hashfn = hasher(), const key_equal& eq = key_equal(), const allocator_type& alloc = allocator_type()) - : raw_hash_set(init.begin(), init.end(), bucket_cnt, hashfn, eq, alloc) - { - } + : raw_hash_set(init.begin(), init.end(), bucket_cnt, hashfn, eq, alloc) {} template = 0> raw_hash_set(std::initializer_list init, size_t bucket_cnt, const hasher& hashfn, const allocator_type& alloc) - : raw_hash_set(init, bucket_cnt, hashfn, key_equal(), alloc) - { - } + : raw_hash_set(init, bucket_cnt, hashfn, key_equal(), alloc) {} raw_hash_set(std::initializer_list init, size_t bucket_cnt, const hasher& hashfn, const allocator_type& alloc) - : raw_hash_set(init, bucket_cnt, hashfn, key_equal(), alloc) - { - } + : raw_hash_set(init, bucket_cnt, hashfn, key_equal(), alloc) {} template = 0> raw_hash_set(std::initializer_list init, size_t bucket_cnt, const allocator_type& alloc) - : raw_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) - { - } + : raw_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) {} raw_hash_set(std::initializer_list init, size_t bucket_cnt, const allocator_type& alloc) - : raw_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) - { - } + : raw_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) {} template = 0> raw_hash_set(std::initializer_list init, const allocator_type& alloc) - : raw_hash_set(init, 0, hasher(), key_equal(), alloc) - { - } + : raw_hash_set(init, 0, hasher(), key_equal(), alloc) {} raw_hash_set(std::initializer_list init, const allocator_type& alloc) - : raw_hash_set(init, 0, hasher(), key_equal(), alloc) - { - } + : raw_hash_set(init, 0, hasher(), key_equal(), alloc) {} raw_hash_set(const raw_hash_set& that) - : raw_hash_set(that, AllocTraits::select_on_container_copy_construction(that.alloc_ref())) - { - } + : raw_hash_set(that, AllocTraits::select_on_container_copy_construction(that.alloc_ref())) {} raw_hash_set(const raw_hash_set& that, const allocator_type& a) - : raw_hash_set(0, that.hash_ref(), that.eq_ref(), a) - { + : raw_hash_set(0, that.hash_ref(), that.eq_ref(), a) { rehash(that.capacity()); // operator=() should preserve load_factor // Because the table is guaranteed to be empty, we can do something faster // than a full `insert`. @@ -1454,8 +1321,7 @@ class raw_hash_set // `that` must be left valid. If Hash is std::function, moving it // would create a nullptr functor that cannot be called. // ------------------------------------------------------------------- - settings_(std::move(that.settings_)) - { + settings_(std::move(that.settings_)) { // growth_left was copied above, reset the one from `that`. that.growth_left() = 0; } @@ -1465,8 +1331,7 @@ class raw_hash_set , slots_(nullptr) , size_(0) , capacity_(0) - , settings_(0, that.hash_ref(), that.eq_ref(), a) - { + , settings_(0, that.hash_ref(), that.eq_ref(), a) { if (a == that.alloc_ref()) { std::swap(ctrl_, that.ctrl_); std::swap(slots_, that.slots_); @@ -1483,8 +1348,7 @@ class raw_hash_set } } - raw_hash_set& operator=(const raw_hash_set& that) - { + raw_hash_set& operator=(const raw_hash_set& that) { raw_hash_set tmp(that, AllocTraits::propagate_on_container_copy_assignment::value ? that.alloc_ref() : alloc_ref()); swap(tmp); @@ -1493,8 +1357,7 @@ class raw_hash_set raw_hash_set& operator=(raw_hash_set&& that) noexcept( std::allocator_traits::is_always_equal::value && std::is_nothrow_move_assignable_v && - std::is_nothrow_move_assignable_v) - { + std::is_nothrow_move_assignable_v) { // TODO(sbenza): We should only use the operations from the noexcept clause // to make sure we actually adhere to that contract. return move_assign(std::move(that), typename AllocTraits::propagate_on_container_move_assignment()); @@ -1502,14 +1365,12 @@ class raw_hash_set ~raw_hash_set() { destroy_slots(); } - iterator begin() - { + iterator begin() { auto it = iterator_at(0); it.skip_empty_or_deleted(); return it; } - iterator end() - { + iterator end() { #if 0 // GTL_BIDIRECTIONAL return iterator_at(capacity_); #else @@ -1527,13 +1388,13 @@ class raw_hash_set size_t capacity() const { return capacity_; } size_t max_size() const { return (std::numeric_limits::max)(); } - GTL_ATTRIBUTE_REINITIALIZES void clear() - { + GTL_ATTRIBUTE_REINITIALIZES void clear() { if (empty()) return; if (capacity_) { if constexpr (!std::is_trivially_destructible::value || - std::is_same::value) { + std::is_same::value) + { // node map or not trivially destructible... we need to iterate and destroy values one by one for (size_t i = 0; i != capacity_; ++i) { if (IsFull(ctrl_[i])) { @@ -1558,8 +1419,7 @@ class raw_hash_set RequiresInsertable = 0, typename std::enable_if_t::value, int> = 0, T* = nullptr> - std::pair insert(T&& value) - { + std::pair insert(T&& value) { return emplace(std::forward(value)); } @@ -1577,8 +1437,7 @@ class raw_hash_set template = 0, typename std::enable_if_t::value, int> = 0> - std::pair insert(const T& value) - { + std::pair insert(const T& value) { return emplace(value); } @@ -1594,16 +1453,14 @@ class raw_hash_set RequiresInsertable = 0, typename std::enable_if_t::value, int> = 0, T* = nullptr> - iterator insert(const_iterator, T&& value) - { + iterator insert(const_iterator, T&& value) { return insert(std::forward(value)).first; } template = 0, typename std::enable_if_t::value, int> = 0> - iterator insert(const_iterator, const T& value) - { + iterator insert(const_iterator, const T& value) { return insert(value).first; } @@ -1614,8 +1471,7 @@ class raw_hash_set std::is_same::iterator_category, std::random_access_iterator_tag>; template - struct has_difference_operator - { + struct has_difference_operator { private: using yes = std::true_type; using no = std::false_type; @@ -1630,30 +1486,26 @@ class raw_hash_set }; template::value, int> = 0> - void insert(InputIt first, InputIt last) - { + void insert(InputIt first, InputIt last) { this->reserve(this->size() + (last - first)); for (; first != last; ++first) emplace(*first); } template::value, int> = 0> - void insert(InputIt first, InputIt last) - { + void insert(InputIt first, InputIt last) { for (; first != last; ++first) emplace(*first); } template = 0> - void insert(std::initializer_list ilist) - { + void insert(std::initializer_list ilist) { insert(ilist.begin(), ilist.end()); } void insert(std::initializer_list ilist) { insert(ilist.begin(), ilist.end()); } - insert_return_type insert(node_type&& node) - { + insert_return_type insert(node_type&& node) { if (!node) return { end(), false, node_type() }; const auto& elem = PolicyTraits::element(CommonAccess::GetSlot(node)); @@ -1666,8 +1518,7 @@ class raw_hash_set } } - insert_return_type insert(node_type&& node, size_t hashval) - { + insert_return_type insert(node_type&& node, size_t hashval) { if (!node) return { end(), false, node_type() }; const auto& elem = PolicyTraits::element(CommonAccess::GetSlot(node)); @@ -1681,8 +1532,7 @@ class raw_hash_set } } - iterator insert(const_iterator, node_type&& node) - { + iterator insert(const_iterator, node_type&& node) { auto res = insert(std::move(node)); node = std::move(res.node); return res.position; @@ -1699,14 +1549,12 @@ class raw_hash_set // m.emplace("abc", "xyz"); // ----------------------------------------------------------------- template::value, int> = 0> - std::pair emplace(Args&&... args) - { + std::pair emplace(Args&&... args) { return PolicyTraits::apply(EmplaceDecomposable{ *this }, std::forward(args)...); } template::value, int> = 0> - std::pair emplace_with_hash(size_t hashval, Args&&... args) - { + std::pair emplace_with_hash(size_t hashval, Args&&... args) { return PolicyTraits::apply(EmplaceDecomposableHashval{ *this, hashval }, std::forward(args)...); } @@ -1715,8 +1563,7 @@ class raw_hash_set // destroys. // --------------------------------------------------------------------------- template::value, int> = 0> - std::pair emplace(Args&&... args) - { + std::pair emplace(Args&&... args) { typename gtl::aligned_storage_t raw; slot_type* slot = reinterpret_cast(&raw); @@ -1726,8 +1573,7 @@ class raw_hash_set } template::value, int> = 0> - std::pair emplace_with_hash(size_t hashval, Args&&... args) - { + std::pair emplace_with_hash(size_t hashval, Args&&... args) { typename gtl::aligned_storage_t raw; slot_type* slot = reinterpret_cast(&raw); @@ -1737,14 +1583,12 @@ class raw_hash_set } template - iterator emplace_hint(const_iterator, Args&&... args) - { + iterator emplace_hint(const_iterator, Args&&... args) { return emplace(std::forward(args)...).first; } template - iterator emplace_hint_with_hash(size_t hashval, const_iterator, Args&&... args) - { + iterator emplace_hint_with_hash(size_t hashval, const_iterator, Args&&... args) { return emplace_with_hash(hashval, std::forward(args)...).first; } @@ -1772,14 +1616,12 @@ class raw_hash_set // WARNING: This API is currently experimental. If there is a way to implement // the same thing with the rest of the API, prefer that. // --------------------------------------------------------------------------- - class constructor - { + class constructor { friend class raw_hash_set; public: template - void operator()(Args&&... args) const - { + void operator()(Args&&... args) const { assert(*slot_); PolicyTraits::construct(alloc_, *slot_, std::forward(args)...); *slot_ = nullptr; @@ -1788,9 +1630,7 @@ class raw_hash_set private: constructor(allocator_type* a, slot_type** slot) : alloc_(a) - , slot_(slot) - { - } + , slot_(slot) {} allocator_type* alloc_; slot_type** slot_; @@ -1816,14 +1656,12 @@ class raw_hash_set // }); // ----------------------------------------------------- template - iterator lazy_emplace(const key_arg& key, F&& f) - { + iterator lazy_emplace(const key_arg& key, F&& f) { return lazy_emplace_with_hash(key, this->hash(key), std::forward(f)); } template - iterator lazy_emplace_with_hash(const key_arg& key, size_t hashval, F&& f) - { + iterator lazy_emplace_with_hash(const key_arg& key, size_t hashval, F&& f) { auto res = find_or_prepare_insert(key, hashval); if (res.second) { lazy_emplace_at(res.first, std::forward(f)); @@ -1833,23 +1671,20 @@ class raw_hash_set } template - decltype(auto) lazy_emplace_at(size_t& idx, F&& f, C& c) - { + decltype(auto) lazy_emplace_at(size_t& idx, F&& f, C& c) { slot_type* slot = slots_ + idx; return std::forward(f)(constructor(&alloc_ref(), &slot), c); } template - void lazy_emplace_at(size_t& idx, F&& f) - { + void lazy_emplace_at(size_t& idx, F&& f) { slot_type* slot = slots_ + idx; std::forward(f)(constructor(&alloc_ref(), &slot)); assert(!slot); } template - void emplace_single_with_hash(const key_arg& key, size_t hashval, F&& f) - { + void emplace_single_with_hash(const key_arg& key, size_t hashval, F&& f) { auto res = find_or_prepare_insert(key, hashval); if (res.second) { lazy_emplace_at(res.first, std::forward(f)); @@ -1869,8 +1704,7 @@ class raw_hash_set // s.erase("abc"); // ------------------------------------------------------------- template - size_type erase(const key_arg& key) - { + size_type erase(const key_arg& key) { auto it = find(key); if (it == end()) return 0; @@ -1893,8 +1727,7 @@ class raw_hash_set // } // } // ---------------------------------------------------------------------------- - void _erase(iterator it) - { + void _erase(iterator it) { assert(it != end()); PolicyTraits::destroy(&alloc_ref(), it.slot_); erase_meta_only(it); @@ -1904,16 +1737,14 @@ class raw_hash_set // This overload is necessary because otherwise erase(const K&) would be // a better match if non-const iterator is passed as an argument. // ---------------------------------------------------------------------------- - iterator erase(iterator it) - { + iterator erase(iterator it) { auto res = it; ++res; _erase(it); return res; } - iterator erase(const_iterator first, const_iterator last) - { + iterator erase(const_iterator first, const_iterator last) { while (first != last) { _erase(first++); } @@ -1924,33 +1755,30 @@ class raw_hash_set // If the element already exists in `this`, it is left unmodified in `src`. // ---------------------------------------------------------------------------- template - void merge(raw_hash_set& src) - { // NOLINT + void merge(raw_hash_set& src) { // NOLINT assert(this != &src); for (auto it = src.begin(), e = src.end(); it != e; ++it) { if (PolicyTraits::apply(InsertSlot{ *this, std::move(*it.slot_) }, PolicyTraits::element(it.slot_)) - .second) { + .second) + { src.erase_meta_only(it); } } } template - void merge(raw_hash_set&& src) - { + void merge(raw_hash_set&& src) { merge(src); } - node_type extract(const_iterator position) - { + node_type extract(const_iterator position) { auto node = CommonAccess::Make(alloc_ref(), position.inner_.slot_); erase_meta_only(position); return node; } template, int> = 0> - node_type extract(const key_arg& key) - { + node_type extract(const key_arg& key) { auto it = find(key); return it == end() ? node_type() : extract(const_iterator{ it }); } @@ -1958,8 +1786,7 @@ class raw_hash_set void swap(raw_hash_set& that) noexcept(std::is_nothrow_swappable_v && std::is_nothrow_swappable_v && (!AllocTraits::propagate_on_container_swap::value || - std::is_nothrow_swappable_v)) - { + std::is_nothrow_swappable_v)) { using std::swap; swap(ctrl_, that.ctrl_); swap(slots_, that.slots_); @@ -1984,8 +1811,7 @@ class raw_hash_set bool phmap_load(InputArchive&); #endif - void rehash(size_t n) - { + void rehash(size_t n) { if (n == 0 && capacity_ == 0) return; if (n == 0 && size_ == 0) { @@ -2014,8 +1840,7 @@ class raw_hash_set // // Uses "abc" directly without copying it into std::string. // s.count("abc"); template - size_t count(const key_arg& key) const - { + size_t count(const key_arg& key) const { return find(key) == end() ? size_t(0) : size_t(1); } @@ -2025,8 +1850,7 @@ class raw_hash_set // NOTE: This is a very low level operation and should not be used without // specific benchmarks indicating its importance. // ----------------------------------------------------------------------- - void prefetch_hash(size_t hashval) const - { + void prefetch_hash(size_t hashval) const { (void)hashval; #if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86)) auto seq = probe(hashval); @@ -2040,8 +1864,7 @@ class raw_hash_set } template - void prefetch(const key_arg& key) const - { + void prefetch(const key_arg& key) const { prefetch_hash(this->hash(key)); } @@ -2054,8 +1877,7 @@ class raw_hash_set // called heterogeneous key support. // -------------------------------------------------------------------------- template - iterator find(const key_arg& key, size_t hashval) - { + iterator find(const key_arg& key, size_t hashval) { size_t offset; if (find_impl(key, hashval, offset)) return iterator_at(offset); @@ -2064,8 +1886,7 @@ class raw_hash_set } template - pointer find_ptr(const key_arg& key, size_t hashval) - { + pointer find_ptr(const key_arg& key, size_t hashval) { size_t offset; if (find_impl(key, hashval, offset)) return &PolicyTraits::element(slots_ + offset); @@ -2074,45 +1895,38 @@ class raw_hash_set } template - iterator find(const key_arg& key) - { + iterator find(const key_arg& key) { return find(key, this->hash(key)); } template - const_iterator find(const key_arg& key, size_t hashval) const - { + const_iterator find(const key_arg& key, size_t hashval) const { return const_cast(this)->find(key, hashval); } template - const_iterator find(const key_arg& key) const - { + const_iterator find(const key_arg& key) const { return find(key, this->hash(key)); } template - bool contains(const key_arg& key) const - { + bool contains(const key_arg& key) const { return find(key) != end(); } template - bool contains(const key_arg& key, size_t hashval) const - { + bool contains(const key_arg& key, size_t hashval) const { return find(key, hashval) != end(); } template - std::pair equal_range(const key_arg& key) - { + std::pair equal_range(const key_arg& key) { auto it = find(key); if (it != end()) return { it, std::next(it) }; return { it, it }; } template - std::pair equal_range(const key_arg& key) const - { + std::pair equal_range(const key_arg& key) const { auto it = find(key); if (it != end()) return { it, std::next(it) }; @@ -2122,20 +1936,17 @@ class raw_hash_set size_t bucket_count() const { return capacity_; } float load_factor() const { return capacity_ ? static_cast(size()) / capacity_ : 0.0; } float max_load_factor() const { return 1.0f; } - void max_load_factor(float) - { + void max_load_factor(float) { // Does nothing. } - hasher hash_function() const - { + hasher hash_function() const { return hash_ref(); } // warning: doesn't match internal hash - use hash() member function key_equal key_eq() const { return eq_ref(); } allocator_type get_allocator() const { return alloc_ref(); } - friend bool operator==(const raw_hash_set& a, const raw_hash_set& b) - { + friend bool operator==(const raw_hash_set& a, const raw_hash_set& b) { if (a.size() != b.size()) return false; const raw_hash_set* outer = &a; @@ -2153,8 +1964,7 @@ class raw_hash_set friend void swap(raw_hash_set& a, raw_hash_set& b) noexcept(noexcept(a.swap(b))) { a.swap(b); } template - size_t hash(const K& key) const - { + size_t hash(const K& key) const { return HashElement{ hash_ref() }(key); } @@ -2163,8 +1973,7 @@ class raw_hash_set friend struct hashtable_debug_internal::HashtableDebugAccess; template - bool find_impl(const key_arg& key, size_t hashval, size_t& offset) - { + bool find_impl(const key_arg& key, size_t hashval, size_t& offset) { auto seq = probe(hashval); while (true) { Group g{ ctrl_ + seq.offset() }; @@ -2180,32 +1989,26 @@ class raw_hash_set } } - struct FindElement - { + struct FindElement { template - const_iterator operator()(const K& key, Args&&...) const - { + const_iterator operator()(const K& key, Args&&...) const { return s.find(key); } const raw_hash_set& s; }; - struct HashElement - { + struct HashElement { template - size_t operator()(const K& key, Args&&...) const - { + size_t operator()(const K& key, Args&&...) const { return phmap_mix()(static_cast(h(key))); } const hasher& h; }; template - struct EqualElement - { + struct EqualElement { template - bool operator()(const K2& lhs, Args&&...) const - { + bool operator()(const K2& lhs, Args&&...) const { return eq(lhs, rhs); } const K1& rhs; @@ -2213,8 +2016,7 @@ class raw_hash_set }; template - std::pair emplace_decomposable(const K& key, size_t hashval, Args&&... args) - { + std::pair emplace_decomposable(const K& key, size_t hashval, Args&&... args) { auto res = find_or_prepare_insert(key, hashval); if (res.second) { emplace_at(res.first, std::forward(args)...); @@ -2223,21 +2025,17 @@ class raw_hash_set return { iterator_at(res.first), res.second }; } - struct EmplaceDecomposable - { + struct EmplaceDecomposable { template - std::pair operator()(const K& key, Args&&... args) const - { + std::pair operator()(const K& key, Args&&... args) const { return s.emplace_decomposable(key, s.hash(key), std::forward(args)...); } raw_hash_set& s; }; - struct EmplaceDecomposableHashval - { + struct EmplaceDecomposableHashval { template - std::pair operator()(const K& key, Args&&... args) const - { + std::pair operator()(const K& key, Args&&... args) const { return s.emplace_decomposable(key, hashval, std::forward(args)...); } raw_hash_set& s; @@ -2245,11 +2043,9 @@ class raw_hash_set }; template - struct InsertSlot - { + struct InsertSlot { template - std::pair operator()(const K& key, Args&&...) && - { + std::pair operator()(const K& key, Args&&...) && { size_t hashval = s.hash(key); auto res = s.find_or_prepare_insert(key, hashval); if (res.second) { @@ -2266,11 +2062,9 @@ class raw_hash_set }; template - struct InsertSlotWithHash - { + struct InsertSlotWithHash { template - std::pair operator()(const K& key, Args&&...) && - { + std::pair operator()(const K& key, Args&&...) && { auto res = s.find_or_prepare_insert(key, hashval); if (res.second) { PolicyTraits::transfer(&s.alloc_ref(), s.slots_ + res.first, &slot); @@ -2291,8 +2085,7 @@ class raw_hash_set // This can be used in conjunction with Policy::transfer to move the object to // another place. // ---------------------------------------------------------------------------- - void erase_meta_only(const_iterator it) - { + void erase_meta_only(const_iterator it) { assert(IsFull(*it.inner_.ctrl_) && "erasing a dangling iterator"); --size_; const size_t index = (size_t)(it.inner_.ctrl_ - ctrl_); @@ -2312,10 +2105,10 @@ class raw_hash_set growth_left() += was_never_full; } - void initialize_slots(size_t new_capacity) - { + void initialize_slots(size_t new_capacity) { assert(new_capacity); - if (std::is_same_v> && slots_ == nullptr) {} + if (std::is_same_v> && slots_ == nullptr) { + } auto layout = MakeLayout(new_capacity); char* mem = static_cast(Allocate(&alloc_ref(), layout.AllocSize())); @@ -2325,13 +2118,13 @@ class raw_hash_set reset_growth_left(new_capacity); } - void destroy_slots() - { + void destroy_slots() { if (!capacity_) return; - + if constexpr (!std::is_trivially_destructible::value || - std::is_same::value) { + std::is_same::value) + { // node map or not trivially destructible... we need to iterate and destroy values one by one for (size_t i = 0; i != capacity_; ++i) { if (IsFull(ctrl_[i])) { @@ -2350,8 +2143,7 @@ class raw_hash_set growth_left() = 0; } - void resize(size_t new_capacity) - { + void resize(size_t new_capacity) { assert(IsValidCapacity(new_capacity)); auto* old_ctrl = ctrl_; auto* old_slots = slots_; @@ -2375,8 +2167,7 @@ class raw_hash_set } } - void drop_deletes_without_resize() GTL_ATTRIBUTE_NOINLINE - { + void drop_deletes_without_resize() GTL_ATTRIBUTE_NOINLINE { assert(IsValidCapacity(capacity_)); assert(!is_small()); // ------------------------------------------------------------------------ @@ -2441,8 +2232,7 @@ class raw_hash_set reset_growth_left(capacity_); } - void rehash_and_grow_if_necessary() - { + void rehash_and_grow_if_necessary() { if (capacity_ == 0) { resize(1); } else if (size() <= CapacityToGrowth(capacity()) / 2) { @@ -2454,8 +2244,7 @@ class raw_hash_set } } - bool has_element(const value_type& elem, size_t hashval) const - { + bool has_element(const value_type& elem, size_t hashval) const { auto seq = probe(hashval); while (true) { Group g{ ctrl_ + seq.offset() }; @@ -2471,8 +2260,7 @@ class raw_hash_set return false; } - bool has_element(const value_type& elem) const - { + bool has_element(const value_type& elem) const { size_t hashval = PolicyTraits::apply(HashElement{ hash_ref() }, elem); return has_element(elem, hashval); } @@ -2487,13 +2275,11 @@ class raw_hash_set // - there are enough slots // - the element with the hash is not in the table // ------------------------------------------------------------------------- - struct FindInfo - { + struct FindInfo { size_t offset; size_t probe_length; }; - FindInfo find_first_non_full(size_t hashval) - { + FindInfo find_first_non_full(size_t hashval) { auto seq = probe(hashval); while (true) { Group g{ ctrl_ + seq.offset() }; @@ -2507,14 +2293,12 @@ class raw_hash_set } // TODO(alkis): Optimize this assuming *this and that don't overlap. - raw_hash_set& move_assign(raw_hash_set&& that, std::true_type) - { + raw_hash_set& move_assign(raw_hash_set&& that, std::true_type) { raw_hash_set tmp(std::move(that)); swap(tmp); return *this; } - raw_hash_set& move_assign(raw_hash_set&& that, std::false_type) - { + raw_hash_set& move_assign(raw_hash_set&& that, std::false_type) { raw_hash_set tmp(std::move(that), alloc_ref()); swap(tmp); return *this; @@ -2522,8 +2306,7 @@ class raw_hash_set protected: template - std::pair find_or_prepare_insert(const K& key, size_t hashval) - { + std::pair find_or_prepare_insert(const K& key, size_t hashval) { auto seq = probe(hashval); while (true) { Group g{ ctrl_ + seq.offset() }; @@ -2539,8 +2322,7 @@ class raw_hash_set return { prepare_insert(hashval), true }; } - size_t prepare_insert(size_t hashval) GTL_ATTRIBUTE_NOINLINE - { + size_t prepare_insert(size_t hashval) GTL_ATTRIBUTE_NOINLINE { auto target = find_first_non_full(hashval); if (GTL_PREDICT_FALSE(growth_left() == 0 && !IsDeleted(ctrl_[target.offset]))) { rehash_and_grow_if_necessary(); @@ -2561,8 +2343,7 @@ class raw_hash_set // POSTCONDITION: *m.iterator_at(i) == value_type(forward(args)...). // -------------------------------------------------------------------------- template - void emplace_at(size_t i, Args&&... args) - { + void emplace_at(size_t i, Args&&... args) { PolicyTraits::construct(&alloc_ref(), slots_ + i, std::forward(args)...); #ifdef GTL_CHECK_CONSTRUCTED_VALUE @@ -2578,8 +2359,7 @@ class raw_hash_set protected: // Sets the control byte, and if `i < Group::kWidth`, set the cloned byte at // the end too. - void set_ctrl(size_t i, ctrl_t h) - { + void set_ctrl(size_t i, ctrl_t h) { assert(i < capacity_); if (IsFull(h)) { @@ -2595,14 +2375,12 @@ class raw_hash_set private: friend struct RawHashSetTestOnlyAccess; - probe_seq probe(size_t hashval) const - { + probe_seq probe(size_t hashval) const { return probe_seq(H1(hashval, ctrl_), capacity_); } // Reset all ctrl bytes back to kEmpty, except the sentinel. - void reset_ctrl(size_t capacity) - { + void reset_ctrl(size_t capacity) { std::memset(ctrl_, kEmpty, capacity + Group::kWidth); ctrl_[capacity] = kSentinel; SanitizerPoisonMemoryRegion(slots_, sizeof(slot_type) * capacity); @@ -2668,15 +2446,16 @@ class raw_hash_set slot_type* slots_ = nullptr; // [capacity * slot_type] size_t size_ = 0; // number of full slots size_t capacity_ = 0; // total number of slots - std::tuple - settings_{ 0, hasher{}, key_equal{}, allocator_type{} }; + std::tuple settings_{ 0, + hasher{}, + key_equal{}, + allocator_type{} }; }; // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- template -class raw_hash_map : public raw_hash_set -{ +class raw_hash_map : public raw_hash_set { // P is Policy. It's passed as a template argument to support maps that have // incomplete types as values, as in unordered_map. // MappedReference<> may be a non-reference type. @@ -2719,50 +2498,42 @@ class raw_hash_map : public raw_hash_set // m.insert_or_assign(n, n); // ------------------------------------------------------------------------ template - std::pair insert_or_assign(key_arg&& k, V&& v) - { + std::pair insert_or_assign(key_arg&& k, V&& v) { return insert_or_assign_impl(std::forward(k), std::forward(v)); } template - std::pair insert_or_assign(key_arg&& k, const V& v) - { + std::pair insert_or_assign(key_arg&& k, const V& v) { return insert_or_assign_impl(std::forward(k), v); } template - std::pair insert_or_assign(const key_arg& k, V&& v) - { + std::pair insert_or_assign(const key_arg& k, V&& v) { return insert_or_assign_impl(k, std::forward(v)); } template - std::pair insert_or_assign(const key_arg& k, const V& v) - { + std::pair insert_or_assign(const key_arg& k, const V& v) { return insert_or_assign_impl(k, v); } template - iterator insert_or_assign(const_iterator, key_arg&& k, V&& v) - { + iterator insert_or_assign(const_iterator, key_arg&& k, V&& v) { return insert_or_assign(std::forward(k), std::forward(v)).first; } template - iterator insert_or_assign(const_iterator, key_arg&& k, const V& v) - { + iterator insert_or_assign(const_iterator, key_arg&& k, const V& v) { return insert_or_assign(std::forward(k), v).first; } template - iterator insert_or_assign(const_iterator, const key_arg& k, V&& v) - { + iterator insert_or_assign(const_iterator, const key_arg& k, V&& v) { return insert_or_assign(k, std::forward(v)).first; } template - iterator insert_or_assign(const_iterator, const key_arg& k, const V& v) - { + iterator insert_or_assign(const_iterator, const key_arg& k, const V& v) { return insert_or_assign(k, v).first; } @@ -2770,34 +2541,29 @@ class raw_hash_map : public raw_hash_set class... Args, typename std::enable_if_t, int> = 0, K* = nullptr> - std::pair try_emplace(key_arg&& k, Args&&... args) - { + std::pair try_emplace(key_arg&& k, Args&&... args) { return try_emplace_impl(std::forward(k), std::forward(args)...); } template, int> = 0> - std::pair try_emplace(const key_arg& k, Args&&... args) - { + std::pair try_emplace(const key_arg& k, Args&&... args) { return try_emplace_impl(k, std::forward(args)...); } template - iterator try_emplace(const_iterator, key_arg&& k, Args&&... args) - { + iterator try_emplace(const_iterator, key_arg&& k, Args&&... args) { return try_emplace(std::forward(k), std::forward(args)...).first; } template - iterator try_emplace(const_iterator, const key_arg& k, Args&&... args) - { + iterator try_emplace(const_iterator, const key_arg& k, Args&&... args) { return try_emplace(k, std::forward(args)...).first; } template - MappedReference

at(const key_arg& key) - { + MappedReference

at(const key_arg& key) { auto it = this->find(key); if (it == this->end()) ThrowStdOutOfRange("phmap at(): lookup non-existent key"); @@ -2805,8 +2571,7 @@ class raw_hash_map : public raw_hash_set } template - MappedConstReference

at(const key_arg& key) const - { + MappedConstReference

at(const key_arg& key) const { auto it = this->find(key); if (it == this->end()) ThrowStdOutOfRange("phmap at(): lookup non-existent key"); @@ -2814,21 +2579,18 @@ class raw_hash_map : public raw_hash_set } template - MappedReference

operator[](key_arg&& key) - { + MappedReference

operator[](key_arg&& key) { return Policy::value(&*try_emplace(std::forward(key)).first); } template - MappedReference

operator[](const key_arg& key) - { + MappedReference

operator[](const key_arg& key) { return Policy::value(&*try_emplace(key).first); } private: template - std::pair insert_or_assign_impl(K&& k, V&& v) - { + std::pair insert_or_assign_impl(K&& k, V&& v) { size_t hashval = this->hash(k); auto res = this->find_or_prepare_insert(k, hashval); if (res.second) { @@ -2840,8 +2602,7 @@ class raw_hash_map : public raw_hash_set } template - std::pair try_emplace_impl(K&& k, Args&&... args) - { + std::pair try_emplace_impl(K&& k, Args&&... args) { size_t hashval = this->hash(k); auto res = this->find_or_prepare_insert(k, hashval); if (res.second) { @@ -2858,8 +2619,7 @@ class raw_hash_map : public raw_hash_set // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Returns "random" seed. -inline size_t RandomSeed() -{ +inline size_t RandomSeed() { static thread_local size_t counter = 0; size_t value = ++counter; return value ^ static_cast(reinterpret_cast(&counter)); @@ -2870,28 +2630,23 @@ using defer_lock_t = boost::defer_lock_t; using try_to_lock_t = boost::try_to_lock_t; using adopt_lock_t = boost::adopt_lock_t; #else -struct adopt_lock_t -{ +struct adopt_lock_t { explicit adopt_lock_t() = default; }; -struct defer_lock_t -{ +struct defer_lock_t { explicit defer_lock_t() = default; }; -struct try_to_lock_t -{ +struct try_to_lock_t { explicit try_to_lock_t() = default; }; #endif // ------------------------ lockable object used internally ------------------------- template -class LockableBaseImpl -{ +class LockableBaseImpl { public: // ---------------------------------------------------- - struct DoNothing - { + struct DoNothing { using mutex_type = MutexType; DoNothing() noexcept {} explicit DoNothing(mutex_type&) noexcept {} @@ -2900,9 +2655,7 @@ class LockableBaseImpl DoNothing(mutex_type&, defer_lock_t) noexcept {} DoNothing(mutex_type&, try_to_lock_t) {} template - explicit DoNothing(T&&) - { - } + explicit DoNothing(T&&) {} DoNothing& operator=(const DoNothing&) { return *this; } DoNothing& operator=(DoNothing&&) noexcept { return *this; } void swap(DoNothing&) {} @@ -2910,82 +2663,67 @@ class LockableBaseImpl }; // ---------------------------------------------------- - class WriteLock - { + class WriteLock { public: using mutex_type = MutexType; WriteLock() : m_(nullptr) - , locked_(false) - { - } + , locked_(false) {} explicit WriteLock(mutex_type& m) - : m_(&m) - { + : m_(&m) { m_->lock(); locked_ = true; } WriteLock(mutex_type& m, adopt_lock_t) noexcept : m_(&m) - , locked_(true) - { - } + , locked_(true) {} WriteLock(mutex_type& m, defer_lock_t) noexcept : m_(&m) - , locked_(false) - { - } + , locked_(false) {} WriteLock(mutex_type& m, try_to_lock_t) : m_(&m) - , locked_(false) - { + , locked_(false) { m_->try_lock(); } WriteLock(WriteLock&& o) noexcept : m_(std::move(o.m_)) - , locked_(std::move(o.locked_)) - { + , locked_(std::move(o.locked_)) { o.locked_ = false; o.m_ = nullptr; } - WriteLock& operator=(WriteLock&& other) noexcept - { + WriteLock& operator=(WriteLock&& other) noexcept { WriteLock temp(std::move(other)); swap(temp); return *this; } - ~WriteLock() - { + ~WriteLock() { if (locked_) m_->unlock(); } - void lock() - { + void lock() { if (!locked_) { m_->lock(); locked_ = true; } } - void unlock() - { + void unlock() { if (locked_) { m_->unlock(); locked_ = false; } } - bool try_lock() - { + bool try_lock() { if (locked_) return true; locked_ = m_->try_lock(); @@ -2994,8 +2732,7 @@ class LockableBaseImpl bool owns_lock() const noexcept { return locked_; } - void swap(WriteLock& o) noexcept - { + void swap(WriteLock& o) noexcept { std::swap(m_, o.m_); std::swap(locked_, o.locked_); } @@ -3008,82 +2745,67 @@ class LockableBaseImpl }; // ---------------------------------------------------- - class ReadLock - { + class ReadLock { public: using mutex_type = MutexType; ReadLock() : m_(nullptr) - , locked_(false) - { - } + , locked_(false) {} explicit ReadLock(mutex_type& m) - : m_(&m) - { + : m_(&m) { m_->lock_shared(); locked_ = true; } ReadLock(mutex_type& m, adopt_lock_t) noexcept : m_(&m) - , locked_(true) - { - } + , locked_(true) {} ReadLock(mutex_type& m, defer_lock_t) noexcept : m_(&m) - , locked_(false) - { - } + , locked_(false) {} ReadLock(mutex_type& m, try_to_lock_t) : m_(&m) - , locked_(false) - { + , locked_(false) { m_->try_lock_shared(); } ReadLock(ReadLock&& o) noexcept : m_(std::move(o.m_)) - , locked_(std::move(o.locked_)) - { + , locked_(std::move(o.locked_)) { o.locked_ = false; o.m_ = nullptr; } - ReadLock& operator=(ReadLock&& other) noexcept - { + ReadLock& operator=(ReadLock&& other) noexcept { ReadLock temp(std::move(other)); swap(temp); return *this; } - ~ReadLock() - { + ~ReadLock() { if (locked_) m_->unlock_shared(); } - void lock() - { + void lock() { if (!locked_) { m_->lock_shared(); locked_ = true; } } - void unlock() - { + void unlock() { if (locked_) { m_->unlock_shared(); locked_ = false; } } - bool try_lock() - { + bool try_lock() { if (locked_) return true; locked_ = m_->try_lock_shared(); @@ -3092,8 +2814,7 @@ class LockableBaseImpl bool owns_lock() const noexcept { return locked_; } - void swap(ReadLock& o) noexcept - { + void swap(ReadLock& o) noexcept { std::swap(m_, o.m_); std::swap(locked_, o.locked_); } @@ -3106,26 +2827,22 @@ class LockableBaseImpl }; // ---------------------------------------------------- - class WriteLocks - { + class WriteLocks { public: using mutex_type = MutexType; explicit WriteLocks(mutex_type& m1, mutex_type& m2) : _m1(m1) - , _m2(m2) - { + , _m2(m2) { std::lock(m1, m2); } WriteLocks(adopt_lock_t, mutex_type& m1, mutex_type& m2) : _m1(m1) - , _m2(m2) - { // adopt means we already own the mutexes + , _m2(m2) { // adopt means we already own the mutexes } - ~WriteLocks() - { + ~WriteLocks() { _m1.unlock(); _m2.unlock(); } @@ -3139,27 +2856,23 @@ class LockableBaseImpl }; // ---------------------------------------------------- - class ReadLocks - { + class ReadLocks { public: using mutex_type = MutexType; explicit ReadLocks(mutex_type& m1, mutex_type& m2) : _m1(m1) - , _m2(m2) - { + , _m2(m2) { _m1.lock_shared(); _m2.lock_shared(); } ReadLocks(adopt_lock_t, mutex_type& m1, mutex_type& m2) : _m1(m1) - , _m2(m2) - { // adopt means we already own the mutexes + , _m2(m2) { // adopt means we already own the mutexes } - ~ReadLocks() - { + ~ReadLocks() { _m1.unlock_shared(); _m2.unlock_shared(); } @@ -3191,8 +2904,7 @@ class LockableBaseImpl // Generic mutex support (always write locks) // -------------------------------------------------------------------------- template -class LockableImpl : public Mtx_ -{ +class LockableImpl : public Mtx_ { public: using mutex_type = Mtx_; using Base = LockableBaseImpl; @@ -3208,8 +2920,7 @@ class LockableImpl : public Mtx_ // Null mutex (no-op) - when we don't want internal synchronization // --------------------------------------------------------------------------- template<> -class LockableImpl : public NullMutex -{ +class LockableImpl : public NullMutex { public: using mutex_type = NullMutex; using Base = LockableBaseImpl; @@ -3226,19 +2937,17 @@ class LockableImpl : public NullMutex // -------------------------------------------------------------------------- #ifdef ABSL_SYNCHRONIZATION_MUTEX_H_ -struct AbslMutex : protected absl::Mutex -{ - void lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() { this->Lock(); } - void unlock() ABSL_UNLOCK_FUNCTION() { this->Unlock(); } - void try_lock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) { this->TryLock(); } - void lock_shared() ABSL_SHARED_LOCK_FUNCTION() { this->ReaderLock(); } - void unlock_shared() ABSL_UNLOCK_FUNCTION() { this->ReaderUnlock(); } - void try_lock_shared() ABSL_SHARED_TRYLOCK_FUNCTION(true) { this->ReaderTryLock(); } +struct AbslMutex : protected absl::Mutex { + void lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() { this->Lock(); } + void unlock() ABSL_UNLOCK_FUNCTION() { this->Unlock(); } + void try_lock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) { this->TryLock(); } + void lock_shared() ABSL_SHARED_LOCK_FUNCTION() { this->ReaderLock(); } + void unlock_shared() ABSL_UNLOCK_FUNCTION() { this->ReaderUnlock(); } + void try_lock_shared() ABSL_SHARED_TRYLOCK_FUNCTION(true) { this->ReaderTryLock(); } }; template<> -class LockableImpl : public AbslMutex -{ +class LockableImpl : public AbslMutex { public: using mutex_type = AbslMutex; using Base = LockableBaseImpl; @@ -3258,8 +2967,7 @@ class LockableImpl : public AbslMutex #ifdef BOOST_THREAD_SHARED_MUTEX_HPP // --------------------------------------------------------------------------- template<> -class LockableImpl : public boost::shared_mutex -{ +class LockableImpl : public boost::shared_mutex { public: using mutex_type = boost::shared_mutex; using Base = LockableBaseImpl; @@ -3270,14 +2978,13 @@ class LockableImpl : public boost::shared_mutex using UniqueLocks = typename Base::WriteLocks; using UpgradeToUnique = typename Base::DoNothing; // we already have unique ownership }; -#endif // BOOST_THREAD_SHARED_MUTEX_HPP +#endif // BOOST_THREAD_SHARED_MUTEX_HPP // -------------------------------------------------------------------------- // std::shared_mutex support (read and write lock support) // -------------------------------------------------------------------------- template<> -class LockableImpl : public std::shared_mutex -{ +class LockableImpl : public std::shared_mutex { public: using mutex_type = std::shared_mutex; using Base = LockableBaseImpl; @@ -3300,8 +3007,7 @@ template -class parallel_hash_set -{ +class parallel_hash_set { using PolicyTraits = hash_policy_traits; using KeyArgImpl = KeyArg::value && IsTransparent::value>; @@ -3345,10 +3051,8 @@ class parallel_hash_set using SharedLock = typename Lockable::SharedLock; // -------------------------------------------------------------------- - struct alignas(gtl_hardware_destructive_interference_size) Inner : public Lockable - { - struct Params - { + struct alignas(gtl_hardware_destructive_interference_size) Inner : public Lockable { + struct Params { size_t bucket_cnt; const hasher& hashfn; const key_equal& eq; @@ -3358,12 +3062,9 @@ class parallel_hash_set Inner() {} Inner(Params const& p) - : set_(p.bucket_cnt, p.hashfn, p.eq, p.alloc) - { - } + : set_(p.bucket_cnt, p.hashfn, p.eq, p.alloc) {} - bool operator==(const Inner& o) const - { + bool operator==(const Inner& o) const { typename Lockable::SharedLocks l(const_cast(*this), const_cast(o)); return set_ == o.set_; } @@ -3385,9 +3086,7 @@ class parallel_hash_set template struct SameAsElementReference : std::is_same>, - typename std::remove_cv_t>> - { - }; + typename std::remove_cv_t>> {}; // An enabler for insert(T&&): T must be convertible to init_type or be the // same as [cv] value_type [ref]. @@ -3409,8 +3108,7 @@ class parallel_hash_set "Allocators with custom pointer types are not supported"); // --------------------- i t e r a t o r ------------------------------ - class iterator - { + class iterator { friend class parallel_hash_set; public: @@ -3428,24 +3126,21 @@ class parallel_hash_set reference operator*() const { return *it_; } pointer operator->() const { return &operator*(); } - iterator& operator++() - { + iterator& operator++() { assert(inner_); // null inner means we are already at the end ++it_; skip_empty(); return *this; } - iterator operator++(int) - { + iterator operator++(int) { assert(inner_); // null inner means we are already at the end auto tmp = *this; ++*this; return tmp; } - friend bool operator==(const iterator& a, const iterator& b) - { + friend bool operator==(const iterator& a, const iterator& b) { return a.inner_ == b.inner_ && (!a.inner_ || a.it_ == b.it_); } @@ -3455,14 +3150,12 @@ class parallel_hash_set iterator(Inner* inner, Inner* inner_end, const EmbeddedIterator& it) : inner_(inner) , inner_end_(inner_end) - , it_(it) - { // for begin() and end() + , it_(it) { // for begin() and end() if (inner) it_end_ = inner->set_.end(); } - void skip_empty() - { + void skip_empty() { while (it_ == it_end_) { ++inner_; if (inner_ == inner_end_) { @@ -3481,8 +3174,7 @@ class parallel_hash_set }; // --------------------- c o n s t i t e r a t o r ----------------- - class const_iterator - { + class const_iterator { friend class parallel_hash_set; public: @@ -3496,15 +3188,12 @@ class parallel_hash_set const_iterator() {} // Implicit construction from iterator. const_iterator(iterator i) - : iter_(std::move(i)) - { - } + : iter_(std::move(i)) {} reference operator*() const { return *(iter_); } pointer operator->() const { return iter_.operator->(); } - const_iterator& operator++() - { + const_iterator& operator++() { ++iter_; return *this; } @@ -3515,9 +3204,7 @@ class parallel_hash_set private: const_iterator(const Inner* inner, const Inner* inner_end, const EmbeddedIterator& it) - : iter_(const_cast(inner), const_cast(inner_end), const_cast(it)) - { - } + : iter_(const_cast(inner), const_cast(inner_end), const_cast(it)) {} iterator iter_; }; @@ -3529,39 +3216,27 @@ class parallel_hash_set parallel_hash_set() noexcept(std::is_nothrow_default_constructible_v && std::is_nothrow_default_constructible_v && - std::is_nothrow_default_constructible_v) - { - } + std::is_nothrow_default_constructible_v) {} explicit parallel_hash_set(size_t bucket_cnt, const hasher& hash_param = hasher(), const key_equal& eq = key_equal(), const allocator_type& alloc = allocator_type()) : parallel_hash_set(typename Inner::Params{ bucket_cnt, hash_param, eq, alloc }, - std::make_index_sequence{}) - { - } + std::make_index_sequence{}) {} template parallel_hash_set(typename Inner::Params const& p, std::index_sequence) - : sets_{ ((void)i, p)... } - { - } + : sets_{ ((void)i, p)... } {} parallel_hash_set(size_t bucket_cnt, const hasher& hash_param, const allocator_type& alloc) - : parallel_hash_set(bucket_cnt, hash_param, key_equal(), alloc) - { - } + : parallel_hash_set(bucket_cnt, hash_param, key_equal(), alloc) {} parallel_hash_set(size_t bucket_cnt, const allocator_type& alloc) - : parallel_hash_set(bucket_cnt, hasher(), key_equal(), alloc) - { - } + : parallel_hash_set(bucket_cnt, hasher(), key_equal(), alloc) {} explicit parallel_hash_set(const allocator_type& alloc) - : parallel_hash_set(0, hasher(), key_equal(), alloc) - { - } + : parallel_hash_set(0, hasher(), key_equal(), alloc) {} template parallel_hash_set(InputIter first, @@ -3570,8 +3245,7 @@ class parallel_hash_set const hasher& hash_param = hasher(), const key_equal& eq = key_equal(), const allocator_type& alloc = allocator_type()) - : parallel_hash_set(bucket_cnt, hash_param, eq, alloc) - { + : parallel_hash_set(bucket_cnt, hash_param, eq, alloc) { insert(first, last); } @@ -3581,21 +3255,15 @@ class parallel_hash_set size_t bucket_cnt, const hasher& hash_param, const allocator_type& alloc) - : parallel_hash_set(first, last, bucket_cnt, hash_param, key_equal(), alloc) - { - } + : parallel_hash_set(first, last, bucket_cnt, hash_param, key_equal(), alloc) {} template parallel_hash_set(InputIter first, InputIter last, size_t bucket_cnt, const allocator_type& alloc) - : parallel_hash_set(first, last, bucket_cnt, hasher(), key_equal(), alloc) - { - } + : parallel_hash_set(first, last, bucket_cnt, hasher(), key_equal(), alloc) {} template parallel_hash_set(InputIter first, InputIter last, const allocator_type& alloc) - : parallel_hash_set(first, last, 0, hasher(), key_equal(), alloc) - { - } + : parallel_hash_set(first, last, 0, hasher(), key_equal(), alloc) {} // Instead of accepting std::initializer_list as the first // argument like std::unordered_set does, we have two overloads @@ -3623,66 +3291,47 @@ class parallel_hash_set const hasher& hash_param = hasher(), const key_equal& eq = key_equal(), const allocator_type& alloc = allocator_type()) - : parallel_hash_set(init.begin(), init.end(), bucket_cnt, hash_param, eq, alloc) - { - } + : parallel_hash_set(init.begin(), init.end(), bucket_cnt, hash_param, eq, alloc) {} parallel_hash_set(std::initializer_list init, size_t bucket_cnt = 0, const hasher& hash_param = hasher(), const key_equal& eq = key_equal(), const allocator_type& alloc = allocator_type()) - : parallel_hash_set(init.begin(), init.end(), bucket_cnt, hash_param, eq, alloc) - { - } + : parallel_hash_set(init.begin(), init.end(), bucket_cnt, hash_param, eq, alloc) {} template = 0> parallel_hash_set(std::initializer_list init, size_t bucket_cnt, const hasher& hash_param, const allocator_type& alloc) - : parallel_hash_set(init, bucket_cnt, hash_param, key_equal(), alloc) - { - } + : parallel_hash_set(init, bucket_cnt, hash_param, key_equal(), alloc) {} parallel_hash_set(std::initializer_list init, size_t bucket_cnt, const hasher& hash_param, const allocator_type& alloc) - : parallel_hash_set(init, bucket_cnt, hash_param, key_equal(), alloc) - { - } + : parallel_hash_set(init, bucket_cnt, hash_param, key_equal(), alloc) {} template = 0> parallel_hash_set(std::initializer_list init, size_t bucket_cnt, const allocator_type& alloc) - : parallel_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) - { - } + : parallel_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) {} parallel_hash_set(std::initializer_list init, size_t bucket_cnt, const allocator_type& alloc) - : parallel_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) - { - } + : parallel_hash_set(init, bucket_cnt, hasher(), key_equal(), alloc) {} template = 0> parallel_hash_set(std::initializer_list init, const allocator_type& alloc) - : parallel_hash_set(init, 0, hasher(), key_equal(), alloc) - { - } + : parallel_hash_set(init, 0, hasher(), key_equal(), alloc) {} parallel_hash_set(std::initializer_list init, const allocator_type& alloc) - : parallel_hash_set(init, 0, hasher(), key_equal(), alloc) - { - } + : parallel_hash_set(init, 0, hasher(), key_equal(), alloc) {} parallel_hash_set(const parallel_hash_set& that) - : parallel_hash_set(that, AllocTraits::select_on_container_copy_construction(that.alloc_ref())) - { - } + : parallel_hash_set(that, AllocTraits::select_on_container_copy_construction(that.alloc_ref())) {} parallel_hash_set(const parallel_hash_set& that, const allocator_type& a) - : parallel_hash_set(0, that.hash_ref(), that.eq_ref(), a) - { + : parallel_hash_set(0, that.hash_ref(), that.eq_ref(), a) { for (size_t i = 0; i < num_tables; ++i) sets_[i].set_ = { that.sets_[i].set_, a }; } @@ -3690,18 +3339,14 @@ class parallel_hash_set parallel_hash_set(parallel_hash_set&& that) noexcept(std::is_nothrow_copy_constructible_v && std::is_nothrow_copy_constructible_v && std::is_nothrow_copy_constructible_v) - : parallel_hash_set(std::move(that), that.alloc_ref()) - { - } + : parallel_hash_set(std::move(that), that.alloc_ref()) {} - parallel_hash_set(parallel_hash_set&& that, const allocator_type& a) - { + parallel_hash_set(parallel_hash_set&& that, const allocator_type& a) { for (size_t i = 0; i < num_tables; ++i) sets_[i].set_ = { std::move(that.sets_[i]).set_, a }; } - parallel_hash_set& operator=(const parallel_hash_set& that) - { + parallel_hash_set& operator=(const parallel_hash_set& that) { for (size_t i = 0; i < num_tables; ++i) sets_[i].set_ = that.sets_[i].set_; return *this; @@ -3709,8 +3354,7 @@ class parallel_hash_set parallel_hash_set& operator=(parallel_hash_set&& that) noexcept( std::allocator_traits::is_always_equal::value && std::is_nothrow_move_assignable_v && - std::is_nothrow_move_assignable_v) - { + std::is_nothrow_move_assignable_v) { for (size_t i = 0; i < num_tables; ++i) sets_[i].set_ = std::move(that.sets_[i].set_); return *this; @@ -3718,8 +3362,7 @@ class parallel_hash_set ~parallel_hash_set() {} - iterator begin() - { + iterator begin() { auto it = iterator(&sets_[0], &sets_[0] + num_tables, sets_[0].set_.begin()); it.skip_empty(); return it; @@ -3733,16 +3376,14 @@ class parallel_hash_set bool empty() const { return !size(); } - size_t size() const - { + size_t size() const { size_t sz = 0; for (const auto& inner : sets_) sz += inner.set_.size(); return sz; } - size_t capacity() const - { + size_t capacity() const { size_t c = 0; for (const auto& inner : sets_) c += inner.set_.capacity(); @@ -3751,8 +3392,7 @@ class parallel_hash_set size_t max_size() const { return (std::numeric_limits::max)(); } - GTL_ATTRIBUTE_REINITIALIZES void clear() - { + GTL_ATTRIBUTE_REINITIALIZES void clear() { for (auto& inner : sets_) { UniqueLock m(inner); inner.set_.clear(); @@ -3763,8 +3403,7 @@ class parallel_hash_set // extension - clears only specified submap // ---------------------------------------- - void clear(std::size_t submap_index) - { + void clear(std::size_t submap_index) { Inner& inner = sets_[submap_index]; UniqueLock m(inner); inner.set_.clear(); @@ -3782,8 +3421,7 @@ class parallel_hash_set RequiresInsertable = 0, typename std::enable_if_t::value, int> = 0, T* = nullptr> - std::pair insert(T&& value) - { + std::pair insert(T&& value) { return emplace(std::forward(value)); } @@ -3801,8 +3439,7 @@ class parallel_hash_set template = 0, typename std::enable_if_t::value, int> = 0> - std::pair insert(const T& value) - { + std::pair insert(const T& value) { return emplace(value); } @@ -3818,38 +3455,33 @@ class parallel_hash_set RequiresInsertable = 0, typename std::enable_if_t::value, int> = 0, T* = nullptr> - iterator insert(const_iterator, T&& value) - { + iterator insert(const_iterator, T&& value) { return insert(std::forward(value)).first; } template = 0, typename std::enable_if_t::value, int> = 0> - iterator insert(const_iterator, const T& value) - { + iterator insert(const_iterator, const T& value) { return insert(value).first; } iterator insert(const_iterator, init_type&& value) { return insert(std::move(value)).first; } template - void insert(InputIt first, InputIt last) - { + void insert(InputIt first, InputIt last) { for (; first != last; ++first) insert(*first); } template = 0> - void insert(std::initializer_list ilist) - { + void insert(std::initializer_list ilist) { insert(ilist.begin(), ilist.end()); } void insert(std::initializer_list ilist) { insert(ilist.begin(), ilist.end()); } - insert_return_type insert(node_type&& node) - { + insert_return_type insert(node_type&& node) { if (!node) return { end(), false, node_type() }; auto& key = node.key(); @@ -3864,11 +3496,9 @@ class parallel_hash_set iterator insert(const_iterator, node_type&& node) { return insert(std::move(node)).first; } - struct ReturnKey_ - { + struct ReturnKey_ { template - Key operator()(Key&& k, const Args&...) const - { + Key operator()(Key&& k, const Args&...) const { return std::forward(k); } }; @@ -3879,19 +3509,16 @@ class parallel_hash_set // same as emplace, but hashval is provided // -------------------------------------------------------------------- template - std::pair emplace_decomposable_with_hash(const K& key, size_t hashval, Args&&... args) - { + std::pair emplace_decomposable_with_hash(const K& key, size_t hashval, Args&&... args) { Inner& inner = sets_[subidx(hashval)]; auto& set = inner.set_; UniqueLock m(inner); return make_rv(&inner, set.emplace_decomposable(key, hashval, std::forward(args)...)); } - struct EmplaceDecomposableHashval - { + struct EmplaceDecomposableHashval { template - std::pair operator()(const K& key, Args&&... args) const - { + std::pair operator()(const K& key, Args&&... args) const { return s.emplace_decomposable_with_hash(key, hashval, std::forward(args)...); } parallel_hash_set& s; @@ -3909,8 +3536,7 @@ class parallel_hash_set // m.emplace("abc", "xyz"); // -------------------------------------------------------------------- template::value, int> = 0> - std::pair emplace_with_hash(size_t hashval, Args&&... args) - { + std::pair emplace_with_hash(size_t hashval, Args&&... args) { return PolicyTraits::apply(EmplaceDecomposableHashval{ *this, hashval }, std::forward(args)...); } @@ -3919,8 +3545,7 @@ class parallel_hash_set // destroys. // -------------------------------------------------------------------- template::value, int> = 0> - std::pair emplace_with_hash(size_t hashval, Args&&... args) - { + std::pair emplace_with_hash(size_t hashval, Args&&... args) { typename gtl::aligned_storage_t raw; slot_type* slot = reinterpret_cast(&raw); @@ -3934,14 +3559,12 @@ class parallel_hash_set } template - iterator emplace_hint_with_hash(size_t hashval, const_iterator, Args&&... args) - { + iterator emplace_hint_with_hash(size_t hashval, const_iterator, Args&&... args) { return emplace_with_hash(hashval, std::forward(args)...).first; } template - iterator lazy_emplace_with_hash(const key_arg& key, size_t hashval, F&& f) - { + iterator lazy_emplace_with_hash(const key_arg& key, size_t hashval, F&& f) { Inner& inner = sets_[subidx(hashval)]; auto& set = inner.set_; UniqueLock m(inner); @@ -3953,8 +3576,7 @@ class parallel_hash_set // -------------------------------------------------------------------- template - std::pair emplace_decomposable(const K& key, Args&&... args) - { + std::pair emplace_decomposable(const K& key, Args&&... args) { size_t hashval = this->hash(key); Inner& inner = sets_[subidx(hashval)]; auto& set = inner.set_; @@ -3962,11 +3584,9 @@ class parallel_hash_set return make_rv(&inner, set.emplace_decomposable(key, hashval, std::forward(args)...)); } - struct EmplaceDecomposable - { + struct EmplaceDecomposable { template - std::pair operator()(const K& key, Args&&... args) const - { + std::pair operator()(const K& key, Args&&... args) const { return s.emplace_decomposable(key, std::forward(args)...); } parallel_hash_set& s; @@ -3983,8 +3603,7 @@ class parallel_hash_set // m.emplace("abc", "xyz"); // -------------------------------------------------------------------- template::value, int> = 0> - std::pair emplace(Args&&... args) - { + std::pair emplace(Args&&... args) { return PolicyTraits::apply(EmplaceDecomposable{ *this }, std::forward(args)...); } @@ -3993,8 +3612,7 @@ class parallel_hash_set // destroys. // -------------------------------------------------------------------- template::value, int> = 0> - std::pair emplace(Args&&... args) - { + std::pair emplace(Args&&... args) { typename gtl::aligned_storage_t raw; slot_type* slot = reinterpret_cast(&raw); size_t hashval = this->hash(PolicyTraits::key(slot)); @@ -4009,28 +3627,24 @@ class parallel_hash_set } template - iterator emplace_hint(const_iterator, Args&&... args) - { + iterator emplace_hint(const_iterator, Args&&... args) { return emplace(std::forward(args)...).first; } - iterator make_iterator(Inner* inner, const EmbeddedIterator it) - { + iterator make_iterator(Inner* inner, const EmbeddedIterator it) { if (it == inner->set_.end()) return iterator(); return iterator(inner, &sets_[0] + num_tables, it); } - std::pair make_rv(Inner* inner, const std::pair& res) - { + std::pair make_rv(Inner* inner, const std::pair& res) { return { iterator(inner, &sets_[0] + num_tables, res.first), res.second }; } // lazy_emplace // ------------ template - iterator lazy_emplace(const key_arg& key, F&& f) - { + iterator lazy_emplace(const key_arg& key, F&& f) { auto hashval = this->hash(key); Inner& inner = sets_[subidx(hashval)]; auto& set = inner.set_; @@ -4041,8 +3655,7 @@ class parallel_hash_set // emplace_single // -------------- template - void emplace_single_with_hash(const key_arg& key, size_t hashval, F&& f) - { + void emplace_single_with_hash(const key_arg& key, size_t hashval, F&& f) { Inner& inner = sets_[subidx(hashval)]; auto& set = inner.set_; UniqueLock m(inner); @@ -4050,8 +3663,7 @@ class parallel_hash_set } template - void emplace_single(const key_arg& key, F&& f) - { + void emplace_single(const key_arg& key, F&& f) { auto hashval = this->hash(key); emplace_single_with_hash(key, hashval, std::forward(f)); } @@ -4060,8 +3672,7 @@ class parallel_hash_set // and if_contains returns true. This is a const API and lambda should not modify the value // ----------------------------------------------------------------------------------------- template - bool if_contains(const key_arg& key, F&& f) const - { + bool if_contains(const key_arg& key, F&& f) const { return const_cast(this)->template modify_if_impl(key, std::forward(f)); } @@ -4071,8 +3682,7 @@ class parallel_hash_set // time. // ----------------------------------------------------------------------------------------- template - bool if_contains_unsafe(const key_arg& key, F&& f) const - { + bool if_contains_unsafe(const key_arg& key, F&& f) const { return const_cast(this) ->template modify_if_impl::DoNothing>(key, std::forward(f)); } @@ -4082,15 +3692,13 @@ class parallel_hash_set // mapped value // ---------------------------------------------------------------------------------------------------- template - bool modify_if(const key_arg& key, F&& f) - { + bool modify_if(const key_arg& key, F&& f) { return modify_if_impl(key, std::forward(f)); } // ----------------------------------------------------------------------------------------- template - bool modify_if_impl(const key_arg& key, F&& f) - { + bool modify_if_impl(const key_arg& key, F&& f) { L m; auto [inner, ptr] = this->template find_ptr(key, this->hash(key), m); if (ptr == nullptr) @@ -4110,14 +3718,12 @@ class parallel_hash_set // returns true if key was erased, false otherwise. // ---------------------------------------------------------------------------------------------------- template - bool erase_if(const key_arg& key, F&& f) - { + bool erase_if(const key_arg& key, F&& f) { return erase_if_impl(key, std::forward(f)); } template - bool erase_if_impl(const key_arg& key, F&& f) - { + bool erase_if_impl(const key_arg& key, F&& f) { static_assert(std::is_invocable_v); L m; auto it = this->template find(key, this->hash(key), m); @@ -4137,8 +3743,7 @@ class parallel_hash_set // returns true if key was not already present, false otherwise. // --------------------------------------------------------------------------------------- template - bool lazy_emplace_l(const key_arg& key, FExists&& fExists, FEmplace&& fEmplace) - { + bool lazy_emplace_l(const key_arg& key, FExists&& fExists, FEmplace&& fEmplace) { size_t hashval = this->hash(key); UniqueLock m; auto res = this->find_or_prepare_insert_with_hash(hashval, key, m); @@ -4174,8 +3779,7 @@ class parallel_hash_set // }); // ------------------------------------------------- template - void for_each(F&& fCallback) const - { + void for_each(F&& fCallback) const { for (auto const& inner : sets_) { SharedLock m(const_cast(inner)); std::for_each(inner.set_.begin(), inner.set_.end(), fCallback); @@ -4184,8 +3788,7 @@ class parallel_hash_set // this version allows to modify the values template - void for_each_m(F&& fCallback) - { + void for_each_m(F&& fCallback) { for (auto& inner : sets_) { UniqueLock m(const_cast(inner)); std::for_each(inner.set_.begin(), inner.set_.end(), fCallback); @@ -4194,8 +3797,7 @@ class parallel_hash_set #if __cplusplus >= 201703L template - void for_each(ExecutionPolicy&& policy, F&& fCallback) const - { + void for_each(ExecutionPolicy&& policy, F&& fCallback) const { std::for_each(std::forward(policy), sets_.begin(), sets_.end(), [&](auto const& inner) { SharedLock m(const_cast(inner)); std::for_each(inner.set_.begin(), inner.set_.end(), fCallback); @@ -4203,8 +3805,7 @@ class parallel_hash_set } template - void for_each_m(ExecutionPolicy&& policy, F&& fCallback) - { + void for_each_m(ExecutionPolicy&& policy, F&& fCallback) { std::for_each(std::forward(policy), sets_.begin(), sets_.end(), [&](auto& inner) { UniqueLock m(inner); std::for_each(inner.set_.begin(), inner.set_.end(), fCallback); @@ -4218,8 +3819,7 @@ class parallel_hash_set // for (auto& p : set) { ...; }}); // ------------------------------------------------- template - void with_submap(size_t idx, F&& fCallback) const - { + void with_submap(size_t idx, F&& fCallback) const { const Inner& inner = sets_[idx]; const auto& set = inner.set_; SharedLock m(const_cast(inner)); @@ -4227,8 +3827,7 @@ class parallel_hash_set } template - void with_submap_m(size_t idx, F&& fCallback) - { + void with_submap_m(size_t idx, F&& fCallback) { Inner& inner = sets_[idx]; auto& set = inner.set_; UniqueLock m(inner); @@ -4249,8 +3848,7 @@ class parallel_hash_set // s.erase("abc"); // -------------------------------------------------------------------- template - size_type erase(const key_arg& key) - { + size_type erase(const key_arg& key) { auto hashval = this->hash(key); Inner& inner = sets_[subidx(hashval)]; auto& set = inner.set_; @@ -4282,8 +3880,7 @@ class parallel_hash_set // } // } // -------------------------------------------------------------------- - void _erase(iterator it) - { + void _erase(iterator it) { assert(it.inner_ != nullptr); it.inner_->set_._erase(it.it_); } @@ -4293,14 +3890,12 @@ class parallel_hash_set // a better match if non-const iterator is passed as an argument. // Do not use erase APIs taking iterators when accessing the map concurrently // -------------------------------------------------------------------- - iterator erase(iterator it) - { + iterator erase(iterator it) { _erase(it++); return it; } - iterator erase(const_iterator first, const_iterator last) - { + iterator erase(const_iterator first, const_iterator last) { while (first != last) { _erase(first++); } @@ -4311,8 +3906,7 @@ class parallel_hash_set // If the element already exists in `this`, it is left unmodified in `src`. // -------------------------------------------------------------------- template - void merge(parallel_hash_set& src) - { // NOLINT + void merge(parallel_hash_set& src) { // NOLINT assert(this != &src); if (this != &src) { for (size_t i = 0; i < num_tables; ++i) { @@ -4323,19 +3917,16 @@ class parallel_hash_set } template - void merge(parallel_hash_set&& src) - { + void merge(parallel_hash_set&& src) { merge(src); } - node_type extract(const_iterator position) - { + node_type extract(const_iterator position) { return position.iter_.inner_->set_.extract(EmbeddedConstIterator(position.iter_.it_)); } template, int> = 0> - node_type extract(const key_arg& key) - { + node_type extract(const key_arg& key) { auto it = find(key); return it == end() ? node_type() : extract(const_iterator{ it }); } @@ -4343,8 +3934,7 @@ class parallel_hash_set template void swap(parallel_hash_set& that) noexcept( std::is_nothrow_swappable_v && - (!AllocTraits::propagate_on_container_swap::value || std::is_nothrow_swappable_v)) - { + (!AllocTraits::propagate_on_container_swap::value || std::is_nothrow_swappable_v)) { using std::swap; using Lockable2 = LockableImpl; @@ -4355,8 +3945,7 @@ class parallel_hash_set } } - void rehash(size_t n) - { + void rehash(size_t n) { size_t nn = n / num_tables; for (auto& inner : sets_) { UniqueLock m(inner); @@ -4364,8 +3953,7 @@ class parallel_hash_set } } - void reserve(size_t n) - { + void reserve(size_t n) { size_t target = GrowthToLowerboundCapacity(n); size_t normalized = 16 * NormalizeCapacity(n / num_tables); rehash(normalized > target ? normalized : target); @@ -4382,8 +3970,7 @@ class parallel_hash_set // s.count("abc"); // -------------------------------------------------------------------- template - size_t count(const key_arg& key) const - { + size_t count(const key_arg& key) const { return this->contains(key) ? 1 : 0; } @@ -4393,8 +3980,7 @@ class parallel_hash_set // NOTE: This is a very low level operation and should not be used without // specific benchmarks indicating its importance. // -------------------------------------------------------------------- - void prefetch_hash(size_t hashval) const - { + void prefetch_hash(size_t hashval) const { const Inner& inner = sets_[subidx(hashval)]; const auto& set = inner.set_; SharedLock m(const_cast(inner)); @@ -4402,8 +3988,7 @@ class parallel_hash_set } template - void prefetch(const key_arg& key) const - { + void prefetch(const key_arg& key) const { prefetch_hash(this->hash(key)); } @@ -4416,54 +4001,46 @@ class parallel_hash_set // called heterogeneous key support. // -------------------------------------------------------------------- template - iterator find(const key_arg& key, size_t hashval) - { + iterator find(const key_arg& key, size_t hashval) { SharedLock m; return find(key, hashval, m); } template - iterator find(const key_arg& key) - { + iterator find(const key_arg& key) { return this->find(key, this->hash(key)); } template - const_iterator find(const key_arg& key, size_t hashval) const - { + const_iterator find(const key_arg& key, size_t hashval) const { return const_cast(this)->find(key, hashval); } template - const_iterator find(const key_arg& key) const - { + const_iterator find(const key_arg& key) const { return find(key, this->hash(key)); } template - bool contains(const key_arg& key) const - { + bool contains(const key_arg& key) const { return this->contains(key, this->hash(key)); } template - bool contains(const key_arg& key, size_t hashval) const - { + bool contains(const key_arg& key, size_t hashval) const { return const_cast(this)->contains_impl(key, hashval); } - + template - bool contains_impl(const key_arg& key, size_t hashval) - { - Inner& inner = sets_[subidx(hashval)]; - auto& set = inner.set_; + bool contains_impl(const key_arg& key, size_t hashval) { + Inner& inner = sets_[subidx(hashval)]; + auto& set = inner.set_; SharedLock lock(inner); return set.find(key, hashval) != set.end(); } template - std::pair equal_range(const key_arg& key) - { + std::pair equal_range(const key_arg& key) { auto it = find(key); if (it != end()) return { it, std::next(it) }; @@ -4471,16 +4048,14 @@ class parallel_hash_set } template - std::pair equal_range(const key_arg& key) const - { + std::pair equal_range(const key_arg& key) const { auto it = find(key); if (it != end()) return { it, std::next(it) }; return { it, it }; } - size_t bucket_count() const - { + size_t bucket_count() const { size_t sz = 0; for (const auto& inner : sets_) { SharedLock m(const_cast(inner)); @@ -4489,27 +4064,23 @@ class parallel_hash_set return sz; } - float load_factor() const - { + float load_factor() const { size_t _capacity = bucket_count(); return _capacity ? static_cast(static_cast(size()) / _capacity) : 0; } float max_load_factor() const { return 1.0f; } - void max_load_factor(float) - { + void max_load_factor(float) { // Does nothing. } - hasher hash_function() const - { + hasher hash_function() const { return hash_ref(); } // warning: doesn't match internal hash - use hash() member function key_equal key_eq() const { return eq_ref(); } allocator_type get_allocator() const { return alloc_ref(); } - friend bool operator==(const parallel_hash_set& a, const parallel_hash_set& b) - { + friend bool operator==(const parallel_hash_set& a, const parallel_hash_set& b) { return std::equal(a.sets_.begin(), a.sets_.end(), b.sets_.begin()); } @@ -4518,14 +4089,12 @@ class parallel_hash_set template friend void swap( parallel_hash_set& a, - parallel_hash_set& b) noexcept(noexcept(a.swap(b))) - { + parallel_hash_set& b) noexcept(noexcept(a.swap(b))) { a.swap(b); } template - size_t hash(const K& key) const - { + size_t hash(const K& key) const { return HashElement{ hash_ref() }(key); } @@ -4541,32 +4110,26 @@ class parallel_hash_set template friend struct hashtable_debug_internal::HashtableDebugAccess; - struct FindElement - { + struct FindElement { template - const_iterator operator()(const K& key, Args&&...) const - { + const_iterator operator()(const K& key, Args&&...) const { return s.find(key); } const parallel_hash_set& s; }; - struct HashElement - { + struct HashElement { template - size_t operator()(const K& key, Args&&...) const - { + size_t operator()(const K& key, Args&&...) const { return phmap_mix()(h(key)); } const hasher& h; }; template - struct EqualElement - { + struct EqualElement { template - bool operator()(const K2& lhs, Args&&...) const - { + bool operator()(const K2& lhs, Args&&...) const { return eq(lhs, rhs); } const K1& rhs; @@ -4578,23 +4141,20 @@ class parallel_hash_set // This can be used in conjunction with Policy::transfer to move the object to // another place. // -------------------------------------------------------------------- - void erase_meta_only(const_iterator cit) - { + void erase_meta_only(const_iterator cit) { auto& it = cit.iter_; assert(it.set_ != nullptr); it.set_.erase_meta_only(const_iterator(it.it_)); } - void drop_deletes_without_resize() GTL_ATTRIBUTE_NOINLINE - { + void drop_deletes_without_resize() GTL_ATTRIBUTE_NOINLINE { for (auto& inner : sets_) { UniqueLock m(inner); inner.set_.drop_deletes_without_resize(); } } - bool has_element(const value_type& elem) const - { + bool has_element(const value_type& elem) const { size_t hashval = PolicyTraits::apply(HashElement{ hash_ref() }, elem); Inner& inner = sets_[subidx(hashval)]; auto& set = inner.set_; @@ -4606,8 +4166,7 @@ class parallel_hash_set // -------------------------------------------------------------------- template parallel_hash_set& move_assign(parallel_hash_set&& that, - std::true_type) - { + std::true_type) { parallel_hash_set tmp(std::move(that)); swap(tmp); return *this; @@ -4615,8 +4174,7 @@ class parallel_hash_set template parallel_hash_set& move_assign(parallel_hash_set&& that, - std::false_type) - { + std::false_type) { parallel_hash_set tmp(std::move(that), alloc_ref()); swap(tmp); return *this; @@ -4624,8 +4182,7 @@ class parallel_hash_set protected: template - std::pair find_ptr(const key_arg& key, size_t hashval, L& mutexlock) - { + std::pair find_ptr(const key_arg& key, size_t hashval, L& mutexlock) { Inner& inner = sets_[subidx(hashval)]; auto& set = inner.set_; mutexlock = std::move(L(inner)); @@ -4633,8 +4190,7 @@ class parallel_hash_set } template - iterator find(const key_arg& key, size_t hashval, L& mutexlock) - { + iterator find(const key_arg& key, size_t hashval, L& mutexlock) { Inner& inner = sets_[subidx(hashval)]; auto& set = inner.set_; mutexlock = std::move(L(inner)); @@ -4644,8 +4200,7 @@ class parallel_hash_set template std::tuple find_or_prepare_insert_with_hash(size_t hashval, const K& key, - UniqueLock& mutexlock) - { + UniqueLock& mutexlock) { Inner& inner = sets_[subidx(hashval)]; auto& set = inner.set_; mutexlock = std::move(UniqueLock(inner)); @@ -4654,14 +4209,12 @@ class parallel_hash_set } template - std::tuple find_or_prepare_insert(const K& key, UniqueLock& mutexlock) - { + std::tuple find_or_prepare_insert(const K& key, UniqueLock& mutexlock) { return find_or_prepare_insert_with_hash(this->hash(key), key, mutexlock); } iterator iterator_at(Inner* inner, const EmbeddedIterator& it) { return { inner, &sets_[0] + num_tables, it }; } - const_iterator iterator_at(Inner* inner, const EmbeddedIterator& it) const - { + const_iterator iterator_at(Inner* inner, const EmbeddedIterator& it) const { return { inner, &sets_[0] + num_tables, it }; } @@ -4672,8 +4225,7 @@ class parallel_hash_set private: friend struct RawHashSetTestOnlyAccess; - size_t growth_left() - { + size_t growth_left() { size_t sz = 0; for (const auto& set : sets_) sz += set.growth_left(); @@ -4702,8 +4254,7 @@ template -class parallel_hash_map : public parallel_hash_set -{ +class parallel_hash_map : public parallel_hash_set { // P is Policy. It's passed as a template argument to support maps that have // incomplete types as values, as in unordered_map. // MappedReference<> may be a non-reference type. @@ -4752,50 +4303,42 @@ class parallel_hash_map : public parallel_hash_set m; // m.insert_or_assign(n, n); template - std::pair insert_or_assign(key_arg&& k, V&& v) - { + std::pair insert_or_assign(key_arg&& k, V&& v) { return insert_or_assign_impl(std::forward(k), std::forward(v)); } template - std::pair insert_or_assign(key_arg&& k, const V& v) - { + std::pair insert_or_assign(key_arg&& k, const V& v) { return insert_or_assign_impl(std::forward(k), v); } template - std::pair insert_or_assign(const key_arg& k, V&& v) - { + std::pair insert_or_assign(const key_arg& k, V&& v) { return insert_or_assign_impl(k, std::forward(v)); } template - std::pair insert_or_assign(const key_arg& k, const V& v) - { + std::pair insert_or_assign(const key_arg& k, const V& v) { return insert_or_assign_impl(k, v); } template - iterator insert_or_assign(const_iterator, key_arg&& k, V&& v) - { + iterator insert_or_assign(const_iterator, key_arg&& k, V&& v) { return insert_or_assign(std::forward(k), std::forward(v)).first; } template - iterator insert_or_assign(const_iterator, key_arg&& k, const V& v) - { + iterator insert_or_assign(const_iterator, key_arg&& k, const V& v) { return insert_or_assign(std::forward(k), v).first; } template - iterator insert_or_assign(const_iterator, const key_arg& k, V&& v) - { + iterator insert_or_assign(const_iterator, const key_arg& k, V&& v) { return insert_or_assign(k, std::forward(v)).first; } template - iterator insert_or_assign(const_iterator, const key_arg& k, const V& v) - { + iterator insert_or_assign(const_iterator, const key_arg& k, const V& v) { return insert_or_assign(k, v).first; } @@ -4803,34 +4346,29 @@ class parallel_hash_map : public parallel_hash_set, int> = 0, K* = nullptr> - std::pair try_emplace(key_arg&& k, Args&&... args) - { + std::pair try_emplace(key_arg&& k, Args&&... args) { return try_emplace_impl(std::forward(k), std::forward(args)...); } template, int> = 0> - std::pair try_emplace(const key_arg& k, Args&&... args) - { + std::pair try_emplace(const key_arg& k, Args&&... args) { return try_emplace_impl(k, std::forward(args)...); } template - iterator try_emplace(const_iterator, key_arg&& k, Args&&... args) - { + iterator try_emplace(const_iterator, key_arg&& k, Args&&... args) { return try_emplace(std::forward(k), std::forward(args)...).first; } template - iterator try_emplace(const_iterator, const key_arg& k, Args&&... args) - { + iterator try_emplace(const_iterator, const key_arg& k, Args&&... args) { return try_emplace(k, std::forward(args)...).first; } template - MappedReference

at(const key_arg& key) - { + MappedReference

at(const key_arg& key) { auto it = this->find(key); if (it == this->end()) ThrowStdOutOfRange("phmap at(): lookup non-existent key"); @@ -4838,8 +4376,7 @@ class parallel_hash_map : public parallel_hash_set - MappedConstReference

at(const key_arg& key) const - { + MappedConstReference

at(const key_arg& key) const { auto it = this->find(key); if (it == this->end()) ThrowStdOutOfRange("phmap at(): lookup non-existent key"); @@ -4852,28 +4389,24 @@ class parallel_hash_map : public parallel_hash_set, int> = 0, K* = nullptr> - std::pair try_emplace_with_hash(size_t hashval, key_arg&& k, Args&&... args) - { + std::pair try_emplace_with_hash(size_t hashval, key_arg&& k, Args&&... args) { return try_emplace_impl_with_hash(hashval, std::forward(k), std::forward(args)...); } template, int> = 0> - std::pair try_emplace_with_hash(size_t hashval, const key_arg& k, Args&&... args) - { + std::pair try_emplace_with_hash(size_t hashval, const key_arg& k, Args&&... args) { return try_emplace_impl_with_hash(hashval, k, std::forward(args)...); } template - iterator try_emplace_with_hash(size_t hashval, const_iterator, key_arg&& k, Args&&... args) - { + iterator try_emplace_with_hash(size_t hashval, const_iterator, key_arg&& k, Args&&... args) { return try_emplace_with_hash(hashval, std::forward(k), std::forward(args)...).first; } template - iterator try_emplace_with_hash(size_t hashval, const_iterator, const key_arg& k, Args&&... args) - { + iterator try_emplace_with_hash(size_t hashval, const_iterator, const key_arg& k, Args&&... args) { return try_emplace_with_hash(hashval, k, std::forward(args)...).first; } @@ -4884,8 +4417,7 @@ class parallel_hash_map : public parallel_hash_set - bool try_emplace_l(K&& k, F&& f, Args&&... args) - { + bool try_emplace_l(K&& k, F&& f, Args&&... args) { size_t hashval = this->hash(k); UniqueLock m; auto res = this->find_or_prepare_insert_with_hash(hashval, k, m); @@ -4907,21 +4439,18 @@ class parallel_hash_map : public parallel_hash_set - MappedReference

operator[](key_arg&& key) - { + MappedReference

operator[](key_arg&& key) { return Policy::value(&*try_emplace(std::forward(key)).first); } template - MappedReference

operator[](const key_arg& key) - { + MappedReference

operator[](const key_arg& key) { return Policy::value(&*try_emplace(key).first); } private: template - std::pair insert_or_assign_impl(K&& k, V&& v) - { + std::pair insert_or_assign_impl(K&& k, V&& v) { size_t hashval = this->hash(k); UniqueLock m; auto res = this->find_or_prepare_insert(k, m); @@ -4935,14 +4464,12 @@ class parallel_hash_map : public parallel_hash_set - std::pair try_emplace_impl(K&& k, Args&&... args) - { + std::pair try_emplace_impl(K&& k, Args&&... args) { return try_emplace_impl_with_hash(this->hash(k), std::forward(k), std::forward(args)...); } template - std::pair try_emplace_impl_with_hash(size_t hashval, K&& k, Args&&... args) - { + std::pair try_emplace_impl_with_hash(size_t hashval, K&& k, Args&&... args) { UniqueLock m; auto res = this->find_or_prepare_insert_with_hash(hashval, k, m); typename Base::Inner* inner = std::get<0>(res); @@ -4977,29 +4504,25 @@ class parallel_hash_map : public parallel_hash_set -struct FlatHashSetPolicy -{ +struct FlatHashSetPolicy { using slot_type = T; using key_type = T; using init_type = T; using constant_iterators = std::true_type; - using is_flat = std::true_type; + using is_flat = std::true_type; template - static void construct(Allocator* alloc, slot_type* slot, Args&&... args) - { + static void construct(Allocator* alloc, slot_type* slot, Args&&... args) { std::allocator_traits::construct(*alloc, slot, std::forward(args)...); } template - static void destroy(Allocator* alloc, slot_type* slot) - { + static void destroy(Allocator* alloc, slot_type* slot) { std::allocator_traits::destroy(*alloc, slot); } template - static void transfer(Allocator* alloc, slot_type* new_slot, slot_type* old_slot) - { + static void transfer(Allocator* alloc, slot_type* new_slot, slot_type* old_slot) { construct(alloc, new_slot, std::move(*old_slot)); destroy(alloc, old_slot); } @@ -5007,8 +4530,8 @@ struct FlatHashSetPolicy static T& element(slot_type* slot) { return *slot; } template - static decltype(gtl::priv::DecomposeValue(std::declval(), std::declval()...)) apply(F&& f, Args&&... args) - { + static decltype(gtl::priv::DecomposeValue(std::declval(), std::declval()...)) apply(F&& f, + Args&&... args) { return gtl::priv::DecomposeValue(std::forward(f), std::forward(args)...); } @@ -5018,36 +4541,31 @@ struct FlatHashSetPolicy // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- template -struct FlatHashMapPolicy -{ +struct FlatHashMapPolicy { using slot_policy = priv::map_slot_policy; using slot_type = typename slot_policy::slot_type; using key_type = K; using mapped_type = V; using init_type = std::pair; - using is_flat = std::true_type; + using is_flat = std::true_type; template - static void construct(Allocator* alloc, slot_type* slot, Args&&... args) - { + static void construct(Allocator* alloc, slot_type* slot, Args&&... args) { slot_policy::construct(alloc, slot, std::forward(args)...); } template - static void destroy(Allocator* alloc, slot_type* slot) - { + static void destroy(Allocator* alloc, slot_type* slot) { slot_policy::destroy(alloc, slot); } template - static void transfer(Allocator* alloc, slot_type* new_slot, slot_type* old_slot) - { + static void transfer(Allocator* alloc, slot_type* new_slot, slot_type* old_slot) { slot_policy::transfer(alloc, new_slot, old_slot); } template - static decltype(gtl::priv::DecomposePair(std::declval(), std::declval()...)) apply(F&& f, Args&&... args) - { + static decltype(gtl::priv::DecomposePair(std::declval(), std::declval()...)) apply(F&& f, Args&&... args) { return gtl::priv::DecomposePair(std::forward(f), std::forward(args)...); } @@ -5060,32 +4578,27 @@ struct FlatHashMapPolicy }; template -struct node_hash_policy -{ +struct node_hash_policy { static_assert(std::is_lvalue_reference_v, ""); using slot_type = typename std::remove_cv_t>*; template - static void construct(Alloc* alloc, slot_type* slot, Args&&... args) - { + static void construct(Alloc* alloc, slot_type* slot, Args&&... args) { *slot = Policy::new_element(alloc, std::forward(args)...); } template - static void destroy(Alloc* alloc, slot_type* slot) - { + static void destroy(Alloc* alloc, slot_type* slot) { Policy::delete_element(alloc, *slot); } template - static void transfer(Alloc*, slot_type* new_slot, slot_type* old_slot) - { + static void transfer(Alloc*, slot_type* new_slot, slot_type* old_slot) { *new_slot = *old_slot; } - static size_t space_used(const slot_type* slot) - { + static size_t space_used(const slot_type* slot) { if (slot == nullptr) return Policy::element_space_used(nullptr); return Policy::element_space_used(*slot); @@ -5094,14 +4607,12 @@ struct node_hash_policy static Reference element(slot_type* slot) { return **slot; } template - static auto value(T* elem) -> decltype(P::value(elem)) - { + static auto value(T* elem) -> decltype(P::value(elem)) { return P::value(elem); } template - static auto apply(Ts&&... ts) -> decltype(P::apply(std::forward(ts)...)) - { + static auto apply(Ts&&... ts) -> decltype(P::apply(std::forward(ts)...)) { return P::apply(std::forward(ts)...); } }; @@ -5109,16 +4620,14 @@ struct node_hash_policy // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- template -struct NodeHashSetPolicy : gtl::priv::node_hash_policy> -{ +struct NodeHashSetPolicy : gtl::priv::node_hash_policy> { using key_type = T; using init_type = T; using constant_iterators = std::true_type; - using is_flat = std::false_type; + using is_flat = std::false_type; template - static T* new_element(Allocator* alloc, Args&&... args) - { + static T* new_element(Allocator* alloc, Args&&... args) { using ValueAlloc = typename std::allocator_traits::template rebind_alloc; ValueAlloc value_alloc(*alloc); T* res = std::allocator_traits::allocate(value_alloc, 1); @@ -5127,8 +4636,7 @@ struct NodeHashSetPolicy : gtl::priv::node_hash_policy> } template - static void delete_element(Allocator* alloc, T* elem) - { + static void delete_element(Allocator* alloc, T* elem) { using ValueAlloc = typename std::allocator_traits::template rebind_alloc; ValueAlloc value_alloc(*alloc); std::allocator_traits::destroy(value_alloc, elem); @@ -5136,8 +4644,8 @@ struct NodeHashSetPolicy : gtl::priv::node_hash_policy> } template - static decltype(gtl::priv::DecomposeValue(std::declval(), std::declval()...)) apply(F&& f, Args&&... args) - { + static decltype(gtl::priv::DecomposeValue(std::declval(), std::declval()...)) apply(F&& f, + Args&&... args) { return gtl::priv::DecomposeValue(std::forward(f), std::forward(args)...); } @@ -5148,19 +4656,17 @@ struct NodeHashSetPolicy : gtl::priv::node_hash_policy> // -------------------------------------------------------------------------- template class NodeHashMapPolicy - : public gtl::priv::node_hash_policy&, NodeHashMapPolicy> -{ + : public gtl::priv::node_hash_policy&, NodeHashMapPolicy> { using value_type = std::pair; public: using key_type = Key; using mapped_type = Value; using init_type = std::pair; - using is_flat = std::false_type; + using is_flat = std::false_type; template - static value_type* new_element(Allocator* alloc, Args&&... args) - { + static value_type* new_element(Allocator* alloc, Args&&... args) { using PairAlloc = typename std::allocator_traits::template rebind_alloc; PairAlloc pair_alloc(*alloc); value_type* res = std::allocator_traits::allocate(pair_alloc, 1); @@ -5169,8 +4675,7 @@ class NodeHashMapPolicy } template - static void delete_element(Allocator* alloc, value_type* pair) - { + static void delete_element(Allocator* alloc, value_type* pair) { using PairAlloc = typename std::allocator_traits::template rebind_alloc; PairAlloc pair_alloc(*alloc); std::allocator_traits::destroy(pair_alloc, pair); @@ -5178,8 +4683,7 @@ class NodeHashMapPolicy } template - static decltype(gtl::priv::DecomposePair(std::declval(), std::declval()...)) apply(F&& f, Args&&... args) - { + static decltype(gtl::priv::DecomposePair(std::declval(), std::declval()...)) apply(F&& f, Args&&... args) { return gtl::priv::DecomposePair(std::forward(f), std::forward(args)...); } @@ -5196,85 +4700,63 @@ class NodeHashMapPolicy // Supports heterogeneous lookup for basic_string-like elements. // support char16_t wchar_t .... template -struct StringHashEqT -{ - struct Hash - { +struct StringHashEqT { + struct Hash { using is_transparent = void; - size_t operator()(std::basic_string_view v) const - { + size_t operator()(std::basic_string_view v) const { std::string_view bv{ reinterpret_cast(v.data()), v.size() * sizeof(CharT) }; return std::hash()(bv); } }; - struct Eq - { + struct Eq { using is_transparent = void; - bool operator()(std::basic_string_view lhs, std::basic_string_view rhs) const - { + bool operator()(std::basic_string_view lhs, std::basic_string_view rhs) const { return lhs == rhs; } }; }; template<> -struct HashEq : StringHashEqT -{ -}; +struct HashEq : StringHashEqT {}; template<> -struct HashEq : StringHashEqT -{ -}; +struct HashEq : StringHashEqT {}; // char16_t template<> -struct HashEq : StringHashEqT -{ -}; +struct HashEq : StringHashEqT {}; template<> -struct HashEq : StringHashEqT -{ -}; +struct HashEq : StringHashEqT {}; // wchar_t template<> -struct HashEq : StringHashEqT -{ -}; +struct HashEq : StringHashEqT {}; template<> -struct HashEq : StringHashEqT -{ -}; +struct HashEq : StringHashEqT {}; // Supports heterogeneous lookup for pointers and smart pointers. // ------------------------------------------------------------- template -struct HashEq -{ - struct Hash - { +struct HashEq { + struct Hash { using is_transparent = void; template - size_t operator()(const U& ptr) const - { + size_t operator()(const U& ptr) const { // we want phmap::Hash and not phmap::Hash // so "struct std::hash " override works return gtl::Hash{}((T*)(uintptr_t)HashEq::ToPtr(ptr)); } }; - struct Eq - { + struct Eq { using is_transparent = void; template - bool operator()(const A& a, const B& b) const - { + bool operator()(const A& a, const B& b) const { return HashEq::ToPtr(a) == HashEq::ToPtr(b); } }; @@ -5283,27 +4765,21 @@ struct HashEq static const T* ToPtr(const T* ptr) { return ptr; } template - static const T* ToPtr(const std::unique_ptr& ptr) - { + static const T* ToPtr(const std::unique_ptr& ptr) { return ptr.get(); } template - static const T* ToPtr(const std::shared_ptr& ptr) - { + static const T* ToPtr(const std::shared_ptr& ptr) { return ptr.get(); } }; template -struct HashEq> : HashEq -{ -}; +struct HashEq> : HashEq {}; template -struct HashEq> : HashEq -{ -}; +struct HashEq> : HashEq {}; namespace hashtable_debug_internal { @@ -5311,22 +4787,16 @@ namespace hashtable_debug_internal { // -------------------------------------------------------------------------- template -struct has_member_type_raw_hash_set : std::false_type -{ -}; +struct has_member_type_raw_hash_set : std::false_type {}; template -struct has_member_type_raw_hash_set> : std::true_type -{ -}; +struct has_member_type_raw_hash_set> : std::true_type {}; template -struct HashtableDebugAccess::value>> -{ +struct HashtableDebugAccess::value>> { using Traits = typename Set::PolicyTraits; using Slot = typename Traits::slot_type; - static size_t GetNumProbes(const Set& set, const typename Set::key_type& key) - { + static size_t GetNumProbes(const Set& set, const typename Set::key_type& key) { size_t num_probes = 0; size_t hashval = set.hash(key); auto seq = set.probe(hashval); @@ -5345,8 +4815,7 @@ struct HashtableDebugAccess -struct has_member_type_EmbeddedSet : std::false_type -{ -}; +struct has_member_type_EmbeddedSet : std::false_type {}; template -struct has_member_type_EmbeddedSet> : std::true_type -{ -}; +struct has_member_type_EmbeddedSet> : std::true_type {}; template -struct HashtableDebugAccess::value>> -{ +struct HashtableDebugAccess::value>> { using Traits = typename Set::PolicyTraits; using Slot = typename Traits::slot_type; using EmbeddedSet = typename Set::EmbeddedSet; - static size_t GetNumProbes(const Set& set, const typename Set::key_type& key) - { + static size_t GetNumProbes(const Set& set, const typename Set::key_type& key) { size_t hashval = set.hash(key); auto& inner = set.sets_[set.subidx(hashval)]; auto& inner_set = inner.set_; @@ -5427,8 +4889,7 @@ struct HashtableDebugAccess // default values in phmap_fwd_decl.hpp -class flat_hash_set : public gtl::priv::raw_hash_set, Hash, Eq, Alloc> -{ +class flat_hash_set : public gtl::priv::raw_hash_set, Hash, Eq, Alloc> { using Base = typename flat_hash_set::raw_hash_set; public: @@ -5489,8 +4950,7 @@ class flat_hash_set : public gtl::priv::raw_hash_set // default values in // phmap_fwd_decl.hpp -class flat_hash_map : public gtl::priv::raw_hash_map, Hash, Eq, Alloc> -{ +class flat_hash_map : public gtl::priv::raw_hash_map, Hash, Eq, Alloc> { using Base = typename flat_hash_map::raw_hash_map; @@ -5552,8 +5012,7 @@ class flat_hash_map : public gtl::priv::raw_hash_map // default values in phmap_fwd_decl.hpp -class node_hash_set : public gtl::priv::raw_hash_set, Hash, Eq, Alloc> -{ +class node_hash_set : public gtl::priv::raw_hash_set, Hash, Eq, Alloc> { using Base = typename node_hash_set::raw_hash_set; public: @@ -5616,8 +5075,7 @@ class node_hash_set : public gtl::priv::raw_hash_set // default values in // phmap_fwd_decl.hpp -class node_hash_map : public gtl::priv::raw_hash_map, Hash, Eq, Alloc> -{ +class node_hash_map : public gtl::priv::raw_hash_map, Hash, Eq, Alloc> { using Base = typename node_hash_map::raw_hash_map; public: @@ -5670,9 +5128,14 @@ class node_hash_map : public gtl::priv::raw_hash_map // default values in phmap_fwd_decl.hpp class parallel_flat_hash_set - : public gtl::priv:: - parallel_hash_set, Hash, Eq, Alloc> -{ + : public gtl::priv::parallel_hash_set, + Hash, + Eq, + Alloc> { using Base = typename parallel_flat_hash_set::parallel_hash_set; public: @@ -5729,8 +5192,7 @@ class parallel_flat_hash_map gtl::priv::FlatHashMapPolicy, Hash, Eq, - Alloc> -{ + Alloc> { using Base = typename parallel_flat_hash_map::parallel_hash_map; public: @@ -5785,9 +5247,14 @@ class parallel_flat_hash_map // ----------------------------------------------------------------------------- template class parallel_node_hash_set - : public gtl::priv:: - parallel_hash_set, Hash, Eq, Alloc> -{ + : public gtl::priv::parallel_hash_set, + Hash, + Eq, + Alloc> { using Base = typename parallel_node_hash_set::parallel_hash_set; public: @@ -5846,8 +5313,7 @@ class parallel_node_hash_map gtl::priv::NodeHashMapPolicy, Hash, Eq, - Alloc> -{ + Alloc> { using Base = typename parallel_node_hash_map::parallel_hash_map; public: @@ -5904,8 +5370,7 @@ class parallel_node_hash_map namespace gtl { namespace priv { template -std::size_t erase_if(C& c, Pred pred) -{ +std::size_t erase_if(C& c, Pred pred) { auto old_size = c.size(); for (auto i = c.begin(), last = c.end(); i != last;) { if (pred(*i)) { @@ -5920,51 +5385,43 @@ std::size_t erase_if(C& c, Pred pred) // ======== erase_if for gtl set containers ================================== template -std::size_t erase_if(gtl::flat_hash_set& c, Pred pred) -{ +std::size_t erase_if(gtl::flat_hash_set& c, Pred pred) { return gtl::priv::erase_if(c, std::move(pred)); } template -std::size_t erase_if(gtl::node_hash_set& c, Pred pred) -{ +std::size_t erase_if(gtl::node_hash_set& c, Pred pred) { return gtl::priv::erase_if(c, std::move(pred)); } template -std::size_t erase_if(gtl::parallel_flat_hash_set& c, Pred pred) -{ +std::size_t erase_if(gtl::parallel_flat_hash_set& c, Pred pred) { return gtl::priv::erase_if(c, std::move(pred)); } template -std::size_t erase_if(gtl::parallel_node_hash_set& c, Pred pred) -{ +std::size_t erase_if(gtl::parallel_node_hash_set& c, Pred pred) { return gtl::priv::erase_if(c, std::move(pred)); } // ======== erase_if for gtl map containers ================================== template -std::size_t erase_if(gtl::flat_hash_map& c, Pred pred) -{ +std::size_t erase_if(gtl::flat_hash_map& c, Pred pred) { return gtl::priv::erase_if(c, std::move(pred)); } template -std::size_t erase_if(gtl::node_hash_map& c, Pred pred) -{ +std::size_t erase_if(gtl::node_hash_map& c, Pred pred) { return gtl::priv::erase_if(c, std::move(pred)); } template -std::size_t erase_if(gtl::parallel_flat_hash_map& c, Pred pred) -{ +std::size_t erase_if(gtl::parallel_flat_hash_map& c, Pred pred) { return gtl::priv::erase_if(c, std::move(pred)); } template -std::size_t erase_if(gtl::parallel_node_hash_map& c, Pred pred) -{ +std::size_t erase_if(gtl::parallel_node_hash_map& c, Pred pred) { return gtl::priv::erase_if(c, std::move(pred)); } diff --git a/include/gtl/phmap_dump.hpp b/include/gtl/phmap_dump.hpp index ca9335c..32ce271 100644 --- a/include/gtl/phmap_dump.hpp +++ b/include/gtl/phmap_dump.hpp @@ -30,19 +30,14 @@ namespace type_traits_internal { #if defined(__GLIBCXX__) && __GLIBCXX__ < 20150801 template -struct IsTriviallyCopyable : public std::integral_constant -{ -}; +struct IsTriviallyCopyable : public std::integral_constant {}; #else template -struct IsTriviallyCopyable : public std::is_trivially_copyable -{ -}; +struct IsTriviallyCopyable : public std::is_trivially_copyable {}; #endif template -struct IsTriviallyCopyable> -{ +struct IsTriviallyCopyable> { static constexpr bool value = IsTriviallyCopyable::value && IsTriviallyCopyable::value; }; } @@ -52,15 +47,14 @@ namespace priv { #if !defined(GTL_NON_DETERMINISTIC) && !defined(GTL_DISABLE_DUMP) static constexpr size_t s_version_base = std::numeric_limits::max() - 32; -static constexpr size_t s_version = s_version_base + 1; +static constexpr size_t s_version = s_version_base + 1; // ------------------------------------------------------------------------ // dump/load for raw_hash_set // ------------------------------------------------------------------------ template template -bool raw_hash_set::phmap_dump(OutputArchive& ar) const -{ +bool raw_hash_set::phmap_dump(OutputArchive& ar) const { static_assert(type_traits_internal::IsTriviallyCopyable::value, "value_type should be trivially copyable"); @@ -77,8 +71,7 @@ bool raw_hash_set::phmap_dump(OutputArchive& ar) const template template -bool raw_hash_set::phmap_load(InputArchive& ar) -{ +bool raw_hash_set::phmap_load(InputArchive& ar) { static_assert(type_traits_internal::IsTriviallyCopyable::value, "value_type should be trivially copyable"); raw_hash_set().swap(*this); // clear any existing content @@ -87,7 +80,7 @@ bool raw_hash_set::phmap_load(InputArchive& ar) if (version <= s_version_base) { // we didn't store the version, version actually contains the size // we didn't store growth_left either - size_ = version; + size_ = version; version = 0; } else { ar.loadBinary(&size_, sizeof(size_t)); @@ -121,8 +114,7 @@ template template -bool parallel_hash_set::phmap_dump(OutputArchive& ar) const -{ +bool parallel_hash_set::phmap_dump(OutputArchive& ar) const { static_assert(type_traits_internal::IsTriviallyCopyable::value, "value_type should be trivially copyable"); @@ -149,8 +141,7 @@ template template -bool parallel_hash_set::phmap_load(InputArchive& ar) -{ +bool parallel_hash_set::phmap_load(InputArchive& ar) { static_assert(type_traits_internal::IsTriviallyCopyable::value, "value_type should be trivially copyable"); @@ -183,30 +174,25 @@ bool parallel_hash_set::phmap // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ -class BinaryOutputArchive -{ +class BinaryOutputArchive { public: - BinaryOutputArchive(const char* file_path) - { + BinaryOutputArchive(const char* file_path) { ofs_.open(file_path, std::ofstream::out | std::ofstream::trunc | std::ofstream::binary); } - bool saveBinary(const void* p, size_t sz) - { + bool saveBinary(const void* p, size_t sz) { ofs_.write(reinterpret_cast(p), sz); return true; } template - typename std::enable_if::value, bool>::type saveBinary(const V& v) - { + typename std::enable_if::value, bool>::type saveBinary(const V& v) { ofs_.write(reinterpret_cast(&v), sizeof(V)); return true; } template - auto saveBinary(const Map& v) -> decltype(v.phmap_dump(*this), bool()) - { + auto saveBinary(const Map& v) -> decltype(v.phmap_dump(*this), bool()) { return v.phmap_dump(*this); } @@ -214,27 +200,23 @@ class BinaryOutputArchive std::ofstream ofs_; }; -class BinaryInputArchive -{ +class BinaryInputArchive { public: BinaryInputArchive(const char* file_path) { ifs_.open(file_path, std::ofstream::in | std::ofstream::binary); } - bool loadBinary(void* p, size_t sz) - { + bool loadBinary(void* p, size_t sz) { ifs_.read(reinterpret_cast(p), sz); return true; } template - typename std::enable_if::value, bool>::type loadBinary(V* v) - { + typename std::enable_if::value, bool>::type loadBinary(V* v) { ifs_.read(reinterpret_cast(v), sizeof(V)); return true; } template - auto loadBinary(Map* v) -> decltype(v->phmap_load(*this), bool()) - { + auto loadBinary(Map* v) -> decltype(v->phmap_load(*this), bool()) { return v->phmap_load(*this); } @@ -255,16 +237,14 @@ namespace cereal { template void save(typename std::enable_if::value && PhmapTrivCopyable::value, typename cereal::BinaryOutputArchive>::type& ar, - gtl::flat_hash_map const& hmap) -{ + gtl::flat_hash_map const& hmap) { hmap.phmap_dump(ar); } template void load(typename std::enable_if::value && PhmapTrivCopyable::value, typename cereal::BinaryInputArchive>::type& ar, - gtl::flat_hash_map& hmap) -{ + gtl::flat_hash_map& hmap) { hmap.phmap_load(ar); } @@ -273,16 +253,14 @@ void load(typename std::enable_if::value && PhmapTrivCopyab template void save(typename std::enable_if::value && PhmapTrivCopyable::value, typename cereal::BinaryOutputArchive>::type& ar, - gtl::parallel_flat_hash_map const& hmap) -{ + gtl::parallel_flat_hash_map const& hmap) { hmap.phmap_dump(ar); } template void load(typename std::enable_if::value && PhmapTrivCopyable::value, typename cereal::BinaryInputArchive>::type& ar, - gtl::parallel_flat_hash_map& hmap) -{ + gtl::parallel_flat_hash_map& hmap) { hmap.phmap_load(ar); } @@ -290,15 +268,13 @@ void load(typename std::enable_if::value && PhmapTrivCopyab // ----------------------------------------------------------- template void save(typename std::enable_if::value, typename cereal::BinaryOutputArchive>::type& ar, - gtl::flat_hash_set const& hset) -{ + gtl::flat_hash_set const& hset) { hset.phmap_dump(ar); } template void load(typename std::enable_if::value, typename cereal::BinaryInputArchive>::type& ar, - gtl::flat_hash_set& hset) -{ + gtl::flat_hash_set& hset) { hset.phmap_load(ar); } @@ -306,15 +282,13 @@ void load(typename std::enable_if::value, typename cereal:: // -------------------------------------------------------------------- template void save(typename std::enable_if::value, typename cereal::BinaryOutputArchive>::type& ar, - gtl::parallel_flat_hash_set const& hset) -{ + gtl::parallel_flat_hash_set const& hset) { hset.phmap_dump(ar); } template void load(typename std::enable_if::value, typename cereal::BinaryInputArchive>::type& ar, - gtl::parallel_flat_hash_set& hset) -{ + gtl::parallel_flat_hash_set& hset) { hset.phmap_load(ar); } } diff --git a/include/gtl/phmap_fwd_decl.hpp b/include/gtl/phmap_fwd_decl.hpp index b478730..a2acb05 100644 --- a/include/gtl/phmap_fwd_decl.hpp +++ b/include/gtl/phmap_fwd_decl.hpp @@ -54,8 +54,7 @@ namespace priv { // The hash of an object of type T is computed by using gtl::Hash. template -struct HashEq -{ +struct HashEq { using Hash = gtl::Hash; using Eq = gtl::EqualTo; }; @@ -74,8 +73,7 @@ using Allocator = typename gtl::Allocator; template using Pair = typename gtl::Pair; -struct empty -{}; +struct empty {}; } // namespace priv diff --git a/include/gtl/phmap_utils.hpp b/include/gtl/phmap_utils.hpp index 922de43..b0f21f9 100644 --- a/include/gtl/phmap_utils.hpp +++ b/include/gtl/phmap_utils.hpp @@ -49,16 +49,13 @@ namespace gtl { // --------------------------------------------------------------- // --------------------------------------------------------------- template -struct phmap_mix -{ +struct phmap_mix { inline size_t operator()(size_t) const; }; template<> -struct phmap_mix<4> -{ - inline size_t operator()(size_t a) const - { +struct phmap_mix<4> { + inline size_t operator()(size_t a) const { static constexpr uint64_t kmul = 0xcc9e2d51UL; // static constexpr uint64_t kmul = 0x3B9ACB93UL; // [greg] my own random prime uint64_t l = a * kmul; @@ -68,11 +65,9 @@ struct phmap_mix<4> #if defined(GTL_HAS_UMUL128) template<> -struct phmap_mix<8> -{ +struct phmap_mix<8> { // Very fast mixing (similar to Abseil) - inline size_t operator()(size_t a) const - { + inline size_t operator()(size_t a) const { static constexpr uint64_t k = 0xde5fb9d2630458e9ULL; // static constexpr uint64_t k = 0x7C9D0BF0567102A5ULL; // [greg] my own random prime uint64_t h; @@ -82,11 +77,9 @@ struct phmap_mix<8> }; #else template<> -struct phmap_mix<8> -{ - inline size_t operator()(size_t a) const - { - a = (~a) + (a << 21); // a = (a << 21) - a - 1; +struct phmap_mix<8> { + inline size_t operator()(size_t a) const { + a = (~a) + (a << 21); // a = (a << 21) - a - 1; a = a ^ (a >> 24); a = (a + (a << 3)) + (a << 8); // a * 265 a = a ^ (a >> 14); @@ -100,20 +93,17 @@ struct phmap_mix<8> // -------------------------------------------- template -struct fold_if_needed -{ +struct fold_if_needed { inline size_t operator()(uint64_t) const; }; template<> -struct fold_if_needed<4> -{ +struct fold_if_needed<4> { inline size_t operator()(uint64_t a) const { return static_cast(a ^ (a >> 32)); } }; template<> -struct fold_if_needed<8> -{ +struct fold_if_needed<8> { inline size_t operator()(uint64_t a) const { return static_cast(a); } }; @@ -121,8 +111,7 @@ struct fold_if_needed<8> // see if class T has a hash_value() friend method // --------------------------------------------------------------- template -struct has_hash_value -{ +struct has_hash_value { private: typedef std::true_type yes; typedef std::false_type no; @@ -145,17 +134,14 @@ using Hash = ::absl::Hash; // gtl::Hash // --------------------------------------------------------------- template -struct Hash -{ +struct Hash { template::value, int>::type = 0> - size_t _hash(const T& val) const - { + size_t _hash(const T& val) const { return hash_value(val); } template::value, int>::type = 0> - size_t _hash(const T& val) const - { + size_t _hash(const T& val) const { return std::hash()(val); } @@ -163,88 +149,73 @@ struct Hash }; template -struct gtl_unary_function -{ +struct gtl_unary_function { typedef ArgumentType argument_type; typedef ResultType result_type; }; template<> -struct Hash : public gtl_unary_function -{ +struct Hash : public gtl_unary_function { inline size_t operator()(bool val) const noexcept { return static_cast(val); } }; template<> -struct Hash : public gtl_unary_function -{ +struct Hash : public gtl_unary_function { inline size_t operator()(char val) const noexcept { return static_cast(val); } }; template<> -struct Hash : public gtl_unary_function -{ +struct Hash : public gtl_unary_function { inline size_t operator()(signed char val) const noexcept { return static_cast(val); } }; template<> -struct Hash : public gtl_unary_function -{ +struct Hash : public gtl_unary_function { inline size_t operator()(unsigned char val) const noexcept { return static_cast(val); } }; #ifdef GTL_HAS_NATIVE_WCHAR_T template<> -struct Hash : public gtl_unary_function -{ +struct Hash : public gtl_unary_function { inline size_t operator()(wchar_t val) const noexcept { return static_cast(val); } }; #endif template<> -struct Hash : public gtl_unary_function -{ +struct Hash : public gtl_unary_function { inline size_t operator()(int16_t val) const noexcept { return static_cast(val); } }; template<> -struct Hash : public gtl_unary_function -{ +struct Hash : public gtl_unary_function { inline size_t operator()(uint16_t val) const noexcept { return static_cast(val); } }; template<> -struct Hash : public gtl_unary_function -{ +struct Hash : public gtl_unary_function { inline size_t operator()(int32_t val) const noexcept { return static_cast(val); } }; template<> -struct Hash : public gtl_unary_function -{ +struct Hash : public gtl_unary_function { inline size_t operator()(uint32_t val) const noexcept { return static_cast(val); } }; template<> -struct Hash : public gtl_unary_function -{ - inline size_t operator()(int64_t val) const noexcept - { +struct Hash : public gtl_unary_function { + inline size_t operator()(int64_t val) const noexcept { return fold_if_needed()(static_cast(val)); } }; template<> -struct Hash : public gtl_unary_function -{ +struct Hash : public gtl_unary_function { inline size_t operator()(uint64_t val) const noexcept { return fold_if_needed()(val); } }; template<> -struct Hash : public gtl_unary_function -{ - inline size_t operator()(float val) const noexcept - { +struct Hash : public gtl_unary_function { + inline size_t operator()(float val) const noexcept { // -0.0 and 0.0 should return same hash uint32_t as_int; std::memcpy(&as_int, &val, sizeof(as_int)); @@ -253,10 +224,8 @@ struct Hash : public gtl_unary_function }; template<> -struct Hash : public gtl_unary_function -{ - inline size_t operator()(double val) const noexcept - { +struct Hash : public gtl_unary_function { + inline size_t operator()(double val) const noexcept { // -0.0 and 0.0 should return same hash uint64_t as_int; std::memcpy(&as_int, &val, sizeof(as_int)); @@ -273,16 +242,13 @@ struct Hash : public gtl_unary_function #endif template -struct Combiner -{ +struct Combiner { H operator()(H seed, size_t value); }; template -struct Combiner -{ - H operator()(H h1, size_t k1) - { +struct Combiner { + H operator()(H h1, size_t k1) { // Copyright 2005-2014 Daniel James. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -302,10 +268,8 @@ struct Combiner }; template -struct Combiner -{ - H operator()(H h, size_t k) - { +struct Combiner { + H operator()(H h, size_t k) { // Copyright 2005-2014 Daniel James. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -330,8 +294,7 @@ struct Combiner // define HashState to combine member hashes... see example below // ----------------------------------------------------------------------------- template -class HashStateBase -{ +class HashStateBase { public: template static H combine(H state, const T& value, const Ts&... values); @@ -341,8 +304,7 @@ class HashStateBase template template -H HashStateBase::combine(H seed, const T& v, const Ts&... vs) -{ +H HashStateBase::combine(H seed, const T& v, const Ts&... vs) { return HashStateBase::combine(Combiner()(seed, gtl::Hash()(v)), vs...); } @@ -355,10 +317,8 @@ using HashState = HashStateBase; // define Hash for std::pair // ------------------------- template -struct Hash> -{ - size_t operator()(std::pair const& p) const noexcept - { +struct Hash> { + size_t operator()(std::pair const& p) const noexcept { return gtl::HashState().combine(gtl::Hash()(p.first), p.second); } }; @@ -366,10 +326,8 @@ struct Hash> // define Hash for std::tuple // -------------------------- template -struct Hash> -{ - size_t operator()(std::tuple const& t) const noexcept - { +struct Hash> { + size_t operator()(std::tuple const& t) const noexcept { size_t seed = 0; return _hash_helper(seed, t); } @@ -377,15 +335,13 @@ struct Hash> private: template typename std::enable_if::value, size_t>::type _hash_helper(size_t seed, - const TUP&) const noexcept - { + const TUP&) const noexcept { return seed; } template typename std::enable_if < - I::value, size_t>::type _hash_helper(size_t seed, const TUP& t) const noexcept - { + I::value, size_t>::type _hash_helper(size_t seed, const TUP& t) const noexcept { const auto& el = std::get(t); using el_type = typename std::remove_cv::type>::type; seed = Combiner()(seed, gtl::Hash()(el)); diff --git a/include/gtl/soa.hpp b/include/gtl/soa.hpp index 025e2b9..0e9fe57 100644 --- a/include/gtl/soa.hpp +++ b/include/gtl/soa.hpp @@ -43,8 +43,7 @@ namespace gtl { template -class soa -{ +class soa { public: using storage_type = std::tuple...>; @@ -55,14 +54,12 @@ class soa using col_type = typename nth_col_type::value_type; template - const auto& get_column() const - { + const auto& get_column() const { return std::get(data_); } template - nth_col_type& get_column() - { + nth_col_type& get_column() { return std::get(data_); } @@ -71,36 +68,42 @@ class soa bool empty() const { return get_column<0>().empty(); } template - void insert(Xs... xs) - { + void insert(Xs... xs) { insert_impl(std::index_sequence_for{}, std::forward_as_tuple(xs...)); } - auto operator[](size_t idx) const { return std::apply([=](auto& ...x) { return std::tie(x[idx]...); }, data_); } + auto operator[](size_t idx) const { + return std::apply([=](auto&... x) { return std::tie(x[idx]...); }, data_); + } - auto operator[](size_t idx) { return std::apply([=](auto& ...x) { return std::tie(x[idx]...); }, data_); } + auto operator[](size_t idx) { + return std::apply([=](auto&... x) { return std::tie(x[idx]...); }, data_); + } template - auto view(size_t row) const - { + auto view(size_t row) const { return get_row_impl(std::integer_sequence{}, row); } template - auto view(size_t row) - { + auto view(size_t row) { return get_row_impl(std::integer_sequence{}, row); } - void clear() { std::apply([](auto& ...x) { (x.clear(), ...); }, data_); } + void clear() { + std::apply([](auto&... x) { (x.clear(), ...); }, data_); + } - void resize(size_t sz) { std::apply([=](auto& ...x) { (x.resize(sz), ...); }, data_); } + void resize(size_t sz) { + std::apply([=](auto&... x) { (x.resize(sz), ...); }, data_); + } - void reserve(size_t sz) { std::apply([=](auto& ...x) { (x.reserve(sz), ...); }, data_); } + void reserve(size_t sz) { + std::apply([=](auto&... x) { (x.reserve(sz), ...); }, data_); + } template - void sort_by_field(C&& comp) - { + void sort_by_field(C&& comp) { size_t num_elems = size(); thread_local sort_data sort_tmp; // thread_local makes it static @@ -118,17 +121,15 @@ class soa } template - void sort_by_field() - { + void sort_by_field() { sort_by_field([](auto&& a, auto&& b) { return a < b; }); } - void print(std::basic_ostream& ss) const - { + void print(std::basic_ostream& ss) const { size_t num_elems = size(); ss << "soa {\n"; for (size_t i = 0; i < num_elems; ++i) { - const auto t = (*this)[i]; + const auto t = (*this)[i]; ss << "\t"; print(ss, t, std::make_index_sequence()); ss << '\n'; @@ -137,45 +138,38 @@ class soa } private: - struct sort_data - { - std::vector o; // sort order - bit_vector done; - void resize(size_t sz) - { + struct sort_data { + std::vector o; // sort order + bit_vector done; + void resize(size_t sz) { o.resize(sz); done.resize(sz); } }; template - static void print(std::basic_ostream& ss, const TupType& _tup, std::index_sequence) - { + static void print(std::basic_ostream& ss, const TupType& _tup, std::index_sequence) { // c++17 unary left fold, of the form `... op pack`, where `op` is the comma operator (..., (ss << (I == 0 ? "" : ", ") << std::get(_tup))); } template - void insert_impl(std::integer_sequence, T t) - { + void insert_impl(std::integer_sequence, T t) { ((get_column().push_back(std::get(t))), ...); } template - auto get_row_impl(std::integer_sequence, size_t row) const - { + auto get_row_impl(std::integer_sequence, size_t row) const { return std::tie(get_column()[row]...); } template - auto get_row_impl(std::integer_sequence, size_t row) - { + auto get_row_impl(std::integer_sequence, size_t row) { return std::tie(get_column()[row]...); } template - void sort_by_reference_impl(sort_data& sort_tmp, std::integer_sequence) - { + void sort_by_reference_impl(sort_data& sort_tmp, std::integer_sequence) { ((sort_col_by_reference(sort_tmp, std::integral_constant{})), ...); } @@ -183,8 +177,7 @@ class soa // so if o[0] = 5, it means that c[5] should go to c[0]. // c contains the values to be reordered according to o. template - void reorder(C& c, const std::vector& o, bit_vector& done) - { + void reorder(C& c, const std::vector& o, bit_vector& done) { size_t num_elems = o.size(); done.reset(); @@ -209,8 +202,7 @@ class soa } template - void sort_col_by_reference(sort_data& sort_tmp, std::integral_constant) - { + void sort_col_by_reference(sort_data& sort_tmp, std::integral_constant) { auto& col = std::get(data_); reorder(col, sort_tmp.o, sort_tmp.done); } @@ -219,8 +211,7 @@ class soa }; template -std::ostream& operator<<(std::ostream& cout, const gtl::soa& soa) -{ +std::ostream& operator<<(std::ostream& cout, const gtl::soa& soa) { soa.print(cout); return cout; } diff --git a/include/gtl/stopwatch.hpp b/include/gtl/stopwatch.hpp index c2a611c..16487cf 100644 --- a/include/gtl/stopwatch.hpp +++ b/include/gtl/stopwatch.hpp @@ -16,11 +16,9 @@ namespace gtl { // ------------------------------------------------------------------------------- template -class stopwatch -{ +class stopwatch { public: - stopwatch(bool do_start = true) - { + stopwatch(bool do_start = true) { if (do_start) start(); } @@ -37,8 +35,7 @@ class stopwatch using point = std::chrono::time_point; template - static T get_diff(const point& start, const point& end) - { + static T get_diff(const point& start, const point& end) { using duration_t = std::chrono::duration; return std::chrono::duration_cast(end - start).count(); } @@ -49,12 +46,10 @@ class stopwatch // ------------------------------------------------------------------------------- template -class start_snap -{ +class start_snap { public: start_snap(StopWatch& sw) - : _sw(sw) - { + : _sw(sw) { _sw.start(); } ~start_snap() { _sw.snap(); } diff --git a/include/gtl/utils.hpp b/include/gtl/utils.hpp index a8dc1eb..e98df4c 100644 --- a/include/gtl/utils.hpp +++ b/include/gtl/utils.hpp @@ -26,19 +26,20 @@ namespace gtl { // scoped_set_unset rollback(...); // good // --------------------------------------------------------------------------- template -class scoped_set_unset -{ +class scoped_set_unset { public: template scoped_set_unset(Set&& set, Unset&& unset, bool do_it = true) : do_it_(do_it) - , unset_(std::move(unset)) - { + , unset_(std::move(unset)) { if (do_it_) std::forward(set)(); } - ~scoped_set_unset() { if (do_it_) unset_(); } + ~scoped_set_unset() { + if (do_it_) + unset_(); + } void dismiss() noexcept { do_it_ = false; } @@ -62,16 +63,16 @@ class scoped_set_unset // scoped_guard rollback(...); // good // --------------------------------------------------------------------------- template -class scoped_guard -{ +class scoped_guard { public: scoped_guard(F&& unset, bool do_it = true) noexcept(std::is_nothrow_move_constructible_v) : do_it_(do_it) - , unset_(std::move(unset)) - { - } + , unset_(std::move(unset)) {} - ~scoped_guard() { if (do_it_) unset_(); } + ~scoped_guard() { + if (do_it_) + unset_(); + } void dismiss() noexcept { do_it_ = false; } @@ -96,8 +97,7 @@ class scoped_guard // scoped_set_value rollback(retries, 7); // good // --------------------------------------------------------------------------- template -class scoped_set_value -{ +class scoped_set_value { public: template scoped_set_value(T& var, V&& val, bool do_it = true) noexcept(std::is_nothrow_copy_constructible_v && @@ -105,15 +105,17 @@ class scoped_set_value std::is_nothrow_move_assignable_v && std::is_nothrow_copy_assignable_v) : v_(var) - , do_it_(do_it) - { + , do_it_(do_it) { if (do_it_) { old_value_ = std::move(v_); v_ = std::forward(val); } } - ~scoped_set_value() { if (do_it_) v_ = std::move(old_value_); } + ~scoped_set_value() { + if (do_it_) + v_ = std::move(old_value_); + } void dismiss() noexcept { do_it_ = false; } @@ -130,8 +132,7 @@ class scoped_set_value // assigns val to var, and returns true if the value changed // --------------------------------------------------------------------------- template -bool change(T& var, V&& val) noexcept(std::is_nothrow_move_assignable_v && std::is_nothrow_copy_assignable_v) -{ +bool change(T& var, V&& val) noexcept(std::is_nothrow_move_assignable_v && std::is_nothrow_copy_assignable_v) { if (var != val) { var = std::forward(val); return true; @@ -143,8 +144,7 @@ bool change(T& var, V&& val) noexcept(std::is_nothrow_move_assignable_v && st // assigns val to var, and returns the previous value // --------------------------------------------------------------------------- template -T replace(T& var, V&& val) noexcept(std::is_nothrow_move_assignable_v && std::is_nothrow_copy_assignable_v) -{ +T replace(T& var, V&& val) noexcept(std::is_nothrow_move_assignable_v && std::is_nothrow_copy_assignable_v) { T old = std::move(var); var = std::forward(val); return old; @@ -153,23 +153,18 @@ T replace(T& var, V&& val) noexcept(std::is_nothrow_move_assignable_v && std: // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- template -struct always_false : std::false_type -{ -}; +struct always_false : std::false_type {}; // --------------------------------------------------------------------------- // A baseclass to keep track of modifications. // Change member `x_` using `set_with_ts` // --------------------------------------------------------------------------- -class timestamp -{ +class timestamp { public: timestamp() noexcept { stamp_ = ++clock_; } timestamp(uint64_t stamp) noexcept - : stamp_(stamp) - { - } + : stamp_(stamp) {} void touch() noexcept { stamp_ = ++clock_; } void touch(const timestamp& o) noexcept { stamp_ = o.stamp_; } @@ -186,8 +181,7 @@ class timestamp // returns most recent timestamp operator|(const timestamp& o) const noexcept { return stamp_ > o.stamp_ ? stamp_ : o.stamp_; } - timestamp& operator|=(const timestamp& o) noexcept - { + timestamp& operator|=(const timestamp& o) noexcept { *this = *this | o; return *this; } @@ -197,8 +191,7 @@ class timestamp timestamp get_timestamp() const noexcept { return *this; } template - bool set_with_ts(T& var, V&& val) - { + bool set_with_ts(T& var, V&& val) { if (gtl::change(var, std::forward(val))) { this->touch(); return true; @@ -215,25 +208,21 @@ class timestamp // A baseclass (using CRTP) for classes providing get_timestamp() // --------------------------------------------------------------------------- template -class provides_timestamp -{ +class provides_timestamp { public: template - bool is_newer_than(const TS& o) const - { + bool is_newer_than(const TS& o) const { return static_cast(this)->get_timestamp() > o.get_timestamp(); } template - bool is_older_than(const TS& o) const - { + bool is_older_than(const TS& o) const { return static_cast(this)->get_timestamp() < o.get_timestamp(); } // returns most recent template - timestamp operator|(const TS& o) const - { + timestamp operator|(const TS& o) const { return static_cast(this)->get_timestamp() | o.get_timestamp(); } }; diff --git a/include/gtl/vec_utils.hpp b/include/gtl/vec_utils.hpp index aee8afc..968e36b 100644 --- a/include/gtl/vec_utils.hpp +++ b/include/gtl/vec_utils.hpp @@ -34,8 +34,7 @@ concept VectorLike = requires(T v) { // returns a new vector which is the concatenation of the vectors passed as arguments // ---------------------------------------------------------------------------------- template -auto cat(Vs&&... vs) -{ +auto cat(Vs&&... vs) { std::common_type_t res; res.reserve((0 + ... + vs.size())); (..., (res.insert(res.end(), std::begin(std::forward(vs)), std::end(std::forward(vs))))); @@ -46,8 +45,7 @@ auto cat(Vs&&... vs) // implements python-like slicing for vectors, negative indices start from the end // ------------------------------------------------------------------------------- template -auto slice(V&& v, int first = 0, int last = -1, int stride = 1) -{ +auto slice(V&& v, int first = 0, int last = -1, int stride = 1) { std::remove_const_t> res; auto first_iter = (first >= 0 ? std::begin(std::forward(v)) + first : std::end(std::forward(v)) + (first + 1)); @@ -68,8 +66,7 @@ template class V> #ifndef _LIBCPP_VERSION // until this is available requires std::invocable #endif -auto map(F&& f, const V& v) -{ +auto map(F&& f, const V& v) { using result_type = std::invoke_result_t; V> res; res.reserve(v.size()); diff --git a/include/gtl/vector.hpp b/include/gtl/vector.hpp index b627b8e..26efda8 100644 --- a/include/gtl/vector.hpp +++ b/include/gtl/vector.hpp @@ -65,8 +65,7 @@ static constexpr size_t jemallocMinInPlaceExpandable = 4096; inline size_t goodMallocSize(size_t minSize) noexcept { return minSize; } -inline void* checkedMalloc(size_t size) -{ +inline void* checkedMalloc(size_t size) { void* p = malloc(size); if (!p) { throw std::bad_alloc(); @@ -97,16 +96,14 @@ inline void* thunk_return_nullptr() { return nullptr; } } // namespace detail template -class vector -{ +class vector { //=========================================================================== //--------------------------------------------------------------------------- // implementation private: typedef std::allocator_traits A; - struct Impl : public Allocator - { + struct Impl : public Allocator { // typedefs typedef typename A::pointer pointer; typedef typename A::size_type size_type; @@ -119,27 +116,20 @@ class vector : Allocator() , b_(nullptr) , e_(nullptr) - , z_(nullptr) - { - } + , z_(nullptr) {} /* implicit */ Impl(const Allocator& alloc) : Allocator(alloc) , b_(nullptr) , e_(nullptr) - , z_(nullptr) - { - } + , z_(nullptr) {} /* implicit */ Impl(Allocator&& alloc) : Allocator(std::move(alloc)) , b_(nullptr) , e_(nullptr) - , z_(nullptr) - { - } + , z_(nullptr) {} /* implicit */ Impl(size_type n, const Allocator& alloc = Allocator()) - : Allocator(alloc) - { + : Allocator(alloc) { init(n); } @@ -147,8 +137,7 @@ class vector : Allocator(std::move(other)) , b_(other.b_) , e_(other.e_) - , z_(other.z_) - { + , z_(other.z_) { other.b_ = other.e_ = other.z_ = nullptr; } @@ -157,8 +146,7 @@ class vector // allocation // note that 'allocate' and 'deallocate' are inherited from Allocator - T* D_allocate(size_type n) - { + T* D_allocate(size_type n) { if constexpr (usingStdAllocator) { return static_cast(checkedMalloc(n * sizeof(T))); } else { @@ -166,8 +154,7 @@ class vector } } - void D_deallocate(T* p, size_type n) noexcept - { + void D_deallocate(T* p, size_type n) noexcept { if constexpr (usingStdAllocator) { free(p); } else { @@ -176,16 +163,14 @@ class vector } // helpers - void swapData(Impl& other) - { + void swapData(Impl& other) { std::swap(b_, other.b_); std::swap(e_, other.e_); std::swap(z_, other.z_); } // data ops - inline void destroy() noexcept - { + inline void destroy() noexcept { if (b_) { // THIS DISPATCH CODE IS DUPLICATED IN vector::D_destroy_range_a. // It has been inlined here for speed. It calls the static vector @@ -200,8 +185,7 @@ class vector } } - void init(size_type n) - { + void init(size_type n) { if (UNLIKELY(n == 0)) { b_ = e_ = z_ = nullptr; } else { @@ -212,8 +196,7 @@ class vector } } - void set(pointer newB, size_type newSize, size_type newCap) - { + void set(pointer newB, size_type newSize, size_type newCap) { z_ = newB + newCap; e_ = newB + newSize; b_ = newB; @@ -221,22 +204,19 @@ class vector pointer data() const { return z_; } - void reset(size_type newCap) - { + void reset(size_type newCap) { destroy(); scoped_guard rollback([&] { init(0); }); init(newCap); rollback.dismiss(); } - void reset() - { // same as reset(0) + void reset() { // same as reset(0) destroy(); b_ = e_ = z_ = nullptr; } } impl_; - static void swap(Impl& a, Impl& b) - { + static void swap(Impl& a, Impl& b) { using std::swap; if constexpr (!usingStdAllocator) { swap(static_cast(a), static_cast(b)); @@ -291,8 +271,7 @@ class vector // that reason there are several different specializations of construct. template - void M_construct(U* p, Args&&... args) - { + void M_construct(U* p, Args&&... args) { if constexpr (usingStdAllocator) { new (p) U(std::forward(args)...); } else { @@ -301,22 +280,19 @@ class vector } template - static void S_construct(U* p, Args&&... args) - { + static void S_construct(U* p, Args&&... args) { new (p) U(std::forward(args)...); } template - static void S_construct_a(Allocator& a, U* p, Args&&... args) - { + static void S_construct_a(Allocator& a, U* p, Args&&... args) { std::allocator_traits::construct(a, p, std::forward(args)...); } // scalar optimization // TODO we can expand this optimization to: default copyable and assignable template::value>::type> - void M_construct(U* p, U arg) - { + void M_construct(U* p, U arg) { if constexpr (usingStdAllocator) { *p = arg; } else { @@ -325,21 +301,18 @@ class vector } template::value>::type> - static void S_construct(U* p, U arg) - { + static void S_construct(U* p, U arg) { *p = arg; } template::value>::type> - static void S_construct_a(Allocator& a, U* p, U arg) - { + static void S_construct_a(Allocator& a, U* p, U arg) { std::allocator_traits::construct(a, p, arg); } // const& optimization template::value>::type> - void M_construct(U* p, const U& value) - { + void M_construct(U* p, const U& value) { if constexpr (usingStdAllocator) { new (p) U(value); } else { @@ -348,22 +321,19 @@ class vector } template::value>::type> - static void S_construct(U* p, const U& value) - { + static void S_construct(U* p, const U& value) { new (p) U(value); } template::value>::type> - static void S_construct_a(Allocator& a, U* p, const U& value) - { + static void S_construct_a(Allocator& a, U* p, const U& value) { std::allocator_traits::construct(a, p, value); } //--------------------------------------------------------------------------- // destroy - void M_destroy(T* p) noexcept - { + void M_destroy(T* p) noexcept { if constexpr (usingStdAllocator) { if constexpr (!std::is_trivially_destructible_v) { p->~T(); @@ -381,16 +351,14 @@ class vector // destroy_range // wrappers - void M_destroy_range_e(T* pos) noexcept - { + void M_destroy_range_e(T* pos) noexcept { D_destroy_range_a(pos, impl_.e_); impl_.e_ = pos; } // dispatch // THIS DISPATCH CODE IS DUPLICATED IN IMPL. SEE IMPL FOR DETAILS. - void D_destroy_range_a(T* first, T* last) noexcept - { + void D_destroy_range_a(T* first, T* last) noexcept { if constexpr (usingStdAllocator) { S_destroy_range(first, last); } else { @@ -399,16 +367,14 @@ class vector } // allocator - static void S_destroy_range_a(Allocator& a, T* first, T* last) noexcept - { + static void S_destroy_range_a(Allocator& a, T* first, T* last) noexcept { for (; first != last; ++first) { std::allocator_traits::destroy(a, first); } } // optimized - static void S_destroy_range(T* first, T* last) noexcept - { + static void S_destroy_range(T* first, T* last) noexcept { if constexpr (!std::is_trivially_destructible_v) { for (; first != last; ++first) first->~T(); @@ -419,21 +385,18 @@ class vector // uninitialized_fill_n // wrappers - void M_uninitialized_fill_n_e(size_type sz) - { + void M_uninitialized_fill_n_e(size_type sz) { D_uninitialized_fill_n_a(impl_.e_, sz); impl_.e_ += sz; } - void M_uninitialized_fill_n_e(size_type sz, VT value) - { + void M_uninitialized_fill_n_e(size_type sz, VT value) { D_uninitialized_fill_n_a(impl_.e_, sz, value); impl_.e_ += sz; } // dispatch - void D_uninitialized_fill_n_a(T* dest, size_type sz) - { + void D_uninitialized_fill_n_a(T* dest, size_type sz) { if constexpr (usingStdAllocator) { S_uninitialized_fill_n(dest, sz); } else { @@ -441,8 +404,7 @@ class vector } } - void D_uninitialized_fill_n_a(T* dest, size_type sz, VT value) - { + void D_uninitialized_fill_n_a(T* dest, size_type sz, VT value) { if constexpr (usingStdAllocator) { S_uninitialized_fill_n(dest, sz, value); } else { @@ -452,8 +414,7 @@ class vector // allocator template - static void S_uninitialized_fill_n_a(Allocator& a, T* dest, size_type sz, Args&&... args) - { + static void S_uninitialized_fill_n_a(Allocator& a, T* dest, size_type sz, Args&&... args) { auto b = dest; auto e = dest + sz; scoped_guard rollback([&] { S_destroy_range_a(a, dest, b); }); @@ -464,8 +425,7 @@ class vector } // optimized - static void S_uninitialized_fill_n(T* dest, size_type n) - { + static void S_uninitialized_fill_n(T* dest, size_type n) { if constexpr (!std::is_class_v) { if (LIKELY(n != 0)) { std::memset((void*)dest, 0, sizeof(T) * n); @@ -486,8 +446,7 @@ class vector } } - static void S_uninitialized_fill_n(T* dest, size_type n, const T& value) - { + static void S_uninitialized_fill_n(T* dest, size_type n, const T& value) { auto b = dest; auto e = dest + n; scoped_guard rollback([&] { S_destroy_range(dest, b); }); @@ -505,23 +464,20 @@ class vector // wrappers template - void M_uninitialized_copy_e(It first, It last) - { + void M_uninitialized_copy_e(It first, It last) { D_uninitialized_copy_a(impl_.e_, first, last); impl_.e_ += std::distance(first, last); } template - void M_uninitialized_move_e(It first, It last) - { + void M_uninitialized_move_e(It first, It last) { D_uninitialized_move_a(impl_.e_, first, last); impl_.e_ += std::distance(first, last); } // dispatch template - void D_uninitialized_copy_a(T* dest, It first, It last) - { + void D_uninitialized_copy_a(T* dest, It first, It last) { if constexpr (usingStdAllocator) { if constexpr (std::is_trivially_copyable_v) { S_uninitialized_copy_bits(dest, first, last); @@ -534,15 +490,13 @@ class vector } template - void D_uninitialized_move_a(T* dest, It first, It last) - { + void D_uninitialized_move_a(T* dest, It first, It last) { D_uninitialized_copy_a(dest, std::make_move_iterator(first), std::make_move_iterator(last)); } // allocator template - static void S_uninitialized_copy_a(Allocator& a, T* dest, It first, It last) - { + static void S_uninitialized_copy_a(Allocator& a, T* dest, It first, It last) { auto b = dest; scoped_guard rollback([&] { S_destroy_range_a(a, dest, b); }); for (; first != last; ++first, ++b) { @@ -553,8 +507,7 @@ class vector // optimized template - static void S_uninitialized_copy(T* dest, It first, It last) - { + static void S_uninitialized_copy(T* dest, It first, It last) { auto b = dest; scoped_guard rollback([&] { S_destroy_range(dest, b); }); for (; first != last; ++first, ++b) { @@ -563,15 +516,13 @@ class vector rollback.dismiss(); } - static void S_uninitialized_copy_bits(T* dest, const T* first, const T* last) - { + static void S_uninitialized_copy_bits(T* dest, const T* first, const T* last) { if (last != first) { std::memcpy((void*)dest, (const void*)first, (last - first) * sizeof(T)); } } - static void S_uninitialized_copy_bits(T* dest, std::move_iterator first, std::move_iterator last) - { + static void S_uninitialized_copy_bits(T* dest, std::move_iterator first, std::move_iterator last) { T* bFirst = first.base(); T* bLast = last.base(); if (bLast != bFirst) { @@ -580,8 +531,7 @@ class vector } template - static void S_uninitialized_copy_bits(T* dest, It first, It last) - { + static void S_uninitialized_copy_bits(T* dest, It first, It last) { S_uninitialized_copy(dest, first, last); } @@ -593,8 +543,7 @@ class vector // wholly by vector itself. template - static It S_copy_n(T* dest, It first, size_type n) - { + static It S_copy_n(T* dest, It first, size_type n) { auto e = dest + n; for (; dest != e; ++dest, ++first) { *dest = *first; @@ -602,8 +551,7 @@ class vector return first; } - static const T* S_copy_n(T* dest, const T* first, size_type n) - { + static const T* S_copy_n(T* dest, const T* first, size_type n) { if constexpr (std::is_trivially_copyable_v) { std::memcpy((void*)dest, (const void*)first, n * sizeof(T)); return first + n; @@ -612,8 +560,7 @@ class vector } } - static std::move_iterator S_copy_n(T* dest, std::move_iterator mIt, size_type n) - { + static std::move_iterator S_copy_n(T* dest, std::move_iterator mIt, size_type n) { if constexpr (std::is_trivially_copyable_v) { T* first = mIt.base(); std::memcpy((void*)dest, (void*)first, n * sizeof(T)); @@ -663,8 +610,7 @@ class vector // move, which is required to leave the source in a valid state. // wrappers - void M_relocate(T* newB) - { + void M_relocate(T* newB) { relocate_move(newB, impl_.b_, impl_.e_); relocate_done(newB, impl_.b_, impl_.e_); } @@ -677,36 +623,30 @@ class vector relocate_use_move; // move - void relocate_move(T* dest, T* first, T* last) - { + void relocate_move(T* dest, T* first, T* last) { relocate_move_or_memcpy(dest, first, last, relocate_use_memcpy()); } - void relocate_move_or_memcpy(T* dest, T* first, T* last, std::true_type) - { + void relocate_move_or_memcpy(T* dest, T* first, T* last, std::true_type) { if (first != nullptr) { std::memcpy((void*)dest, (void*)first, (last - first) * sizeof(T)); } } - void relocate_move_or_memcpy(T* dest, T* first, T* last, std::false_type) - { + void relocate_move_or_memcpy(T* dest, T* first, T* last, std::false_type) { relocate_move_or_copy(dest, first, last, relocate_use_move()); } - void relocate_move_or_copy(T* dest, T* first, T* last, std::true_type) - { + void relocate_move_or_copy(T* dest, T* first, T* last, std::true_type) { D_uninitialized_move_a(dest, first, last); } - void relocate_move_or_copy(T* dest, T* first, T* last, std::false_type) - { + void relocate_move_or_copy(T* dest, T* first, T* last, std::false_type) { D_uninitialized_copy_a(dest, first, last); } // done - void relocate_done(T* /*dest*/, T* first, T* last) noexcept - { + void relocate_done(T* /*dest*/, T* first, T* last) noexcept { if constexpr (std::is_trivially_copyable_v && usingStdAllocator) { // used memcpy; data has been relocated, do not call destructor } else { @@ -715,8 +655,7 @@ class vector } // undo - void relocate_undo(T* dest, T* first, T* last) noexcept - { + void relocate_undo(T* dest, T* first, T* last) noexcept { if constexpr (std::is_trivially_copyable_v && usingStdAllocator) { // used memcpy, old data is still valid, nothing to do } else if constexpr (std::is_nothrow_move_constructible::value && usingStdAllocator) { @@ -738,47 +677,35 @@ class vector vector() = default; explicit vector(const Allocator& a) - : impl_(a) - { - } + : impl_(a) {} explicit vector(size_type n, const Allocator& a = Allocator()) - : impl_(n, a) - { + : impl_(n, a) { M_uninitialized_fill_n_e(n); } vector(size_type n, VT value, const Allocator& a = Allocator()) - : impl_(n, a) - { + : impl_(n, a) { M_uninitialized_fill_n_e(n, value); } template::iterator_category> vector(It first, It last, const Allocator& a = Allocator()) - : vector(first, last, a, Category()) - { - } + : vector(first, last, a, Category()) {} vector(const vector& other) - : impl_(other.size(), A::select_on_container_copy_construction(other.impl_)) - { + : impl_(other.size(), A::select_on_container_copy_construction(other.impl_)) { M_uninitialized_copy_e(other.begin(), other.end()); } vector(vector&& other) noexcept - : impl_(std::move(other.impl_)) - { - } + : impl_(std::move(other.impl_)) {} vector(const vector& other, const Allocator& a) - : vector(other.begin(), other.end(), a) - { - } + : vector(other.begin(), other.end(), a) {} /* may throw */ vector(vector&& other, const Allocator& a) - : impl_(a) - { + : impl_(a) { if (impl_ == other.impl_) { impl_.swapData(other.impl_); } else { @@ -788,20 +715,16 @@ class vector } vector(std::initializer_list il, const Allocator& a = Allocator()) - : vector(il.begin(), il.end(), a) - { - } + : vector(il.begin(), il.end(), a) {} // ------------------- gtl extensions ------------------------------------------------------- vector(std::unique_ptr data, size_type sz, size_type cap, const Allocator& a = Allocator()) - : impl_(a) - { + : impl_(a) { impl_.set(data.release(), sz, cap); } // return value to be used in accordance with vector's allocator - std::unique_ptr steal_data() - { + std::unique_ptr steal_data() { std::unique_ptr res(impl_.data()); impl_.set(nullptr, nullptr, nullptr); // don't deallocate the buffer!! return res; @@ -811,8 +734,7 @@ class vector ~vector() = default; // the cleanup occurs in impl_ - vector& operator=(const vector& other) - { + vector& operator=(const vector& other) { if (UNLIKELY(this == &other)) { return *this; } @@ -829,8 +751,7 @@ class vector return *this; } - vector& operator=(vector&& other) noexcept - { + vector& operator=(vector&& other) noexcept { if (UNLIKELY(this == &other)) { return *this; } @@ -838,20 +759,17 @@ class vector return *this; } - vector& operator=(std::initializer_list il) - { + vector& operator=(std::initializer_list il) { assign(il.begin(), il.end()); return *this; } template::iterator_category> - void assign(It first, It last) - { + void assign(It first, It last) { assign(first, last, Category()); } - void assign(size_type n, VT value) - { + void assign(size_type n, VT value) { if (n > capacity()) { // Not enough space. Do not reserve in place, since we will // discard the old values anyways. @@ -881,15 +799,13 @@ class vector // contract dispatch for iterator types vector(It first, It last) template vector(ForwardIterator first, ForwardIterator last, const Allocator& a, std::forward_iterator_tag) - : impl_(size_type(std::distance(first, last)), a) - { + : impl_(size_type(std::distance(first, last)), a) { M_uninitialized_copy_e(first, last); } template vector(InputIterator first, InputIterator last, const Allocator& a, std::input_iterator_tag) - : impl_(a) - { + : impl_(a) { for (; first != last; ++first) { emplace_back(*first); } @@ -897,8 +813,7 @@ class vector // contract dispatch for allocator movement in operator=(vector&&) void moveFrom(vector&& other, std::true_type) { swap(impl_, other.impl_); } - void moveFrom(vector&& other, std::false_type) - { + void moveFrom(vector&& other, std::false_type) { if (impl_ == other.impl_) { impl_.swapData(other.impl_); } else { @@ -909,8 +824,7 @@ class vector // contract dispatch for iterator types in assign(It first, It last) template - void assign(ForwardIterator first, ForwardIterator last, std::forward_iterator_tag) - { + void assign(ForwardIterator first, ForwardIterator last, std::forward_iterator_tag) { const auto newSize = size_type(std::distance(first, last)); if (newSize > capacity()) { impl_.reset(newSize); @@ -925,8 +839,7 @@ class vector } template - void assign(InputIterator first, InputIterator last, std::input_iterator_tag) - { + void assign(InputIterator first, InputIterator last, std::input_iterator_tag) { auto p = impl_.b_; for (; first != last && p != impl_.e_; ++first, ++p) { *p = *first; @@ -941,8 +854,7 @@ class vector } // contract dispatch for aliasing under VT optimization - bool dataIsInternalAndNotVT(const T& t) - { + bool dataIsInternalAndNotVT(const T& t) { if (should_pass_by_value) { return false; } @@ -974,14 +886,12 @@ class vector public: size_type size() const noexcept { return size_type(impl_.e_ - impl_.b_); } - size_type max_size() const noexcept - { + size_type max_size() const noexcept { // good luck gettin' there return ~size_type(0); } - void resize(size_type n) - { + void resize(size_type n) { if (n <= size()) { M_destroy_range_e(impl_.b_ + n); } else { @@ -990,8 +900,7 @@ class vector } } - void resize(size_type n, VT t) - { + void resize(size_type n, VT t) { if (n <= size()) { M_destroy_range_e(impl_.b_ + n); } else if (dataIsInternalAndNotVT(t) && n > capacity()) { @@ -1008,8 +917,7 @@ class vector bool empty() const noexcept { return impl_.b_ == impl_.e_; } - void reserve(size_type n) - { + void reserve(size_type n) { if (n <= capacity()) { return; } @@ -1032,8 +940,7 @@ class vector impl_.b_ = newB; } - void shrink_to_fit() noexcept - { + void shrink_to_fit() noexcept { if (empty()) { impl_.reset(); return; @@ -1051,7 +958,8 @@ class vector // xallocx() will shrink to precisely newCapacityBytes (which was generated // by goodMallocSize()) if it successfully shrinks in place. if constexpr ((usingJEMalloc() && usingStdAllocator) && newCapacityBytes >= gtl::jemallocMinInPlaceExpandable && - xallocx(p, newCapacityBytes, 0, 0) == newCapacityBytes) { + xallocx(p, newCapacityBytes, 0, 0) == newCapacityBytes) + { impl_.z_ += newCap - oldCap; } else { T* newB = nullptr; @@ -1082,8 +990,7 @@ class vector } private: - bool reserve_in_place(size_type n) - { + bool reserve_in_place(size_type n) { if constexpr (usingStdAllocator && usingJEMalloc()) { // jemalloc can never grow in place blocks smaller than 4096 bytes. @@ -1105,45 +1012,37 @@ class vector //--------------------------------------------------------------------------- // element access public: - reference operator[](size_type n) - { + reference operator[](size_type n) { assert(n < size()); return impl_.b_[n]; } - const_reference operator[](size_type n) const - { + const_reference operator[](size_type n) const { assert(n < size()); return impl_.b_[n]; } - const_reference at(size_type n) const - { + const_reference at(size_type n) const { if (UNLIKELY(n >= size())) { throw std::out_of_range("vector: index is greater than size."); } return (*this)[n]; } - reference at(size_type n) - { + reference at(size_type n) { auto const& cThis = *this; return const_cast(cThis.at(n)); } - reference front() - { + reference front() { assert(!empty()); return *impl_.b_; } - const_reference front() const - { + const_reference front() const { assert(!empty()); return *impl_.b_; } - reference back() - { + reference back() { assert(!empty()); return impl_.e_[-1]; } - const_reference back() const - { + const_reference back() const { assert(!empty()); return impl_.e_[-1]; } @@ -1160,8 +1059,7 @@ class vector // modifiers (common) public: template - reference emplace_back(Args&&... args) - { + reference emplace_back(Args&&... args) { if (impl_.e_ != impl_.z_) { M_construct(impl_.e_, std::forward(args)...); ++impl_.e_; @@ -1171,8 +1069,7 @@ class vector return back(); } - void push_back(const T& value) - { + void push_back(const T& value) { if (impl_.e_ != impl_.z_) { M_construct(impl_.e_, value); ++impl_.e_; @@ -1181,8 +1078,7 @@ class vector } } - void push_back(T&& value) - { + void push_back(T&& value) { if (impl_.e_ != impl_.z_) { M_construct(impl_.e_, std::move(value)); ++impl_.e_; @@ -1191,15 +1087,13 @@ class vector } } - void pop_back() - { + void pop_back() { assert(!empty()); --impl_.e_; M_destroy(impl_.e_); } - void swap(vector& other) noexcept - { + void swap(vector& other) noexcept { if constexpr (!usingStdAllocator && A::propagate_on_container_swap::value) { swap(impl_, other.impl_); } else { @@ -1228,8 +1122,7 @@ class vector // defined growth strategy, probably as part of the allocator. // - size_type computePushBackCapacity() const - { + size_type computePushBackCapacity() const { if (capacity() == 0) { return std::max(64 / sizeof(T), size_type(1)); } @@ -1243,11 +1136,11 @@ class vector } template - void emplace_back_aux(Args&&... args) - { + void emplace_back_aux(Args&&... args) { size_type byte_sz = gtl::goodMallocSize(computePushBackCapacity() * sizeof(T)); if constexpr (usingStdAllocator && usingJEMalloc() && - ((impl_.z_ - impl_.b_) * sizeof(T) >= gtl::jemallocMinInPlaceExpandable)) { + ((impl_.z_ - impl_.b_) * sizeof(T) >= gtl::jemallocMinInPlaceExpandable)) + { // Try to reserve in place. // Ask xallocx to allocate in place at least size()+1 and at most sz // space. @@ -1312,8 +1205,7 @@ class vector public: iterator erase(const_iterator position) { return erase(position, position + 1); } - iterator erase(const_iterator first, const_iterator last) - { + iterator erase(const_iterator first, const_iterator last) { assert(isValid(first) && isValid(last)); assert(first <= last); if (first != last) { @@ -1350,8 +1242,7 @@ class vector private: // we have the private section first because it defines some macros bool isValid(const_iterator it) { return cbegin() <= it && it <= cend(); } - size_type computeInsertCapacity(size_type n) - { + size_type computeInsertCapacity(size_type n) { size_type nc = std::max(computePushBackCapacity(), size() + n); size_type ac = gtl::goodMallocSize(nc * sizeof(T)) / sizeof(T); return ac; @@ -1410,8 +1301,7 @@ class vector //--------------------------------------------------------------------------- // window - void make_window(iterator position, size_type n) - { + void make_window(iterator position, size_type n) { // The result is guaranteed to be non-negative, so use an unsigned type: size_type tail = size_type(std::distance(position, impl_.e_)); @@ -1422,7 +1312,7 @@ class vector } else { if constexpr (std::is_trivially_copyable_v && usingStdAllocator) { #pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wnonnull" // disable erroneous warning +#pragma GCC diagnostic ignored "-Wnonnull" // disable erroneous warning std::memmove((void*)(position + n), (void*)position, tail * sizeof(T)); #pragma GCC diagnostic pop impl_.e_ += n; @@ -1443,8 +1333,7 @@ class vector } } - void undo_window(iterator position, size_type n) noexcept - { + void undo_window(iterator position, size_type n) noexcept { D_destroy_range_a(position + n, impl_.e_); impl_.e_ = position; } @@ -1452,8 +1341,7 @@ class vector //--------------------------------------------------------------------------- // frame - void wrap_frame(T* ledge, size_type idx, size_type n) - { + void wrap_frame(T* ledge, size_type idx, size_type n) { assert(size() >= idx); assert(n != 0); @@ -1472,8 +1360,7 @@ class vector //--------------------------------------------------------------------------- // use fresh? - bool insert_use_fresh(bool at_end, size_type n) - { + bool insert_use_fresh(bool at_end, size_type n) { if (at_end) { if (size() + n <= capacity()) { return false; @@ -1500,8 +1387,7 @@ class vector IsInternalFunc&& isInternalFunc, InsertInternalFunc&& insertInternalFunc, ConstructFunc&& constructFunc, - DestroyFunc&& destroyFunc) - { + DestroyFunc&& destroyFunc) { if (n == 0) { return const_cast(cpos); } @@ -1571,8 +1457,7 @@ class vector public: template - iterator emplace(const_iterator cpos, Args&&... args) - { + iterator emplace(const_iterator cpos, Args&&... args) { return do_real_insert( cpos, 1, @@ -1582,8 +1467,7 @@ class vector [&](iterator start) { M_destroy(start); }); } - iterator insert(const_iterator cpos, const T& value) - { + iterator insert(const_iterator cpos, const T& value) { return do_real_insert( cpos, 1, @@ -1593,8 +1477,7 @@ class vector [&](iterator start) { M_destroy(start); }); } - iterator insert(const_iterator cpos, T&& value) - { + iterator insert(const_iterator cpos, T&& value) { return do_real_insert( cpos, 1, @@ -1604,8 +1487,7 @@ class vector [&](iterator start) { M_destroy(start); }); } - iterator insert(const_iterator cpos, size_type n, VT value) - { + iterator insert(const_iterator cpos, size_type n, VT value) { return do_real_insert( cpos, n, @@ -1616,8 +1498,7 @@ class vector } template::iterator_category> - iterator insert(const_iterator cpos, It first, It last) - { + iterator insert(const_iterator cpos, It first, It last) { return insert(cpos, first, last, Category()); } @@ -1627,8 +1508,7 @@ class vector // insert dispatch for iterator types private: template - iterator insert(const_iterator cpos, FIt first, FIt last, std::forward_iterator_tag) - { + iterator insert(const_iterator cpos, FIt first, FIt last, std::forward_iterator_tag) { size_type n = size_type(std::distance(first, last)); return do_real_insert( cpos, @@ -1640,8 +1520,7 @@ class vector } template - iterator insert(const_iterator cpos, IIt first, IIt last, std::input_iterator_tag) - { + iterator insert(const_iterator cpos, IIt first, IIt last, std::input_iterator_tag) { T* position = const_cast(cpos); assert(isValid(position)); size_type idx = std::distance(begin(), position); @@ -1661,15 +1540,13 @@ class vector //--------------------------------------------------------------------------- // lexicographical functions public: - bool operator==(const vector& other) const - { + bool operator==(const vector& other) const { return size() == other.size() && std::equal(begin(), end(), other.begin()); } bool operator!=(const vector& other) const { return !(*this == other); } - bool operator<(const vector& other) const - { + bool operator<(const vector& other) const { return std::lexicographical_compare(begin(), end(), other.begin(), other.end()); } @@ -1696,8 +1573,7 @@ class vector // specialized functions template -void swap(vector& lhs, vector& rhs) noexcept -{ +void swap(vector& lhs, vector& rhs) noexcept { lhs.swap(rhs); } @@ -1706,8 +1582,7 @@ void swap(vector& lhs, vector& rhs) noexcept // other template -void compactResize(vector* v, size_t sz) -{ +void compactResize(vector* v, size_t sz) { v->resize(sz); v->shrink_to_fit(); } @@ -1736,16 +1611,14 @@ void compactResize(vector* v, size_t sz) // template -T* relinquish(vector& v) -{ +T* relinquish(vector& v) { T* ret = v.data(); v.impl_.b_ = v.impl_.e_ = v.impl_.z_ = nullptr; return ret; } template -void attach(vector& v, T* data, size_t sz, size_t cap) -{ +void attach(vector& v, T* data, size_t sz, size_t cap) { assert(v.data() == nullptr); v.impl_.b_ = data; v.impl_.e_ = data + sz; @@ -1759,14 +1632,12 @@ vector(InputIt, InputIt, Allocator = Allocator()) #endif template -void erase(vector& v, U value) -{ +void erase(vector& v, U value) { v.erase(std::remove(v.begin(), v.end(), value), v.end()); } template -void erase_if(vector& v, Predicate predicate) -{ +void erase_if(vector& v, Predicate predicate) { v.erase(std::remove_if(v.begin(), v.end(), std::ref(predicate)), v.end()); } } // namespace gtl diff --git a/tests/btree/btree_test.cpp b/tests/btree/btree_test.cpp index 54f901f..854c66c 100644 --- a/tests/btree/btree_test.cpp +++ b/tests/btree/btree_test.cpp @@ -64,19 +64,17 @@ using ::testing::ElementsAreArray; using ::testing::IsEmpty; using ::testing::Pair; -#define GTL_INTERNAL_CHECK(condition, message) \ - if (!(condition)) \ +#define GTL_INTERNAL_CHECK(condition, message) \ + if (!(condition)) \ assert(0) template -void CheckPairEquals(const T& x, const U& y) -{ +void CheckPairEquals(const T& x, const U& y) { GTL_INTERNAL_CHECK(x == y, "Values are unequal."); } template -void CheckPairEquals(const std::pair& x, const std::pair& y) -{ +void CheckPairEquals(const std::pair& x, const std::pair& y) { CheckPairEquals(x.first, y.first); CheckPairEquals(x.second, y.second); } @@ -87,8 +85,7 @@ void CheckPairEquals(const std::pair& x, const std::pair& y) // against. TreeType is expected to be btree_{set,map,multiset,multimap} and // CheckerType is expected to be {set,map,multiset,multimap}. template -class base_checker -{ +class base_checker { public: using key_type = typename TreeType::key_type; using value_type = typename TreeType::value_type; @@ -106,22 +103,16 @@ class base_checker public: base_checker() - : const_tree_(tree_) - { - } + : const_tree_(tree_) {} base_checker(const base_checker& x) : tree_(x.tree_) , const_tree_(tree_) - , checker_(x.checker_) - { - } + , checker_(x.checker_) {} template base_checker(InputIterator b, InputIterator e) : tree_(b, e) , const_tree_(tree_) - , checker_(b, e) - { - } + , checker_(b, e) {} iterator begin() { return tree_.begin(); } const_iterator begin() const { return tree_.begin(); } @@ -133,8 +124,7 @@ class base_checker const_reverse_iterator rend() const { return tree_.rend(); } template - IterType iter_check(IterType tree_iter, CheckerIterType checker_iter) const - { + IterType iter_check(IterType tree_iter, CheckerIterType checker_iter) const { if (tree_iter == tree_.end()) { GTL_INTERNAL_CHECK(checker_iter == checker_.end(), "Checker iterator not at end."); } else { @@ -143,8 +133,7 @@ class base_checker return tree_iter; } template - IterType riter_check(IterType tree_iter, CheckerIterType checker_iter) const - { + IterType riter_check(IterType tree_iter, CheckerIterType checker_iter) const { if (tree_iter == tree_.rend()) { GTL_INTERNAL_CHECK(checker_iter == checker_.rend(), "Checker iterator not at rend."); } else { @@ -152,11 +141,9 @@ class base_checker } return tree_iter; } - void value_check(const value_type& x) - { - typename KeyOfValue::type - key_of_value; - const key_type& key = key_of_value(x); + void value_check(const value_type& x) { + typename KeyOfValue::type key_of_value; + const key_type& key = key_of_value(x); CheckPairEquals(*find(key), x); lower_bound(key); upper_bound(key); @@ -164,8 +151,7 @@ class base_checker contains(key); count(key); } - void erase_check(const key_type& key) - { + void erase_check(const key_type& key) { EXPECT_FALSE(tree_.contains(key)); EXPECT_EQ(tree_.find(key), const_tree_.end()); EXPECT_FALSE(const_tree_.contains(key)); @@ -173,24 +159,15 @@ class base_checker EXPECT_EQ(tree_.equal_range(key).first, const_tree_.equal_range(key).second); } - iterator lower_bound(const key_type& key) - { + iterator lower_bound(const key_type& key) { return iter_check(tree_.lower_bound(key), checker_.lower_bound(key)); } + const_iterator lower_bound(const key_type& key) const { return iter_check(tree_.lower_bound(key), checker_.lower_bound(key)); } - const_iterator lower_bound(const key_type& key) const - { - return iter_check(tree_.lower_bound(key), checker_.lower_bound(key)); - } - iterator upper_bound(const key_type& key) - { + iterator upper_bound(const key_type& key) { return iter_check(tree_.upper_bound(key), checker_.upper_bound(key)); } + const_iterator upper_bound(const key_type& key) const { return iter_check(tree_.upper_bound(key), checker_.upper_bound(key)); } - const_iterator upper_bound(const key_type& key) const - { - return iter_check(tree_.upper_bound(key), checker_.upper_bound(key)); - } - std::pair equal_range(const key_type& key) - { + std::pair equal_range(const key_type& key) { std::pair checker_res = checker_.equal_range(key); std::pair tree_res = tree_.equal_range(key); @@ -198,37 +175,30 @@ class base_checker iter_check(tree_res.second, checker_res.second); return tree_res; } - std::pair equal_range(const key_type& key) const - { - std::pair - checker_res = checker_.equal_range(key); - std::pair tree_res = tree_.equal_range(key); + std::pair equal_range(const key_type& key) const { + std::pair checker_res = + checker_.equal_range(key); + std::pair tree_res = tree_.equal_range(key); iter_check(tree_res.first, checker_res.first); iter_check(tree_res.second, checker_res.second); return tree_res; } - iterator find(const key_type& key) { return iter_check(tree_.find(key), checker_.find(key)); } - const_iterator find(const key_type& key) const - { - return iter_check(tree_.find(key), checker_.find(key)); - } - bool contains(const key_type& key) const { return find(key) != end(); } - size_type count(const key_type& key) const - { + iterator find(const key_type& key) { return iter_check(tree_.find(key), checker_.find(key)); } + const_iterator find(const key_type& key) const { return iter_check(tree_.find(key), checker_.find(key)); } + bool contains(const key_type& key) const { return find(key) != end(); } + size_type count(const key_type& key) const { size_type res = checker_.count(key); EXPECT_EQ(res, tree_.count(key)); return res; } - base_checker& operator=(const base_checker& x) - { + base_checker& operator=(const base_checker& x) { tree_ = x.tree_; checker_ = x.checker_; return *this; } - int erase(const key_type& key) - { + int erase(const key_type& key) { size_t size = tree_.size(); int res = (int)checker_.erase(key); EXPECT_EQ(res, tree_.count(key)); @@ -238,8 +208,7 @@ class base_checker erase_check(key); return res; } - iterator erase(iterator iter) - { + iterator erase(iterator iter) { key_type key = iter.key(); size_t size = tree_.size(); size_t count = tree_.count(key); @@ -260,8 +229,7 @@ class base_checker return iter_check(iter, checker_next); } - void erase(iterator begin, iterator end) - { + void erase(iterator begin, iterator end) { size_t size = tree_.size(); int count = std::distance(begin, end); auto checker_begin = checker_.lower_bound(begin.key()); @@ -280,19 +248,16 @@ class base_checker EXPECT_EQ(tree_.size(), size - count); } - void clear() - { + void clear() { tree_.clear(); checker_.clear(); } - void swap(base_checker& x) - { + void swap(base_checker& x) { tree_.swap(x.tree_); checker_.swap(x.checker_); } - void verify() const - { + void verify() const { tree_.verify(); EXPECT_EQ(tree_.size(), checker_.size()); @@ -331,14 +296,12 @@ class base_checker const TreeType& tree() const { return tree_; } - size_type size() const - { + size_type size() const { EXPECT_EQ(tree_.size(), checker_.size()); return tree_.size(); } size_type max_size() const { return tree_.max_size(); } - bool empty() const - { + bool empty() const { EXPECT_EQ(tree_.empty(), checker_.empty()); return tree_.empty(); } @@ -353,8 +316,7 @@ namespace { // A checker for unique sorted associative containers. TreeType is expected to // be btree_{set,map} and CheckerType is expected to be {set,map}. template -class unique_checker : public base_checker -{ +class unique_checker : public base_checker { using super_type = base_checker; public: @@ -363,23 +325,16 @@ class unique_checker : public base_checker public: unique_checker() - : super_type() - { - } + : super_type() {} unique_checker(const unique_checker& x) - : super_type(x) - { - } + : super_type(x) {} template unique_checker(InputIterator b, InputIterator e) - : super_type(b, e) - { - } + : super_type(b, e) {} unique_checker& operator=(const unique_checker&) = default; // Insertion routines. - std::pair insert(const value_type& x) - { + std::pair insert(const value_type& x) { size_t size = this->tree_.size(); std::pair checker_res = this->checker_.insert(x); std::pair tree_res = this->tree_.insert(x); @@ -389,19 +344,17 @@ class unique_checker : public base_checker EXPECT_EQ(this->tree_.size(), size + tree_res.second); return tree_res; } - iterator insert(iterator position, const value_type& x) - { + iterator insert(iterator position, const value_type& x) { size_t size = this->tree_.size(); std::pair checker_res = this->checker_.insert(x); - iterator tree_res = this->tree_.insert(position, x); + iterator tree_res = this->tree_.insert(position, x); CheckPairEquals(*tree_res, *checker_res.first); EXPECT_EQ(this->tree_.size(), this->checker_.size()); EXPECT_EQ(this->tree_.size(), size + checker_res.second); return tree_res; } template - void insert(InputIterator b, InputIterator e) - { + void insert(InputIterator b, InputIterator e) { for (; b != e; ++b) { insert(*b); } @@ -412,8 +365,7 @@ class unique_checker : public base_checker // to be btree_{multiset,multimap} and CheckerType is expected to be // {multiset,multimap}. template -class multi_checker : public base_checker -{ +class multi_checker : public base_checker { using super_type = base_checker; public: @@ -422,23 +374,16 @@ class multi_checker : public base_checker public: multi_checker() - : super_type() - { - } + : super_type() {} multi_checker(const multi_checker& x) - : super_type(x) - { - } + : super_type(x) {} template multi_checker(InputIterator b, InputIterator e) - : super_type(b, e) - { - } + : super_type(b, e) {} multi_checker& operator=(const multi_checker&) = default; // Insertion routines. - iterator insert(const value_type& x) - { + iterator insert(const value_type& x) { size_t size = this->tree_.size(); auto checker_res = this->checker_.insert(x); iterator tree_res = this->tree_.insert(x); @@ -447,8 +392,7 @@ class multi_checker : public base_checker EXPECT_EQ(this->tree_.size(), size + 1); return tree_res; } - iterator insert(iterator position, const value_type& x) - { + iterator insert(iterator position, const value_type& x) { size_t size = this->tree_.size(); auto checker_res = this->checker_.insert(x); iterator tree_res = this->tree_.insert(position, x); @@ -458,8 +402,7 @@ class multi_checker : public base_checker return tree_res; } template - void insert(InputIterator b, InputIterator e) - { + void insert(InputIterator b, InputIterator e) { for (; b != e; ++b) { insert(*b); } @@ -467,8 +410,7 @@ class multi_checker : public base_checker }; template -void DoTest([[maybe_unused]] const char* name, T* b, const std::vector& values) -{ +void DoTest([[maybe_unused]] const char* name, T* b, const std::vector& values) { typename KeyOfValue::type key_of_value; T& mutable_b = *b; @@ -602,8 +544,7 @@ void DoTest([[maybe_unused]] const char* name, T* b, const std::vector& value } template -void ConstTest() -{ +void ConstTest() { using value_type = typename T::value_type; typename KeyOfValue::type key_of_value; @@ -655,8 +596,7 @@ void ConstTest() } template -void BtreeTest() -{ +void BtreeTest() { ConstTest(); using V = typename remove_pair_const::type; @@ -679,8 +619,7 @@ void BtreeTest() } template -void BtreeMultiTest() -{ +void BtreeMultiTest() { ConstTest(); using V = typename remove_pair_const::type; @@ -713,8 +652,7 @@ void BtreeMultiTest() } template -struct PropagatingCountingAlloc : public CountingAllocator -{ +struct PropagatingCountingAlloc : public CountingAllocator { using propagate_on_container_copy_assignment = std::true_type; using propagate_on_container_move_assignment = std::true_type; using propagate_on_container_swap = std::true_type; @@ -724,20 +662,16 @@ struct PropagatingCountingAlloc : public CountingAllocator template explicit PropagatingCountingAlloc(const PropagatingCountingAlloc& other) - : Base(other.bytes_used_) - { - } + : Base(other.bytes_used_) {} template - struct rebind - { + struct rebind { using other = PropagatingCountingAlloc; }; }; template -void BtreeAllocatorTest() -{ +void BtreeAllocatorTest() { using value_type = typename T::value_type; int64_t bytes1 = 0, bytes2 = 0; @@ -823,8 +757,7 @@ void BtreeAllocatorTest() } template -void BtreeMapTest() -{ +void BtreeMapTest() { using value_type = typename T::value_type; using mapped_type = typename T::mapped_type; @@ -850,16 +783,14 @@ void BtreeMapTest() } template -void BtreeMultiMapTest() -{ +void BtreeMultiMapTest() { using mapped_type = typename T::mapped_type; mapped_type m = Generator(0)(0); (void)m; } template -void SetTest() -{ +void SetTest() { using BtreeSet = gtl::btree_set; using CountingBtreeSet = gtl::btree_set, PropagatingCountingAlloc>; BtreeTest>(); @@ -867,11 +798,9 @@ void SetTest() } template -void MapTest() -{ - using BtreeMap = gtl::btree_map; - using CountingBtreeMap = - gtl::btree_map, PropagatingCountingAlloc>>; +void MapTest() { + using BtreeMap = gtl::btree_map; + using CountingBtreeMap = gtl::btree_map, PropagatingCountingAlloc>>; BtreeTest>(); BtreeAllocatorTest(); BtreeMapTest(); @@ -887,8 +816,7 @@ TEST(Btree, map_string) { MapTest(); } TEST(Btree, map_pair) { MapTest>(); } template -void MultiSetTest() -{ +void MultiSetTest() { using BtreeMSet = gtl::btree_multiset; using CountingBtreeMSet = gtl::btree_multiset, PropagatingCountingAlloc>; BtreeMultiTest>(); @@ -896,11 +824,9 @@ void MultiSetTest() } template -void MultiMapTest() -{ - using BtreeMMap = gtl::btree_multimap; - using CountingBtreeMMap = - gtl::btree_multimap, PropagatingCountingAlloc>>; +void MultiMapTest() { + using BtreeMMap = gtl::btree_multimap; + using CountingBtreeMMap = gtl::btree_multimap, PropagatingCountingAlloc>>; BtreeMultiTest>(); BtreeMultiMapTest(); BtreeAllocatorTest(); @@ -915,19 +841,16 @@ TEST(Btree, multimap_int64) { MultiMapTest(); } TEST(Btree, multimap_string) { MultiMapTest(); } TEST(Btree, multimap_pair) { MultiMapTest>(); } -struct CompareIntToString -{ +struct CompareIntToString { bool operator()(const std::string& a, const std::string& b) const { return a < b; } bool operator()(const std::string& a, int b) const { return a < std::to_string(b); } bool operator()(int a, const std::string& b) const { return std::to_string(a) < b; } using is_transparent = void; }; -struct NonTransparentCompare -{ +struct NonTransparentCompare { template - bool operator()(const T& t, const U& u) const - { + bool operator()(const T& t, const U& u) const { // Treating all comparators as transparent can cause inefficiencies (see // N3657 C++ proposal). Test that for comparators without 'is_transparent' // alias (like this one), we do not attempt heterogeneous lookup. @@ -937,20 +860,17 @@ struct NonTransparentCompare }; template -bool CanEraseWithEmptyBrace(T t, decltype(t.erase({}))*) -{ +bool CanEraseWithEmptyBrace(T t, decltype(t.erase({}))*) { return true; } template -bool CanEraseWithEmptyBrace(T, ...) -{ +bool CanEraseWithEmptyBrace(T, ...) { return false; } template -void TestHeterogeneous(T table) -{ +void TestHeterogeneous(T table) { auto lb = table.lower_bound("3"); EXPECT_EQ(lb, table.lower_bound(3)); EXPECT_NE(lb, table.lower_bound(4)); @@ -999,8 +919,7 @@ void TestHeterogeneous(T table) TestHeterogeneous(table); } -TEST(Btree, HeterogeneousLookup) -{ +TEST(Btree, HeterogeneousLookup) { TestHeterogeneous(btree_set{ "1", "3", "5" }); TestHeterogeneous(btree_map{ {"1", 1}, @@ -1030,8 +949,7 @@ TEST(Btree, HeterogeneousLookup) EXPECT_EQ(-1, cmap.at({})); } -TEST(Btree, NoHeterogeneousLookupWithoutAlias) -{ +TEST(Btree, NoHeterogeneousLookupWithoutAlias) { using StringSet = gtl::btree_set; StringSet s; ASSERT_TRUE(s.insert("hello").second); @@ -1056,8 +974,7 @@ TEST(Btree, NoHeterogeneousLookupWithoutAlias) EXPECT_FALSE(ms.contains("blah")); } -TEST(Btree, DefaultTransparent) -{ +TEST(Btree, DefaultTransparent) { { // `int` does not have a default transparent comparator. // The input value is converted to key_type. @@ -1075,14 +992,12 @@ TEST(Btree, DefaultTransparent) } } -class StringLike -{ +class StringLike { public: StringLike() = default; StringLike(const char* s) - : s_(s) - { // NOLINT + : s_(s) { // NOLINT ++constructor_calls_; } @@ -1099,8 +1014,7 @@ class StringLike int StringLike::constructor_calls_ = 0; -TEST(Btree, HeterogeneousLookupDoesntDegradePerformance) -{ +TEST(Btree, HeterogeneousLookupDoesntDegradePerformance) { using StringSet = gtl::btree_set; StringSet s; for (int i = 0; i < 100; ++i) { @@ -1137,22 +1051,17 @@ TEST(Btree, HeterogeneousLookupDoesntDegradePerformance) // Verify that swapping btrees swaps the key comparison functors and that we can // use non-default constructible comparators. -struct SubstringLess -{ +struct SubstringLess { SubstringLess() = delete; explicit SubstringLess(int length) - : n(length) - { - } - bool operator()(const std::string& a, const std::string& b) const - { + : n(length) {} + bool operator()(const std::string& a, const std::string& b) const { return std::string_view(a).substr(0, n) < std::string_view(b).substr(0, n); } int n; }; -TEST(Btree, SwapKeyCompare) -{ +TEST(Btree, SwapKeyCompare) { using SubstringSet = gtl::btree_set; SubstringSet s1(SubstringLess(1), SubstringSet::allocator_type()); SubstringSet s2(SubstringLess(2), SubstringSet::allocator_type()); @@ -1174,8 +1083,7 @@ TEST(Btree, SwapKeyCompare) ASSERT_FALSE(s2.insert("bb").second); } -TEST(Btree, UpperBoundRegression) -{ +TEST(Btree, UpperBoundRegression) { // Regress a bug where upper_bound would default-construct a new key_compare // instead of copying the existing one. using SubstringSet = gtl::btree_set; @@ -1191,8 +1099,7 @@ TEST(Btree, UpperBoundRegression) EXPECT_EQ("aab", *it); } -TEST(Btree, Comparison) -{ +TEST(Btree, Comparison) { const int kSetSize = 1201; gtl::btree_set my_set; for (int i = 0; i < kSetSize; ++i) { @@ -1246,8 +1153,7 @@ TEST(Btree, Comparison) EXPECT_TRUE(my_map != my_map_copy); } -TEST(Btree, RangeCtorSanity) -{ +TEST(Btree, RangeCtorSanity) { std::vector ivec; ivec.push_back(1); std::map imap; @@ -1262,8 +1168,7 @@ TEST(Btree, RangeCtorSanity) EXPECT_EQ(1, tmap.size()); } -TEST(Btree, BtreeMapCanHoldMoveOnlyTypes) -{ +TEST(Btree, BtreeMapCanHoldMoveOnlyTypes) { gtl::btree_map> m; std::unique_ptr& v = m["A"]; @@ -1274,8 +1179,7 @@ TEST(Btree, BtreeMapCanHoldMoveOnlyTypes) EXPECT_EQ("X", *iter->second); } -TEST(Btree, InitializerListConstructor) -{ +TEST(Btree, InitializerListConstructor) { gtl::btree_set set({ "a", "b" }); EXPECT_EQ(set.count("a"), 1); EXPECT_EQ(set.count("b"), 1); @@ -1304,8 +1208,7 @@ TEST(Btree, InitializerListConstructor) EXPECT_EQ(++it, range.second); } -TEST(Btree, InitializerListInsert) -{ +TEST(Btree, InitializerListInsert) { gtl::btree_set set; set.insert({ "a", "b" }); EXPECT_EQ(set.count("a"), 1); @@ -1342,27 +1245,21 @@ TEST(Btree, InitializerListInsert) } template -void AssertKeyCompareToAdapted() -{ +void AssertKeyCompareToAdapted() { using Adapted = typename key_compare_to_adapter::type; - static_assert(!std::is_same_v, - "key_compare_to_adapter should have adapted this comparator."); - static_assert( - std::is_same_v>, - "Adapted comparator should be a key-compare-to comparator."); + static_assert(!std::is_same_v, "key_compare_to_adapter should have adapted this comparator."); + static_assert(std::is_same_v>, + "Adapted comparator should be a key-compare-to comparator."); } template -void AssertKeyCompareToNotAdapted() -{ +void AssertKeyCompareToNotAdapted() { using Unadapted = typename key_compare_to_adapter::type; - static_assert(std::is_same_v, - "key_compare_to_adapter shouldn't have adapted this comparator."); + static_assert(std::is_same_v, "key_compare_to_adapter shouldn't have adapted this comparator."); static_assert(std::is_same_v>, "Un-adapted comparator should return bool."); } -TEST(Btree, KeyCompareToAdapter) -{ +TEST(Btree, KeyCompareToAdapter) { AssertKeyCompareToAdapted, std::string>(); AssertKeyCompareToAdapted, std::string>(); AssertKeyCompareToAdapted, std::string_view>(); @@ -1371,8 +1268,7 @@ TEST(Btree, KeyCompareToAdapter) AssertKeyCompareToNotAdapted, int>(); } -TEST(Btree, RValueInsert) -{ +TEST(Btree, RValueInsert) { InstanceTracker tracker; gtl::btree_set set; @@ -1421,13 +1317,11 @@ TEST(Btree, RValueInsert) } // namespace -class BtreeNodePeer -{ +class BtreeNodePeer { public: // Yields the size of a leaf node with a specific number of values. template - constexpr static size_t GetTargetNodeSize(size_t target_values_per_node) - { + constexpr static size_t GetTargetNodeSize(size_t target_values_per_node) { return btree_node, std::allocator, @@ -1437,8 +1331,7 @@ class BtreeNodePeer // Yields the number of values in a (non-root) leaf node for this set. template - constexpr static size_t GetNumValuesPerNode() - { + constexpr static size_t GetNumValuesPerNode() { return btree_node::kNodeValues; } }; @@ -1448,13 +1341,11 @@ namespace { // A btree set with a specific number of values per node. template> class SizedBtreeSet - : public btree_set_container< - btree, - BtreeNodePeer::GetTargetNodeSize(TargetValuesPerNode), - /*Multi=*/false>>> -{ + : public btree_set_container, + BtreeNodePeer::GetTargetNodeSize(TargetValuesPerNode), + /*Multi=*/false>>> { using Base = typename SizedBtreeSet::btree_set_container; public: @@ -1467,8 +1358,7 @@ void ExpectOperationCounts(const int expected_moves, const int expected_comparisons, const std::vector& values, InstanceTracker* tracker, - Set* set) -{ + Set* set) { for (const int v : values) set->insert(MovableOnlyInstance(v)); set->clear(); @@ -1481,8 +1371,7 @@ void ExpectOperationCounts(const int expected_moves, // Note: when the values in this test change, it is expected to have an impact // on performance. -TEST(Btree, MovesComparisonsCopiesSwapsTracking) -{ +TEST(Btree, MovesComparisonsCopiesSwapsTracking) { InstanceTracker tracker; // Note: this is minimum number of values per node. SizedBtreeSet set3; @@ -1521,18 +1410,15 @@ TEST(Btree, MovesComparisonsCopiesSwapsTracking) ExpectOperationCounts(534529, 125279, values, &tracker, &set100); } -struct MovableOnlyInstanceThreeWayCompare -{ - gtl::weak_ordering operator()(const MovableOnlyInstance& a, const MovableOnlyInstance& b) const - { +struct MovableOnlyInstanceThreeWayCompare { + gtl::weak_ordering operator()(const MovableOnlyInstance& a, const MovableOnlyInstance& b) const { return a.compare(b); } }; // Note: when the values in this test change, it is expected to have an impact // on performance. -TEST(Btree, MovesComparisonsCopiesSwapsTrackingThreeWayCompare) -{ +TEST(Btree, MovesComparisonsCopiesSwapsTrackingThreeWayCompare) { InstanceTracker tracker; // Note: this is minimum number of values per node. SizedBtreeSet m; for (int i = 1; i <= 99; ++i) { @@ -1618,8 +1500,7 @@ TEST(Btree, BtreeMapCanHoldNoDefaultCtorTypes) EXPECT_EQ(iter25->second.num, 75); } -TEST(Btree, BtreeMultimapCanHoldNoDefaultCtorTypes) -{ +TEST(Btree, BtreeMultimapCanHoldNoDefaultCtorTypes) { gtl::btree_multimap m; for (int i = 1; i <= 99; ++i) { @@ -1644,8 +1525,7 @@ TEST(Btree, BtreeMultimapCanHoldNoDefaultCtorTypes) EXPECT_EQ(iter25->second.num, 75); } -TEST(Btree, MapAt) -{ +TEST(Btree, MapAt) { gtl::btree_map map = { {1, 2}, { 2, 4} @@ -1659,8 +1539,7 @@ TEST(Btree, MapAt) EXPECT_THROW(map.at(3), std::out_of_range); } -TEST(Btree, BtreeMultisetEmplace) -{ +TEST(Btree, BtreeMultisetEmplace) { const int value_to_insert = 123456; gtl::btree_multiset s; auto iter = s.emplace(value_to_insert); @@ -1674,8 +1553,7 @@ TEST(Btree, BtreeMultisetEmplace) EXPECT_EQ(std::distance(result.first, result.second), 2); } -TEST(Btree, BtreeMultisetEmplaceHint) -{ +TEST(Btree, BtreeMultisetEmplaceHint) { const int value_to_insert = 123456; gtl::btree_multiset s; auto iter = s.emplace(value_to_insert); @@ -1687,8 +1565,7 @@ TEST(Btree, BtreeMultisetEmplaceHint) EXPECT_EQ(*emplace_iter, value_to_insert); } -TEST(Btree, BtreeMultimapEmplace) -{ +TEST(Btree, BtreeMultimapEmplace) { const int key_to_insert = 123456; const char value0[] = "a"; gtl::btree_multimap s; @@ -1706,8 +1583,7 @@ TEST(Btree, BtreeMultimapEmplace) EXPECT_EQ(std::distance(result.first, result.second), 2); } -TEST(Btree, BtreeMultimapEmplaceHint) -{ +TEST(Btree, BtreeMultimapEmplaceHint) { const int key_to_insert = 123456; const char value0[] = "a"; gtl::btree_multimap s; @@ -1723,8 +1599,7 @@ TEST(Btree, BtreeMultimapEmplaceHint) EXPECT_EQ(emplace_iter->second, value1); } -TEST(Btree, ConstIteratorAccessors) -{ +TEST(Btree, ConstIteratorAccessors) { gtl::btree_set set; for (int i = 0; i < 100; ++i) { set.insert(i); @@ -1754,8 +1629,7 @@ TEST(Btree, ConstIteratorAccessors) // literal 0. Defining this function allows for avoiding ClangTidy warnings. bool Identity(const bool b) { return b; } -TEST(Btree, ValueComp) -{ +TEST(Btree, ValueComp) { gtl::btree_set s; EXPECT_TRUE(s.value_comp()(1, 2)); EXPECT_FALSE(s.value_comp()(2, 2)); @@ -1772,8 +1646,7 @@ TEST(Btree, ValueComp) EXPECT_TRUE(Identity(m2.value_comp()(std::make_pair("b", 0), std::make_pair("a", 0)) > 0)); } -TEST(Btree, DefaultConstruction) -{ +TEST(Btree, DefaultConstruction) { gtl::btree_set s; gtl::btree_map m; gtl::btree_multiset ms; @@ -1847,8 +1720,7 @@ TEST(Btree, DefaultConstruction) } #endif -TEST(Btree, ComparableSet) -{ +TEST(Btree, ComparableSet) { gtl::btree_set s1 = { 1, 2 }; gtl::btree_set s2 = { 2, 3 }; EXPECT_LT(s1, s2); @@ -1859,8 +1731,7 @@ TEST(Btree, ComparableSet) EXPECT_GE(s1, s1); } -TEST(Btree, ComparableSetsDifferentLength) -{ +TEST(Btree, ComparableSetsDifferentLength) { gtl::btree_set s1 = { 1, 2 }; gtl::btree_set s2 = { 1, 2, 3 }; EXPECT_LT(s1, s2); @@ -1869,8 +1740,7 @@ TEST(Btree, ComparableSetsDifferentLength) EXPECT_GE(s2, s1); } -TEST(Btree, ComparableMultiset) -{ +TEST(Btree, ComparableMultiset) { gtl::btree_multiset s1 = { 1, 2 }; gtl::btree_multiset s2 = { 2, 3 }; EXPECT_LT(s1, s2); @@ -1881,8 +1751,7 @@ TEST(Btree, ComparableMultiset) EXPECT_GE(s1, s1); } -TEST(Btree, ComparableMap) -{ +TEST(Btree, ComparableMap) { gtl::btree_map s1 = { {1, 2} }; @@ -1897,8 +1766,7 @@ TEST(Btree, ComparableMap) EXPECT_GE(s1, s1); } -TEST(Btree, ComparableMultimap) -{ +TEST(Btree, ComparableMultimap) { gtl::btree_multimap s1 = { {1, 2} }; @@ -1913,8 +1781,7 @@ TEST(Btree, ComparableMultimap) EXPECT_GE(s1, s1); } -TEST(Btree, ComparableSetWithCustomComparator) -{ +TEST(Btree, ComparableSetWithCustomComparator) { // As specified by // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf section // [container.requirements.general].12, ordering associative containers always @@ -1930,8 +1797,7 @@ TEST(Btree, ComparableSetWithCustomComparator) EXPECT_GE(s1, s1); } -TEST(Btree, EraseReturnsIterator) -{ +TEST(Btree, EraseReturnsIterator) { gtl::btree_set set = { 1, 2, 3, 4, 5 }; auto result_it = set.erase(set.begin(), set.find(3)); EXPECT_EQ(result_it, set.find(3)); @@ -1939,8 +1805,7 @@ TEST(Btree, EraseReturnsIterator) EXPECT_EQ(result_it, set.end()); } -TEST(Btree, ExtractAndInsertNodeHandleSet) -{ +TEST(Btree, ExtractAndInsertNodeHandleSet) { gtl::btree_set src1 = { 1, 2, 3, 4, 5 }; auto nh = src1.extract(src1.find(3)); EXPECT_THAT(src1, ElementsAre(1, 2, 4, 5)); @@ -1963,8 +1828,7 @@ TEST(Btree, ExtractAndInsertNodeHandleSet) } template -void TestExtractWithTrackingForSet() -{ +void TestExtractWithTrackingForSet() { InstanceTracker tracker; { Set s; @@ -1996,8 +1860,7 @@ void TestExtractWithTrackingForSet() } template -void TestExtractWithTrackingForMap() -{ +void TestExtractWithTrackingForMap() { InstanceTracker tracker; { Map m; @@ -2030,17 +1893,14 @@ void TestExtractWithTrackingForMap() EXPECT_EQ(0, tracker.instances()); } -TEST(Btree, ExtractTracking) -{ +TEST(Btree, ExtractTracking) { TestExtractWithTrackingForSet>(); TestExtractWithTrackingForSet>(); TestExtractWithTrackingForMap>(); - TestExtractWithTrackingForMap< - gtl::btree_multimap>(); + TestExtractWithTrackingForMap>(); } -TEST(Btree, ExtractAndInsertNodeHandleMultiSet) -{ +TEST(Btree, ExtractAndInsertNodeHandleMultiSet) { gtl::btree_multiset src1 = { 1, 2, 3, 3, 4, 5 }; auto nh = src1.extract(src1.find(3)); EXPECT_THAT(src1, ElementsAre(1, 2, 3, 4, 5)); @@ -2057,8 +1917,7 @@ TEST(Btree, ExtractAndInsertNodeHandleMultiSet) EXPECT_EQ(res, ++other.find(3)); } -TEST(Btree, ExtractAndInsertNodeHandleMap) -{ +TEST(Btree, ExtractAndInsertNodeHandleMap) { gtl::btree_map src1 = { {1, 2}, { 3, 4}, @@ -2087,8 +1946,7 @@ TEST(Btree, ExtractAndInsertNodeHandleMap) EXPECT_EQ(res.node.mapped(), 6); } -TEST(Btree, ExtractAndInsertNodeHandleMultiMap) -{ +TEST(Btree, ExtractAndInsertNodeHandleMultiMap) { gtl::btree_multimap src1 = { {1, 2}, { 3, 4}, @@ -2113,29 +1971,20 @@ TEST(Btree, ExtractAndInsertNodeHandleMultiMap) // For multisets, insert with hint also affects correctness because we need to // insert immediately before the hint if possible. -struct InsertMultiHintData -{ +struct InsertMultiHintData { int key; int not_key; - bool operator==(const InsertMultiHintData other) const - { - return key == other.key && not_key == other.not_key; - } + bool operator==(const InsertMultiHintData other) const { return key == other.key && not_key == other.not_key; } }; -struct InsertMultiHintDataKeyCompare -{ +struct InsertMultiHintDataKeyCompare { using is_transparent = void; - bool operator()(const InsertMultiHintData a, const InsertMultiHintData b) const - { - return a.key < b.key; - } + bool operator()(const InsertMultiHintData a, const InsertMultiHintData b) const { return a.key < b.key; } bool operator()(const int a, const InsertMultiHintData b) const { return a < b.key; } bool operator()(const InsertMultiHintData a, const int b) const { return a.key < b; } }; -TEST(Btree, InsertHintNodeHandle) -{ +TEST(Btree, InsertHintNodeHandle) { // For unique sets, insert with hint is just a performance optimization. // Test that insert works correctly when the hint is right or wrong. { @@ -2187,10 +2036,8 @@ TEST(Btree, InsertHintNodeHandle) EXPECT_EQ(it, other.begin()); } -struct IntCompareToCmp -{ - gtl::weak_ordering operator()(const int& a, const int& b) const - { +struct IntCompareToCmp { + gtl::weak_ordering operator()(const int& a, const int& b) const { if (a < b) return gtl::weak_ordering::less; if (a > b) @@ -2199,8 +2046,7 @@ struct IntCompareToCmp } }; -TEST(Btree, MergeIntoUniqueContainers) -{ +TEST(Btree, MergeIntoUniqueContainers) { gtl::btree_set src1 = { 1, 2, 3 }; gtl::btree_multiset src2 = { 3, 4, 4, 5 }; gtl::btree_set dst; @@ -2213,8 +2059,7 @@ TEST(Btree, MergeIntoUniqueContainers) EXPECT_THAT(dst, ElementsAre(1, 2, 3, 4, 5)); } -TEST(Btree, MergeIntoUniqueContainersWithCompareTo) -{ +TEST(Btree, MergeIntoUniqueContainersWithCompareTo) { gtl::btree_set src1 = { 1, 2, 3 }; gtl::btree_multiset src2 = { 3, 4, 4, 5 }; gtl::btree_set dst; @@ -2227,8 +2072,7 @@ TEST(Btree, MergeIntoUniqueContainersWithCompareTo) EXPECT_THAT(dst, ElementsAre(1, 2, 3, 4, 5)); } -TEST(Btree, MergeIntoMultiContainers) -{ +TEST(Btree, MergeIntoMultiContainers) { gtl::btree_set src1 = { 1, 2, 3 }; gtl::btree_multiset src2 = { 3, 4, 4, 5 }; gtl::btree_multiset dst; @@ -2241,8 +2085,7 @@ TEST(Btree, MergeIntoMultiContainers) EXPECT_THAT(dst, ElementsAre(1, 2, 3, 3, 4, 4, 5)); } -TEST(Btree, MergeIntoMultiContainersWithCompareTo) -{ +TEST(Btree, MergeIntoMultiContainersWithCompareTo) { gtl::btree_set src1 = { 1, 2, 3 }; gtl::btree_multiset src2 = { 3, 4, 4, 5 }; gtl::btree_multiset dst; @@ -2255,8 +2098,7 @@ TEST(Btree, MergeIntoMultiContainersWithCompareTo) EXPECT_THAT(dst, ElementsAre(1, 2, 3, 3, 4, 4, 5)); } -TEST(Btree, MergeIntoMultiMapsWithDifferentComparators) -{ +TEST(Btree, MergeIntoMultiMapsWithDifferentComparators) { gtl::btree_map src1 = { {1, 1}, { 2, 2}, @@ -2275,36 +2117,26 @@ TEST(Btree, MergeIntoMultiMapsWithDifferentComparators) EXPECT_THAT(dst, ElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3))); dst.merge(src2); EXPECT_TRUE(src2.empty()); - EXPECT_THAT( - dst, - ElementsAre( - Pair(1, 1), Pair(2, 2), Pair(3, 3), Pair(3, 2), Pair(4, 1), Pair(4, 4), Pair(5, 5))); + EXPECT_THAT(dst, ElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3), Pair(3, 2), Pair(4, 1), Pair(4, 4), Pair(5, 5))); } -struct KeyCompareToWeakOrdering -{ +struct KeyCompareToWeakOrdering { template - gtl::weak_ordering operator()(const T& a, const T& b) const - { - return a < b ? gtl::weak_ordering::less - : a == b ? gtl::weak_ordering::equivalent - : gtl::weak_ordering::greater; + gtl::weak_ordering operator()(const T& a, const T& b) const { + return a < b ? gtl::weak_ordering::less : a == b ? gtl::weak_ordering::equivalent : gtl::weak_ordering::greater; } }; -struct KeyCompareToStrongOrdering -{ +struct KeyCompareToStrongOrdering { template - gtl::strong_ordering operator()(const T& a, const T& b) const - { + gtl::strong_ordering operator()(const T& a, const T& b) const { return a < b ? gtl::strong_ordering::less : a == b ? gtl::strong_ordering::equal : gtl::strong_ordering::greater; } }; -TEST(Btree, UserProvidedKeyCompareToComparators) -{ +TEST(Btree, UserProvidedKeyCompareToComparators) { gtl::btree_set weak_set = { 1, 2, 3 }; EXPECT_TRUE(weak_set.contains(2)); EXPECT_FALSE(weak_set.contains(4)); @@ -2314,8 +2146,7 @@ TEST(Btree, UserProvidedKeyCompareToComparators) EXPECT_FALSE(strong_set.contains(4)); } -TEST(Btree, TryEmplaceBasicTest) -{ +TEST(Btree, TryEmplaceBasicTest) { gtl::btree_map m; // Should construct a std::string from the literal. @@ -2336,8 +2167,7 @@ TEST(Btree, TryEmplaceBasicTest) })); } -TEST(Btree, TryEmplaceWithHintWorks) -{ +TEST(Btree, TryEmplaceWithHintWorks) { // Use a counting comparator here to verify that hint is used. int calls = 0; auto cmp = [&calls](int x, int y) { @@ -2397,8 +2227,7 @@ TEST(Btree, TryEmplaceWithHintWorks) EXPECT_TRUE(std::is_sorted(m.begin(), m.end())); } -TEST(Btree, TryEmplaceWithBadHint) -{ +TEST(Btree, TryEmplaceWithBadHint) { gtl::btree_map m = { {1, 1}, { 9, 9} @@ -2426,8 +2255,7 @@ TEST(Btree, TryEmplaceWithBadHint) })); } -TEST(Btree, TryEmplaceMaintainsSortedOrder) -{ +TEST(Btree, TryEmplaceMaintainsSortedOrder) { gtl::btree_map m; std::pair pair5 = { 5, "five" }; @@ -2444,22 +2272,19 @@ TEST(Btree, TryEmplaceMaintainsSortedOrder) EXPECT_TRUE(std::is_sorted(m.begin(), m.end())); } -TEST(Btree, TryEmplaceWithHintAndNoValueArgsWorks) -{ +TEST(Btree, TryEmplaceWithHintAndNoValueArgsWorks) { gtl::btree_map m; m.try_emplace(m.end(), 1); EXPECT_EQ(0, m[1]); } -TEST(Btree, TryEmplaceWithHintAndMultipleValueArgsWorks) -{ +TEST(Btree, TryEmplaceWithHintAndMultipleValueArgsWorks) { gtl::btree_map m; m.try_emplace(m.end(), 1, 10, 'a'); EXPECT_EQ(std::string(10, 'a'), m[1]); } -TEST(Btree, MoveAssignmentAllocatorPropagation) -{ +TEST(Btree, MoveAssignmentAllocatorPropagation) { InstanceTracker tracker; int64_t bytes1 = 0, bytes2 = 0; @@ -2483,9 +2308,7 @@ TEST(Btree, MoveAssignmentAllocatorPropagation) } // Test non-propagating allocator_type with equal allocators. { - gtl::btree_set, - CountingAllocator> + gtl::btree_set, CountingAllocator> set1(cmp, allocator1), set2(cmp, allocator1); for (int i = 0; i < 100; ++i) @@ -2497,9 +2320,7 @@ TEST(Btree, MoveAssignmentAllocatorPropagation) } // Test non-propagating allocator_type with different allocators. { - gtl::btree_set, - CountingAllocator> + gtl::btree_set, CountingAllocator> set1(cmp, allocator1), set2(cmp, allocator2); for (int i = 0; i < 100; ++i) @@ -2511,8 +2332,7 @@ TEST(Btree, MoveAssignmentAllocatorPropagation) } } -TEST(Btree, EmptyTree) -{ +TEST(Btree, EmptyTree) { gtl::btree_set s; EXPECT_TRUE(s.empty()); EXPECT_EQ(s.size(), 0u); @@ -2521,8 +2341,7 @@ TEST(Btree, EmptyTree) bool IsEven(int k) { return k % 2 == 0; } -TEST(Btree, EraseIf) -{ +TEST(Btree, EraseIf) { // Test that erase_if works with all the container types and supports lambdas. { gtl::btree_set s = { 1, 3, 5, 6, 100 }; diff --git a/tests/btree/btree_test.hpp b/tests/btree/btree_test.hpp index eea9943..4e421bf 100644 --- a/tests/btree/btree_test.hpp +++ b/tests/btree/btree_test.hpp @@ -63,19 +63,16 @@ namespace test_internal { // have occurred on the type. This is used as a base class for the copyable, // copyable+movable, and movable types below that are used in actual tests. Use // InstanceTracker in tests to track the number of instances. -class BaseCountedInstance -{ +class BaseCountedInstance { public: explicit BaseCountedInstance(size_t x) - : value_(x) - { + : value_(x) { ++num_instances_; ++num_live_instances_; } BaseCountedInstance(const BaseCountedInstance& x) : value_(x.value_) - , is_live_(x.is_live_) - { + , is_live_(x.is_live_) { ++num_instances_; if (is_live_) ++num_live_instances_; @@ -83,21 +80,18 @@ class BaseCountedInstance } BaseCountedInstance(BaseCountedInstance&& x) : value_(x.value_) - , is_live_(x.is_live_) - { + , is_live_(x.is_live_) { x.is_live_ = false; ++num_instances_; ++num_moves_; } - ~BaseCountedInstance() - { + ~BaseCountedInstance() { --num_instances_; if (is_live_) --num_live_instances_; } - BaseCountedInstance& operator=(const BaseCountedInstance& x) - { + BaseCountedInstance& operator=(const BaseCountedInstance& x) { value_ = x.value_; if (is_live_) --num_live_instances_; @@ -107,8 +101,7 @@ class BaseCountedInstance ++num_copies_; return *this; } - BaseCountedInstance& operator=(BaseCountedInstance&& x) - { + BaseCountedInstance& operator=(BaseCountedInstance&& x) { value_ = x.value_; if (is_live_) --num_live_instances_; @@ -118,66 +111,56 @@ class BaseCountedInstance return *this; } - bool operator==(const BaseCountedInstance& x) const - { + bool operator==(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ == x.value_; } - bool operator!=(const BaseCountedInstance& x) const - { + bool operator!=(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ != x.value_; } - bool operator<(const BaseCountedInstance& x) const - { + bool operator<(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ < x.value_; } - bool operator>(const BaseCountedInstance& x) const - { + bool operator>(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ > x.value_; } - bool operator<=(const BaseCountedInstance& x) const - { + bool operator<=(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ <= x.value_; } - bool operator>=(const BaseCountedInstance& x) const - { + bool operator>=(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ >= x.value_; } - gtl::weak_ordering compare(const BaseCountedInstance& x) const - { + gtl::weak_ordering compare(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ < x.value_ ? gtl::weak_ordering::less : value_ == x.value_ ? gtl::weak_ordering::equivalent : gtl::weak_ordering::greater; } - size_t value() const - { + size_t value() const { if (!is_live_) std::abort(); return value_; } - friend std::ostream& operator<<(std::ostream& o, const BaseCountedInstance& v) - { + friend std::ostream& operator<<(std::ostream& o, const BaseCountedInstance& v) { return o << "[value:" << v.value() << "]"; } // Implementation of efficient swap() that counts swaps. - static void SwapImpl(BaseCountedInstance& lhs, // NOLINT(runtime/references) - BaseCountedInstance& rhs) - { // NOLINT(runtime/references) + static void SwapImpl(BaseCountedInstance& lhs, // NOLINT(runtime/references) + BaseCountedInstance& rhs) { // NOLINT(runtime/references) using std::swap; swap(lhs.value_, rhs.value_); swap(lhs.is_live_, rhs.is_live_); @@ -214,17 +197,14 @@ class BaseCountedInstance // Helper to track the BaseCountedInstance instance counters. Expects that the // number of instances and live_instances are the same when it is constructed // and when it is destructed. -class InstanceTracker -{ +class InstanceTracker { public: InstanceTracker() : start_instances_(BaseCountedInstance::num_instances_) - , start_live_instances_(BaseCountedInstance::num_live_instances_) - { + , start_live_instances_(BaseCountedInstance::num_live_instances_) { ResetCopiesMovesSwaps(); } - ~InstanceTracker() - { + ~InstanceTracker() { if (instances() != 0) std::abort(); if (live_instances() != 0) @@ -238,10 +218,7 @@ class InstanceTracker // Returns the number of live BaseCountedInstance instances compared to when // the InstanceTracker was constructed - size_t live_instances() const - { - return BaseCountedInstance::num_live_instances_ - start_live_instances_; - } + size_t live_instances() const { return BaseCountedInstance::num_live_instances_ - start_live_instances_; } // Returns the number of moves on BaseCountedInstance objects since // construction or since the last call to ResetCopiesMovesSwaps(). @@ -257,17 +234,13 @@ class InstanceTracker // Returns the number of comparisons on BaseCountedInstance objects since // construction or the last call to ResetCopiesMovesSwaps(). - size_t comparisons() const - { - return BaseCountedInstance::num_comparisons_ - start_comparisons_; - } + size_t comparisons() const { return BaseCountedInstance::num_comparisons_ - start_comparisons_; } // Resets the base values for moves, copies, comparisons, and swaps to the // current values, so that subsequent Get*() calls for moves, copies, // comparisons, and swaps will compare to the situation at the point of this // call. - void ResetCopiesMovesSwaps() - { + void ResetCopiesMovesSwaps() { start_moves_ = BaseCountedInstance::num_moves_; start_copies_ = BaseCountedInstance::num_copies_; start_swaps_ = BaseCountedInstance::num_swaps_; @@ -284,39 +257,29 @@ class InstanceTracker }; // Copyable, not movable. -class CopyableOnlyInstance : public BaseCountedInstance -{ +class CopyableOnlyInstance : public BaseCountedInstance { public: explicit CopyableOnlyInstance(size_t x) - : BaseCountedInstance(x) - { - } + : BaseCountedInstance(x) {} CopyableOnlyInstance(const CopyableOnlyInstance& rhs) = default; CopyableOnlyInstance& operator=(const CopyableOnlyInstance& rhs) = default; - friend void swap(CopyableOnlyInstance& lhs, CopyableOnlyInstance& rhs) - { - BaseCountedInstance::SwapImpl(lhs, rhs); - } + friend void swap(CopyableOnlyInstance& lhs, CopyableOnlyInstance& rhs) { BaseCountedInstance::SwapImpl(lhs, rhs); } static bool supports_move() { return false; } }; // Copyable and movable. -class CopyableMovableInstance : public BaseCountedInstance -{ +class CopyableMovableInstance : public BaseCountedInstance { public: explicit CopyableMovableInstance(size_t x) - : BaseCountedInstance(x) - { - } + : BaseCountedInstance(x) {} CopyableMovableInstance(const CopyableMovableInstance& rhs) = default; CopyableMovableInstance(CopyableMovableInstance&& rhs) = default; CopyableMovableInstance& operator=(const CopyableMovableInstance& rhs) = default; CopyableMovableInstance& operator=(CopyableMovableInstance&& rhs) = default; - friend void swap(CopyableMovableInstance& lhs, CopyableMovableInstance& rhs) - { + friend void swap(CopyableMovableInstance& lhs, CopyableMovableInstance& rhs) { BaseCountedInstance::SwapImpl(lhs, rhs); } @@ -324,20 +287,14 @@ class CopyableMovableInstance : public BaseCountedInstance }; // Only movable, not default-constructible. -class MovableOnlyInstance : public BaseCountedInstance -{ +class MovableOnlyInstance : public BaseCountedInstance { public: explicit MovableOnlyInstance(size_t x) - : BaseCountedInstance(x) - { - } + : BaseCountedInstance(x) {} MovableOnlyInstance(MovableOnlyInstance&& other) = default; MovableOnlyInstance& operator=(MovableOnlyInstance&& other) = default; - friend void swap(MovableOnlyInstance& lhs, MovableOnlyInstance& rhs) - { - BaseCountedInstance::SwapImpl(lhs, rhs); - } + friend void swap(MovableOnlyInstance& lhs, MovableOnlyInstance& rhs) { BaseCountedInstance::SwapImpl(lhs, rhs); } static bool supports_move() { return true; } }; @@ -348,24 +305,19 @@ namespace priv { // Like remove_const but propagates the removal through std::pair. template -struct remove_pair_const -{ +struct remove_pair_const { using type = typename std::remove_const::type; }; template -struct remove_pair_const> -{ - using type = - std::pair::type, typename remove_pair_const::type>; +struct remove_pair_const> { + using type = std::pair::type, typename remove_pair_const::type>; }; // Utility class to provide an accessor for a key given a value. The default // behavior is to treat the value as a pair and return the first element. template -struct KeyOfValue -{ - struct type - { +struct KeyOfValue { + struct type { const K& operator()(const V& p) const { return p.first; } }; }; @@ -373,16 +325,13 @@ struct KeyOfValue // Partial specialization of KeyOfValue class for when the key and value are // the same type such as in set<> and btree_set<>. template -struct KeyOfValue -{ - struct type - { +struct KeyOfValue { + struct type { const K& operator()(const K& k) const { return k; } }; }; -inline char* GenerateDigits(char buf[16], unsigned val, unsigned maxval) -{ +inline char* GenerateDigits(char buf[16], unsigned val, unsigned maxval) { assert(val <= maxval); constexpr unsigned kBase = 64; // avoid integer division. unsigned p = 15; @@ -396,15 +345,11 @@ inline char* GenerateDigits(char buf[16], unsigned val, unsigned maxval) } template -struct Generator -{ +struct Generator { int maxval; explicit Generator(int m) - : maxval(m) - { - } - K operator()(int i) const - { + : maxval(m) {} + K operator()(int i) const { assert(i <= maxval); return K(i); } @@ -420,37 +365,29 @@ struct Generator #endif template<> -struct Generator -{ +struct Generator { int maxval; explicit Generator(int m) - : maxval(m) - { - } - std::string operator()(int i) const - { + : maxval(m) {} + std::string operator()(int i) const { char buf[16]; return GenerateDigits(buf, i, maxval); } }; template -struct Generator> -{ +struct Generator> { Generator::type> tgen; Generator::type> ugen; explicit Generator(int m) : tgen(m) - , ugen(m) - { - } + , ugen(m) {} std::pair operator()(int i) const { return std::make_pair(tgen(i), ugen(i)); } }; // Generate n values for our tests and benchmarks. Value range is [0, maxval]. -inline std::vector GenerateNumbersWithSeed(size_t n, int maxval, int seed) -{ +inline std::vector GenerateNumbersWithSeed(size_t n, int maxval, int seed) { // NOTE: Some tests rely on generated numbers not changing between test runs. // We use std::minstd_rand0 because it is well-defined, but don't use // std::uniform_int_distribution because platforms use different algorithms. @@ -473,8 +410,7 @@ inline std::vector GenerateNumbersWithSeed(size_t n, int maxval, int seed) // Generates n values in the range [0, maxval]. template -std::vector GenerateValuesWithSeed(size_t n, int maxval, int seed) -{ +std::vector GenerateValuesWithSeed(size_t n, int maxval, int seed) { const std::vector nums = GenerateNumbersWithSeed(n, maxval, seed); Generator gen(maxval); std::vector vec; @@ -497,8 +433,7 @@ namespace priv { // containers - that chain of allocators uses the same state and is // thus easier to query for aggregate allocation information. template -class CountingAllocator : public std::allocator -{ +class CountingAllocator : public std::allocator { public: using Alloc = std::allocator; using AllocTraits = typename std::allocator_traits; @@ -506,52 +441,38 @@ class CountingAllocator : public std::allocator using size_type = typename AllocTraits::size_type; CountingAllocator() - : bytes_used_(nullptr) - { - } + : bytes_used_(nullptr) {} explicit CountingAllocator(int64_t* b) - : bytes_used_(b) - { - } + : bytes_used_(b) {} template CountingAllocator(const CountingAllocator& x) : Alloc(x) - , bytes_used_(x.bytes_used_) - { - } + , bytes_used_(x.bytes_used_) {} - pointer allocate(size_type n, - std::allocator_traits>::const_pointer hint = nullptr) - { + pointer allocate(size_type n, std::allocator_traits>::const_pointer hint = nullptr) { assert(bytes_used_ != nullptr); *bytes_used_ += n * sizeof(T); return AllocTraits::allocate(*this, n, hint); } - void deallocate(pointer p, size_type n) - { + void deallocate(pointer p, size_type n) { AllocTraits::deallocate(*this, p, n); assert(bytes_used_ != nullptr); *bytes_used_ -= n * sizeof(T); } template - class rebind - { + class rebind { public: using other = CountingAllocator; }; - friend bool operator==(const CountingAllocator& a, const CountingAllocator& b) - { + friend bool operator==(const CountingAllocator& a, const CountingAllocator& b) { return a.bytes_used_ == b.bytes_used_; } - friend bool operator!=(const CountingAllocator& a, const CountingAllocator& b) - { - return !(a == b); - } + friend bool operator!=(const CountingAllocator& a, const CountingAllocator& b) { return !(a == b); } int64_t* bytes_used_; }; diff --git a/tests/misc/bitvector_test.cpp b/tests/misc/bitvector_test.cpp index 9e7b33c..986f2e2 100644 --- a/tests/misc/bitvector_test.cpp +++ b/tests/misc/bitvector_test.cpp @@ -10,30 +10,26 @@ #include "gtest/gtest.h" #include -void set_bits_naive(gtl::bit_vector& v, size_t first, size_t last) -{ +void set_bits_naive(gtl::bit_vector& v, size_t first, size_t last) { for (size_t i = first; i < last; ++i) { v.set(i); // EXPECT_TRUE(v[i]); } } -void flip_bits_naive(gtl::bit_vector& v, size_t first, size_t last) -{ +void flip_bits_naive(gtl::bit_vector& v, size_t first, size_t last) { for (size_t i = first; i < last; ++i) v.flip(i); } -void reset_bits_naive(gtl::bit_vector& v, size_t first, size_t last) -{ +void reset_bits_naive(gtl::bit_vector& v, size_t first, size_t last) { for (size_t i = first; i < last; ++i) { v.reset(i); // EXPECT_FALSE(v[i]); } } -const std::vector& get_test_vector() -{ +const std::vector& get_test_vector() { static std::vector res; if (res.empty()) { res.push_back(gtl::bit_vector(0)); @@ -94,8 +90,7 @@ const std::vector& get_test_vector() return res; } -TEST(BitVectorTest, resize) -{ +TEST(BitVectorTest, resize) { gtl::bit_vector v1(128), v2(100); v1.set(); v2.set(); @@ -115,8 +110,7 @@ TEST(BitVectorTest, resize) EXPECT_TRUE(v1 == v2); } -TEST(BitVectorTest, bit_view_change) -{ +TEST(BitVectorTest, bit_view_change) { static constexpr size_t sz = 500; gtl::bit_vector tv1(sz), tv2(sz); @@ -154,8 +148,7 @@ TEST(BitVectorTest, bit_view_change) bv_change_test(tv1, tv2, sz - 130); } -TEST(BitVectorTest, bitwise_op_on_bv) -{ +TEST(BitVectorTest, bitwise_op_on_bv) { { static constexpr size_t sz = 500; gtl::bit_vector v1(sz), v2(sz), v3(sz); @@ -188,8 +181,7 @@ TEST(BitVectorTest, bitwise_op_on_bv) } } -TEST(BitVectorTest, bitwise_assign_op_on_full_bit_vector) -{ +TEST(BitVectorTest, bitwise_assign_op_on_full_bit_vector) { const std::vector& testv = get_test_vector(); for (auto v1 : testv) { auto v2 = v1; @@ -206,13 +198,8 @@ TEST(BitVectorTest, bitwise_assign_op_on_full_bit_vector) } } -TEST(BitVectorTest, bit_shift) -{ - auto check = [](const gtl::bit_vector& v_orig, - const gtl::bit_vector& v2, - int i_shift, - size_t first, - size_t last) { +TEST(BitVectorTest, bit_shift) { + auto check = [](const gtl::bit_vector& v_orig, const gtl::bit_vector& v2, int i_shift, size_t first, size_t last) { size_t shift = (i_shift >= 0) ? (size_t)i_shift : (size_t)-i_shift; last = std::min(last, v2.size()); if (shift <= last - first) { @@ -226,25 +213,22 @@ TEST(BitVectorTest, bit_shift) } }; - auto bitshift_check = [&](const gtl::bit_vector& v_orig, - int shift, - size_t first = 0, - size_t last = gtl::bit_vector::npos) { - if (last == gtl::bit_vector::npos) - last = v_orig.size(); - if (first == 0 && last == v_orig.size()) { - gtl::bit_vector v = (shift >= 0) ? (v_orig >> (size_t)shift) - : (v_orig << (size_t)-shift); - check(v_orig, v, shift, first, last); - } else { - gtl::bit_vector v(v_orig); - if (shift >= 0) - v.view(first, last) >>= (size_t)shift; - else - v.view(first, last) <<= (size_t)-shift; - check(v_orig, v, shift, first, last); - } - }; + auto bitshift_check = + [&](const gtl::bit_vector& v_orig, int shift, size_t first = 0, size_t last = gtl::bit_vector::npos) { + if (last == gtl::bit_vector::npos) + last = v_orig.size(); + if (first == 0 && last == v_orig.size()) { + gtl::bit_vector v = (shift >= 0) ? (v_orig >> (size_t)shift) : (v_orig << (size_t)-shift); + check(v_orig, v, shift, first, last); + } else { + gtl::bit_vector v(v_orig); + if (shift >= 0) + v.view(first, last) >>= (size_t)shift; + else + v.view(first, last) <<= (size_t)-shift; + check(v_orig, v, shift, first, last); + } + }; auto check_range = [&](const gtl::bit_vector& v, int shift, size_t width) { if (v.size() > width) { @@ -273,15 +257,13 @@ TEST(BitVectorTest, bit_shift) } } -TEST(BitVectorTest, view_assignment) -{ +TEST(BitVectorTest, view_assignment) { auto check_va = [](const gtl::bit_vector& v2, size_t div, const size_t incr = 3) { size_t sz = v2.size(); if (sz) { gtl::bit_vector v(sz, false), v1(sz); for (size_t i = 0; i < div; ++i) - v.view((i * sz) / div, ((i + 1) * sz) / div) = - v2.view((i * sz) / div, ((i + 1) * sz) / div); + v.view((i * sz) / div, ((i + 1) * sz) / div) = v2.view((i * sz) / div, ((i + 1) * sz) / div); EXPECT_TRUE(v == v2); for (size_t i = 0; i < sz - 1; ++i) { @@ -332,8 +314,7 @@ TEST(BitVectorTest, view_assignment) } } -TEST(BitVectorTest, unary_predicates_on_full_bit_vector) -{ +TEST(BitVectorTest, unary_predicates_on_full_bit_vector) { auto check_sz = [](size_t sz) { gtl::bit_vector v(sz); @@ -352,8 +333,7 @@ TEST(BitVectorTest, unary_predicates_on_full_bit_vector) check_sz(199); } -TEST(BitVectorTest, binary_predicates_on_full_bit_vector) -{ +TEST(BitVectorTest, binary_predicates_on_full_bit_vector) { const std::vector& testv = get_test_vector(); for (auto v1 : testv) { auto v1_copy = v1; @@ -374,18 +354,16 @@ TEST(BitVectorTest, binary_predicates_on_full_bit_vector) } } -TEST(BitVectorTest, count) -{ - auto count_naive = - [](const gtl::bit_vector& v, size_t first = 0, size_t last = gtl::bit_vector::npos) { - size_t n = 0; - if (last == gtl::bit_vector::npos) - last = v.size(); - for (size_t i = first; i < last; ++i) - if (v[i]) - ++n; - return n; - }; +TEST(BitVectorTest, count) { + auto count_naive = [](const gtl::bit_vector& v, size_t first = 0, size_t last = gtl::bit_vector::npos) { + size_t n = 0; + if (last == gtl::bit_vector::npos) + last = v.size(); + for (size_t i = first; i < last; ++i) + if (v[i]) + ++n; + return n; + }; const std::vector& testv = get_test_vector(); for (auto v : testv) { @@ -410,8 +388,7 @@ TEST(BitVectorTest, count) } } -TEST(BitVectorTest, find_first) -{ +TEST(BitVectorTest, find_first) { gtl::bit_vector v{ 0, 0, 0x020202 }; EXPECT_TRUE(v.find_first() == 129); EXPECT_TRUE(v.view(10).find_first() == 119); // returns the index from start of view @@ -425,8 +402,7 @@ TEST(BitVectorTest, find_first) EXPECT_TRUE(v2.view(67).find_next(191) == 198); } -TEST(BitVectorTest, hash) -{ +TEST(BitVectorTest, hash) { gtl::bit_vector v{ 0xfafafaull, 0ull, 0x4444444444444444ull }; auto x = std::hash()(v); @@ -439,8 +415,7 @@ TEST(BitVectorTest, hash) EXPECT_TRUE(z != y); } -TEST(BitVectorTest, conversions) -{ +TEST(BitVectorTest, conversions) { static constexpr size_t sz = 100; gtl::bit_vector v(sz); for (size_t i = 0; i < sz; i += 4) diff --git a/tests/misc/lru_cache_test.cpp b/tests/misc/lru_cache_test.cpp index 9402546..8090788 100644 --- a/tests/misc/lru_cache_test.cpp +++ b/tests/misc/lru_cache_test.cpp @@ -4,22 +4,19 @@ constexpr int CACHETEST1_NUM_OF_RECORDS = 100; constexpr int CACHETEST1_CACHE_CAPACITY = 50; -TEST(CacheTest, SimplePut) -{ +TEST(CacheTest, SimplePut) { gtl::lru_cache cache; cache.insert(7, 777); EXPECT_TRUE(cache.exists(7)); EXPECT_EQ(777, *cache.get(7)); } -TEST(CacheTest, MissingValue) -{ +TEST(CacheTest, MissingValue) { gtl::lru_cache cache; EXPECT_FALSE(cache.get(7)); } -TEST(CacheTest1, KeepsAllValuesWithinCapacity) -{ +TEST(CacheTest1, KeepsAllValuesWithinCapacity) { gtl::lru_cache cache(CACHETEST1_CACHE_CAPACITY); for (int i = 0; i < CACHETEST1_NUM_OF_RECORDS; ++i) { @@ -30,9 +27,7 @@ TEST(CacheTest1, KeepsAllValuesWithinCapacity) EXPECT_FALSE(cache.exists(i)); } - for (int i = CACHETEST1_NUM_OF_RECORDS - CACHETEST1_CACHE_CAPACITY; - i < CACHETEST1_NUM_OF_RECORDS; - ++i) { + for (int i = CACHETEST1_NUM_OF_RECORDS - CACHETEST1_CACHE_CAPACITY; i < CACHETEST1_NUM_OF_RECORDS; ++i) { EXPECT_TRUE(cache.exists(i)); EXPECT_EQ(i, *cache.get(i)); } @@ -41,8 +36,7 @@ TEST(CacheTest1, KeepsAllValuesWithinCapacity) EXPECT_EQ(static_cast(CACHETEST1_CACHE_CAPACITY), size); } -TEST(CacheTest1, mtKeepsAllValuesWithinCapacity) -{ +TEST(CacheTest1, mtKeepsAllValuesWithinCapacity) { gtl::mt_lru_cache cache(5000); // an approximation for (int i = 0; i < 10000; ++i) { diff --git a/tests/misc/vector_test.cpp b/tests/misc/vector_test.cpp index 71a2a29..907fd75 100644 --- a/tests/misc/vector_test.cpp +++ b/tests/misc/vector_test.cpp @@ -33,15 +33,13 @@ using RandomT = std::mt19937; static RandomT rng; template -Integral2 random(Integral1 low, Integral2 up) -{ +Integral2 random(Integral1 low, Integral2 up) { std::uniform_int_distribution range(low, up); return static_cast(range(rng)); } template -void randomString(String* toFill, unsigned int maxSize = 1000) -{ +void randomString(String* toFill, unsigned int maxSize = 1000) { assert(toFill); toFill->resize(random(0, maxSize)); for (auto& c : *toFill) { @@ -50,15 +48,13 @@ void randomString(String* toFill, unsigned int maxSize = 1000) } template -void Num2String(String& str, Integral /* n */) -{ +void Num2String(String& str, Integral /* n */) { str.resize(10, '\0'); sprintf(&str[0], "%ul", 10); str.resize(strlen(str.c_str())); } -std::list RandomList(unsigned int maxSize) -{ +std::list RandomList(unsigned int maxSize) { std::list lst(random(0u, maxSize)); std::list::iterator i = lst.begin(); for (; i != lst.end(); ++i) { @@ -77,14 +73,12 @@ template<> std::string randomObject(); template<> -int randomObject() -{ +int randomObject() { return random(0, 1024); } template<> -std::string randomObject() -{ +std::string randomObject() { std::string result; randomString(&result); return result; @@ -102,8 +96,7 @@ using StringVector = gtl::vector; #include "./vector_test.cpp.h" // nolint #undef VECTOR -TEST(vector, clause_23_3_6_1_3_ambiguity) -{ +TEST(vector, clause_23_3_6_1_3_ambiguity) { gtl::vector v(10, 20); EXPECT_EQ(v.size(), 10); for (const auto& i : v) { @@ -111,8 +104,7 @@ TEST(vector, clause_23_3_6_1_3_ambiguity) } } -TEST(vector, clause_23_3_6_1_11_ambiguity) -{ +TEST(vector, clause_23_3_6_1_11_ambiguity) { gtl::vector v; v.assign(10, 20); EXPECT_EQ(v.size(), 10); @@ -121,8 +113,7 @@ TEST(vector, clause_23_3_6_1_11_ambiguity) } } -TEST(vector, clause_23_3_6_2_6) -{ +TEST(vector, clause_23_3_6_2_6) { gtl::vector v; auto const n = random(0U, 10000U); v.reserve(n); @@ -133,8 +124,7 @@ TEST(vector, clause_23_3_6_2_6) // Nothing to verify except that the call made it through } -TEST(vector, clause_23_3_6_4_ambiguity) -{ +TEST(vector, clause_23_3_6_4_ambiguity) { gtl::vector v; gtl::vector::const_iterator it = v.end(); v.insert(it, 10, 20); @@ -144,35 +134,28 @@ TEST(vector, clause_23_3_6_4_ambiguity) } } -TEST(vector, composition) -{ - gtl::vector> matrix(100, gtl::vector(100)); -} +TEST(vector, composition) { gtl::vector> matrix(100, gtl::vector(100)); } -TEST(vector, works_with_std_string) -{ +TEST(vector, works_with_std_string) { gtl::vector v(10, "hello"); EXPECT_EQ(v.size(), 10); v.push_back("world"); } namespace { -class UserDefinedType -{ +class UserDefinedType { public: int whatevs_; }; } // namespace -TEST(vector, works_with_user_defined_type) -{ +TEST(vector, works_with_user_defined_type) { gtl::vector v(10); EXPECT_EQ(v.size(), 10); v.push_back(UserDefinedType()); } -TEST(vector, move_construction) -{ +TEST(vector, move_construction) { gtl::vector v1(100, 100); gtl::vector v2; EXPECT_EQ(v1.size(), 100); @@ -190,8 +173,7 @@ TEST(vector, move_construction) EXPECT_EQ(other.front(), 100); } -TEST(vector, emplace) -{ +TEST(vector, emplace) { gtl::vector s(12, "asd"); EXPECT_EQ(s.size(), 12); EXPECT_EQ(s.front(), "asd"); @@ -201,8 +183,7 @@ TEST(vector, emplace) EXPECT_EQ(std::addressof(emplaced), std::addressof(s.back())); } -TEST(vector, initializer_lists) -{ +TEST(vector, initializer_lists) { gtl::vector vec = { 1, 2, 3 }; EXPECT_EQ(vec.size(), 3); EXPECT_EQ(vec[0], 1); @@ -226,8 +207,7 @@ TEST(vector, initializer_lists) EXPECT_EQ(vec[5], 16); } -TEST(vector, unique_ptr) -{ +TEST(vector, unique_ptr) { gtl::vector> v(12); std::unique_ptr p(new int(12)); v.push_back(std::move(p)); @@ -241,8 +221,7 @@ TEST(vector, unique_ptr) EXPECT_EQ(*v[1], 32); } -TEST(vector, task858056) -{ +TEST(vector, task858056) { gtl::vector cycle; cycle.push_back("foo"); cycle.push_back("bar"); @@ -256,13 +235,11 @@ TEST(vector, task858056) EXPECT_EQ("Cycle detected: [baz] [bar] [foo] ", message); } -TEST(vector, move_iterator) -{ +TEST(vector, move_iterator) { gtl::vector base = { 0, 1, 2 }; auto cp1 = base; - gtl::vector fbvi1(std::make_move_iterator(cp1.begin()), - std::make_move_iterator(cp1.end())); + gtl::vector fbvi1(std::make_move_iterator(cp1.begin()), std::make_move_iterator(cp1.end())); EXPECT_EQ(fbvi1, base); auto cp2 = base; @@ -272,15 +249,12 @@ TEST(vector, move_iterator) auto cp3 = base; gtl::vector fbvi3; - fbvi3.insert( - fbvi3.end(), std::make_move_iterator(cp3.begin()), std::make_move_iterator(cp3.end())); + fbvi3.insert(fbvi3.end(), std::make_move_iterator(cp3.begin()), std::make_move_iterator(cp3.end())); EXPECT_EQ(fbvi3, base); } -TEST(vector, reserve_consistency) -{ - struct S - { +TEST(vector, reserve_consistency) { + struct S { int64_t a, b, c, d; }; @@ -292,8 +266,7 @@ TEST(vector, reserve_consistency) } } -TEST(vector, vector_of_maps) -{ +TEST(vector, vector_of_maps) { gtl::vector> v; v.push_back(std::map()); @@ -310,8 +283,7 @@ TEST(vector, vector_of_maps) EXPECT_EQ(1, v[1].size()); } -TEST(vector, shrink_to_fit_after_clear) -{ +TEST(vector, shrink_to_fit_after_clear) { gtl::vector fb1; fb1.push_back(42); fb1.push_back(1337); @@ -321,8 +293,7 @@ TEST(vector, shrink_to_fit_after_clear) EXPECT_EQ(fb1.capacity(), 0); } -TEST(vector, zero_len) -{ +TEST(vector, zero_len) { gtl::vector fb1(0); gtl::vector fb2(0, 10); gtl::vector fb3(std::move(fb1)); @@ -337,8 +308,7 @@ TEST(vector, zero_len) } #if __cpp_deduction_guides >= 201703 -TEST(vector, deduction_guides) -{ +TEST(vector, deduction_guides) { gtl::vector v(3); gtl::vector x(v.begin(), v.end()); @@ -349,8 +319,7 @@ TEST(vector, deduction_guides) } #endif -TEST(vector, erase) -{ +TEST(vector, erase) { gtl::vector v(3); std::iota(v.begin(), v.end(), 1); v.push_back(2); @@ -360,8 +329,7 @@ TEST(vector, erase) EXPECT_EQ(3u, v[1]); } -TEST(vector, erase_if) -{ +TEST(vector, erase_if) { gtl::vector v(6); std::iota(v.begin(), v.end(), 1); erase_if(v, [](const auto& x) { return x % 2 == 0; }); @@ -372,18 +340,18 @@ TEST(vector, erase_if) } // gtl extension -TEST(vector, stealing_constructor) -{ +TEST(vector, stealing_constructor) { using Alloc = std::allocator; using vec_t = gtl::vector; Alloc alloc; - int *x; - if constexpr (std::is_same_v>) // always the case here, but left as an example of what should be done - x = (int *)gtl::checkedMalloc(4 * sizeof(vec_t::value_type)); + int* x; + if constexpr (std::is_same_v>) // always the case here, but left as an + // example of what should be done + x = (int*)gtl::checkedMalloc(4 * sizeof(vec_t::value_type)); else - x = std::allocator_traits::allocate(alloc, 4); - + x = std::allocator_traits::allocate(alloc, 4); + for (int i = 0; i < 3; ++i) *(x + i) = i; vec_t v(std::unique_ptr(x), 3, 4); diff --git a/tests/phmap/container_memory_test.cpp b/tests/phmap/container_memory_test.cpp index 0f850a3..d4d65bf 100644 --- a/tests/phmap/container_memory_test.cpp +++ b/tests/phmap/container_memory_test.cpp @@ -29,8 +29,7 @@ namespace { using ::testing::Pair; -TEST(Memory, AlignmentLargerThanBase) -{ +TEST(Memory, AlignmentLargerThanBase) { std::allocator alloc; void* mem = Allocate<2>(&alloc, 3); EXPECT_EQ(0u, reinterpret_cast(mem) % 2); @@ -38,8 +37,7 @@ TEST(Memory, AlignmentLargerThanBase) Deallocate<2>(&alloc, mem, 3); } -TEST(Memory, AlignmentSmallerThanBase) -{ +TEST(Memory, AlignmentSmallerThanBase) { std::allocator alloc; void* mem = Allocate<2>(&alloc, 3); EXPECT_EQ(0u, reinterpret_cast(mem) % 2); @@ -47,14 +45,12 @@ TEST(Memory, AlignmentSmallerThanBase) Deallocate<2>(&alloc, mem, 3); } -class Fixture : public ::testing::Test -{ +class Fixture : public ::testing::Test { using Alloc = std::allocator; public: Fixture() { ptr_ = std::allocator_traits::allocate(*alloc(), 1); } - ~Fixture() override - { + ~Fixture() override { std::allocator_traits::destroy(*alloc(), ptr_); std::allocator_traits::deallocate(*alloc(), ptr_, 1); } @@ -66,78 +62,58 @@ class Fixture : public ::testing::Test std::string* ptr_; }; -TEST_F(Fixture, ConstructNoArgs) -{ +TEST_F(Fixture, ConstructNoArgs) { ConstructFromTuple(alloc(), ptr(), std::forward_as_tuple()); EXPECT_EQ(*ptr(), ""); } -TEST_F(Fixture, ConstructOneArg) -{ +TEST_F(Fixture, ConstructOneArg) { ConstructFromTuple(alloc(), ptr(), std::forward_as_tuple("abcde")); EXPECT_EQ(*ptr(), "abcde"); } -TEST_F(Fixture, ConstructTwoArg) -{ +TEST_F(Fixture, ConstructTwoArg) { ConstructFromTuple(alloc(), ptr(), std::forward_as_tuple(5, 'a')); EXPECT_EQ(*ptr(), "aaaaa"); } -TEST(PairArgs, NoArgs) -{ - EXPECT_THAT(PairArgs(), Pair(std::forward_as_tuple(), std::forward_as_tuple())); -} +TEST(PairArgs, NoArgs) { EXPECT_THAT(PairArgs(), Pair(std::forward_as_tuple(), std::forward_as_tuple())); } -TEST(PairArgs, TwoArgs) -{ - EXPECT_EQ(std::make_pair(std::forward_as_tuple(1), std::forward_as_tuple('A')), - PairArgs(1, 'A')); +TEST(PairArgs, TwoArgs) { + EXPECT_EQ(std::make_pair(std::forward_as_tuple(1), std::forward_as_tuple('A')), PairArgs(1, 'A')); } -TEST(PairArgs, Pair) -{ - EXPECT_EQ(std::make_pair(std::forward_as_tuple(1), std::forward_as_tuple('A')), - PairArgs(std::make_pair(1, 'A'))); +TEST(PairArgs, Pair) { + EXPECT_EQ(std::make_pair(std::forward_as_tuple(1), std::forward_as_tuple('A')), PairArgs(std::make_pair(1, 'A'))); } -TEST(PairArgs, Piecewise) -{ - EXPECT_EQ( - std::make_pair(std::forward_as_tuple(1), std::forward_as_tuple('A')), - PairArgs(std::piecewise_construct, std::forward_as_tuple(1), std::forward_as_tuple('A'))); +TEST(PairArgs, Piecewise) { + EXPECT_EQ(std::make_pair(std::forward_as_tuple(1), std::forward_as_tuple('A')), + PairArgs(std::piecewise_construct, std::forward_as_tuple(1), std::forward_as_tuple('A'))); } -TEST(WithConstructed, Simple) -{ - EXPECT_EQ(1u, - WithConstructed(std::make_tuple(std::string("a")), - [](std::string_view str) { return str.size(); })); +TEST(WithConstructed, Simple) { + EXPECT_EQ(1u, WithConstructed(std::make_tuple(std::string("a")), [](std::string_view str) { + return str.size(); + })); } template -decltype(DecomposeValue(std::declval(), std::declval())) DecomposeValueImpl(int, - F&& f, - Arg&& arg) -{ +decltype(DecomposeValue(std::declval(), std::declval())) DecomposeValueImpl(int, F&& f, Arg&& arg) { return DecomposeValue(std::forward(f), std::forward(arg)); } template -const char* DecomposeValueImpl(char, F&&, Arg&&) -{ +const char* DecomposeValueImpl(char, F&&, Arg&&) { return "not decomposable"; } template -decltype(DecomposeValueImpl(0, std::declval(), std::declval())) TryDecomposeValue(F&& f, - Arg&& arg) -{ +decltype(DecomposeValueImpl(0, std::declval(), std::declval())) TryDecomposeValue(F&& f, Arg&& arg) { return DecomposeValueImpl(0, std::forward(f), std::forward(arg)); } -TEST(DecomposeValue, Decomposable) -{ +TEST(DecomposeValue, Decomposable) { auto f = [](const int& x, int&& y) { EXPECT_EQ(&x, &y); EXPECT_EQ(42, x); @@ -146,8 +122,7 @@ TEST(DecomposeValue, Decomposable) EXPECT_EQ('A', TryDecomposeValue(f, 42)); } -TEST(DecomposeValue, NotDecomposable) -{ +TEST(DecomposeValue, NotDecomposable) { auto f = [](void*) { ADD_FAILURE() << "Must not be called"; return 'A'; @@ -156,52 +131,40 @@ TEST(DecomposeValue, NotDecomposable) } template -decltype(DecomposePair(std::declval(), std::declval()...)) -DecomposePairImpl(int, F&& f, Args&&... args) -{ +decltype(DecomposePair(std::declval(), std::declval()...)) DecomposePairImpl(int, F&& f, Args&&... args) { return DecomposePair(std::forward(f), std::forward(args)...); } template -const char* DecomposePairImpl(char, F&&, Args&&...) -{ +const char* DecomposePairImpl(char, F&&, Args&&...) { return "not decomposable"; } template -decltype(DecomposePairImpl(0, std::declval(), std::declval()...)) TryDecomposePair( - F&& f, - Args&&... args) -{ +decltype(DecomposePairImpl(0, std::declval(), std::declval()...)) TryDecomposePair(F&& f, Args&&... args) { return DecomposePairImpl(0, std::forward(f), std::forward(args)...); } -TEST(DecomposePair, Decomposable) -{ - auto f = - [](const int& x, std::piecewise_construct_t, std::tuple k, std::tuple&& v) { - EXPECT_EQ(&x, &std::get<0>(k)); - EXPECT_EQ(42, x); - EXPECT_EQ(0.5, std::get<0>(v)); - return 'A'; - }; +TEST(DecomposePair, Decomposable) { + auto f = [](const int& x, std::piecewise_construct_t, std::tuple k, std::tuple&& v) { + EXPECT_EQ(&x, &std::get<0>(k)); + EXPECT_EQ(42, x); + EXPECT_EQ(0.5, std::get<0>(v)); + return 'A'; + }; EXPECT_EQ('A', TryDecomposePair(f, 42, 0.5)); EXPECT_EQ('A', TryDecomposePair(f, std::make_pair(42, 0.5))); - EXPECT_EQ( - 'A', - TryDecomposePair(f, std::piecewise_construct, std::make_tuple(42), std::make_tuple(0.5))); + EXPECT_EQ('A', TryDecomposePair(f, std::piecewise_construct, std::make_tuple(42), std::make_tuple(0.5))); } -TEST(DecomposePair, NotDecomposable) -{ +TEST(DecomposePair, NotDecomposable) { auto f = [](...) { ADD_FAILURE() << "Must not be called"; return 'A'; }; EXPECT_STREQ("not decomposable", TryDecomposePair(f)); - EXPECT_STREQ( - "not decomposable", - TryDecomposePair(f, std::piecewise_construct, std::make_tuple(), std::make_tuple(0.5))); + EXPECT_STREQ("not decomposable", + TryDecomposePair(f, std::piecewise_construct, std::make_tuple(), std::make_tuple(0.5))); } } // namespace diff --git a/tests/phmap/dump_load_test.cpp b/tests/phmap/dump_load_test.cpp index b20ee0d..f337c60 100644 --- a/tests/phmap/dump_load_test.cpp +++ b/tests/phmap/dump_load_test.cpp @@ -8,8 +8,7 @@ namespace gtl { namespace priv { namespace { -TEST(DumpLoad, FlatHashSet_uin32) -{ +TEST(DumpLoad, FlatHashSet_uin32) { gtl::flat_hash_set st1 = { 1991, 1202 }; { @@ -25,8 +24,7 @@ TEST(DumpLoad, FlatHashSet_uin32) EXPECT_TRUE(st1 == st2); } -TEST(DumpLoad, FlatHashMap_uint64_uint32) -{ +TEST(DumpLoad, FlatHashMap_uint64_uint32) { gtl::flat_hash_map mp1 = { {78731, 99 }, { 13141, 299}, @@ -47,8 +45,7 @@ TEST(DumpLoad, FlatHashMap_uint64_uint32) EXPECT_TRUE(mp1 == mp2); } -TEST(DumpLoad, ParallelFlatHashMap_uint64_uint32) -{ +TEST(DumpLoad, ParallelFlatHashMap_uint64_uint32) { gtl::parallel_flat_hash_map mp1 = { {99, 299 }, { 992, 2991}, diff --git a/tests/phmap/erase_if_test.cpp b/tests/phmap/erase_if_test.cpp index ca120f1..d2a557f 100644 --- a/tests/phmap/erase_if_test.cpp +++ b/tests/phmap/erase_if_test.cpp @@ -8,10 +8,9 @@ namespace phmap { namespace priv { namespace { -TEST(EraseIf, FlatHashSet_uint32) -{ - gtl::flat_hash_set st1 = { 3, 6, 7, 9 }; - auto num_erased = erase_if(st1, [](const uint32_t& v) { return v >= 7; }); +TEST(EraseIf, FlatHashSet_uint32) { + gtl::flat_hash_set st1 = { 3, 6, 7, 9 }; + auto num_erased = erase_if(st1, [](const uint32_t& v) { return v >= 7; }); EXPECT_TRUE(num_erased == 2); gtl::flat_hash_set st2 = { 0, 2, 3, 6 }; @@ -21,14 +20,13 @@ TEST(EraseIf, FlatHashSet_uint32) EXPECT_TRUE(st1 == st2); } -TEST(EraseIf, FlatHashMap_uint64_uint32) -{ +TEST(EraseIf, FlatHashMap_uint64_uint32) { using map = gtl::flat_hash_map; map st1 = { - {3, 0}, - { 6, 0}, - { 7, 0}, - { 9, 0} + {3, 0}, + { 6, 0}, + { 7, 0}, + { 9, 0} }; auto num_erased = erase_if(st1, [](const map::value_type& v) { return v.first >= 7; }); EXPECT_TRUE(num_erased == 2); @@ -45,14 +43,13 @@ TEST(EraseIf, FlatHashMap_uint64_uint32) EXPECT_TRUE(st1 == st2); } -TEST(EraseIf, ParallelFlatHashMap_uint64_uint32) -{ +TEST(EraseIf, ParallelFlatHashMap_uint64_uint32) { using map = gtl::parallel_flat_hash_map; map st1 = { - {3, 0}, - { 6, 0}, - { 7, 0}, - { 9, 0} + {3, 0}, + { 6, 0}, + { 7, 0}, + { 9, 0} }; auto num_erased = erase_if(st1, [](const map::value_type& v) { return v.first >= 7; }); EXPECT_TRUE(num_erased == 2); diff --git a/tests/phmap/flat_hash_map_test.cpp b/tests/phmap/flat_hash_map_test.cpp index 60ed858..ed55dce 100644 --- a/tests/phmap/flat_hash_map_test.cpp +++ b/tests/phmap/flat_hash_map_test.cpp @@ -57,11 +57,8 @@ using ::testing::Pair; using ::testing::UnorderedElementsAre; template -using Map = THIS_HASH_MAP> THIS_EXTRA_TPL_PARAMS>; +using Map = + THIS_HASH_MAP> THIS_EXTRA_TPL_PARAMS>; template(), ""); - struct Hash - { + struct Hash { size_t operator()(const Int& obj) const { return obj.value; } }; @@ -139,11 +129,9 @@ TEST(THIS_TEST_NAME, StandardLayout) } // gcc becomes unhappy if this is inside the method, so pull it out here. -struct balast -{}; +struct balast {}; -TEST(THIS_TEST_NAME, IteratesMsan) -{ +TEST(THIS_TEST_NAME, IteratesMsan) { // Because SwissTable randomizes on pointer addresses, we keep old tables // around to ensure we don't reuse old memory. std::vector> garbage; @@ -161,16 +149,12 @@ TEST(THIS_TEST_NAME, IteratesMsan) // Demonstration of the "Lazy Key" pattern. This uses heterogeneous insert to // avoid creating expensive key elements when the item is already present in the // map. -struct LazyInt -{ +struct LazyInt { explicit LazyInt(size_t val, int* tracker_) : value(val) - , tracker(tracker_) - { - } + , tracker(tracker_) {} - explicit operator size_t() const - { + explicit operator size_t() const { ++*tracker; return value; } @@ -179,31 +163,26 @@ struct LazyInt int* tracker; }; -struct Hash -{ +struct Hash { using is_transparent = void; int* tracker; - size_t operator()(size_t obj) const - { + size_t operator()(size_t obj) const { ++*tracker; return obj; } - size_t operator()(const LazyInt& obj) const - { + size_t operator()(const LazyInt& obj) const { ++*tracker; return obj.value; } }; -struct Eq -{ +struct Eq { using is_transparent = void; bool operator()(size_t lhs, size_t rhs) const { return lhs == rhs; } bool operator()(size_t lhs, const LazyInt& rhs) const { return lhs == rhs.value; } }; -TEST(THIS_TEST_NAME, PtrKet) -{ +TEST(THIS_TEST_NAME, PtrKet) { using H = ThisMap; H hash; int a, b; @@ -211,8 +190,7 @@ TEST(THIS_TEST_NAME, PtrKet) hash.insert(H::value_type(&b, false)); } -TEST(THIS_TEST_NAME, LazyKeyPattern) -{ +TEST(THIS_TEST_NAME, LazyKeyPattern) { // hashes are only guaranteed in opt mode, we use assertions to track internal // state that can cause extra calls to hash. int conversions = 0; @@ -253,10 +231,8 @@ TEST(THIS_TEST_NAME, LazyKeyPattern) #endif } -TEST(THIS_TEST_NAME, BitfieldArgument) -{ - union - { +TEST(THIS_TEST_NAME, BitfieldArgument) { + union { int n : 1; }; n = 0; @@ -275,8 +251,7 @@ TEST(THIS_TEST_NAME, BitfieldArgument) m[n]; } -TEST(THIS_TEST_NAME, MergeExtractInsert) -{ +TEST(THIS_TEST_NAME, MergeExtractInsert) { // We can't test mutable keys, or non-copyable keys with ThisMap. // Test that the nodes have the proper API. ThisMap m = { @@ -294,8 +269,7 @@ TEST(THIS_TEST_NAME, MergeExtractInsert) EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 17), Pair(2, 9))); } -#if 0 && !defined(__ANDROID__) && !defined(__APPLE__) && !defined(__EMSCRIPTEN__) && \ - defined(GTL_HAVE_STD_ANY) +#if 0 && !defined(__ANDROID__) && !defined(__APPLE__) && !defined(__EMSCRIPTEN__) && defined(GTL_HAVE_STD_ANY) TEST(THIS_TEST_NAME, Any) { ThisMap m; m.emplace(1, 7); diff --git a/tests/phmap/flat_hash_set_test.cpp b/tests/phmap/flat_hash_set_test.cpp index a35fc1f..fb12c10 100644 --- a/tests/phmap/flat_hash_set_test.cpp +++ b/tests/phmap/flat_hash_set_test.cpp @@ -47,17 +47,14 @@ INSTANTIATE_TYPED_TEST_SUITE_P(THIS_TEST_NAME, LookupTest, SetTypes); INSTANTIATE_TYPED_TEST_SUITE_P(THIS_TEST_NAME, MembersTest, SetTypes); INSTANTIATE_TYPED_TEST_SUITE_P(THIS_TEST_NAME, ModifiersTest, SetTypes); -TEST(THIS_TEST_NAME, EmplaceString) -{ +TEST(THIS_TEST_NAME, EmplaceString) { std::vector v = { "a", "b" }; gtl::THIS_HASH_SET hs(v.begin(), v.end()); // EXPECT_THAT(hs, UnorderedElementsAreArray(v)); } -TEST(THIS_TEST_NAME, BitfieldArgument) -{ - union - { +TEST(THIS_TEST_NAME, BitfieldArgument) { + union { int n : 1; }; n = 0; @@ -73,18 +70,12 @@ TEST(THIS_TEST_NAME, BitfieldArgument) s.equal_range(n); } -TEST(THIS_TEST_NAME, MergeExtractInsert) -{ - struct Hash - { +TEST(THIS_TEST_NAME, MergeExtractInsert) { + struct Hash { size_t operator()(const std::unique_ptr& p) const { return *p; } }; - struct Eq - { - bool operator()(const std::unique_ptr& a, const std::unique_ptr& b) const - { - return *a == *b; - } + struct Eq { + bool operator()(const std::unique_ptr& a, const std::unique_ptr& b) const { return *a == *b; } }; gtl::THIS_HASH_SET, Hash, Eq> set1, set2; set1.insert(std::make_unique(7)); diff --git a/tests/phmap/hash_generator_testing.hpp b/tests/phmap/hash_generator_testing.hpp index 49ae089..421c38a 100644 --- a/tests/phmap/hash_generator_testing.hpp +++ b/tests/phmap/hash_generator_testing.hpp @@ -39,26 +39,20 @@ namespace hash_internal { namespace generator_internal { template -struct IsMap : std::false_type -{ -}; +struct IsMap : std::false_type {}; template -struct IsMap> : std::true_type -{ -}; +struct IsMap> : std::true_type {}; } // namespace generator_internal namespace { -class RandomDeviceSeedSeq -{ +class RandomDeviceSeedSeq { public: using result_type = typename std::random_device::result_type; template - void generate(Iterator start, Iterator end) - { + void generate(Iterator start, Iterator end) { while (start != end) { *start = gen_(); ++start; @@ -72,48 +66,38 @@ class RandomDeviceSeedSeq std::mt19937_64* GetSharedRng(); // declaration -std::mt19937_64* GetSharedRng() -{ +std::mt19937_64* GetSharedRng() { RandomDeviceSeedSeq seed_seq; static auto* rng = new std::mt19937_64(seed_seq); return rng; } -enum Enum -{ +enum Enum { kEnumEmpty, kEnumDeleted, }; -enum class EnumClass : uint64_t -{ +enum class EnumClass : uint64_t { kEmpty, kDeleted, }; -inline std::ostream& operator<<(std::ostream& o, const EnumClass& ec) -{ - return o << static_cast(ec); -} +inline std::ostream& operator<<(std::ostream& o, const EnumClass& ec) { return o << static_cast(ec); } template struct Generator; template -struct Generator::value>::type> -{ - T operator()() const - { +struct Generator::value>::type> { + T operator()() const { std::uniform_int_distribution dist; return dist(*GetSharedRng()); } }; template<> -struct Generator -{ - Enum operator()() const - { +struct Generator { + Enum operator()() const { std::uniform_int_distribution::type> dist; while (true) { @@ -125,10 +109,8 @@ struct Generator }; template<> -struct Generator -{ - EnumClass operator()() const - { +struct Generator { + EnumClass operator()() const { std::uniform_int_distribution::type> dist; while (true) { EnumClass variate = static_cast(dist(*GetSharedRng())); @@ -139,10 +121,8 @@ struct Generator }; template<> -struct Generator -{ - std::string operator()() const - { +struct Generator { + std::string operator()() const { // NOLINTNEXTLINE(runtime/int) std::uniform_int_distribution chars(0x20, 0x7E); std::string res; @@ -153,10 +133,8 @@ struct Generator }; template<> -struct Generator -{ - std::string_view operator()() const - { +struct Generator { + std::string_view operator()() const { static auto* arena = new std::deque(); // NOLINTNEXTLINE(runtime/int) std::uniform_int_distribution chars(0x20, 0x7E); @@ -169,45 +147,33 @@ struct Generator }; template<> -struct Generator -{ +struct Generator { NonStandardLayout operator()() const { return NonStandardLayout(Generator()()); } }; template -struct Generator> -{ - std::pair operator()() const - { +struct Generator> { + std::pair operator()() const { return std::pair(Generator::type>()(), Generator::type>()()); } }; template -struct Generator> -{ - std::tuple operator()() const - { - return std::tuple(Generator::type>()()...); - } +struct Generator> { + std::tuple operator()() const { return std::tuple(Generator::type>()()...); } }; template -struct Generator< - U, - std::void_t().key()), decltype(std::declval().value())>> +struct Generator().key()), decltype(std::declval().value())>> : Generator().key())>::type, - typename std::decay().value())>::type>> -{ -}; + typename std::decay().value())>::type>> {}; template using GeneratedType = - decltype(std::declval< - const Generator::value, - typename Container::value_type, - typename Container::key_type>::type>&>()()); + decltype(std::declval::value, + typename Container::value_type, + typename Container::key_type>::type>&>()()); } // namespace hash_internal } // namespace priv @@ -218,13 +184,11 @@ using gtl::priv::hash_internal::Enum; using gtl::priv::hash_internal::EnumClass; template<> -struct hash -{ +struct hash { std::size_t operator()(EnumClass const& p) const { return (std::size_t)p; } }; template<> -struct hash -{ +struct hash { std::size_t operator()(Enum const& p) const { return (std::size_t)p; } }; } diff --git a/tests/phmap/hash_policy_testing.hpp b/tests/phmap/hash_policy_testing.hpp index 6a3aafc..dfd1b22 100644 --- a/tests/phmap/hash_policy_testing.hpp +++ b/tests/phmap/hash_policy_testing.hpp @@ -31,28 +31,20 @@ namespace priv { namespace hash_testing_internal { template -struct WithId -{ +struct WithId { WithId() - : id_(next_id()) - { - } + : id_(next_id()) {} WithId(const WithId& that) - : id_(that.id_) - { - } + : id_(that.id_) {} WithId(WithId&& that) - : id_(that.id_) - { + : id_(that.id_) { that.id_ = 0; } - WithId& operator=(const WithId& that) - { + WithId& operator=(const WithId& that) { id_ = that.id_; return *this; } - WithId& operator=(WithId&& that) - { + WithId& operator=(WithId&& that) { id_ = that.id_; that.id_ = 0; return *this; @@ -65,16 +57,13 @@ struct WithId protected: explicit WithId(size_t id) - : id_(id) - { - } + : id_(id) {} private: size_t id_; template - static size_t next_id() - { + static size_t next_id() { // 0 is reserved for moved from state. static size_t gId = 1; return gId++; @@ -83,47 +72,33 @@ struct WithId } // namespace hash_testing_internal -struct NonStandardLayout -{ +struct NonStandardLayout { NonStandardLayout() {} explicit NonStandardLayout(std::string s) - : value(std::move(s)) - { - } + : value(std::move(s)) {} virtual ~NonStandardLayout() {} - friend bool operator==(const NonStandardLayout& a, const NonStandardLayout& b) - { - return a.value == b.value; - } - friend bool operator!=(const NonStandardLayout& a, const NonStandardLayout& b) - { - return a.value != b.value; - } + friend bool operator==(const NonStandardLayout& a, const NonStandardLayout& b) { return a.value == b.value; } + friend bool operator!=(const NonStandardLayout& a, const NonStandardLayout& b) { return a.value != b.value; } template - friend H AbslHashValue(H h, const NonStandardLayout& v) - { + friend H AbslHashValue(H h, const NonStandardLayout& v) { return H::combine(std::move(h), v.value); } std::string value; }; -struct StatefulTestingHash : gtl::priv::hash_testing_internal::WithId -{ +struct StatefulTestingHash : gtl::priv::hash_testing_internal::WithId { template - size_t operator()(const T& t) const - { + size_t operator()(const T& t) const { return gtl::Hash{}(t); } }; -struct StatefulTestingEqual : gtl::priv::hash_testing_internal::WithId -{ +struct StatefulTestingEqual : gtl::priv::hash_testing_internal::WithId { template - bool operator()(const T& t, const U& u) const - { + bool operator()(const T& t, const U& u) const { return t == u; } }; @@ -131,15 +106,12 @@ struct StatefulTestingEqual : gtl::priv::hash_testing_internal::WithId -struct Alloc : std::allocator -{ +struct Alloc : std::allocator { using propagate_on_container_swap = std::true_type; // Using old paradigm for this to ensure compatibility. explicit Alloc(size_t id = 0) - : id_(id) - { - } + : id_(id) {} Alloc(const Alloc&) = default; Alloc& operator=(const Alloc&) = default; @@ -147,13 +119,10 @@ struct Alloc : std::allocator template Alloc(const Alloc& that) : std::allocator(that) - , id_(that.id()) - { - } + , id_(that.id()) {} template - struct rebind - { + struct rebind { using other = Alloc; }; @@ -167,9 +136,7 @@ struct Alloc : std::allocator }; template -auto items(const Map& m) - -> std::vector> -{ +auto items(const Map& m) -> std::vector> { using std::get; std::vector> res; res.reserve(m.size()); @@ -179,8 +146,7 @@ auto items(const Map& m) } template -auto keys(const Set& s) -> std::vector::type> -{ +auto keys(const Set& s) -> std::vector::type> { std::vector::type> res; res.reserve(s.size()); for (const auto& v : s) @@ -195,12 +161,8 @@ namespace std { // inject specialization of std::hash for NonStandardLayout into namespace std // ---------------------------------------------------------------- template<> -struct hash -{ - std::size_t operator()(gtl::priv::NonStandardLayout const& p) const - { - return std::hash()(p.value); - } +struct hash { + std::size_t operator()(gtl::priv::NonStandardLayout const& p) const { return std::hash()(p.value); } }; } @@ -212,8 +174,7 @@ struct hash // From GCC-4.9 Changelog: (src: https://gcc.gnu.org/gcc-4.9/changes.html) // "the unordered associative containers in and // meet the allocator-aware container requirements;" -#if (defined(__GLIBCXX__) && __GLIBCXX__ <= 20140425) || \ - (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 9)) +#if (defined(__GLIBCXX__) && __GLIBCXX__ <= 20140425) || (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 9)) #define GTL_UNORDERED_SUPPORTS_ALLOC_CTORS 0 #else #define GTL_UNORDERED_SUPPORTS_ALLOC_CTORS 1 diff --git a/tests/phmap/hash_policy_testing_test.cpp b/tests/phmap/hash_policy_testing_test.cpp index 464b849..13dea05 100644 --- a/tests/phmap/hash_policy_testing_test.cpp +++ b/tests/phmap/hash_policy_testing_test.cpp @@ -21,8 +21,7 @@ namespace gtl { namespace priv { namespace { -TEST(_, Hash) -{ +TEST(_, Hash) { StatefulTestingHash h1; EXPECT_EQ(1u, h1.id()); StatefulTestingHash h2; diff --git a/tests/phmap/hashtable_debug.hpp b/tests/phmap/hashtable_debug.hpp index 700cffa..1401312 100644 --- a/tests/phmap/hashtable_debug.hpp +++ b/tests/phmap/hashtable_debug.hpp @@ -43,28 +43,25 @@ namespace priv { // however, the exact meaning of this number varies according to the container // type. template -size_t GetHashtableDebugNumProbes(const C& c, const typename C::key_type& key) -{ +size_t GetHashtableDebugNumProbes(const C& c, const typename C::key_type& key) { return gtl::priv::hashtable_debug_internal::HashtableDebugAccess::GetNumProbes(c, key); } // Gets a histogram of the number of probes for each elements in the container. // The sum of all the values in the vector is equal to container.size(). template -std::vector GetHashtableDebugNumProbesHistogram(const C& container) -{ +std::vector GetHashtableDebugNumProbesHistogram(const C& container) { std::vector v; for (auto it = container.begin(); it != container.end(); ++it) { - size_t num_probes = GetHashtableDebugNumProbes( - container, gtl::priv::hashtable_debug_internal::GetKey(*it, 0)); + size_t num_probes = + GetHashtableDebugNumProbes(container, gtl::priv::hashtable_debug_internal::GetKey(*it, 0)); v.resize((std::max)(v.size(), num_probes + 1)); v[num_probes]++; } return v; } -struct HashtableDebugProbeSummary -{ +struct HashtableDebugProbeSummary { size_t total_elements; size_t total_num_probes; double mean; @@ -73,8 +70,7 @@ struct HashtableDebugProbeSummary // Gets a summary of the probe count distribution for the elements in the // container. template -HashtableDebugProbeSummary GetHashtableDebugProbeSummary(const C& container) -{ +HashtableDebugProbeSummary GetHashtableDebugProbeSummary(const C& container) { auto probes = GetHashtableDebugNumProbesHistogram(container); HashtableDebugProbeSummary summary = {}; for (size_t i = 0; i < probes.size(); ++i) { @@ -88,18 +84,15 @@ HashtableDebugProbeSummary GetHashtableDebugProbeSummary(const C& container) // Returns the number of bytes requested from the allocator by the container // and not freed. template -size_t AllocatedByteSize(const C& c) -{ +size_t AllocatedByteSize(const C& c) { return gtl::priv::hashtable_debug_internal::HashtableDebugAccess::AllocatedByteSize(c); } // Returns a tight lower bound for AllocatedByteSize(c) where `c` is of type `C` // and `c.size()` is equal to `num_elements`. template -size_t LowerBoundAllocatedByteSize(size_t num_elements) -{ - return gtl::priv::hashtable_debug_internal::HashtableDebugAccess< - C>::LowerBoundAllocatedByteSize(num_elements); +size_t LowerBoundAllocatedByteSize(size_t num_elements) { + return gtl::priv::hashtable_debug_internal::HashtableDebugAccess::LowerBoundAllocatedByteSize(num_elements); } } // namespace priv diff --git a/tests/phmap/node_hash_map_test.cpp b/tests/phmap/node_hash_map_test.cpp index f6544e0..be72ad3 100644 --- a/tests/phmap/node_hash_map_test.cpp +++ b/tests/phmap/node_hash_map_test.cpp @@ -33,17 +33,13 @@ using ::testing::Field; using ::testing::Pair; using ::testing::UnorderedElementsAre; -using MapTypes = - ::testing::Types>>, - gtl::THIS_HASH_MAP>>>; +using MapTypes = ::testing::Types< + gtl::THIS_HASH_MAP>>, + gtl::THIS_HASH_MAP>>>; INSTANTIATE_TYPED_TEST_SUITE_P(THIS_TEST_NAME, ConstructorTest, MapTypes); INSTANTIATE_TYPED_TEST_SUITE_P(THIS_TEST_NAME, LookupTest, MapTypes); @@ -52,8 +48,7 @@ INSTANTIATE_TYPED_TEST_SUITE_P(THIS_TEST_NAME, ModifiersTest, MapTypes); using M = gtl::THIS_HASH_MAP>; -TEST(THIS_TEST_NAME, Emplace) -{ +TEST(THIS_TEST_NAME, Emplace) { M m; Tracked t(53); m.emplace("a", t); @@ -114,17 +109,13 @@ TEST(THIS_TEST_NAME, Emplace) ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(7, t.num_copies()); - m.emplace(std::piecewise_construct, - std::forward_as_tuple(std::string("a")), - std::forward_as_tuple(t)); + m.emplace(std::piecewise_construct, std::forward_as_tuple(std::string("a")), std::forward_as_tuple(t)); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(7, t.num_copies()); } -TEST(THIS_TEST_NAME, AssignRecursive) -{ - struct Tree - { +TEST(THIS_TEST_NAME, AssignRecursive) { + struct Tree { // Verify that unordered_map can be instantiated. gtl::THIS_HASH_MAP children; }; @@ -134,50 +125,40 @@ TEST(THIS_TEST_NAME, AssignRecursive) root = child; } -TEST(FlatHashMap, MoveOnlyKey) -{ - struct Key - { +TEST(FlatHashMap, MoveOnlyKey) { + struct Key { Key() = default; Key(Key&&) = default; Key& operator=(Key&&) = default; }; - struct Eq - { + struct Eq { bool operator()(const Key&, const Key&) const { return true; } }; - struct Hash - { + struct Hash { size_t operator()(const Key&) const { return 0; } }; gtl::THIS_HASH_MAP m; m[Key()]; } -struct NonMovableKey -{ +struct NonMovableKey { explicit NonMovableKey(int i_) - : i(i_) - { - } + : i(i_) {} NonMovableKey(NonMovableKey&&) = delete; int i; }; -struct NonMovableKeyHash -{ +struct NonMovableKeyHash { using is_transparent = void; size_t operator()(const NonMovableKey& k) const { return k.i; } size_t operator()(int k) const { return k; } }; -struct NonMovableKeyEq -{ +struct NonMovableKeyEq { using is_transparent = void; bool operator()(const NonMovableKey& a, const NonMovableKey& b) const { return a.i == b.i; } bool operator()(const NonMovableKey& a, int b) const { return a.i == b; } }; -TEST(THIS_TEST_NAME, MergeExtractInsert) -{ +TEST(THIS_TEST_NAME, MergeExtractInsert) { gtl::THIS_HASH_MAP set1, set2; set1.emplace(std::piecewise_construct, std::make_tuple(7), std::make_tuple(-7)); set1.emplace(std::piecewise_construct, std::make_tuple(17), std::make_tuple(-17)); diff --git a/tests/phmap/node_hash_policy_test.cpp b/tests/phmap/node_hash_policy_test.cpp index bd0d6ad..99af2ab 100644 --- a/tests/phmap/node_hash_policy_test.cpp +++ b/tests/phmap/node_hash_policy_test.cpp @@ -24,42 +24,36 @@ namespace { using ::testing::Pointee; -struct Policy : node_hash_policy -{ +struct Policy : node_hash_policy { using key_type = int; using init_type = int; template - static int* new_element(Alloc*, int value) - { + static int* new_element(Alloc*, int value) { return new int(value); } template - static void delete_element(Alloc*, int* elem) - { + static void delete_element(Alloc*, int* elem) { delete elem; } }; using NodePolicy = hash_policy_traits; -struct NodeTest : ::testing::Test -{ +struct NodeTest : ::testing::Test { std::allocator alloc; int n = 53; int* a = &n; }; -TEST_F(NodeTest, ConstructDestroy) -{ +TEST_F(NodeTest, ConstructDestroy) { NodePolicy::construct(&alloc, &a, 42); EXPECT_THAT(a, Pointee(42)); NodePolicy::destroy(&alloc, &a); } -TEST_F(NodeTest, transfer) -{ +TEST_F(NodeTest, transfer) { int s = 42; int* b = &s; NodePolicy::transfer(&alloc, &a, &b); diff --git a/tests/phmap/node_hash_set_test.cpp b/tests/phmap/node_hash_set_test.cpp index f167360..306ac64 100644 --- a/tests/phmap/node_hash_set_test.cpp +++ b/tests/phmap/node_hash_set_test.cpp @@ -32,36 +32,29 @@ using ::gtl::priv::hash_internal::EnumClass; using ::testing::Pointee; using ::testing::UnorderedElementsAre; -using SetTypes = ::testing::Types< - THIS_HASH_SET>, - THIS_HASH_SET>, - THIS_HASH_SET>, - THIS_HASH_SET>>; +using SetTypes = + ::testing::Types>, + THIS_HASH_SET>, + THIS_HASH_SET>, + THIS_HASH_SET>>; INSTANTIATE_TYPED_TEST_SUITE_P(THIS_TEST_NAME, ConstructorTest, SetTypes); INSTANTIATE_TYPED_TEST_SUITE_P(THIS_TEST_NAME, LookupTest, SetTypes); INSTANTIATE_TYPED_TEST_SUITE_P(THIS_TEST_NAME, MembersTest, SetTypes); INSTANTIATE_TYPED_TEST_SUITE_P(THIS_TEST_NAME, ModifiersTest, SetTypes); -TEST(THIS_TEST_NAME, MoveableNotCopyableCompiles) -{ +TEST(THIS_TEST_NAME, MoveableNotCopyableCompiles) { THIS_HASH_SET> t; THIS_HASH_SET> u; u = std::move(t); } -TEST(THIS_TEST_NAME, MergeExtractInsert) -{ - struct Hash - { +TEST(THIS_TEST_NAME, MergeExtractInsert) { + struct Hash { size_t operator()(const std::unique_ptr& p) const { return *p; } }; - struct Eq - { - bool operator()(const std::unique_ptr& a, const std::unique_ptr& b) const - { - return *a == *b; - } + struct Eq { + bool operator()(const std::unique_ptr& a, const std::unique_ptr& b) const { return *a == *b; } }; gtl::THIS_HASH_SET, Hash, Eq> set1, set2; set1.insert(std::make_unique(7)); diff --git a/tests/phmap/parallel_hash_map_test.cpp b/tests/phmap/parallel_hash_map_test.cpp index 1d035ba..f2e8ea4 100644 --- a/tests/phmap/parallel_hash_map_test.cpp +++ b/tests/phmap/parallel_hash_map_test.cpp @@ -9,8 +9,7 @@ namespace gtl { namespace priv { namespace { -TEST(THIS_TEST_NAME, Swap) -{ +TEST(THIS_TEST_NAME, Swap) { using Map = ThisMap; using MapB = ThisMap_NullMutex; @@ -27,8 +26,7 @@ TEST(THIS_TEST_NAME, Swap) EXPECT_TRUE(u[0] == 1); } -TEST(THIS_TEST_NAME, IfContains) -{ +TEST(THIS_TEST_NAME, IfContains) { // ---------------- // test if_contains // ---------------- @@ -48,8 +46,7 @@ TEST(THIS_TEST_NAME, IfContains) EXPECT_FALSE(m.if_contains(3, get_value)); } -TEST(THIS_TEST_NAME, ModifyIf) -{ +TEST(THIS_TEST_NAME, ModifyIf) { // -------------- // test modify_if // -------------- @@ -66,8 +63,7 @@ TEST(THIS_TEST_NAME, ModifyIf) EXPECT_FALSE(m.modify_if(3, set_value)); // because m[3] does not exist } -TEST(THIS_TEST_NAME, TryEmplaceL) -{ +TEST(THIS_TEST_NAME, TryEmplaceL) { // ------------------ // test try_emplace_l // ------------------ @@ -95,8 +91,7 @@ TEST(THIS_TEST_NAME, TryEmplaceL) EXPECT_EQ(m[4], 999); } -TEST(THIS_TEST_NAME, LazyEmplaceL) -{ +TEST(THIS_TEST_NAME, LazyEmplaceL) { // -------------------- // test lazy_emplace_l // -------------------- @@ -122,8 +117,7 @@ TEST(THIS_TEST_NAME, LazyEmplaceL) EXPECT_EQ(m[5], 6); } -TEST(THIS_TEST_NAME, EraseIf) -{ +TEST(THIS_TEST_NAME, EraseIf) { // ------------- // test erase_if // ------------- @@ -148,8 +142,7 @@ TEST(THIS_TEST_NAME, EraseIf) EXPECT_EQ(m[5], 0); } -TEST(THIS_TEST_NAME, ForEach) -{ +TEST(THIS_TEST_NAME, ForEach) { // ------------- // test for_each // ------------- @@ -185,8 +178,7 @@ TEST(THIS_TEST_NAME, ForEach) EXPECT_EQ(counter, 3); } -TEST(THIS_TEST_NAME, EmplaceSingle) -{ +TEST(THIS_TEST_NAME, EmplaceSingle) { // -------------------- // test emplace_single // -------------------- diff --git a/tests/phmap/parallel_hash_set_test.cpp b/tests/phmap/parallel_hash_set_test.cpp index 52a6f51..4945574 100644 --- a/tests/phmap/parallel_hash_set_test.cpp +++ b/tests/phmap/parallel_hash_set_test.cpp @@ -9,24 +9,19 @@ namespace gtl { namespace priv { namespace { -struct Entry -{ +struct Entry { Entry(int k, int v = 0) : key(k) - , value(v) - { - } + , value(v) {} - bool operator==(const Entry& o) const - { + bool operator==(const Entry& o) const { return key == o.key; // not checking value } // Demonstrates how to provide the hash function as a friend member function of the class // This can be used as an alternative to providing a std::hash specialization // -------------------------------------------------------------------------------------- - friend size_t hash_value(const Entry& p) - { + friend size_t hash_value(const Entry& p) { return gtl::HashState().combine(0, p.key); // not checking value } @@ -34,15 +29,14 @@ struct Entry int value; }; -TEST(THIS_TEST_NAME, IfContains) -{ +TEST(THIS_TEST_NAME, IfContains) { // ---------------- // test if_contains // ---------------- using Set = gtl::THIS_HASH_SET; Set m = { - {1, 7}, - { 2, 9} + {1, 7}, + { 2, 9} }; const Set& const_m(m); @@ -54,15 +48,14 @@ TEST(THIS_TEST_NAME, IfContains) EXPECT_FALSE(m.if_contains(Entry{ 3 }, get_value)); } -TEST(THIS_TEST_NAME, ModifyIf) -{ +TEST(THIS_TEST_NAME, ModifyIf) { // -------------- // test modify_if // -------------- using Set = gtl::THIS_HASH_SET; Set m = { - {1, 7}, - { 2, 9} + {1, 7}, + { 2, 9} }; auto set_value = [](Set::value_type& v) { v.value = 11; }; @@ -76,47 +69,41 @@ TEST(THIS_TEST_NAME, ModifyIf) EXPECT_FALSE(m.modify_if(Entry{ 3 }, set_value)); // because m[3] does not exist } -TEST(THIS_TEST_NAME, LazyEmplaceL) -{ +TEST(THIS_TEST_NAME, LazyEmplaceL) { // -------------------- // test lazy_emplace_l // -------------------- using Set = gtl::THIS_HASH_SET; Set m = { - {1, 7}, - { 2, 9} + {1, 7}, + { 2, 9} }; // insert a value that is not already present. // right now m[5] does not exist m.lazy_emplace_l( Entry{ 5 }, - [](Set::value_type& v) { v.value = 6; }, // called only when key was already present - [](const Set::constructor& ctor) { - ctor(5, 13); - }); // construct value_type in place when key not present + [](Set::value_type& v) { v.value = 6; }, // called only when key was already present + [](const Set::constructor& ctor) { ctor(5, 13); }); // construct value_type in place when key not present EXPECT_EQ(m.find(Entry{ 5 })->value, 13); // change a value that is present. m.lazy_emplace_l( Entry{ 5 }, - [](Set::value_type& v) { v.value = 6; }, // called only when key was already present - [](const Set::constructor& ctor) { - ctor(5, 13); - }); // construct value_type in place when key not present + [](Set::value_type& v) { v.value = 6; }, // called only when key was already present + [](const Set::constructor& ctor) { ctor(5, 13); }); // construct value_type in place when key not present EXPECT_EQ(m.find(Entry{ 5 })->value, 6); } -TEST(THIS_TEST_NAME, EraseIf) -{ +TEST(THIS_TEST_NAME, EraseIf) { // ------------- // test erase_if // ------------- using Set = gtl::THIS_HASH_SET; Set m = { - {1, 7}, - { 2, 9}, - { 5, 6} + {1, 7}, + { 2, 9}, + { 5, 6} }; EXPECT_EQ(m.erase_if(Entry{ 9 }, @@ -133,16 +120,15 @@ TEST(THIS_TEST_NAME, EraseIf) EXPECT_EQ(m.find(Entry{ 5 }), m.end()); } -TEST(THIS_TEST_NAME, ForEach) -{ +TEST(THIS_TEST_NAME, ForEach) { // ------------- // test for_each // ------------- using Set = gtl::THIS_HASH_SET; Set m = { - {1, 7 }, - { 2, 8 }, - { 5, 11} + {1, 7 }, + { 2, 8 }, + { 5, 11} }; int counter = 0; @@ -153,8 +139,7 @@ TEST(THIS_TEST_NAME, ForEach) EXPECT_EQ(counter, 3); } -TEST(THIS_TEST_NAME, EmplaceSingle) -{ +TEST(THIS_TEST_NAME, EmplaceSingle) { using Set = gtl::THIS_HASH_SET; // -------------------- diff --git a/tests/phmap/raw_hash_set_allocator_test.cpp b/tests/phmap/raw_hash_set_allocator_test.cpp index 64bb308..9f55c61 100644 --- a/tests/phmap/raw_hash_set_allocator_test.cpp +++ b/tests/phmap/raw_hash_set_allocator_test.cpp @@ -23,22 +23,19 @@ namespace gtl { namespace priv { namespace { -enum AllocSpec -{ +enum AllocSpec { kPropagateOnCopy = 1, kPropagateOnMove = 2, kPropagateOnSwap = 4, }; -struct AllocState -{ +struct AllocState { size_t num_allocs = 0; std::set owned; }; template -class CheckedAlloc -{ +class CheckedAlloc { public: template friend class CheckedAlloc; @@ -47,49 +44,38 @@ class CheckedAlloc CheckedAlloc() {} explicit CheckedAlloc(size_t id) - : id_(id) - { - } + : id_(id) {} CheckedAlloc(const CheckedAlloc&) = default; CheckedAlloc& operator=(const CheckedAlloc&) = default; template CheckedAlloc(const CheckedAlloc& that) : id_(that.id_) - , state_(that.state_) - { - } + , state_(that.state_) {} template - struct rebind - { + struct rebind { using other = CheckedAlloc; }; - using propagate_on_container_copy_assignment = - std::integral_constant; + using propagate_on_container_copy_assignment = std::integral_constant; - using propagate_on_container_move_assignment = - std::integral_constant; + using propagate_on_container_move_assignment = std::integral_constant; - using propagate_on_container_swap = - std::integral_constant; + using propagate_on_container_swap = std::integral_constant; - CheckedAlloc select_on_container_copy_construction() const - { + CheckedAlloc select_on_container_copy_construction() const { if (Spec & kPropagateOnCopy) return *this; return {}; } - T* allocate(size_t n) - { + T* allocate(size_t n) { T* ptr = std::allocator().allocate(n); track_alloc(ptr); return ptr; } - void deallocate(T* ptr, size_t n) - { + void deallocate(T* ptr, size_t n) { memset(ptr, 0, n * sizeof(T)); // The freed memory must be unpoisoned. track_dealloc(ptr); return std::allocator().deallocate(ptr, n); @@ -100,8 +86,7 @@ class CheckedAlloc size_t num_allocs() const { return state_->num_allocs; } - void swap(CheckedAlloc& that) - { + void swap(CheckedAlloc& that) { using std::swap; swap(id_, that.id_); swap(state_, that.state_); @@ -109,21 +94,16 @@ class CheckedAlloc friend void swap(CheckedAlloc& a, CheckedAlloc& b) { a.swap(b); } - friend std::ostream& operator<<(std::ostream& o, const CheckedAlloc& a) - { - return o << "alloc(" << a.id_ << ")"; - } + friend std::ostream& operator<<(std::ostream& o, const CheckedAlloc& a) { return o << "alloc(" << a.id_ << ")"; } private: - void track_alloc(void* ptr) - { + void track_alloc(void* ptr) { AllocState* state = state_.get(); ++state->num_allocs; if (!state->owned.insert(ptr).second) ADD_FAILURE() << *this << " got previously allocated memory: " << ptr; } - void track_dealloc(void* ptr) - { + void track_dealloc(void* ptr) { if (state_->owned.erase(ptr) != 1) ADD_FAILURE() << *this << " deleting memory owned by another allocator: " << ptr; } @@ -133,52 +113,44 @@ class CheckedAlloc std::shared_ptr state_ = std::make_shared(); }; -struct Identity -{ +struct Identity { int32_t operator()(int32_t v) const { return v; } }; -struct Policy -{ +struct Policy { using slot_type = Tracked; using init_type = Tracked; using key_type = int32_t; - using is_flat = std::false_type; + using is_flat = std::false_type; template - static void construct(allocator_type* alloc, slot_type* slot, Args&&... args) - { + static void construct(allocator_type* alloc, slot_type* slot, Args&&... args) { std::allocator_traits::construct(*alloc, slot, std::forward(args)...); } template - static void destroy(allocator_type* alloc, slot_type* slot) - { + static void destroy(allocator_type* alloc, slot_type* slot) { std::allocator_traits::destroy(*alloc, slot); } template - static void transfer(allocator_type* alloc, slot_type* new_slot, slot_type* old_slot) - { + static void transfer(allocator_type* alloc, slot_type* new_slot, slot_type* old_slot) { construct(alloc, new_slot, std::move(*old_slot)); destroy(alloc, old_slot); } template - static auto apply(F&& f, int32_t v) -> decltype(std::forward(f)(v, v)) - { + static auto apply(F&& f, int32_t v) -> decltype(std::forward(f)(v, v)) { return std::forward(f)(v, v); } template - static auto apply(F&& f, const slot_type& v) -> decltype(std::forward(f)(v.val(), v)) - { + static auto apply(F&& f, const slot_type& v) -> decltype(std::forward(f)(v.val(), v)) { return std::forward(f)(v.val(), v); } template - static auto apply(F&& f, slot_type&& v) -> decltype(std::forward(f)(v.val(), std::move(v))) - { + static auto apply(F&& f, slot_type&& v) -> decltype(std::forward(f)(v.val(), std::move(v))) { return std::forward(f)(v.val(), std::move(v)); } @@ -186,14 +158,12 @@ struct Policy }; template -struct PropagateTest : public ::testing::Test -{ +struct PropagateTest : public ::testing::Test { using Alloc = CheckedAlloc, Spec>; using Table = raw_hash_set, Alloc>; - PropagateTest() - { + PropagateTest() { EXPECT_EQ(a1, t1.get_allocator()); EXPECT_NE(a2, t1.get_allocator()); } @@ -209,16 +179,14 @@ using NoPropagateOnMove = PropagateTest; TEST_F(PropagateOnAll, Empty) { EXPECT_EQ(0u, a1.num_allocs()); } -TEST_F(PropagateOnAll, InsertAllocates) -{ +TEST_F(PropagateOnAll, InsertAllocates) { auto it = t1.insert(0).first; EXPECT_EQ(1u, a1.num_allocs()); EXPECT_EQ(0u, it->num_moves()); EXPECT_EQ(0u, it->num_copies()); } -TEST_F(PropagateOnAll, InsertDecomposes) -{ +TEST_F(PropagateOnAll, InsertDecomposes) { auto it = t1.insert(0).first; EXPECT_EQ(1u, a1.num_allocs()); EXPECT_EQ(0u, it->num_moves()); @@ -230,8 +198,7 @@ TEST_F(PropagateOnAll, InsertDecomposes) EXPECT_EQ(0u, it->num_copies()); } -TEST_F(PropagateOnAll, RehashMoves) -{ +TEST_F(PropagateOnAll, RehashMoves) { auto it = t1.insert(0).first; EXPECT_EQ(0u, it->num_moves()); t1.rehash(2 * t1.capacity()); @@ -241,8 +208,7 @@ TEST_F(PropagateOnAll, RehashMoves) EXPECT_EQ(0u, it->num_copies()); } -TEST_F(PropagateOnAll, CopyConstructor) -{ +TEST_F(PropagateOnAll, CopyConstructor) { auto it = t1.insert(0).first; Table u(t1); EXPECT_EQ(2u, a1.num_allocs()); @@ -250,8 +216,7 @@ TEST_F(PropagateOnAll, CopyConstructor) EXPECT_EQ(1u, it->num_copies()); } -TEST_F(NoPropagateOnCopy, CopyConstructor) -{ +TEST_F(NoPropagateOnCopy, CopyConstructor) { auto it = t1.insert(0).first; Table u(t1); EXPECT_EQ(1u, a1.num_allocs()); @@ -260,8 +225,7 @@ TEST_F(NoPropagateOnCopy, CopyConstructor) EXPECT_EQ(1u, it->num_copies()); } -TEST_F(PropagateOnAll, CopyConstructorWithSameAlloc) -{ +TEST_F(PropagateOnAll, CopyConstructorWithSameAlloc) { auto it = t1.insert(0).first; Table u(t1, a1); EXPECT_EQ(2u, a1.num_allocs()); @@ -269,8 +233,7 @@ TEST_F(PropagateOnAll, CopyConstructorWithSameAlloc) EXPECT_EQ(1u, it->num_copies()); } -TEST_F(NoPropagateOnCopy, CopyConstructorWithSameAlloc) -{ +TEST_F(NoPropagateOnCopy, CopyConstructorWithSameAlloc) { auto it = t1.insert(0).first; Table u(t1, a1); EXPECT_EQ(2u, a1.num_allocs()); @@ -278,8 +241,7 @@ TEST_F(NoPropagateOnCopy, CopyConstructorWithSameAlloc) EXPECT_EQ(1u, it->num_copies()); } -TEST_F(PropagateOnAll, CopyConstructorWithDifferentAlloc) -{ +TEST_F(PropagateOnAll, CopyConstructorWithDifferentAlloc) { auto it = t1.insert(0).first; Table u(t1, a2); EXPECT_EQ(a2, u.get_allocator()); @@ -289,8 +251,7 @@ TEST_F(PropagateOnAll, CopyConstructorWithDifferentAlloc) EXPECT_EQ(1u, it->num_copies()); } -TEST_F(NoPropagateOnCopy, CopyConstructorWithDifferentAlloc) -{ +TEST_F(NoPropagateOnCopy, CopyConstructorWithDifferentAlloc) { auto it = t1.insert(0).first; Table u(t1, a2); EXPECT_EQ(a2, u.get_allocator()); @@ -300,8 +261,7 @@ TEST_F(NoPropagateOnCopy, CopyConstructorWithDifferentAlloc) EXPECT_EQ(1u, it->num_copies()); } -TEST_F(PropagateOnAll, MoveConstructor) -{ +TEST_F(PropagateOnAll, MoveConstructor) { auto it = t1.insert(0).first; Table u(std::move(t1)); EXPECT_EQ(1u, a1.num_allocs()); @@ -309,8 +269,7 @@ TEST_F(PropagateOnAll, MoveConstructor) EXPECT_EQ(0u, it->num_copies()); } -TEST_F(NoPropagateOnMove, MoveConstructor) -{ +TEST_F(NoPropagateOnMove, MoveConstructor) { auto it = t1.insert(0).first; Table u(std::move(t1)); EXPECT_EQ(1u, a1.num_allocs()); @@ -318,8 +277,7 @@ TEST_F(NoPropagateOnMove, MoveConstructor) EXPECT_EQ(0u, it->num_copies()); } -TEST_F(PropagateOnAll, MoveConstructorWithSameAlloc) -{ +TEST_F(PropagateOnAll, MoveConstructorWithSameAlloc) { auto it = t1.insert(0).first; Table u(std::move(t1), a1); EXPECT_EQ(1u, a1.num_allocs()); @@ -327,8 +285,7 @@ TEST_F(PropagateOnAll, MoveConstructorWithSameAlloc) EXPECT_EQ(0u, it->num_copies()); } -TEST_F(NoPropagateOnMove, MoveConstructorWithSameAlloc) -{ +TEST_F(NoPropagateOnMove, MoveConstructorWithSameAlloc) { auto it = t1.insert(0).first; Table u(std::move(t1), a1); EXPECT_EQ(1u, a1.num_allocs()); @@ -336,8 +293,7 @@ TEST_F(NoPropagateOnMove, MoveConstructorWithSameAlloc) EXPECT_EQ(0u, it->num_copies()); } -TEST_F(PropagateOnAll, MoveConstructorWithDifferentAlloc) -{ +TEST_F(PropagateOnAll, MoveConstructorWithDifferentAlloc) { auto it = t1.insert(0).first; Table u(std::move(t1), a2); it = u.find(0); @@ -348,8 +304,7 @@ TEST_F(PropagateOnAll, MoveConstructorWithDifferentAlloc) EXPECT_EQ(0u, it->num_copies()); } -TEST_F(NoPropagateOnMove, MoveConstructorWithDifferentAlloc) -{ +TEST_F(NoPropagateOnMove, MoveConstructorWithDifferentAlloc) { auto it = t1.insert(0).first; Table u(std::move(t1), a2); it = u.find(0); @@ -360,8 +315,7 @@ TEST_F(NoPropagateOnMove, MoveConstructorWithDifferentAlloc) EXPECT_EQ(0u, it->num_copies()); } -TEST_F(PropagateOnAll, CopyAssignmentWithSameAlloc) -{ +TEST_F(PropagateOnAll, CopyAssignmentWithSameAlloc) { auto it = t1.insert(0).first; Table u(0, a1); u = t1; @@ -370,8 +324,7 @@ TEST_F(PropagateOnAll, CopyAssignmentWithSameAlloc) EXPECT_EQ(1u, it->num_copies()); } -TEST_F(NoPropagateOnCopy, CopyAssignmentWithSameAlloc) -{ +TEST_F(NoPropagateOnCopy, CopyAssignmentWithSameAlloc) { auto it = t1.insert(0).first; Table u(0, a1); u = t1; @@ -380,8 +333,7 @@ TEST_F(NoPropagateOnCopy, CopyAssignmentWithSameAlloc) EXPECT_EQ(1u, it->num_copies()); } -TEST_F(PropagateOnAll, CopyAssignmentWithDifferentAlloc) -{ +TEST_F(PropagateOnAll, CopyAssignmentWithDifferentAlloc) { auto it = t1.insert(0).first; Table u(0, a2); u = t1; @@ -392,8 +344,7 @@ TEST_F(PropagateOnAll, CopyAssignmentWithDifferentAlloc) EXPECT_EQ(1u, it->num_copies()); } -TEST_F(NoPropagateOnCopy, CopyAssignmentWithDifferentAlloc) -{ +TEST_F(NoPropagateOnCopy, CopyAssignmentWithDifferentAlloc) { auto it = t1.insert(0).first; Table u(0, a2); u = t1; @@ -404,8 +355,7 @@ TEST_F(NoPropagateOnCopy, CopyAssignmentWithDifferentAlloc) EXPECT_EQ(1u, it->num_copies()); } -TEST_F(PropagateOnAll, MoveAssignmentWithSameAlloc) -{ +TEST_F(PropagateOnAll, MoveAssignmentWithSameAlloc) { auto it = t1.insert(0).first; Table u(0, a1); u = std::move(t1); @@ -415,8 +365,7 @@ TEST_F(PropagateOnAll, MoveAssignmentWithSameAlloc) EXPECT_EQ(0u, it->num_copies()); } -TEST_F(NoPropagateOnMove, MoveAssignmentWithSameAlloc) -{ +TEST_F(NoPropagateOnMove, MoveAssignmentWithSameAlloc) { auto it = t1.insert(0).first; Table u(0, a1); u = std::move(t1); @@ -426,8 +375,7 @@ TEST_F(NoPropagateOnMove, MoveAssignmentWithSameAlloc) EXPECT_EQ(0u, it->num_copies()); } -TEST_F(PropagateOnAll, MoveAssignmentWithDifferentAlloc) -{ +TEST_F(PropagateOnAll, MoveAssignmentWithDifferentAlloc) { auto it = t1.insert(0).first; Table u(0, a2); u = std::move(t1); @@ -438,8 +386,7 @@ TEST_F(PropagateOnAll, MoveAssignmentWithDifferentAlloc) EXPECT_EQ(0u, it->num_copies()); } -TEST_F(NoPropagateOnMove, MoveAssignmentWithDifferentAlloc) -{ +TEST_F(NoPropagateOnMove, MoveAssignmentWithDifferentAlloc) { auto it = t1.insert(0).first; Table u(0, a2); u = std::move(t1); @@ -451,8 +398,7 @@ TEST_F(NoPropagateOnMove, MoveAssignmentWithDifferentAlloc) EXPECT_EQ(0u, it->num_copies()); } -TEST_F(PropagateOnAll, Swap) -{ +TEST_F(PropagateOnAll, Swap) { auto it = t1.insert(0).first; Table u(0, a2); u.swap(t1); diff --git a/tests/phmap/raw_hash_set_test.cpp b/tests/phmap/raw_hash_set_test.cpp index 322a386..97217ac 100644 --- a/tests/phmap/raw_hash_set_test.cpp +++ b/tests/phmap/raw_hash_set_test.cpp @@ -16,8 +16,8 @@ #define GTL_NON_DETERMINISTIC 1 #include "gtl/phmap.hpp" -//#include "container_memory.h" -//#include "hash_function_defaults.h" +// #include "container_memory.h" +// #include "hash_function_defaults.h" #include "hash_policy_testing.hpp" #include "hashtable_debug.hpp" @@ -42,11 +42,9 @@ namespace gtl { namespace priv { -struct RawHashSetTestOnlyAccess -{ +struct RawHashSetTestOnlyAccess { template - static auto GetSlots(const C& c) -> decltype(c.slots_) - { + static auto GetSlots(const C& c) -> decltype(c.slots_) { return c.slots_; } }; @@ -61,8 +59,7 @@ using ::testing::Optional; using ::testing::Pair; using ::testing::UnorderedElementsAre; -TEST(Util, NormalizeCapacity) -{ +TEST(Util, NormalizeCapacity) { EXPECT_EQ(1u, NormalizeCapacity(0)); EXPECT_EQ(1u, NormalizeCapacity(1)); EXPECT_EQ(3u, NormalizeCapacity(2)); @@ -75,8 +72,7 @@ TEST(Util, NormalizeCapacity) EXPECT_EQ(15u * 2 + 1, NormalizeCapacity(15 + 2)); } -TEST(Util, GrowthAndCapacity) -{ +TEST(Util, GrowthAndCapacity) { // Verify that GrowthToCapacity gives the minimum capacity that has enough // growth. for (size_t growth = 0; growth < 10000; ++growth) { @@ -99,8 +95,7 @@ TEST(Util, GrowthAndCapacity) } } -TEST(Util, probe_seq) -{ +TEST(Util, probe_seq) { probe_seq<16> seq(0, 127); auto gen = [&]() { size_t res = seq.offset(); @@ -115,8 +110,7 @@ TEST(Util, probe_seq) EXPECT_THAT(offsets, ElementsAre(0, 16, 48, 96, 32, 112, 80, 64)); } -TEST(BitMask, Smoke) -{ +TEST(BitMask, Smoke) { EXPECT_FALSE((BitMask(0))); EXPECT_TRUE((BitMask(5))); @@ -130,8 +124,7 @@ TEST(BitMask, Smoke) EXPECT_THAT((BitMask(0xAA)), ElementsAre(1, 3, 5, 7)); } -TEST(BitMask, WithShift) -{ +TEST(BitMask, WithShift) { // See the non-SSE version of Group for details on what this math is for. uint64_t ctrl = 0x1716151413121110; uint64_t hash = 0x12; @@ -145,8 +138,7 @@ TEST(BitMask, WithShift) EXPECT_EQ(*b, 2u); } -TEST(BitMask, LeadingTrailing) -{ +TEST(BitMask, LeadingTrailing) { EXPECT_EQ((BitMask(0x00001a40).LeadingZeros()), 3u); EXPECT_EQ((BitMask(0x00001a40).TrailingZeros()), 6u); @@ -166,18 +158,14 @@ TEST(BitMask, LeadingTrailing) EXPECT_EQ((BitMask(0x8000000000000000).TrailingZeros()), 7u); } -TEST(Group, EmptyGroup) -{ +TEST(Group, EmptyGroup) { for (h2_t h = 0; h != 128; ++h) EXPECT_FALSE(Group{ EmptyGroup() }.Match(h)); } -TEST(Group, Match) -{ +TEST(Group, Match) { if constexpr (Group::kWidth == 16) { - ctrl_t group[] = { - kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7, 7, 5, 3, 1, 1, 1, 1, 1 - }; + ctrl_t group[] = { kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7, 7, 5, 3, 1, 1, 1, 1, 1 }; EXPECT_THAT(Group{ group }.Match(0), ElementsAre()); EXPECT_THAT(Group{ group }.Match(1), ElementsAre(1, 11, 12, 13, 14, 15)); EXPECT_THAT(Group{ group }.Match(3), ElementsAre(3, 10)); @@ -193,12 +181,9 @@ TEST(Group, Match) } } -TEST(Group, MatchEmpty) -{ +TEST(Group, MatchEmpty) { if constexpr (Group::kWidth == 16) { - ctrl_t group[] = { - kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7, 7, 5, 3, 1, 1, 1, 1, 1 - }; + ctrl_t group[] = { kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7, 7, 5, 3, 1, 1, 1, 1, 1 }; EXPECT_THAT(Group{ group }.MatchEmpty(), ElementsAre(0, 4)); } else if constexpr (Group::kWidth == 8) { ctrl_t group[] = { kEmpty, 1, 2, kDeleted, 2, 1, kSentinel, 1 }; @@ -208,12 +193,9 @@ TEST(Group, MatchEmpty) } } -TEST(Group, MatchEmptyOrDeleted) -{ +TEST(Group, MatchEmptyOrDeleted) { if constexpr (Group::kWidth == 16) { - ctrl_t group[] = { - kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7, 7, 5, 3, 1, 1, 1, 1, 1 - }; + ctrl_t group[] = { kEmpty, 1, kDeleted, 3, kEmpty, 5, kSentinel, 7, 7, 5, 3, 1, 1, 1, 1, 1 }; EXPECT_THAT(Group{ group }.MatchEmptyOrDeleted(), ElementsAre(0, 2, 4)); } else if constexpr (Group::kWidth == 8) { ctrl_t group[] = { kEmpty, 1, 2, kDeleted, 2, 1, kSentinel, 1 }; @@ -223,8 +205,7 @@ TEST(Group, MatchEmptyOrDeleted) } } -TEST(Batch, DropDeletes) -{ +TEST(Batch, DropDeletes) { constexpr size_t kCapacity = 63; constexpr size_t kGroupWidth = priv::Group::kWidth; std::vector ctrl(kCapacity + 1 + kGroupWidth); @@ -249,8 +230,7 @@ TEST(Batch, DropDeletes) } } -TEST(Group, CountLeadingEmptyOrDeleted) -{ +TEST(Group, CountLeadingEmptyOrDeleted) { const std::vector empty_examples = { kEmpty, kDeleted }; const std::vector full_examples = { 0, 1, 2, 3, 5, 9, 127, kSentinel }; @@ -271,12 +251,11 @@ TEST(Group, CountLeadingEmptyOrDeleted) } } -struct IntPolicy -{ +struct IntPolicy { using slot_type = int64_t; using key_type = int64_t; using init_type = int64_t; - using is_flat = std::false_type; + using is_flat = std::false_type; static void construct(void*, int64_t* slot, int64_t v) { *slot = v; } static void destroy(void*, int64_t*) {} @@ -285,65 +264,52 @@ struct IntPolicy static int64_t& element(slot_type* slot) { return *slot; } template - static auto apply(F&& f, int64_t x) -> decltype(std::forward(f)(x, x)) - { + static auto apply(F&& f, int64_t x) -> decltype(std::forward(f)(x, x)) { return std::forward(f)(x, x); } }; -class StringPolicy -{ +class StringPolicy { template::value>::type> + class = typename std::enable_if::value>::type> decltype(std::declval()(std::declval(), std::piecewise_construct, std::declval>(), - std::declval())) static apply_impl(F&& f, - std::pair, V> p) - { + std::declval())) static apply_impl(F&& f, std::pair, V> p) { const std::string_view& key = std::get<0>(p.first); - return std::forward(f)( - key, std::piecewise_construct, std::move(p.first), std::move(p.second)); + return std::forward(f)(key, std::piecewise_construct, std::move(p.first), std::move(p.second)); } public: - struct slot_type - { - struct ctor - {}; + struct slot_type { + struct ctor {}; template slot_type(ctor, Ts&&... ts) - : pair(std::forward(ts)...) - { - } + : pair(std::forward(ts)...) {} std::pair pair; }; using key_type = std::string; using init_type = std::pair; - using is_flat = std::false_type; + using is_flat = std::false_type; template - static void construct(allocator_type* alloc, slot_type* slot, Args... args) - { + static void construct(allocator_type* alloc, slot_type* slot, Args... args) { std::allocator_traits::construct( *alloc, slot, typename slot_type::ctor(), std::forward(args)...); } template - static void destroy(allocator_type* alloc, slot_type* slot) - { + static void destroy(allocator_type* alloc, slot_type* slot) { std::allocator_traits::destroy(*alloc, slot); } template - static void transfer(allocator_type* alloc, slot_type* new_slot, slot_type* old_slot) - { + static void transfer(allocator_type* alloc, slot_type* new_slot, slot_type* old_slot) { construct(alloc, new_slot, std::move(old_slot->pair)); destroy(alloc, old_slot); } @@ -352,84 +318,64 @@ class StringPolicy template static auto apply(F&& f, Args&&... args) - -> decltype(apply_impl(std::forward(f), PairArgs(std::forward(args)...))) - { + -> decltype(apply_impl(std::forward(f), PairArgs(std::forward(args)...))) { return apply_impl(std::forward(f), PairArgs(std::forward(args)...)); } }; -struct StringHash : gtl::Hash -{ +struct StringHash : gtl::Hash { using is_transparent = void; }; -struct StringEq : std::equal_to -{ +struct StringEq : std::equal_to { using is_transparent = void; }; -struct StringTable : raw_hash_set> -{ +struct StringTable : raw_hash_set> { using Base = typename StringTable::raw_hash_set; StringTable() {} using Base::Base; }; struct IntTable - : raw_hash_set, - std::equal_to, - std::allocator> -{ + : raw_hash_set, std::equal_to, std::allocator> { using Base = typename IntTable::raw_hash_set; IntTable() {} using Base::Base; }; template -struct CustomAlloc : std::allocator -{ +struct CustomAlloc : std::allocator { CustomAlloc() {} template - CustomAlloc(const CustomAlloc&) - { - } + CustomAlloc(const CustomAlloc&) {} template - struct rebind - { + struct rebind { using other = CustomAlloc; }; }; struct CustomAllocIntTable - : raw_hash_set, - std::equal_to, - CustomAlloc> -{ + : raw_hash_set, std::equal_to, CustomAlloc> { using Base = typename CustomAllocIntTable::raw_hash_set; using Base::Base; }; -struct BadFastHash -{ +struct BadFastHash { template - size_t operator()(const T&) const - { + size_t operator()(const T&) const { return 0; } }; -struct BadTable : raw_hash_set, std::allocator> -{ +struct BadTable : raw_hash_set, std::allocator> { using Base = typename BadTable::raw_hash_set; BadTable() {} using Base::Base; }; -TEST(Table, Empty) -{ +TEST(Table, Empty) { IntTable t; EXPECT_EQ(0u, t.size()); EXPECT_TRUE(t.empty()); @@ -437,14 +383,12 @@ TEST(Table, Empty) #ifdef __GNUC__ template -GTL_ATTRIBUTE_ALWAYS_INLINE inline void DoNotOptimize(const T& v) -{ +GTL_ATTRIBUTE_ALWAYS_INLINE inline void DoNotOptimize(const T& v) { asm volatile("" : : "r,m"(v) : "memory"); } #endif -TEST(Table, Prefetch) -{ +TEST(Table, Prefetch) { IntTable t; t.emplace(1); // Works for both present and absent keys. @@ -453,9 +397,9 @@ TEST(Table, Prefetch) // Do not run in debug mode, when prefetch is not implemented, or when // sanitizers are enabled. -#if 0 && defined(NDEBUG) && defined(__GNUC__) && defined(__x86_64__) && \ - !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && !defined(THREAD_SANITIZER) && \ - !defined(UNDEFINED_BEHAVIOR_SANITIZER) && !defined(__EMSCRIPTEN__) +#if 0 && defined(NDEBUG) && defined(__GNUC__) && defined(__x86_64__) && !defined(ADDRESS_SANITIZER) && \ + !defined(MEMORY_SANITIZER) && !defined(THREAD_SANITIZER) && !defined(UNDEFINED_BEHAVIOR_SANITIZER) && \ + !defined(__EMSCRIPTEN__) const auto now = [] { return gtl::base_internal::CycleClock::Now(); }; // Make size enough to not fit in L2 cache (16.7 Mb) @@ -483,15 +427,13 @@ TEST(Table, Prefetch) #endif } -TEST(Table, LookupEmpty) -{ +TEST(Table, LookupEmpty) { IntTable t; auto it = t.find(0); EXPECT_TRUE(it == t.end()); } -TEST(Table, Insert1) -{ +TEST(Table, Insert1) { IntTable t; EXPECT_TRUE(t.find(0) == t.end()); auto res = t.emplace(0); @@ -501,8 +443,7 @@ TEST(Table, Insert1) EXPECT_THAT(*t.find(0), 0); } -TEST(Table, Insert2) -{ +TEST(Table, Insert2) { IntTable t; EXPECT_TRUE(t.find(0) == t.end()); auto res = t.emplace(0); @@ -518,8 +459,7 @@ TEST(Table, Insert2) EXPECT_THAT(*t.find(1), 1); } -TEST(Table, InsertCollision) -{ +TEST(Table, InsertCollision) { BadTable t; EXPECT_TRUE(t.find(1) == t.end()); auto res = t.emplace(1); @@ -539,8 +479,7 @@ TEST(Table, InsertCollision) // Test that we do not add existent element in case we need to search through // many groups with deleted elements -TEST(Table, InsertCollisionAndFindAfterDelete) -{ +TEST(Table, InsertCollisionAndFindAfterDelete) { BadTable t; // all elements go to the same group. // Have at least 2 groups with Group::kWidth collisions // plus some extra collisions in the last group. @@ -567,8 +506,7 @@ TEST(Table, InsertCollisionAndFindAfterDelete) EXPECT_TRUE(t.empty()); } -TEST(Table, LazyEmplace) -{ +TEST(Table, LazyEmplace) { StringTable t; bool called = false; auto it = t.lazy_emplace("abc", [&](const StringTable::constructor& f) { @@ -586,15 +524,13 @@ TEST(Table, LazyEmplace) EXPECT_THAT(*it, Pair("abc", "ABC")); } -TEST(Table, ContainsEmpty) -{ +TEST(Table, ContainsEmpty) { IntTable t; EXPECT_FALSE(t.contains(0)); } -TEST(Table, Contains1) -{ +TEST(Table, Contains1) { IntTable t; EXPECT_TRUE(t.insert(0).second); @@ -605,8 +541,7 @@ TEST(Table, Contains1) EXPECT_FALSE(t.contains(0)); } -TEST(Table, Contains2) -{ +TEST(Table, Contains2) { IntTable t; EXPECT_TRUE(t.insert(0).second); @@ -618,63 +553,53 @@ TEST(Table, Contains2) } int decompose_constructed; -struct DecomposeType -{ +struct DecomposeType { DecomposeType(int i_) - : i(i_) - { // NOLINT + : i(i_) { // NOLINT ++decompose_constructed; } explicit DecomposeType(const char* d) - : DecomposeType(*d) - { - } + : DecomposeType(*d) {} int i; }; -struct DecomposeHash -{ +struct DecomposeHash { using is_transparent = void; size_t operator()(DecomposeType a) const { return a.i; } size_t operator()(int a) const { return a; } size_t operator()(const char* a) const { return *a; } }; -struct DecomposeEq -{ +struct DecomposeEq { using is_transparent = void; bool operator()(DecomposeType a, DecomposeType b) const { return a.i == b.i; } bool operator()(DecomposeType a, int b) const { return a.i == b; } bool operator()(DecomposeType a, const char* b) const { return a.i == *b; } }; -struct DecomposePolicy -{ +struct DecomposePolicy { using slot_type = DecomposeType; using key_type = DecomposeType; using init_type = DecomposeType; - using is_flat = std::false_type; + using is_flat = std::false_type; template - static void construct(void*, DecomposeType* slot, T&& v) - { + static void construct(void*, DecomposeType* slot, T&& v) { *slot = DecomposeType(std::forward(v)); } static void destroy(void*, DecomposeType*) {} static DecomposeType& element(slot_type* slot) { return *slot; } template - static auto apply(F&& f, const T& x) -> decltype(std::forward(f)(x, x)) - { + static auto apply(F&& f, const T& x) -> decltype(std::forward(f)(x, x)) { return std::forward(f)(x, x); } }; template -void TestDecompose(bool construct_three) -{ +void TestDecompose(bool construct_three) { DecomposeType elem{ 0 }; const int one = 1; const char* three_p = "3"; @@ -740,17 +665,14 @@ void TestDecompose(bool construct_three) } } -TEST(Table, Decompose) -{ +TEST(Table, Decompose) { TestDecompose(false); - struct TransparentHashIntOverload - { + struct TransparentHashIntOverload { size_t operator()(DecomposeType a) const { return a.i; } size_t operator()(int a) const { return a; } }; - struct TransparentEqIntOverload - { + struct TransparentEqIntOverload { bool operator()(DecomposeType a, DecomposeType b) const { return a.i == b.i; } bool operator()(DecomposeType a, int b) const { return a.i == b; } }; @@ -761,8 +683,7 @@ TEST(Table, Decompose) // Returns the largest m such that a table with m elements has the same number // of buckets as a table with n elements. -size_t MaxDensitySize(size_t n) -{ +size_t MaxDensitySize(size_t n) { IntTable t; t.reserve(n); for (size_t i = 0; i != n; ++i) @@ -828,8 +749,7 @@ TEST(Table, RehashWithNoResize) { } #endif -TEST(Table, InsertEraseStressTest) -{ +TEST(Table, InsertEraseStressTest) { IntTable t; const size_t kMinElementCount = 250; std::deque keys; @@ -847,8 +767,7 @@ TEST(Table, InsertEraseStressTest) } } -TEST(Table, InsertOverloads) -{ +TEST(Table, InsertOverloads) { StringTable t; // These should all trigger the insert(init_type) overload. t.insert({ {}, {} }); @@ -858,8 +777,7 @@ TEST(Table, InsertOverloads) EXPECT_THAT(t, UnorderedElementsAre(Pair("", ""), Pair("ABC", ""), Pair("DEF", "!!!"))); } -TEST(Table, LargeTable) -{ +TEST(Table, LargeTable) { IntTable t; for (int64_t i = 0; i != 100000; ++i) t.emplace(i << 40); @@ -868,8 +786,7 @@ TEST(Table, LargeTable) } // Timeout if copy is quadratic as it was in Rust. -TEST(Table, EnsureNonQuadraticAsInRust) -{ +TEST(Table, EnsureNonQuadraticAsInRust) { static const size_t kLargeSize = 1 << 15; IntTable t; @@ -883,8 +800,7 @@ TEST(Table, EnsureNonQuadraticAsInRust) t2.insert(entry); } -TEST(Table, ClearBug) -{ +TEST(Table, ClearBug) { IntTable t; constexpr size_t capacity = priv::Group::kWidth - 1; constexpr size_t max_size = capacity / 2 + 1; @@ -906,8 +822,7 @@ TEST(Table, ClearBug) EXPECT_LT(std::abs(original - second), capacity * sizeof(IntTable::value_type)); } -TEST(Table, Erase) -{ +TEST(Table, Erase) { IntTable t; EXPECT_TRUE(t.find(0) == t.end()); auto res = t.emplace(0); @@ -918,8 +833,7 @@ TEST(Table, Erase) EXPECT_TRUE(t.find(0) == t.end()); } -TEST(Table, EraseMaintainsValidIterator) -{ +TEST(Table, EraseMaintainsValidIterator) { IntTable t; const int kNumElements = 100; for (int i = 0; i < kNumElements; i++) { @@ -944,8 +858,7 @@ TEST(Table, EraseMaintainsValidIterator) // 3. Take first Group::kWidth - 1 to bad_keys array. // 4. Clear the table without resize. // 5. Go to point 2 while N keys not collected -std::vector CollectBadMergeKeys(size_t N) -{ +std::vector CollectBadMergeKeys(size_t N) { static constexpr int kGroupSize = Group::kWidth - 1; auto topk_range = [](size_t b, size_t e, IntTable* t) -> std::vector { @@ -975,45 +888,36 @@ std::vector CollectBadMergeKeys(size_t N) return bad_keys; } -struct ProbeStats -{ +struct ProbeStats { // Number of elements with specific probe length over all tested tables. std::vector all_probes_histogram; // Ratios total_probe_length/size for every tested table. std::vector single_table_ratios; - [[maybe_unused]] friend ProbeStats operator+(const ProbeStats& a, const ProbeStats& b) - { + [[maybe_unused]] friend ProbeStats operator+(const ProbeStats& a, const ProbeStats& b) { ProbeStats res = a; - res.all_probes_histogram.resize( - std::max(res.all_probes_histogram.size(), b.all_probes_histogram.size())); + res.all_probes_histogram.resize(std::max(res.all_probes_histogram.size(), b.all_probes_histogram.size())); std::transform(b.all_probes_histogram.begin(), b.all_probes_histogram.end(), res.all_probes_histogram.begin(), res.all_probes_histogram.begin(), std::plus()); - res.single_table_ratios.insert(res.single_table_ratios.end(), - b.single_table_ratios.begin(), - b.single_table_ratios.end()); + res.single_table_ratios.insert( + res.single_table_ratios.end(), b.single_table_ratios.begin(), b.single_table_ratios.end()); return res; } // Average ratio total_probe_length/size over tables. - double AvgRatio() const - { + double AvgRatio() const { return std::accumulate(single_table_ratios.begin(), single_table_ratios.end(), 0.0) / single_table_ratios.size(); } // Maximum ratio total_probe_length/size over tables. - double MaxRatio() const - { - return *std::max_element(single_table_ratios.begin(), single_table_ratios.end()); - } + double MaxRatio() const { return *std::max_element(single_table_ratios.begin(), single_table_ratios.end()); } // Percentile ratio total_probe_length/size over tables. - double PercentileRatio(double Percentile = 0.95) const - { + double PercentileRatio(double Percentile = 0.95) const { auto r = single_table_ratios; auto mid = r.begin() + static_cast(r.size() * Percentile); if (mid != r.end()) { @@ -1028,10 +932,8 @@ struct ProbeStats size_t MaxProbe() const { return all_probes_histogram.size(); } // Fraction of elements with specified probe length. - std::vector ProbeNormalizedHistogram() const - { - double total_elements = - (double)std::accumulate(all_probes_histogram.begin(), all_probes_histogram.end(), 0ull); + std::vector ProbeNormalizedHistogram() const { + double total_elements = (double)std::accumulate(all_probes_histogram.begin(), all_probes_histogram.end(), 0ull); std::vector res; for (size_t p : all_probes_histogram) { res.push_back(p / total_elements); @@ -1039,8 +941,7 @@ struct ProbeStats return res; } - size_t PercentileProbe(double Percentile = 0.99) const - { + size_t PercentileProbe(double Percentile = 0.99) const { size_t idx = 0; for (double p : ProbeNormalizedHistogram()) { if (Percentile > p) { @@ -1053,11 +954,9 @@ struct ProbeStats return idx; } - friend std::ostream& operator<<(std::ostream& out, const ProbeStats& s) - { + friend std::ostream& operator<<(std::ostream& out, const ProbeStats& s) { out << "{AvgRatio:" << s.AvgRatio() << ", MaxRatio:" << s.MaxRatio() - << ", PercentileRatio:" << s.PercentileRatio() << ", MaxProbe:" << s.MaxProbe() - << ", Probes=["; + << ", PercentileRatio:" << s.PercentileRatio() << ", MaxProbe:" << s.MaxProbe() << ", Probes=["; for (double p : s.ProbeNormalizedHistogram()) { out << p << ","; } @@ -1067,17 +966,14 @@ struct ProbeStats } }; -struct ExpectedStats -{ +struct ExpectedStats { double avg_ratio; double max_ratio; std::vector> pecentile_ratios; std::vector> pecentile_probes; - [[maybe_unused]] friend std::ostream& operator<<(std::ostream& out, const ExpectedStats& s) - { - out << "{AvgRatio:" << s.avg_ratio << ", MaxRatio:" << s.max_ratio - << ", PercentileRatios: ["; + [[maybe_unused]] friend std::ostream& operator<<(std::ostream& out, const ExpectedStats& s) { + out << "{AvgRatio:" << s.avg_ratio << ", MaxRatio:" << s.max_ratio << ", PercentileRatios: ["; for (auto el : s.pecentile_ratios) { out << el.first << ":" << el.second << ", "; } @@ -1091,18 +987,15 @@ struct ExpectedStats } }; -void VerifyStats(size_t size, const ExpectedStats& exp, const ProbeStats& stats) -{ +void VerifyStats(size_t size, const ExpectedStats& exp, const ProbeStats& stats) { EXPECT_LT(stats.AvgRatio(), exp.avg_ratio) << size << " " << stats; EXPECT_LT(stats.MaxRatio(), exp.max_ratio) << size << " " << stats; for (auto pr : exp.pecentile_ratios) { - EXPECT_LE(stats.PercentileRatio(pr.first), pr.second) - << size << " " << pr.first << " " << stats; + EXPECT_LE(stats.PercentileRatio(pr.first), pr.second) << size << " " << pr.first << " " << stats; } for (auto pr : exp.pecentile_probes) { - EXPECT_LE(stats.PercentileProbe(pr.first), pr.second) - << size << " " << pr.first << " " << stats; + EXPECT_LE(stats.PercentileProbe(pr.first), pr.second) << size << " " << pr.first << " " << stats; } } @@ -1112,8 +1005,7 @@ using ProbeStatsPerSize = std::map; // 1. Create new table and reserve it to keys.size() * 2 // 2. Insert all keys xored with seed // 3. Collect ProbeStats from final table. -ProbeStats CollectProbeStatsOnKeysXoredWithSeed(const std::vector& keys, size_t num_iters) -{ +ProbeStats CollectProbeStatsOnKeysXoredWithSeed(const std::vector& keys, size_t num_iters) { const size_t reserve_size = keys.size() * 2; ProbeStats stats; @@ -1128,8 +1020,7 @@ ProbeStats CollectProbeStatsOnKeysXoredWithSeed(const std::vector& keys } auto probe_histogram = GetHashtableDebugNumProbesHistogram(t1); - stats.all_probes_histogram.resize( - std::max(stats.all_probes_histogram.size(), probe_histogram.size())); + stats.all_probes_histogram.resize(std::max(stats.all_probes_histogram.size(), probe_histogram.size())); std::transform(probe_histogram.begin(), probe_histogram.end(), stats.all_probes_histogram.begin(), @@ -1151,8 +1042,7 @@ ProbeStats CollectProbeStatsOnKeysXoredWithSeed(const std::vector& keys #pragma GCC diagnostic ignored "-Wswitch" #endif -ExpectedStats XorSeedExpectedStats() -{ +ExpectedStats XorSeedExpectedStats() { constexpr bool kRandomizesInserts = #ifdef NDEBUG false; @@ -1165,33 +1055,25 @@ ExpectedStats XorSeedExpectedStats() if constexpr (priv::Group::kWidth == 8) { if (kRandomizesInserts) { return { - 0.05, - 1.0, - {{ 0.95, 0.5 } }, - { { 0.95, 0 }, { 0.99, 2 }, { 0.999, 4 }, { 0.9999, 10 } } + 0.05, 1.0, { { 0.95, 0.5 } }, + { { 0.95, 0 }, { 0.99, 2 }, { 0.999, 4 }, { 0.9999, 10 } } }; } else { return { - 0.05, - 2.0, - {{ 0.95, 0.1 } }, - { { 0.95, 0 }, { 0.99, 2 }, { 0.999, 4 }, { 0.9999, 10 } } + 0.05, 2.0, { { 0.95, 0.1 } }, + { { 0.95, 0 }, { 0.99, 2 }, { 0.999, 4 }, { 0.9999, 10 } } }; } } else { if (kRandomizesInserts) { return { - 0.1, - 1.0, - {{ 0.95, 0.1 } }, - { { 0.95, 0 }, { 0.99, 1 }, { 0.999, 8 }, { 0.9999, 15 } } + 0.1, 1.0, { { 0.95, 0.1 } }, + { { 0.95, 0 }, { 0.99, 1 }, { 0.999, 8 }, { 0.9999, 15 } } }; } else { return { - 0.05, - 1.0, - {{ 0.95, 0.05 } }, - { { 0.95, 0 }, { 0.99, 1 }, { 0.999, 4 }, { 0.9999, 10 } } + 0.05, 1.0, { { 0.95, 0.05 } }, + { { 0.95, 0 }, { 0.99, 1 }, { 0.999, 4 }, { 0.9999, 10 } } }; } } @@ -1203,8 +1085,7 @@ ExpectedStats XorSeedExpectedStats() #pragma GCC diagnostic pop #endif -TEST(Table, DISABLED_EnsureNonQuadraticTopNXorSeedByProbeSeqLength) -{ +TEST(Table, DISABLED_EnsureNonQuadraticTopNXorSeedByProbeSeqLength) { ProbeStatsPerSize stats; std::vector sizes = { Group::kWidth << 5, Group::kWidth << 10 }; for (size_t size : sizes) { @@ -1221,14 +1102,12 @@ TEST(Table, DISABLED_EnsureNonQuadraticTopNXorSeedByProbeSeqLength) // 1. Create new table // 2. Select 10% of keys and insert 10 elements key * 17 + j * 13 // 3. Collect ProbeStats from final table -ProbeStats CollectProbeStatsOnLinearlyTransformedKeys(const std::vector& keys, - size_t num_iters) -{ +ProbeStats CollectProbeStatsOnLinearlyTransformedKeys(const std::vector& keys, size_t num_iters) { ProbeStats stats; - std::random_device rd; - std::mt19937 rng(rd()); - auto linear_transform = [](size_t x, size_t y) { return x * 17 + y * 13; }; + std::random_device rd; + std::mt19937 rng(rd()); + auto linear_transform = [](size_t x, size_t y) { return x * 17 + y * 13; }; std::uniform_int_distribution dist(0, keys.size() - 1); while (num_iters--) { IntTable t1; @@ -1241,8 +1120,7 @@ ProbeStats CollectProbeStatsOnLinearlyTransformedKeys(const std::vector } auto probe_histogram = GetHashtableDebugNumProbesHistogram(t1); - stats.all_probes_histogram.resize( - std::max(stats.all_probes_histogram.size(), probe_histogram.size())); + stats.all_probes_histogram.resize(std::max(stats.all_probes_histogram.size(), probe_histogram.size())); std::transform(probe_histogram.begin(), probe_histogram.end(), stats.all_probes_histogram.begin(), @@ -1264,8 +1142,7 @@ ProbeStats CollectProbeStatsOnLinearlyTransformedKeys(const std::vector #pragma GCC diagnostic ignored "-Wswitch" #endif -ExpectedStats LinearTransformExpectedStats() -{ +ExpectedStats LinearTransformExpectedStats() { constexpr bool kRandomizesInserts = #ifdef NDEBUG false; @@ -1278,33 +1155,25 @@ ExpectedStats LinearTransformExpectedStats() if constexpr (priv::Group::kWidth == 8) { if (kRandomizesInserts) { return { - 0.1, - 0.5, - {{ 0.95, 0.3 } }, - { { 0.95, 0 }, { 0.99, 1 }, { 0.999, 8 }, { 0.9999, 15 } } + 0.1, 0.5, { { 0.95, 0.3 } }, + { { 0.95, 0 }, { 0.99, 1 }, { 0.999, 8 }, { 0.9999, 15 } } }; } else { return { - 0.15, - 0.5, - {{ 0.95, 0.3 } }, - { { 0.95, 0 }, { 0.99, 3 }, { 0.999, 15 }, { 0.9999, 25 } } + 0.15, 0.5, { { 0.95, 0.3 } }, + { { 0.95, 0 }, { 0.99, 3 }, { 0.999, 15 }, { 0.9999, 25 } } }; } } else { if (kRandomizesInserts) { return { - 0.1, - 0.4, - {{ 0.95, 0.3 } }, - { { 0.95, 0 }, { 0.99, 1 }, { 0.999, 8 }, { 0.9999, 15 } } + 0.1, 0.4, { { 0.95, 0.3 } }, + { { 0.95, 0 }, { 0.99, 1 }, { 0.999, 8 }, { 0.9999, 15 } } }; } else { return { - 0.05, - 0.2, - {{ 0.95, 0.1 } }, - { { 0.95, 0 }, { 0.99, 1 }, { 0.999, 6 }, { 0.9999, 10 } } + 0.05, 0.2, { { 0.95, 0.1 } }, + { { 0.95, 0 }, { 0.99, 1 }, { 0.999, 6 }, { 0.9999, 10 } } }; } } @@ -1316,8 +1185,7 @@ ExpectedStats LinearTransformExpectedStats() #pragma GCC diagnostic pop #endif -TEST(Table, DISABLED_EnsureNonQuadraticTopNLinearTransformByProbeSeqLength) -{ +TEST(Table, DISABLED_EnsureNonQuadraticTopNLinearTransformByProbeSeqLength) { ProbeStatsPerSize stats; std::vector sizes = { Group::kWidth << 5, Group::kWidth << 10 }; for (size_t size : sizes) { @@ -1330,8 +1198,7 @@ TEST(Table, DISABLED_EnsureNonQuadraticTopNLinearTransformByProbeSeqLength) } } -TEST(Table, EraseCollision) -{ +TEST(Table, EraseCollision) { BadTable t; // 1 2 3 @@ -1365,8 +1232,7 @@ TEST(Table, EraseCollision) EXPECT_EQ(0u, t.size()); } -TEST(Table, EraseInsertProbing) -{ +TEST(Table, EraseInsertProbing) { BadTable t(100); // 1 2 3 4 @@ -1388,8 +1254,7 @@ TEST(Table, EraseInsertProbing) EXPECT_THAT(t, UnorderedElementsAre(1, 10, 3, 11, 12)); } -TEST(Table, Clear) -{ +TEST(Table, Clear) { IntTable t; EXPECT_TRUE(t.find(0) == t.end()); t.clear(); @@ -1402,8 +1267,7 @@ TEST(Table, Clear) EXPECT_TRUE(t.find(0) == t.end()); } -TEST(Table, Swap) -{ +TEST(Table, Swap) { IntTable t; EXPECT_TRUE(t.find(0) == t.end()); auto res = t.emplace(0); @@ -1417,8 +1281,7 @@ TEST(Table, Swap) EXPECT_THAT(*u.find(0), 0); } -TEST(Table, Rehash) -{ +TEST(Table, Rehash) { IntTable t; EXPECT_TRUE(t.find(0) == t.end()); t.emplace(0); @@ -1430,8 +1293,7 @@ TEST(Table, Rehash) EXPECT_THAT(*t.find(1), 1); } -TEST(Table, RehashDoesNotRehashWhenNotNecessary) -{ +TEST(Table, RehashDoesNotRehashWhenNotNecessary) { IntTable t; t.emplace(0); t.emplace(1); @@ -1440,15 +1302,13 @@ TEST(Table, RehashDoesNotRehashWhenNotNecessary) EXPECT_EQ(p, &*t.find(0)); } -TEST(Table, RehashZeroDoesNotAllocateOnEmptyTable) -{ +TEST(Table, RehashZeroDoesNotAllocateOnEmptyTable) { IntTable t; t.rehash(0); EXPECT_EQ(0u, t.bucket_count()); } -TEST(Table, RehashZeroDeallocatesEmptyTable) -{ +TEST(Table, RehashZeroDeallocatesEmptyTable) { IntTable t; t.emplace(0); t.clear(); @@ -1457,8 +1317,7 @@ TEST(Table, RehashZeroDeallocatesEmptyTable) EXPECT_EQ(0u, t.bucket_count()); } -TEST(Table, RehashZeroForcesRehash) -{ +TEST(Table, RehashZeroForcesRehash) { IntTable t; t.emplace(0); t.emplace(1); @@ -1467,21 +1326,18 @@ TEST(Table, RehashZeroForcesRehash) EXPECT_NE(p, &*t.find(0)); } -TEST(Table, ConstructFromInitList) -{ +TEST(Table, ConstructFromInitList) { using P = std::pair; - struct Q - { + struct Q { operator P() const { return {}; } }; StringTable t = { - P(), Q(), { }, + P(), Q(), {}, { {}, {} } }; } -TEST(Table, CopyConstruct) -{ +TEST(Table, CopyConstruct) { IntTable t; t.emplace(0); EXPECT_EQ(1u, t.size()); @@ -1502,8 +1358,7 @@ TEST(Table, CopyConstruct) } } -TEST(Table, CopyConstructWithAlloc) -{ +TEST(Table, CopyConstructWithAlloc) { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1u, t.size()); @@ -1513,22 +1368,16 @@ TEST(Table, CopyConstructWithAlloc) } struct ExplicitAllocIntTable - : raw_hash_set, - std::equal_to, - Alloc> -{ + : raw_hash_set, std::equal_to, Alloc> { ExplicitAllocIntTable() {} }; -TEST(Table, AllocWithExplicitCtor) -{ +TEST(Table, AllocWithExplicitCtor) { ExplicitAllocIntTable t; EXPECT_EQ(0u, t.size()); } -TEST(Table, MoveConstruct) -{ +TEST(Table, MoveConstruct) { { StringTable t; t.emplace("a", "b"); @@ -1558,8 +1407,7 @@ TEST(Table, MoveConstruct) } } -TEST(Table, MoveConstructWithAlloc) -{ +TEST(Table, MoveConstructWithAlloc) { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1u, t.size()); @@ -1568,8 +1416,7 @@ TEST(Table, MoveConstructWithAlloc) EXPECT_THAT(*u.find("a"), Pair("a", "b")); } -TEST(Table, CopyAssign) -{ +TEST(Table, CopyAssign) { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1u, t.size()); @@ -1579,8 +1426,7 @@ TEST(Table, CopyAssign) EXPECT_THAT(*u.find("a"), Pair("a", "b")); } -TEST(Table, CopySelfAssign) -{ +TEST(Table, CopySelfAssign) { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1u, t.size()); @@ -1589,8 +1435,7 @@ TEST(Table, CopySelfAssign) EXPECT_THAT(*t.find("a"), Pair("a", "b")); } -TEST(Table, MoveAssign) -{ +TEST(Table, MoveAssign) { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1u, t.size()); @@ -1600,8 +1445,7 @@ TEST(Table, MoveAssign) EXPECT_THAT(*u.find("a"), Pair("a", "b")); } -TEST(Table, Equality) -{ +TEST(Table, Equality) { StringTable t; std::vector> v = { {"a", "b" }, @@ -1612,8 +1456,7 @@ TEST(Table, Equality) EXPECT_EQ(u, t); } -TEST(Table, Equality2) -{ +TEST(Table, Equality2) { StringTable t; std::vector> v1 = { {"a", "b" }, @@ -1629,8 +1472,7 @@ TEST(Table, Equality2) EXPECT_NE(u, t); } -TEST(Table, Equality3) -{ +TEST(Table, Equality3) { StringTable t; std::vector> v1 = { {"b", "b" }, @@ -1646,8 +1488,7 @@ TEST(Table, Equality3) EXPECT_NE(u, t); } -TEST(Table, NumDeletedRegression) -{ +TEST(Table, NumDeletedRegression) { IntTable t; t.emplace(0); t.erase(t.find(0)); @@ -1656,8 +1497,7 @@ TEST(Table, NumDeletedRegression) t.clear(); } -TEST(Table, FindFullDeletedRegression) -{ +TEST(Table, FindFullDeletedRegression) { IntTable t; for (int i = 0; i < 1000; ++i) { t.emplace(i); @@ -1666,8 +1506,7 @@ TEST(Table, FindFullDeletedRegression) EXPECT_EQ(0u, t.size()); } -TEST(Table, ReplacingDeletedSlotDoesNotRehash) -{ +TEST(Table, ReplacingDeletedSlotDoesNotRehash) { size_t n; { // Compute n such that n is the maximum number of elements before rehash. @@ -1689,16 +1528,14 @@ TEST(Table, ReplacingDeletedSlotDoesNotRehash) EXPECT_EQ(c, t.bucket_count()) << "rehashing threshold = " << n; } -TEST(Table, NoThrowMoveConstruct) -{ +TEST(Table, NoThrowMoveConstruct) { ASSERT_TRUE(std::is_nothrow_copy_constructible>::value); ASSERT_TRUE(std::is_nothrow_copy_constructible>::value); ASSERT_TRUE(std::is_nothrow_copy_constructible>::value); EXPECT_TRUE(std::is_nothrow_move_constructible::value); } -TEST(Table, NoThrowMoveAssign) -{ +TEST(Table, NoThrowMoveAssign) { ASSERT_TRUE(std::is_nothrow_move_assignable>::value); ASSERT_TRUE(std::is_nothrow_move_assignable>::value); ASSERT_TRUE(std::is_nothrow_move_assignable>::value); @@ -1706,53 +1543,43 @@ TEST(Table, NoThrowMoveAssign) EXPECT_TRUE(std::is_nothrow_move_assignable::value); } -TEST(Table, NoThrowSwappable) -{ +TEST(Table, NoThrowSwappable) { ASSERT_TRUE(std::is_nothrow_swappable_v>); ASSERT_TRUE(std::is_nothrow_swappable_v>); ASSERT_TRUE(std::is_nothrow_swappable_v>); EXPECT_TRUE(std::is_nothrow_swappable_v); } -TEST(Table, HeterogeneousLookup) -{ - struct Hash - { +TEST(Table, HeterogeneousLookup) { + struct Hash { size_t operator()(int64_t i) const { return i; } - size_t operator()(double i) const - { + size_t operator()(double i) const { ADD_FAILURE(); return (size_t)i; } }; - struct Eq - { + struct Eq { bool operator()(int64_t a, int64_t b) const { return a == b; } - bool operator()(double a, int64_t b) const - { + bool operator()(double a, int64_t b) const { ADD_FAILURE(); return a == b; } - bool operator()(int64_t a, double b) const - { + bool operator()(int64_t a, double b) const { ADD_FAILURE(); return a == b; } - bool operator()(double a, double b) const - { + bool operator()(double a, double b) const { ADD_FAILURE(); return a == b; } }; - struct THash - { + struct THash { using is_transparent = void; size_t operator()(int64_t i) const { return i; } size_t operator()(double i) const { return (size_t)i; } }; - struct TEq - { + struct TEq { using is_transparent = void; bool operator()(int64_t a, int64_t b) const { return a == b; } bool operator()(double a, int64_t b) const { return a == b; } @@ -1785,21 +1612,14 @@ template using CallCount = decltype(std::declval().count(17)); template class C, class Table, class = void> -struct VerifyResultOf : std::false_type -{ -}; +struct VerifyResultOf : std::false_type {}; template class C, class Table> -struct VerifyResultOf>> : std::true_type -{ -}; +struct VerifyResultOf>> : std::true_type {}; -TEST(Table, HeterogeneousLookupOverloads) -{ - using NonTransparentTable = raw_hash_set, - std::equal_to, - std::allocator>; +TEST(Table, HeterogeneousLookupOverloads) { + using NonTransparentTable = + raw_hash_set, std::equal_to, std::allocator>; EXPECT_FALSE((VerifyResultOf())); EXPECT_FALSE((VerifyResultOf())); @@ -1820,34 +1640,29 @@ TEST(Table, HeterogeneousLookupOverloads) } // TODO(alkis): Expand iterator tests. -TEST(Iterator, IsDefaultConstructible) -{ +TEST(Iterator, IsDefaultConstructible) { StringTable::iterator i; EXPECT_TRUE(i == StringTable::iterator()); } -TEST(ConstIterator, IsDefaultConstructible) -{ +TEST(ConstIterator, IsDefaultConstructible) { StringTable::const_iterator i; EXPECT_TRUE(i == StringTable::const_iterator()); } -TEST(Iterator, ConvertsToConstIterator) -{ +TEST(Iterator, ConvertsToConstIterator) { StringTable::iterator i; EXPECT_TRUE(i == StringTable::const_iterator()); } -TEST(Iterator, Iterates) -{ +TEST(Iterator, Iterates) { IntTable t; for (size_t i = 3; i != 6; ++i) EXPECT_TRUE(t.emplace(i).second); EXPECT_THAT(t, UnorderedElementsAre(3, 4, 5)); } -TEST(Table, Merge) -{ +TEST(Table, Merge) { StringTable t1, t2; t1.emplace("0", "-0"); t1.emplace("1", "-1"); @@ -1862,8 +1677,7 @@ TEST(Table, Merge) EXPECT_THAT(t2, UnorderedElementsAre(Pair("0", "~0"))); } -TEST(Nodes, EmptyNodeType) -{ +TEST(Nodes, EmptyNodeType) { using node_type = StringTable::node_type; node_type n; EXPECT_FALSE(n); @@ -1872,15 +1686,14 @@ TEST(Nodes, EmptyNodeType) EXPECT_TRUE((std::is_same::value)); } -TEST(Nodes, ExtractInsert) -{ +TEST(Nodes, ExtractInsert) { constexpr char k0[] = "Very long std::string zero."; constexpr char k1[] = "Very long std::string one."; constexpr char k2[] = "Very long std::string two."; StringTable t = { - {k0, ""}, - { k1, ""}, - { k2, ""} + {k0, ""}, + { k1, ""}, + { k2, ""} }; EXPECT_THAT(t, UnorderedElementsAre(Pair(k0, ""), Pair(k1, ""), Pair(k2, ""))); @@ -1920,8 +1733,7 @@ TEST(Nodes, ExtractInsert) EXPECT_FALSE(node); } -IntTable MakeSimpleTable(size_t size) -{ +IntTable MakeSimpleTable(size_t size) { IntTable t; while (t.size() < size) t.insert(t.size()); @@ -1937,8 +1749,7 @@ std::vector OrderOfIteration(const IntTable& t) { return { t.begin(), t.end // We also need to keep the old tables around to avoid getting the same memory // blocks over and over. // not randomizing in phmap -TEST(Table, IterationOrderChangesByInstance) -{ +TEST(Table, IterationOrderChangesByInstance) { for (size_t size : { 2, 6, 12, 20 }) { const auto reference_table = MakeSimpleTable(size); const auto reference = OrderOfIteration(reference_table); @@ -1956,8 +1767,7 @@ TEST(Table, IterationOrderChangesByInstance) } // not randomizing in phmap -TEST(Table, IterationOrderChangesOnRehash) -{ +TEST(Table, IterationOrderChangesOnRehash) { std::vector garbage; for (int i = 0; i < 5000; ++i) { auto t = MakeSimpleTable(20); @@ -1976,8 +1786,7 @@ TEST(Table, IterationOrderChangesOnRehash) // Verify that pointers are invalidated as soon as a second element is inserted. // This prevents dependency on pointer stability on small tables. -TEST(Table, UnstablePointers) -{ +TEST(Table, UnstablePointers) { IntTable table; const auto addr = [&](int i) { return reinterpret_cast(&*table.find(i)); }; @@ -1992,8 +1801,7 @@ TEST(Table, UnstablePointers) } // Confirm that we assert if we try to erase() end(). -TEST(TableDeathTest, EraseOfEndAsserts) -{ +TEST(TableDeathTest, EraseOfEndAsserts) { // Use an assert with side-effects to figure out if they are actually enabled. bool assert_enabled = false; assert([&]() { @@ -2010,8 +1818,7 @@ TEST(TableDeathTest, EraseOfEndAsserts) } #ifdef ADDRESS_SANITIZER -TEST(Sanitizer, PoisoningUnused) -{ +TEST(Sanitizer, PoisoningUnused) { IntTable t; t.reserve(5); // Insert something to force an allocation. @@ -2026,8 +1833,7 @@ TEST(Sanitizer, PoisoningUnused) } } -TEST(Sanitizer, PoisoningOnErase) -{ +TEST(Sanitizer, PoisoningOnErase) { IntTable t; int64_t& v = *t.insert(0).first; diff --git a/tests/phmap/test_instance_tracker.hpp b/tests/phmap/test_instance_tracker.hpp index 63d47ed..1c6df62 100644 --- a/tests/phmap/test_instance_tracker.hpp +++ b/tests/phmap/test_instance_tracker.hpp @@ -26,19 +26,16 @@ namespace test_internal { // have occurred on the type. This is used as a base class for the copyable, // copyable+movable, and movable types below that are used in actual tests. Use // InstanceTracker in tests to track the number of instances. -class BaseCountedInstance -{ +class BaseCountedInstance { public: explicit BaseCountedInstance(int x) - : value_(x) - { + : value_(x) { ++num_instances_; ++num_live_instances_; } BaseCountedInstance(const BaseCountedInstance& x) : value_(x.value_) - , is_live_(x.is_live_) - { + , is_live_(x.is_live_) { ++num_instances_; if (is_live_) ++num_live_instances_; @@ -46,21 +43,18 @@ class BaseCountedInstance } BaseCountedInstance(BaseCountedInstance&& x) : value_(x.value_) - , is_live_(x.is_live_) - { + , is_live_(x.is_live_) { x.is_live_ = false; ++num_instances_; ++num_moves_; } - ~BaseCountedInstance() - { + ~BaseCountedInstance() { --num_instances_; if (is_live_) --num_live_instances_; } - BaseCountedInstance& operator=(const BaseCountedInstance& x) - { + BaseCountedInstance& operator=(const BaseCountedInstance& x) { value_ = x.value_; if (is_live_) --num_live_instances_; @@ -70,8 +64,7 @@ class BaseCountedInstance ++num_copies_; return *this; } - BaseCountedInstance& operator=(BaseCountedInstance&& x) - { + BaseCountedInstance& operator=(BaseCountedInstance&& x) { value_ = x.value_; if (is_live_) --num_live_instances_; @@ -81,58 +74,49 @@ class BaseCountedInstance return *this; } - bool operator==(const BaseCountedInstance& x) const - { + bool operator==(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ == x.value_; } - bool operator!=(const BaseCountedInstance& x) const - { + bool operator!=(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ != x.value_; } - bool operator<(const BaseCountedInstance& x) const - { + bool operator<(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ < x.value_; } - bool operator>(const BaseCountedInstance& x) const - { + bool operator>(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ > x.value_; } - bool operator<=(const BaseCountedInstance& x) const - { + bool operator<=(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ <= x.value_; } - bool operator>=(const BaseCountedInstance& x) const - { + bool operator>=(const BaseCountedInstance& x) const { ++num_comparisons_; return value_ >= x.value_; } - int value() const - { + int value() const { if (!is_live_) std::abort(); return value_; } - friend std::ostream& operator<<(std::ostream& o, const BaseCountedInstance& v) - { + friend std::ostream& operator<<(std::ostream& o, const BaseCountedInstance& v) { return o << "[value:" << v.value() << "]"; } // Implementation of efficient swap() that counts swaps. - static void SwapImpl(BaseCountedInstance& lhs, // NOLINT(runtime/references) - BaseCountedInstance& rhs) - { // NOLINT(runtime/references) + static void SwapImpl(BaseCountedInstance& lhs, // NOLINT(runtime/references) + BaseCountedInstance& rhs) { // NOLINT(runtime/references) using std::swap; swap(lhs.value_, rhs.value_); swap(lhs.is_live_, rhs.is_live_); @@ -169,17 +153,14 @@ class BaseCountedInstance // Helper to track the BaseCountedInstance instance counters. Expects that the // number of instances and live_instances are the same when it is constructed // and when it is destructed. -class InstanceTracker -{ +class InstanceTracker { public: InstanceTracker() : start_instances_(BaseCountedInstance::num_instances_) - , start_live_instances_(BaseCountedInstance::num_live_instances_) - { + , start_live_instances_(BaseCountedInstance::num_live_instances_) { ResetCopiesMovesSwaps(); } - ~InstanceTracker() - { + ~InstanceTracker() { if (instances() != 0) std::abort(); if (live_instances() != 0) @@ -193,10 +174,7 @@ class InstanceTracker // Returns the number of live BaseCountedInstance instances compared to when // the InstanceTracker was constructed - int live_instances() const - { - return BaseCountedInstance::num_live_instances_ - start_live_instances_; - } + int live_instances() const { return BaseCountedInstance::num_live_instances_ - start_live_instances_; } // Returns the number of moves on BaseCountedInstance objects since // construction or since the last call to ResetCopiesMovesSwaps(). @@ -218,8 +196,7 @@ class InstanceTracker // current values, so that subsequent Get*() calls for moves, copies, // comparisons, and swaps will compare to the situation at the point of this // call. - void ResetCopiesMovesSwaps() - { + void ResetCopiesMovesSwaps() { start_moves_ = BaseCountedInstance::num_moves_; start_copies_ = BaseCountedInstance::num_copies_; start_swaps_ = BaseCountedInstance::num_swaps_; @@ -236,39 +213,29 @@ class InstanceTracker }; // Copyable, not movable. -class CopyableOnlyInstance : public BaseCountedInstance -{ +class CopyableOnlyInstance : public BaseCountedInstance { public: explicit CopyableOnlyInstance(int x) - : BaseCountedInstance(x) - { - } + : BaseCountedInstance(x) {} CopyableOnlyInstance(const CopyableOnlyInstance& rhs) = default; CopyableOnlyInstance& operator=(const CopyableOnlyInstance& rhs) = default; - friend void swap(CopyableOnlyInstance& lhs, CopyableOnlyInstance& rhs) - { - BaseCountedInstance::SwapImpl(lhs, rhs); - } + friend void swap(CopyableOnlyInstance& lhs, CopyableOnlyInstance& rhs) { BaseCountedInstance::SwapImpl(lhs, rhs); } static bool supports_move() { return false; } }; // Copyable and movable. -class CopyableMovableInstance : public BaseCountedInstance -{ +class CopyableMovableInstance : public BaseCountedInstance { public: explicit CopyableMovableInstance(int x) - : BaseCountedInstance(x) - { - } + : BaseCountedInstance(x) {} CopyableMovableInstance(const CopyableMovableInstance& rhs) = default; CopyableMovableInstance(CopyableMovableInstance&& rhs) = default; CopyableMovableInstance& operator=(const CopyableMovableInstance& rhs) = default; CopyableMovableInstance& operator=(CopyableMovableInstance&& rhs) = default; - friend void swap(CopyableMovableInstance& lhs, CopyableMovableInstance& rhs) - { + friend void swap(CopyableMovableInstance& lhs, CopyableMovableInstance& rhs) { BaseCountedInstance::SwapImpl(lhs, rhs); } @@ -276,20 +243,14 @@ class CopyableMovableInstance : public BaseCountedInstance }; // Only movable, not default-constructible. -class MovableOnlyInstance : public BaseCountedInstance -{ +class MovableOnlyInstance : public BaseCountedInstance { public: explicit MovableOnlyInstance(int x) - : BaseCountedInstance(x) - { - } + : BaseCountedInstance(x) {} MovableOnlyInstance(MovableOnlyInstance&& other) = default; MovableOnlyInstance& operator=(MovableOnlyInstance&& other) = default; - friend void swap(MovableOnlyInstance& lhs, MovableOnlyInstance& rhs) - { - BaseCountedInstance::SwapImpl(lhs, rhs); - } + friend void swap(MovableOnlyInstance& lhs, MovableOnlyInstance& rhs) { BaseCountedInstance::SwapImpl(lhs, rhs); } static bool supports_move() { return true; } }; diff --git a/tests/phmap/tracked.hpp b/tests/phmap/tracked.hpp index f80a5d4..569ba87 100644 --- a/tests/phmap/tracked.hpp +++ b/tests/phmap/tracked.hpp @@ -24,38 +24,31 @@ namespace priv { // A class that tracks its copies and moves so that it can be queried in tests. template -class Tracked -{ +class Tracked { public: Tracked() {} // NOLINTNEXTLINE(runtime/explicit) Tracked(const T& val) - : val_(val) - { - } + : val_(val) {} Tracked(const Tracked& that) : val_(that.val_) , num_moves_(that.num_moves_) - , num_copies_(that.num_copies_) - { + , num_copies_(that.num_copies_) { ++(*num_copies_); } Tracked(Tracked&& that) : val_(std::move(that.val_)) , num_moves_(std::move(that.num_moves_)) - , num_copies_(std::move(that.num_copies_)) - { + , num_copies_(std::move(that.num_copies_)) { ++(*num_moves_); } - Tracked& operator=(const Tracked& that) - { + Tracked& operator=(const Tracked& that) { val_ = that.val_; num_moves_ = that.num_moves_; num_copies_ = that.num_copies_; ++(*num_copies_); } - Tracked& operator=(Tracked&& that) - { + Tracked& operator=(Tracked&& that) { val_ = std::move(that.val_); num_moves_ = std::move(that.num_moves_); num_copies_ = std::move(that.num_copies_); diff --git a/tests/phmap/unordered_map_constructor_test.hpp b/tests/phmap/unordered_map_constructor_test.hpp index a6507c9..3fbd22e 100644 --- a/tests/phmap/unordered_map_constructor_test.hpp +++ b/tests/phmap/unordered_map_constructor_test.hpp @@ -36,29 +36,24 @@ namespace gtl { namespace priv { template -class ConstructorTest : public ::testing::Test -{ -}; +class ConstructorTest : public ::testing::Test {}; TYPED_TEST_SUITE_P(ConstructorTest); -TYPED_TEST_P(ConstructorTest, NoArgs) -{ +TYPED_TEST_P(ConstructorTest, NoArgs) { TypeParam m; EXPECT_TRUE(m.empty()); EXPECT_THAT(m, ::testing::UnorderedElementsAre()); } -TYPED_TEST_P(ConstructorTest, BucketCount) -{ +TYPED_TEST_P(ConstructorTest, BucketCount) { TypeParam m(123); EXPECT_TRUE(m.empty()); EXPECT_THAT(m, ::testing::UnorderedElementsAre()); EXPECT_GE(m.bucket_count(), 123); } -TYPED_TEST_P(ConstructorTest, BucketCountHash) -{ +TYPED_TEST_P(ConstructorTest, BucketCountHash) { using H = typename TypeParam::hasher; H hasher; TypeParam m(123, hasher); @@ -68,8 +63,7 @@ TYPED_TEST_P(ConstructorTest, BucketCountHash) EXPECT_GE(m.bucket_count(), 123); } -TYPED_TEST_P(ConstructorTest, BucketCountHashEqual) -{ +TYPED_TEST_P(ConstructorTest, BucketCountHashEqual) { using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; H hasher; @@ -82,8 +76,7 @@ TYPED_TEST_P(ConstructorTest, BucketCountHashEqual) EXPECT_GE(m.bucket_count(), 123); } -TYPED_TEST_P(ConstructorTest, BucketCountHashEqualAlloc) -{ +TYPED_TEST_P(ConstructorTest, BucketCountHashEqualAlloc) { using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; using A = typename TypeParam::allocator_type; @@ -100,29 +93,21 @@ TYPED_TEST_P(ConstructorTest, BucketCountHashEqualAlloc) } template -struct is_std_unordered_map : std::false_type -{ -}; +struct is_std_unordered_map : std::false_type {}; template -struct is_std_unordered_map> : std::true_type -{ -}; +struct is_std_unordered_map> : std::true_type {}; using has_cxx14_std_apis = std::true_type; template -using expect_cxx14_apis = - std::disjunction>, has_cxx14_std_apis>; +using expect_cxx14_apis = std::disjunction>, has_cxx14_std_apis>; template -void BucketCountAllocTest(std::false_type) -{ -} +void BucketCountAllocTest(std::false_type) {} template -void BucketCountAllocTest(std::true_type) -{ +void BucketCountAllocTest(std::true_type) { using A = typename TypeParam::allocator_type; A alloc(0); TypeParam m(123, alloc); @@ -132,19 +117,13 @@ void BucketCountAllocTest(std::true_type) EXPECT_GE(m.bucket_count(), 123); } -TYPED_TEST_P(ConstructorTest, BucketCountAlloc) -{ - BucketCountAllocTest(expect_cxx14_apis()); -} +TYPED_TEST_P(ConstructorTest, BucketCountAlloc) { BucketCountAllocTest(expect_cxx14_apis()); } template -void BucketCountHashAllocTest(std::false_type) -{ -} +void BucketCountHashAllocTest(std::false_type) {} template -void BucketCountHashAllocTest(std::true_type) -{ +void BucketCountHashAllocTest(std::true_type) { using H = typename TypeParam::hasher; using A = typename TypeParam::allocator_type; H hasher; @@ -157,8 +136,7 @@ void BucketCountHashAllocTest(std::true_type) EXPECT_GE(m.bucket_count(), 123); } -TYPED_TEST_P(ConstructorTest, BucketCountHashAlloc) -{ +TYPED_TEST_P(ConstructorTest, BucketCountHashAlloc) { BucketCountHashAllocTest(expect_cxx14_apis()); } @@ -169,17 +147,13 @@ using has_alloc_std_constructors = std::false_type; #endif template -using expect_alloc_constructors = - std::disjunction>, has_alloc_std_constructors>; +using expect_alloc_constructors = std::disjunction>, has_alloc_std_constructors>; template -void AllocTest(std::false_type) -{ -} +void AllocTest(std::false_type) {} template -void AllocTest(std::true_type) -{ +void AllocTest(std::true_type) { using A = typename TypeParam::allocator_type; A alloc(0); TypeParam m(alloc); @@ -188,13 +162,9 @@ void AllocTest(std::true_type) EXPECT_THAT(m, ::testing::UnorderedElementsAre()); } -TYPED_TEST_P(ConstructorTest, Alloc) -{ - AllocTest(expect_alloc_constructors()); -} +TYPED_TEST_P(ConstructorTest, Alloc) { AllocTest(expect_alloc_constructors()); } -TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashEqualAlloc) -{ +TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashEqualAlloc) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -213,13 +183,10 @@ TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashEqualAlloc) } template -void InputIteratorBucketAllocTest(std::false_type) -{ -} +void InputIteratorBucketAllocTest(std::false_type) {} template -void InputIteratorBucketAllocTest(std::true_type) -{ +void InputIteratorBucketAllocTest(std::true_type) { using T = hash_internal::GeneratedType; using A = typename TypeParam::allocator_type; A alloc(0); @@ -231,19 +198,15 @@ void InputIteratorBucketAllocTest(std::true_type) EXPECT_GE(m.bucket_count(), 123); } -TYPED_TEST_P(ConstructorTest, InputIteratorBucketAlloc) -{ +TYPED_TEST_P(ConstructorTest, InputIteratorBucketAlloc) { InputIteratorBucketAllocTest(expect_cxx14_apis()); } template -void InputIteratorBucketHashAllocTest(std::false_type) -{ -} +void InputIteratorBucketHashAllocTest(std::false_type) {} template -void InputIteratorBucketHashAllocTest(std::true_type) -{ +void InputIteratorBucketHashAllocTest(std::true_type) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using A = typename TypeParam::allocator_type; @@ -258,13 +221,11 @@ void InputIteratorBucketHashAllocTest(std::true_type) EXPECT_GE(m.bucket_count(), 123); } -TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashAlloc) -{ +TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashAlloc) { InputIteratorBucketHashAllocTest(expect_cxx14_apis()); } -TYPED_TEST_P(ConstructorTest, CopyConstructor) -{ +TYPED_TEST_P(ConstructorTest, CopyConstructor) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -283,13 +244,10 @@ TYPED_TEST_P(ConstructorTest, CopyConstructor) } template -void CopyConstructorAllocTest(std::false_type) -{ -} +void CopyConstructorAllocTest(std::false_type) {} template -void CopyConstructorAllocTest(std::true_type) -{ +void CopyConstructorAllocTest(std::true_type) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -307,15 +265,13 @@ void CopyConstructorAllocTest(std::true_type) EXPECT_EQ(m, n); } -TYPED_TEST_P(ConstructorTest, CopyConstructorAlloc) -{ +TYPED_TEST_P(ConstructorTest, CopyConstructorAlloc) { CopyConstructorAllocTest(expect_alloc_constructors()); } // TODO(alkis): Test non-propagating allocators on copy constructors. -TYPED_TEST_P(ConstructorTest, MoveConstructor) -{ +TYPED_TEST_P(ConstructorTest, MoveConstructor) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -335,13 +291,10 @@ TYPED_TEST_P(ConstructorTest, MoveConstructor) } template -void MoveConstructorAllocTest(std::false_type) -{ -} +void MoveConstructorAllocTest(std::false_type) {} template -void MoveConstructorAllocTest(std::true_type) -{ +void MoveConstructorAllocTest(std::true_type) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -360,15 +313,13 @@ void MoveConstructorAllocTest(std::true_type) EXPECT_EQ(m, n); } -TYPED_TEST_P(ConstructorTest, MoveConstructorAlloc) -{ +TYPED_TEST_P(ConstructorTest, MoveConstructorAlloc) { MoveConstructorAllocTest(expect_alloc_constructors()); } // TODO(alkis): Test non-propagating allocators on move constructors. -TYPED_TEST_P(ConstructorTest, InitializerListBucketHashEqualAlloc) -{ +TYPED_TEST_P(ConstructorTest, InitializerListBucketHashEqualAlloc) { using T = hash_internal::GeneratedType; hash_internal::Generator gen; std::initializer_list values = { gen(), gen(), gen(), gen(), gen() }; @@ -387,13 +338,10 @@ TYPED_TEST_P(ConstructorTest, InitializerListBucketHashEqualAlloc) } template -void InitializerListBucketAllocTest(std::false_type) -{ -} +void InitializerListBucketAllocTest(std::false_type) {} template -void InitializerListBucketAllocTest(std::true_type) -{ +void InitializerListBucketAllocTest(std::true_type) { using T = hash_internal::GeneratedType; using A = typename TypeParam::allocator_type; hash_internal::Generator gen; @@ -405,19 +353,15 @@ void InitializerListBucketAllocTest(std::true_type) EXPECT_GE(m.bucket_count(), 123); } -TYPED_TEST_P(ConstructorTest, InitializerListBucketAlloc) -{ +TYPED_TEST_P(ConstructorTest, InitializerListBucketAlloc) { InitializerListBucketAllocTest(expect_cxx14_apis()); } template -void InitializerListBucketHashAllocTest(std::false_type) -{ -} +void InitializerListBucketHashAllocTest(std::false_type) {} template -void InitializerListBucketHashAllocTest(std::true_type) -{ +void InitializerListBucketHashAllocTest(std::true_type) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using A = typename TypeParam::allocator_type; @@ -432,13 +376,11 @@ void InitializerListBucketHashAllocTest(std::true_type) EXPECT_GE(m.bucket_count(), 123); } -TYPED_TEST_P(ConstructorTest, InitializerListBucketHashAlloc) -{ +TYPED_TEST_P(ConstructorTest, InitializerListBucketHashAlloc) { InitializerListBucketHashAllocTest(expect_cxx14_apis()); } -TYPED_TEST_P(ConstructorTest, Assignment) -{ +TYPED_TEST_P(ConstructorTest, Assignment) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -458,8 +400,7 @@ TYPED_TEST_P(ConstructorTest, Assignment) // TODO(alkis): Test [non-]propagating allocators on move/copy assignments // (it depends on traits). -TYPED_TEST_P(ConstructorTest, MoveAssignment) -{ +TYPED_TEST_P(ConstructorTest, MoveAssignment) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -477,8 +418,7 @@ TYPED_TEST_P(ConstructorTest, MoveAssignment) EXPECT_EQ(m, n); } -TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerList) -{ +TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerList) { using T = hash_internal::GeneratedType; hash_internal::Generator gen; std::initializer_list values = { gen(), gen(), gen(), gen(), gen() }; @@ -487,8 +427,7 @@ TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerList) EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values)); } -TYPED_TEST_P(ConstructorTest, AssignmentOverwritesExisting) -{ +TYPED_TEST_P(ConstructorTest, AssignmentOverwritesExisting) { using T = hash_internal::GeneratedType; hash_internal::Generator gen; TypeParam m({ gen(), gen(), gen() }); @@ -497,8 +436,7 @@ TYPED_TEST_P(ConstructorTest, AssignmentOverwritesExisting) EXPECT_EQ(m, n); } -TYPED_TEST_P(ConstructorTest, MoveAssignmentOverwritesExisting) -{ +TYPED_TEST_P(ConstructorTest, MoveAssignmentOverwritesExisting) { using T = hash_internal::GeneratedType; hash_internal::Generator gen; TypeParam m({ gen(), gen(), gen() }); @@ -508,8 +446,7 @@ TYPED_TEST_P(ConstructorTest, MoveAssignmentOverwritesExisting) EXPECT_EQ(m, n); } -TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerListOverwritesExisting) -{ +TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerListOverwritesExisting) { using T = hash_internal::GeneratedType; hash_internal::Generator gen; std::initializer_list values = { gen(), gen(), gen(), gen(), gen() }; @@ -518,8 +455,7 @@ TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerListOverwritesExisting) EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values)); } -TYPED_TEST_P(ConstructorTest, AssignmentOnSelf) -{ +TYPED_TEST_P(ConstructorTest, AssignmentOnSelf) { using T = hash_internal::GeneratedType; hash_internal::Generator gen; std::initializer_list values = { gen(), gen(), gen(), gen(), gen() }; diff --git a/tests/phmap/unordered_map_lookup_test.hpp b/tests/phmap/unordered_map_lookup_test.hpp index 43432c5..1d59833 100644 --- a/tests/phmap/unordered_map_lookup_test.hpp +++ b/tests/phmap/unordered_map_lookup_test.hpp @@ -32,14 +32,11 @@ namespace gtl { namespace priv { template -class LookupTest : public ::testing::Test -{ -}; +class LookupTest : public ::testing::Test {}; TYPED_TEST_SUITE_P(LookupTest); -TYPED_TEST_P(LookupTest, At) -{ +TYPED_TEST_P(LookupTest, At) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -50,8 +47,7 @@ TYPED_TEST_P(LookupTest, At) } } -TYPED_TEST_P(LookupTest, OperatorBracket) -{ +TYPED_TEST_P(LookupTest, OperatorBracket) { using T = hash_internal::GeneratedType; using V = typename TypeParam::mapped_type; std::vector values; @@ -66,8 +62,7 @@ TYPED_TEST_P(LookupTest, OperatorBracket) EXPECT_EQ(p.second, m[p.first]) << ::testing::PrintToString(p.first); } -TYPED_TEST_P(LookupTest, Count) -{ +TYPED_TEST_P(LookupTest, Count) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -79,8 +74,7 @@ TYPED_TEST_P(LookupTest, Count) EXPECT_EQ(1, m.count(p.first)) << ::testing::PrintToString(p.first); } -TYPED_TEST_P(LookupTest, Find) -{ +TYPED_TEST_P(LookupTest, Find) { using std::get; using T = hash_internal::GeneratedType; std::vector values; @@ -96,8 +90,7 @@ TYPED_TEST_P(LookupTest, Find) } } -TYPED_TEST_P(LookupTest, EqualRange) -{ +TYPED_TEST_P(LookupTest, EqualRange) { using std::get; using T = hash_internal::GeneratedType; std::vector values; diff --git a/tests/phmap/unordered_map_members_test.hpp b/tests/phmap/unordered_map_members_test.hpp index 20fddb8..59b3974 100644 --- a/tests/phmap/unordered_map_members_test.hpp +++ b/tests/phmap/unordered_map_members_test.hpp @@ -34,22 +34,16 @@ namespace gtl { namespace priv { template -class MembersTest : public ::testing::Test -{ -}; +class MembersTest : public ::testing::Test {}; TYPED_TEST_SUITE_P(MembersTest); template -void UseType() -{ -} +void UseType() {} -TYPED_TEST_P(MembersTest, Typedefs) -{ - EXPECT_TRUE(( - std::is_same, - typename TypeParam::value_type>())); +TYPED_TEST_P(MembersTest, Typedefs) { + EXPECT_TRUE((std::is_same, + typename TypeParam::value_type>())); EXPECT_TRUE((std::conjunction>, std::is_integral>())); EXPECT_TRUE((std::conjunction, @@ -61,23 +55,18 @@ TYPED_TEST_P(MembersTest, Typedefs) std::declval(), std::declval())), bool>())); - EXPECT_TRUE((std::is_same())); + EXPECT_TRUE((std::is_same())); EXPECT_TRUE((std::is_same())); - EXPECT_TRUE((std::is_same())); - EXPECT_TRUE( - (std::is_same::pointer, - typename TypeParam::pointer>())); - EXPECT_TRUE((std::is_same< - typename std::allocator_traits::const_pointer, - typename TypeParam::const_pointer>())); + EXPECT_TRUE((std::is_same())); + EXPECT_TRUE((std::is_same::pointer, + typename TypeParam::pointer>())); + EXPECT_TRUE((std::is_same::const_pointer, + typename TypeParam::const_pointer>())); } TYPED_TEST_P(MembersTest, SimpleFunctions) { EXPECT_GT(TypeParam().max_size(), 0); } -TYPED_TEST_P(MembersTest, BeginEnd) -{ +TYPED_TEST_P(MembersTest, BeginEnd) { TypeParam t = { typename TypeParam::value_type{} }; EXPECT_EQ(t.begin(), t.cbegin()); EXPECT_EQ(t.end(), t.cend()); diff --git a/tests/phmap/unordered_map_modifiers_test.hpp b/tests/phmap/unordered_map_modifiers_test.hpp index 390abc5..2ca1e86 100644 --- a/tests/phmap/unordered_map_modifiers_test.hpp +++ b/tests/phmap/unordered_map_modifiers_test.hpp @@ -32,14 +32,11 @@ namespace gtl { namespace priv { template -class ModifiersTest : public ::testing::Test -{ -}; +class ModifiersTest : public ::testing::Test {}; TYPED_TEST_SUITE_P(ModifiersTest); -TYPED_TEST_P(ModifiersTest, Clear) -{ +TYPED_TEST_P(ModifiersTest, Clear) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -50,8 +47,7 @@ TYPED_TEST_P(ModifiersTest, Clear) EXPECT_TRUE(m.empty()); } -TYPED_TEST_P(ModifiersTest, Insert) -{ +TYPED_TEST_P(ModifiersTest, Insert) { using T = hash_internal::GeneratedType; using V = typename TypeParam::mapped_type; T val = hash_internal::Generator()(); @@ -65,8 +61,7 @@ TYPED_TEST_P(ModifiersTest, Insert) EXPECT_EQ(val, *p.first); } -TYPED_TEST_P(ModifiersTest, InsertHint) -{ +TYPED_TEST_P(ModifiersTest, InsertHint) { using T = hash_internal::GeneratedType; using V = typename TypeParam::mapped_type; T val = hash_internal::Generator()(); @@ -80,8 +75,7 @@ TYPED_TEST_P(ModifiersTest, InsertHint) EXPECT_EQ(val, *it); } -TYPED_TEST_P(ModifiersTest, InsertRange) -{ +TYPED_TEST_P(ModifiersTest, InsertRange) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -90,8 +84,7 @@ TYPED_TEST_P(ModifiersTest, InsertRange) ASSERT_THAT(items(m), ::testing::UnorderedElementsAreArray(values)); } -TYPED_TEST_P(ModifiersTest, InsertOrAssign) -{ +TYPED_TEST_P(ModifiersTest, InsertOrAssign) { using std::get; using K = typename TypeParam::key_type; using V = typename TypeParam::mapped_type; @@ -109,8 +102,7 @@ TYPED_TEST_P(ModifiersTest, InsertOrAssign) EXPECT_EQ(val2, get<1>(*p.first)); } -TYPED_TEST_P(ModifiersTest, InsertOrAssignHint) -{ +TYPED_TEST_P(ModifiersTest, InsertOrAssignHint) { using std::get; using K = typename TypeParam::key_type; using V = typename TypeParam::mapped_type; @@ -127,8 +119,7 @@ TYPED_TEST_P(ModifiersTest, InsertOrAssignHint) EXPECT_EQ(val2, get<1>(*it)); } -TYPED_TEST_P(ModifiersTest, Emplace) -{ +TYPED_TEST_P(ModifiersTest, Emplace) { using T = hash_internal::GeneratedType; using V = typename TypeParam::mapped_type; T val = hash_internal::Generator()(); @@ -144,8 +135,7 @@ TYPED_TEST_P(ModifiersTest, Emplace) EXPECT_EQ(val, *p.first); } -TYPED_TEST_P(ModifiersTest, EmplaceHint) -{ +TYPED_TEST_P(ModifiersTest, EmplaceHint) { using T = hash_internal::GeneratedType; using V = typename TypeParam::mapped_type; T val = hash_internal::Generator()(); @@ -159,8 +149,7 @@ TYPED_TEST_P(ModifiersTest, EmplaceHint) EXPECT_EQ(val, *it); } -TYPED_TEST_P(ModifiersTest, TryEmplace) -{ +TYPED_TEST_P(ModifiersTest, TryEmplace) { using T = hash_internal::GeneratedType; using V = typename TypeParam::mapped_type; T val = hash_internal::Generator()(); @@ -176,8 +165,7 @@ TYPED_TEST_P(ModifiersTest, TryEmplace) EXPECT_EQ(val, *p.first); } -TYPED_TEST_P(ModifiersTest, TryEmplaceHint) -{ +TYPED_TEST_P(ModifiersTest, TryEmplaceHint) { using T = hash_internal::GeneratedType; using V = typename TypeParam::mapped_type; T val = hash_internal::Generator()(); @@ -196,24 +184,20 @@ using IfNotVoid = typename std::enable_if::value, V>::type; // In openmap we chose not to return the iterator from erase because that's // more expensive. As such we adapt erase to return an iterator here. -struct EraseFirst -{ +struct EraseFirst { template - auto operator()(Map* m, int) const -> IfNotVoiderase(m->begin()))> - { + auto operator()(Map* m, int) const -> IfNotVoiderase(m->begin()))> { return m->erase(m->begin()); } template - typename Map::iterator operator()(Map* m, ...) const - { + typename Map::iterator operator()(Map* m, ...) const { auto it = m->begin(); m->erase(it++); return it; } }; -TYPED_TEST_P(ModifiersTest, Erase) -{ +TYPED_TEST_P(ModifiersTest, Erase) { using T = hash_internal::GeneratedType; using std::get; std::vector values; @@ -231,8 +215,7 @@ TYPED_TEST_P(ModifiersTest, Erase) EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values2.begin(), values2.end())); } -TYPED_TEST_P(ModifiersTest, EraseRange) -{ +TYPED_TEST_P(ModifiersTest, EraseRange) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -243,8 +226,7 @@ TYPED_TEST_P(ModifiersTest, EraseRange) EXPECT_TRUE(it == m.end()); } -TYPED_TEST_P(ModifiersTest, EraseKey) -{ +TYPED_TEST_P(ModifiersTest, EraseKey) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -255,8 +237,7 @@ TYPED_TEST_P(ModifiersTest, EraseKey) EXPECT_THAT(items(m), ::testing::UnorderedElementsAreArray(values.begin() + 1, values.end())); } -TYPED_TEST_P(ModifiersTest, Swap) -{ +TYPED_TEST_P(ModifiersTest, Swap) { using T = hash_internal::GeneratedType; std::vector v1; std::vector v2; diff --git a/tests/phmap/unordered_set_constructor_test.hpp b/tests/phmap/unordered_set_constructor_test.hpp index ae66bf3..bdd3318 100644 --- a/tests/phmap/unordered_set_constructor_test.hpp +++ b/tests/phmap/unordered_set_constructor_test.hpp @@ -28,29 +28,24 @@ namespace gtl { namespace priv { template -class ConstructorTest : public ::testing::Test -{ -}; +class ConstructorTest : public ::testing::Test {}; TYPED_TEST_SUITE_P(ConstructorTest); -TYPED_TEST_P(ConstructorTest, NoArgs) -{ +TYPED_TEST_P(ConstructorTest, NoArgs) { TypeParam m; EXPECT_TRUE(m.empty()); EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre()); } -TYPED_TEST_P(ConstructorTest, BucketCount) -{ +TYPED_TEST_P(ConstructorTest, BucketCount) { TypeParam m(123); EXPECT_TRUE(m.empty()); EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre()); EXPECT_GE(m.bucket_count(), 123u); } -TYPED_TEST_P(ConstructorTest, BucketCountHash) -{ +TYPED_TEST_P(ConstructorTest, BucketCountHash) { using H = typename TypeParam::hasher; H hasher; TypeParam m(123, hasher); @@ -60,8 +55,7 @@ TYPED_TEST_P(ConstructorTest, BucketCountHash) EXPECT_GE(m.bucket_count(), 123u); } -TYPED_TEST_P(ConstructorTest, BucketCountHashEqual) -{ +TYPED_TEST_P(ConstructorTest, BucketCountHashEqual) { using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; H hasher; @@ -74,8 +68,7 @@ TYPED_TEST_P(ConstructorTest, BucketCountHashEqual) EXPECT_GE(m.bucket_count(), 123u); } -TYPED_TEST_P(ConstructorTest, BucketCountHashEqualAlloc) -{ +TYPED_TEST_P(ConstructorTest, BucketCountHashEqualAlloc) { using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; using A = typename TypeParam::allocator_type; @@ -100,33 +93,25 @@ TYPED_TEST_P(ConstructorTest, BucketCountHashEqualAlloc) } template -struct is_std_unordered_set : std::false_type -{ -}; +struct is_std_unordered_set : std::false_type {}; template -struct is_std_unordered_set> : std::true_type -{ -}; +struct is_std_unordered_set> : std::true_type {}; #if defined(UNORDERED_SET_CXX14) || defined(UNORDERED_SET_CXX17) using has_cxx14_std_apis = std::true_type; #else -using has_cxx14_std_apis = std::false_type; +using has_cxx14_std_apis = std::false_type; #endif template -using expect_cxx14_apis = - std::disjunction>, has_cxx14_std_apis>; +using expect_cxx14_apis = std::disjunction>, has_cxx14_std_apis>; template -void BucketCountAllocTest(std::false_type) -{ -} +void BucketCountAllocTest(std::false_type) {} template -void BucketCountAllocTest(std::true_type) -{ +void BucketCountAllocTest(std::true_type) { using A = typename TypeParam::allocator_type; A alloc(0); TypeParam m(123, alloc); @@ -136,19 +121,13 @@ void BucketCountAllocTest(std::true_type) EXPECT_GE(m.bucket_count(), 123u); } -TYPED_TEST_P(ConstructorTest, BucketCountAlloc) -{ - BucketCountAllocTest(expect_cxx14_apis()); -} +TYPED_TEST_P(ConstructorTest, BucketCountAlloc) { BucketCountAllocTest(expect_cxx14_apis()); } template -void BucketCountHashAllocTest(std::false_type) -{ -} +void BucketCountHashAllocTest(std::false_type) {} template -void BucketCountHashAllocTest(std::true_type) -{ +void BucketCountHashAllocTest(std::true_type) { using H = typename TypeParam::hasher; using A = typename TypeParam::allocator_type; H hasher; @@ -161,8 +140,7 @@ void BucketCountHashAllocTest(std::true_type) EXPECT_GE(m.bucket_count(), 123u); } -TYPED_TEST_P(ConstructorTest, BucketCountHashAlloc) -{ +TYPED_TEST_P(ConstructorTest, BucketCountHashAlloc) { BucketCountHashAllocTest(expect_cxx14_apis()); } @@ -173,17 +151,13 @@ using has_alloc_std_constructors = std::false_type; #endif template -using expect_alloc_constructors = - std::disjunction>, has_alloc_std_constructors>; +using expect_alloc_constructors = std::disjunction>, has_alloc_std_constructors>; template -void AllocTest(std::false_type) -{ -} +void AllocTest(std::false_type) {} template -void AllocTest(std::true_type) -{ +void AllocTest(std::true_type) { using A = typename TypeParam::allocator_type; A alloc(0); TypeParam m(alloc); @@ -192,13 +166,9 @@ void AllocTest(std::true_type) EXPECT_THAT(keys(m), ::testing::UnorderedElementsAre()); } -TYPED_TEST_P(ConstructorTest, Alloc) -{ - AllocTest(expect_alloc_constructors()); -} +TYPED_TEST_P(ConstructorTest, Alloc) { AllocTest(expect_alloc_constructors()); } -TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashEqualAlloc) -{ +TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashEqualAlloc) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -218,13 +188,10 @@ TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashEqualAlloc) } template -void InputIteratorBucketAllocTest(std::false_type) -{ -} +void InputIteratorBucketAllocTest(std::false_type) {} template -void InputIteratorBucketAllocTest(std::true_type) -{ +void InputIteratorBucketAllocTest(std::true_type) { using T = hash_internal::GeneratedType; using A = typename TypeParam::allocator_type; A alloc(0); @@ -237,19 +204,15 @@ void InputIteratorBucketAllocTest(std::true_type) EXPECT_GE(m.bucket_count(), 123u); } -TYPED_TEST_P(ConstructorTest, InputIteratorBucketAlloc) -{ +TYPED_TEST_P(ConstructorTest, InputIteratorBucketAlloc) { InputIteratorBucketAllocTest(expect_cxx14_apis()); } template -void InputIteratorBucketHashAllocTest(std::false_type) -{ -} +void InputIteratorBucketHashAllocTest(std::false_type) {} template -void InputIteratorBucketHashAllocTest(std::true_type) -{ +void InputIteratorBucketHashAllocTest(std::true_type) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using A = typename TypeParam::allocator_type; @@ -265,13 +228,11 @@ void InputIteratorBucketHashAllocTest(std::true_type) EXPECT_GE(m.bucket_count(), 123u); } -TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashAlloc) -{ +TYPED_TEST_P(ConstructorTest, InputIteratorBucketHashAlloc) { InputIteratorBucketHashAllocTest(expect_cxx14_apis()); } -TYPED_TEST_P(ConstructorTest, CopyConstructor) -{ +TYPED_TEST_P(ConstructorTest, CopyConstructor) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -291,13 +252,10 @@ TYPED_TEST_P(ConstructorTest, CopyConstructor) } template -void CopyConstructorAllocTest(std::false_type) -{ -} +void CopyConstructorAllocTest(std::false_type) {} template -void CopyConstructorAllocTest(std::true_type) -{ +void CopyConstructorAllocTest(std::true_type) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -315,15 +273,13 @@ void CopyConstructorAllocTest(std::true_type) EXPECT_EQ(m, n); } -TYPED_TEST_P(ConstructorTest, CopyConstructorAlloc) -{ +TYPED_TEST_P(ConstructorTest, CopyConstructorAlloc) { CopyConstructorAllocTest(expect_alloc_constructors()); } // TODO(alkis): Test non-propagating allocators on copy constructors. -TYPED_TEST_P(ConstructorTest, MoveConstructor) -{ +TYPED_TEST_P(ConstructorTest, MoveConstructor) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -343,13 +299,10 @@ TYPED_TEST_P(ConstructorTest, MoveConstructor) } template -void MoveConstructorAllocTest(std::false_type) -{ -} +void MoveConstructorAllocTest(std::false_type) {} template -void MoveConstructorAllocTest(std::true_type) -{ +void MoveConstructorAllocTest(std::true_type) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -368,15 +321,13 @@ void MoveConstructorAllocTest(std::true_type) EXPECT_EQ(m, n); } -TYPED_TEST_P(ConstructorTest, MoveConstructorAlloc) -{ +TYPED_TEST_P(ConstructorTest, MoveConstructorAlloc) { MoveConstructorAllocTest(expect_alloc_constructors()); } // TODO(alkis): Test non-propagating allocators on move constructors. -TYPED_TEST_P(ConstructorTest, InitializerListBucketHashEqualAlloc) -{ +TYPED_TEST_P(ConstructorTest, InitializerListBucketHashEqualAlloc) { using T = hash_internal::GeneratedType; hash_internal::Generator gen; std::initializer_list values = { gen(), gen(), gen(), gen(), gen() }; @@ -395,13 +346,10 @@ TYPED_TEST_P(ConstructorTest, InitializerListBucketHashEqualAlloc) } template -void InitializerListBucketAllocTest(std::false_type) -{ -} +void InitializerListBucketAllocTest(std::false_type) {} template -void InitializerListBucketAllocTest(std::true_type) -{ +void InitializerListBucketAllocTest(std::true_type) { using T = hash_internal::GeneratedType; using A = typename TypeParam::allocator_type; hash_internal::Generator gen; @@ -413,19 +361,15 @@ void InitializerListBucketAllocTest(std::true_type) EXPECT_GE(m.bucket_count(), 123u); } -TYPED_TEST_P(ConstructorTest, InitializerListBucketAlloc) -{ +TYPED_TEST_P(ConstructorTest, InitializerListBucketAlloc) { InitializerListBucketAllocTest(expect_cxx14_apis()); } template -void InitializerListBucketHashAllocTest(std::false_type) -{ -} +void InitializerListBucketHashAllocTest(std::false_type) {} template -void InitializerListBucketHashAllocTest(std::true_type) -{ +void InitializerListBucketHashAllocTest(std::true_type) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using A = typename TypeParam::allocator_type; @@ -440,13 +384,11 @@ void InitializerListBucketHashAllocTest(std::true_type) EXPECT_GE(m.bucket_count(), 123u); } -TYPED_TEST_P(ConstructorTest, InitializerListBucketHashAlloc) -{ +TYPED_TEST_P(ConstructorTest, InitializerListBucketHashAlloc) { InitializerListBucketHashAllocTest(expect_cxx14_apis()); } -TYPED_TEST_P(ConstructorTest, CopyAssignment) -{ +TYPED_TEST_P(ConstructorTest, CopyAssignment) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -466,8 +408,7 @@ TYPED_TEST_P(ConstructorTest, CopyAssignment) // TODO(alkis): Test [non-]propagating allocators on move/copy assignments // (it depends on traits). -TYPED_TEST_P(ConstructorTest, MoveAssignment) -{ +TYPED_TEST_P(ConstructorTest, MoveAssignment) { using T = hash_internal::GeneratedType; using H = typename TypeParam::hasher; using E = typename TypeParam::key_equal; @@ -485,8 +426,7 @@ TYPED_TEST_P(ConstructorTest, MoveAssignment) EXPECT_EQ(m, n); } -TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerList) -{ +TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerList) { using T = hash_internal::GeneratedType; hash_internal::Generator gen; std::initializer_list values = { gen(), gen(), gen(), gen(), gen() }; @@ -495,8 +435,7 @@ TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerList) EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values)); } -TYPED_TEST_P(ConstructorTest, AssignmentOverwritesExisting) -{ +TYPED_TEST_P(ConstructorTest, AssignmentOverwritesExisting) { using T = hash_internal::GeneratedType; hash_internal::Generator gen; TypeParam m({ gen(), gen(), gen() }); @@ -505,8 +444,7 @@ TYPED_TEST_P(ConstructorTest, AssignmentOverwritesExisting) EXPECT_EQ(m, n); } -TYPED_TEST_P(ConstructorTest, MoveAssignmentOverwritesExisting) -{ +TYPED_TEST_P(ConstructorTest, MoveAssignmentOverwritesExisting) { using T = hash_internal::GeneratedType; hash_internal::Generator gen; TypeParam m({ gen(), gen(), gen() }); @@ -516,8 +454,7 @@ TYPED_TEST_P(ConstructorTest, MoveAssignmentOverwritesExisting) EXPECT_EQ(m, n); } -TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerListOverwritesExisting) -{ +TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerListOverwritesExisting) { using T = hash_internal::GeneratedType; hash_internal::Generator gen; std::initializer_list values = { gen(), gen(), gen(), gen(), gen() }; @@ -526,8 +463,7 @@ TYPED_TEST_P(ConstructorTest, AssignmentFromInitializerListOverwritesExisting) EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values)); } -TYPED_TEST_P(ConstructorTest, AssignmentOnSelf) -{ +TYPED_TEST_P(ConstructorTest, AssignmentOnSelf) { using T = hash_internal::GeneratedType; hash_internal::Generator gen; std::initializer_list values = { gen(), gen(), gen(), gen(), gen() }; diff --git a/tests/phmap/unordered_set_lookup_test.hpp b/tests/phmap/unordered_set_lookup_test.hpp index 66fbfce..99e4efe 100644 --- a/tests/phmap/unordered_set_lookup_test.hpp +++ b/tests/phmap/unordered_set_lookup_test.hpp @@ -24,14 +24,11 @@ namespace gtl { namespace priv { template -class LookupTest : public ::testing::Test -{ -}; +class LookupTest : public ::testing::Test {}; TYPED_TEST_SUITE_P(LookupTest); -TYPED_TEST_P(LookupTest, Count) -{ +TYPED_TEST_P(LookupTest, Count) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -43,8 +40,7 @@ TYPED_TEST_P(LookupTest, Count) EXPECT_EQ(1u, m.count(v)) << ::testing::PrintToString(v); } -TYPED_TEST_P(LookupTest, Find) -{ +TYPED_TEST_P(LookupTest, Find) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -54,18 +50,14 @@ TYPED_TEST_P(LookupTest, Find) m.insert(values.begin(), values.end()); for (const auto& v : values) { typename TypeParam::iterator it = m.find(v); - static_assert(std::is_same::value, - ""); - static_assert( - std::is_same())>::value, - ""); + static_assert(std::is_same::value, ""); + static_assert(std::is_same())>::value, ""); EXPECT_TRUE(m.end() != it) << ::testing::PrintToString(v); EXPECT_EQ(v, *it) << ::testing::PrintToString(v); } } -TYPED_TEST_P(LookupTest, EqualRange) -{ +TYPED_TEST_P(LookupTest, EqualRange) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); diff --git a/tests/phmap/unordered_set_members_test.hpp b/tests/phmap/unordered_set_members_test.hpp index f5874e0..9f1d672 100644 --- a/tests/phmap/unordered_set_members_test.hpp +++ b/tests/phmap/unordered_set_members_test.hpp @@ -23,19 +23,14 @@ namespace gtl { namespace priv { template -class MembersTest : public ::testing::Test -{ -}; +class MembersTest : public ::testing::Test {}; TYPED_TEST_SUITE_P(MembersTest); template -void UseType() -{ -} +void UseType() {} -TYPED_TEST_P(MembersTest, Typedefs) -{ +TYPED_TEST_P(MembersTest, Typedefs) { EXPECT_TRUE((std::is_same())); EXPECT_TRUE((std::conjunction>, std::is_integral>())); @@ -48,23 +43,18 @@ TYPED_TEST_P(MembersTest, Typedefs) std::declval(), std::declval())), bool>())); - EXPECT_TRUE((std::is_same())); + EXPECT_TRUE((std::is_same())); EXPECT_TRUE((std::is_same())); - EXPECT_TRUE((std::is_same())); - EXPECT_TRUE( - (std::is_same::pointer, - typename TypeParam::pointer>())); - EXPECT_TRUE((std::is_same< - typename std::allocator_traits::const_pointer, - typename TypeParam::const_pointer>())); + EXPECT_TRUE((std::is_same())); + EXPECT_TRUE((std::is_same::pointer, + typename TypeParam::pointer>())); + EXPECT_TRUE((std::is_same::const_pointer, + typename TypeParam::const_pointer>())); } TYPED_TEST_P(MembersTest, SimpleFunctions) { EXPECT_GT(TypeParam().max_size(), 0u); } -TYPED_TEST_P(MembersTest, BeginEnd) -{ +TYPED_TEST_P(MembersTest, BeginEnd) { TypeParam t = { typename TypeParam::value_type{} }; EXPECT_EQ(t.begin(), t.cbegin()); EXPECT_EQ(t.end(), t.cend()); diff --git a/tests/phmap/unordered_set_modifiers_test.hpp b/tests/phmap/unordered_set_modifiers_test.hpp index 539de4c..7572cbf 100644 --- a/tests/phmap/unordered_set_modifiers_test.hpp +++ b/tests/phmap/unordered_set_modifiers_test.hpp @@ -24,14 +24,11 @@ namespace gtl { namespace priv { template -class ModifiersTest : public ::testing::Test -{ -}; +class ModifiersTest : public ::testing::Test {}; TYPED_TEST_SUITE_P(ModifiersTest); -TYPED_TEST_P(ModifiersTest, Clear) -{ +TYPED_TEST_P(ModifiersTest, Clear) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -42,8 +39,7 @@ TYPED_TEST_P(ModifiersTest, Clear) EXPECT_TRUE(m.empty()); } -TYPED_TEST_P(ModifiersTest, Insert) -{ +TYPED_TEST_P(ModifiersTest, Insert) { using T = hash_internal::GeneratedType; T val = hash_internal::Generator()(); TypeParam m; @@ -54,8 +50,7 @@ TYPED_TEST_P(ModifiersTest, Insert) EXPECT_FALSE(p.second); } -TYPED_TEST_P(ModifiersTest, InsertHint) -{ +TYPED_TEST_P(ModifiersTest, InsertHint) { using T = hash_internal::GeneratedType; T val = hash_internal::Generator()(); TypeParam m; @@ -67,8 +62,7 @@ TYPED_TEST_P(ModifiersTest, InsertHint) EXPECT_EQ(val, *it); } -TYPED_TEST_P(ModifiersTest, InsertRange) -{ +TYPED_TEST_P(ModifiersTest, InsertRange) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -77,8 +71,7 @@ TYPED_TEST_P(ModifiersTest, InsertRange) ASSERT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values)); } -TYPED_TEST_P(ModifiersTest, Emplace) -{ +TYPED_TEST_P(ModifiersTest, Emplace) { using T = hash_internal::GeneratedType; T val = hash_internal::Generator()(); TypeParam m; @@ -92,8 +85,7 @@ TYPED_TEST_P(ModifiersTest, Emplace) EXPECT_EQ(val, *p.first); } -TYPED_TEST_P(ModifiersTest, EmplaceHint) -{ +TYPED_TEST_P(ModifiersTest, EmplaceHint) { using T = hash_internal::GeneratedType; T val = hash_internal::Generator()(); TypeParam m; @@ -110,24 +102,20 @@ using IfNotVoid = typename std::enable_if::value, V>::type; // In openmap we chose not to return the iterator from erase because that's // more expensive. As such we adapt erase to return an iterator here. -struct EraseFirst -{ +struct EraseFirst { template - auto operator()(Map* m, int) const -> IfNotVoiderase(m->begin()))> - { + auto operator()(Map* m, int) const -> IfNotVoiderase(m->begin()))> { return m->erase(m->begin()); } template - typename Map::iterator operator()(Map* m, ...) const - { + typename Map::iterator operator()(Map* m, ...) const { auto it = m->begin(); m->erase(it++); return it; } }; -TYPED_TEST_P(ModifiersTest, Erase) -{ +TYPED_TEST_P(ModifiersTest, Erase) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -143,8 +131,7 @@ TYPED_TEST_P(ModifiersTest, Erase) EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values2.begin(), values2.end())); } -TYPED_TEST_P(ModifiersTest, EraseRange) -{ +TYPED_TEST_P(ModifiersTest, EraseRange) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -155,8 +142,7 @@ TYPED_TEST_P(ModifiersTest, EraseRange) EXPECT_TRUE(it == m.end()); } -TYPED_TEST_P(ModifiersTest, EraseKey) -{ +TYPED_TEST_P(ModifiersTest, EraseKey) { using T = hash_internal::GeneratedType; std::vector values; std::generate_n(std::back_inserter(values), 10, hash_internal::Generator()); @@ -167,8 +153,7 @@ TYPED_TEST_P(ModifiersTest, EraseKey) EXPECT_THAT(keys(m), ::testing::UnorderedElementsAreArray(values.begin() + 1, values.end())); } -TYPED_TEST_P(ModifiersTest, Swap) -{ +TYPED_TEST_P(ModifiersTest, Swap) { using T = hash_internal::GeneratedType; std::vector v1; std::vector v2;