ID
stringlengths
36
36
Language
stringclasses
1 value
Repository Name
stringclasses
13 values
File Name
stringlengths
2
48
File Path in Repository
stringlengths
11
111
File Path for Unit Test
stringlengths
13
116
Code
stringlengths
0
278k
Unit Test - (Ground Truth)
stringlengths
78
663k
Code Url
stringlengths
91
198
Test Code Url
stringlengths
93
203
Commit Hash
stringclasses
13 values
a03b19bf-a0bc-4b63-a4e3-76d768738a45
cpp
abseil/abseil-cpp
low_level_hash
absl/hash/internal/low_level_hash.cc
absl/hash/internal/low_level_hash_test.cc
#include "absl/hash/internal/low_level_hash.h" #include <cstddef> #include <cstdint> #include "absl/base/internal/unaligned_access.h" #include "absl/base/prefetch.h" #include "absl/numeric/int128.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace hash_internal { static uint64_t Mix(uint64_t v0, uint64_t v1) { absl::uint128 p = v0; p *= v1; return absl::Uint128Low64(p) ^ absl::Uint128High64(p); } uint64_t LowLevelHashLenGt16(const void* data, size_t len, uint64_t seed, const uint64_t salt[5]) { const uint8_t* ptr = static_cast<const uint8_t*>(data); uint64_t starting_length = static_cast<uint64_t>(len); const uint8_t* last_16_ptr = ptr + starting_length - 16; uint64_t current_state = seed ^ salt[0]; if (len > 64) { uint64_t duplicated_state0 = current_state; uint64_t duplicated_state1 = current_state; uint64_t duplicated_state2 = current_state; do { PrefetchToLocalCache(ptr + ABSL_CACHELINE_SIZE); uint64_t a = absl::base_internal::UnalignedLoad64(ptr); uint64_t b = absl::base_internal::UnalignedLoad64(ptr + 8); uint64_t c = absl::base_internal::UnalignedLoad64(ptr + 16); uint64_t d = absl::base_internal::UnalignedLoad64(ptr + 24); uint64_t e = absl::base_internal::UnalignedLoad64(ptr + 32); uint64_t f = absl::base_internal::UnalignedLoad64(ptr + 40); uint64_t g = absl::base_internal::UnalignedLoad64(ptr + 48); uint64_t h = absl::base_internal::UnalignedLoad64(ptr + 56); current_state = Mix(a ^ salt[1], b ^ current_state); duplicated_state0 = Mix(c ^ salt[2], d ^ duplicated_state0); duplicated_state1 = Mix(e ^ salt[3], f ^ duplicated_state1); duplicated_state2 = Mix(g ^ salt[4], h ^ duplicated_state2); ptr += 64; len -= 64; } while (len > 64); current_state = (current_state ^ duplicated_state0) ^ (duplicated_state1 + duplicated_state2); } if (len > 32) { uint64_t a = absl::base_internal::UnalignedLoad64(ptr); uint64_t b = absl::base_internal::UnalignedLoad64(ptr + 8); uint64_t c = absl::base_internal::UnalignedLoad64(ptr + 16); uint64_t d = absl::base_internal::UnalignedLoad64(ptr + 24); uint64_t cs0 = Mix(a ^ salt[1], b ^ current_state); uint64_t cs1 = Mix(c ^ salt[2], d ^ current_state); current_state = cs0 ^ cs1; ptr += 32; len -= 32; } if (len > 16) { uint64_t a = absl::base_internal::UnalignedLoad64(ptr); uint64_t b = absl::base_internal::UnalignedLoad64(ptr + 8); current_state = Mix(a ^ salt[1], b ^ current_state); } uint64_t a = absl::base_internal::UnalignedLoad64(last_16_ptr); uint64_t b = absl::base_internal::UnalignedLoad64(last_16_ptr + 8); return Mix(a ^ salt[1] ^ starting_length, b ^ current_state); } uint64_t LowLevelHash(const void* data, size_t len, uint64_t seed, const uint64_t salt[5]) { if (len > 16) return LowLevelHashLenGt16(data, len, seed, salt); PrefetchToLocalCache(data); const uint8_t* ptr = static_cast<const uint8_t*>(data); uint64_t starting_length = static_cast<uint64_t>(len); uint64_t current_state = seed ^ salt[0]; if (len == 0) return current_state; uint64_t a = 0; uint64_t b = 0; if (len > 8) { a = absl::base_internal::UnalignedLoad64(ptr); b = absl::base_internal::UnalignedLoad64(ptr + len - 8); } else if (len > 3) { a = absl::base_internal::UnalignedLoad32(ptr); b = absl::base_internal::UnalignedLoad32(ptr + len - 4); } else { a = static_cast<uint64_t>((ptr[0] << 8) | ptr[len - 1]); b = static_cast<uint64_t>(ptr[len >> 1]); } return Mix(a ^ salt[1] ^ starting_length, b ^ current_state); } } ABSL_NAMESPACE_END }
#include "absl/hash/internal/low_level_hash.h" #include <cinttypes> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/escaping.h" #define UPDATE_GOLDEN 0 namespace { static const uint64_t kSalt[5] = {0xa0761d6478bd642f, 0xe7037ed1a0b428dbl, 0x8ebc6af09c88c6e3, 0x589965cc75374cc3l, 0x1d8e4e27c47d124f}; TEST(LowLevelHashTest, VerifyGolden) { constexpr size_t kNumGoldenOutputs = 134; static struct { absl::string_view base64_data; uint64_t seed; } cases[] = { {"", uint64_t{0xec42b7ab404b8acb}}, {"ICAg", uint64_t{0}}, {"YWFhYQ==", uint64_t{0}}, {"AQID", uint64_t{0}}, {"AQIDBA==", uint64_t{0}}, {"dGhpcmRfcGFydHl8d3loYXNofDY0", uint64_t{0}}, {"Zw==", uint64_t{0xeeee074043a3ee0f}}, {"xmk=", uint64_t{0x857902089c393de}}, {"c1H/", uint64_t{0x993df040024ca3af}}, {"SuwpzQ==", uint64_t{0xc4e4c2acea740e96}}, {"uqvy++M=", uint64_t{0x6a214b3db872d0cf}}, {"RnzCVPgb", uint64_t{0x44343db6a89dba4d}}, {"6OeNdlouYw==", uint64_t{0x77b5d6d1ae1dd483}}, {"M5/JmmYyDbc=", uint64_t{0x89ab8ecb44d221f1}}, {"MVijWiVdBRdY", uint64_t{0x60244b17577ca81b}}, {"6V7Uq7LNxpu0VA==", uint64_t{0x59a08dcee0717067}}, {"EQ6CdEEhPdyHcOk=", uint64_t{0xf5f20db3ade57396}}, {"PqFB4fxnPgF+l+rc", uint64_t{0xbf8dee0751ad3efb}}, {"a5aPOFwq7LA7+zKvPA==", uint64_t{0x6b7a06b268d63e30}}, {"VOwY21wCGv5D+/qqOvs=", uint64_t{0xb8c37f0ae0f54c82}}, {"KdHmBTx8lHXYvmGJ+Vy7", uint64_t{0x9fcbed0c38e50eef}}, {"qJkPlbHr8bMF7/cA6aE65Q==", uint64_t{0x2af4bade1d8e3a1d}}, {"ygvL0EhHZL0fIx6oHHtkxRQ=", uint64_t{0x714e3aa912da2f2c}}, {"c1rFXkt5YztwZCQRngncqtSs", uint64_t{0xf5ee75e3cbb82c1c}}, {"8hsQrzszzeNQSEcVXLtvIhm6mw==", uint64_t{0x620e7007321b93b9}}, {"ffUL4RocfyP4KfikGxO1yk7omDI=", uint64_t{0xc08528cac2e551fc}}, {"OOB5TT00vF9Od/rLbAWshiErqhpV", uint64_t{0x6a1debf9cc3ad39}}, {"or5wtXM7BFzTNpSzr+Lw5J5PMhVJ/Q==", uint64_t{0x7e0a3c88111fc226}}, {"gk6pCHDUsoopVEiaCrzVDhioRKxb844=", uint64_t{0x1301fef15df39edb}}, {"TNctmwlC5QbEM6/No4R/La3UdkfeMhzs", uint64_t{0x64e181f3d5817ab}}, {"SsQw9iAjhWz7sgcE9OwLuSC6hsM+BfHs2Q==", uint64_t{0xafafc44961078ecb}}, {"ZzO3mVCj4xTT2TT3XqDyEKj2BZQBvrS8RHg=", uint64_t{0x4f7bb45549250094}}, {"+klp5iPQGtppan5MflEls0iEUzqU+zGZkDJX", uint64_t{0xa30061abaa2818c}}, {"RO6bvOnlJc8I9eniXlNgqtKy0IX6VNg16NRmgg==", uint64_t{0xd902ee3e44a5705f}}, {"ZJjZqId1ZXBaij9igClE3nyliU5XWdNRrayGlYA=", uint64_t{0x316d36da516f583}}, {"7BfkhfGMDGbxfMB8uyL85GbaYQtjr2K8g7RpLzr/", uint64_t{0x402d83f9f834f616}}, {"rycWk6wHH7htETQtje9PidS2YzXBx+Qkg2fY7ZYS7A==", uint64_t{0x9c604164c016b72c}}, {"RTkC2OUK+J13CdGllsH0H5WqgspsSa6QzRZouqx6pvI=", uint64_t{0x3f4507e01f9e73ba}}, {"tKjKmbLCNyrLCM9hycOAXm4DKNpM12oZ7dLTmUx5iwAi", uint64_t{0xc3fe0d5be8d2c7c7}}, {"VprUGNH+5NnNRaORxgH/ySrZFQFDL+4VAodhfBNinmn8cg==", uint64_t{0x531858a40bfa7ea1}}, {"gc1xZaY+q0nPcUvOOnWnT3bqfmT/geth/f7Dm2e/DemMfk4=", uint64_t{0x86689478a7a7e8fa}}, {"Mr35fIxqx1ukPAL0su1yFuzzAU3wABCLZ8+ZUFsXn47UmAph", uint64_t{0x4ec948b8e7f27288}}, {"A9G8pw2+m7+rDtWYAdbl8tb2fT7FFo4hLi2vAsa5Y8mKH3CX3g==", uint64_t{0xce46c7213c10032}}, {"DFaJGishGwEHDdj9ixbCoaTjz9KS0phLNWHVVdFsM93CvPft3hM=", uint64_t{0xf63e96ee6f32a8b6}}, {"7+Ugx+Kr3aRNgYgcUxru62YkTDt5Hqis+2po81hGBkcrJg4N0uuy", uint64_t{0x1cfe85e65fc5225}}, {"H2w6O8BUKqu6Tvj2xxaecxEI2wRgIgqnTTG1WwOgDSINR13Nm4d4Vg==", uint64_t{0x45c474f1cee1d2e8}}, {"1XBMnIbqD5jy65xTDaf6WtiwtdtQwv1dCVoqpeKj+7cTR1SaMWMyI04=", uint64_t{0x6e024e14015f329c}}, {"znZbdXG2TSFrKHEuJc83gPncYpzXGbAebUpP0XxzH0rpe8BaMQ17nDbt", uint64_t{0x760c40502103ae1c}}, {"ylu8Atu13j1StlcC1MRMJJXIl7USgDDS22HgVv0WQ8hx/8pNtaiKB17hCQ==", uint64_t{0x17fd05c3c560c320}}, {"M6ZVVzsd7vAvbiACSYHioH/440dp4xG2mLlBnxgiqEvI/aIEGpD0Sf4VS0g=", uint64_t{0x8b34200a6f8e90d9}}, {"li3oFSXLXI+ubUVGJ4blP6mNinGKLHWkvGruun85AhVn6iuMtocbZPVhqxzn", uint64_t{0x6be89e50818bdf69}}, {"kFuQHuUCqBF3Tc3hO4dgdIp223ShaCoog48d5Do5zMqUXOh5XpGK1t5XtxnfGA==", uint64_t{0xfb389773315b47d8}}, {"jWmOad0v0QhXVJd1OdGuBZtDYYS8wBVHlvOeTQx9ZZnm8wLEItPMeihj72E0nWY=", uint64_t{0x4f2512a23f61efee}}, {"z+DHU52HaOQdW4JrZwDQAebEA6rm13Zg/9lPYA3txt3NjTBqFZlOMvTRnVzRbl23", uint64_t{0x59ccd92fc16c6fda}}, {"MmBiGDfYeTayyJa/tVycg+rN7f9mPDFaDc+23j0TlW9094er0ADigsl4QX7V3gG/qw==", uint64_t{0x25c5a7f5bd330919}}, {"774RK+9rOL4iFvs1q2qpo/JVc/I39buvNjqEFDtDvyoB0FXxPI2vXqOrk08VPfIHkmU=", uint64_t{0x51df4174d34c97d7}}, {"+slatXiQ7/2lK0BkVUI1qzNxOOLP3I1iK6OfHaoxgqT63FpzbElwEXSwdsryq3UlHK0I", uint64_t{0x80ce6d76f89cb57}}, {"64mVTbQ47dHjHlOHGS/hjJwr/" "K2frCNpn87exOqMzNUVYiPKmhCbfS7vBUce5tO6Ec9osQ==", uint64_t{0x20961c911965f684}}, {"fIsaG1r530SFrBqaDj1kqE0AJnvvK8MNEZbII2Yw1OK77v0V59xabIh0B5axaz/" "+a2V5WpA=", uint64_t{0x4e5b926ec83868e7}}, {"PGih0zDEOWCYGxuHGDFu9Ivbff/" "iE7BNUq65tycTR2R76TerrXALRosnzaNYO5fjFhTi+CiS", uint64_t{0x3927b30b922eecef}}, {"RnpA/" "zJnEnnLjmICORByRVb9bCOgxF44p3VMiW10G7PvW7IhwsWajlP9kIwNA9FjAD2GoQHk2Q=" "=", uint64_t{0xbd0291284a49b61c}}, {"qFklMceaTHqJpy2qavJE+EVBiNFOi6OxjOA3LeIcBop1K7w8xQi3TrDk+" "BrWPRIbfprszSaPfrI=", uint64_t{0x73a77c575bcc956}}, {"cLbfUtLl3EcQmITWoTskUR8da/VafRDYF/ylPYwk7/" "zazk6ssyrzxMN3mmSyvrXR2yDGNZ3WDrTT", uint64_t{0x766a0e2ade6d09a6}}, {"s/" "Jf1+" "FbsbCpXWPTUSeWyMH6e4CvTFvPE5Fs6Z8hvFITGyr0dtukHzkI84oviVLxhM1xMxrMAy1db" "w==", uint64_t{0x2599f4f905115869}}, {"FvyQ00+j7nmYZVQ8hI1Edxd0AWplhTfWuFGiu34AK5X8u2hLX1bE97sZM0CmeLe+" "7LgoUT1fJ/axybE=", uint64_t{0xd8256e5444d21e53}}, {"L8ncxMaYLBH3g9buPu8hfpWZNlOF7nvWLNv9IozH07uQsIBWSKxoPy8+" "LW4tTuzC6CIWbRGRRD1sQV/4", uint64_t{0xf664a91333fb8dfd}}, {"CDK0meI07yrgV2kQlZZ+" "wuVqhc2NmzqeLH7bmcA6kchsRWFPeVF5Wqjjaj556ABeUoUr3yBmfU3kWOakkg==", uint64_t{0x9625b859be372cd1}}, {"d23/vc5ONh/" "HkMiq+gYk4gaCNYyuFKwUkvn46t+dfVcKfBTYykr4kdvAPNXGYLjM4u1YkAEFpJP+" "nX7eOvs=", uint64_t{0x7b99940782e29898}}, {"NUR3SRxBkxTSbtQORJpu/GdR6b/h6sSGfsMj/KFd99ahbh+9r7LSgSGmkGVB/" "mGoT0pnMTQst7Lv2q6QN6Vm", uint64_t{0x4fe12fa5383b51a8}}, {"2BOFlcI3Z0RYDtS9T9Ie9yJoXlOdigpPeeT+CRujb/" "O39Ih5LPC9hP6RQk1kYESGyaLZZi3jtabHs7DiVx/VDg==", uint64_t{0xe2ccb09ac0f5b4b6}}, {"FF2HQE1FxEvWBpg6Z9zAMH+Zlqx8S1JD/" "wIlViL6ZDZY63alMDrxB0GJQahmAtjlm26RGLnjW7jmgQ4Ie3I+014=", uint64_t{0x7d0a37adbd7b753b}}, {"tHmO7mqVL/PX11nZrz50Hc+M17Poj5lpnqHkEN+4bpMx/" "YGbkrGOaYjoQjgmt1X2QyypK7xClFrjeWrCMdlVYtbW", uint64_t{0xd3ae96ef9f7185f2}}, {"/WiHi9IQcxRImsudkA/KOTqGe8/" "gXkhKIHkjddv5S9hi02M049dIK3EUyAEjkjpdGLUs+BN0QzPtZqjIYPOgwsYE9g==", uint64_t{0x4fb88ea63f79a0d8}}, {"qds+1ExSnU11L4fTSDz/QE90g4Jh6ioqSh3KDOTOAo2pQGL1k/" "9CCC7J23YF27dUTzrWsCQA2m4epXoCc3yPHb3xElA=", uint64_t{0xed564e259bb5ebe9}}, {"8FVYHx40lSQPTHheh08Oq0/" "pGm2OlG8BEf8ezvAxHuGGdgCkqpXIueJBF2mQJhTfDy5NncO8ntS7vaKs7sCNdDaNGOEi", uint64_t{0x3e3256b60c428000}}, {"4ZoEIrJtstiCkeew3oRzmyJHVt/pAs2pj0HgHFrBPztbQ10NsQ/" "lM6DM439QVxpznnBSiHMgMQJhER+70l72LqFTO1JiIQ==", uint64_t{0xfb05bad59ec8705}}, {"hQPtaYI+wJyxXgwD5n8jGIKFKaFA/" "P83KqCKZfPthnjwdOFysqEOYwAaZuaaiv4cDyi9TyS8hk5cEbNP/jrI7q6pYGBLbsM=", uint64_t{0xafdc251dbf97b5f8}}, {"S4gpMSKzMD7CWPsSfLeYyhSpfWOntyuVZdX1xSBjiGvsspwOZcxNKCRIOqAA0moUfOh3I5+" "juQV4rsqYElMD/gWfDGpsWZKQ", uint64_t{0x10ec9c92ddb5dcbc}}, {"oswxop+" "bthuDLT4j0PcoSKby4LhF47ZKg8K17xxHf74UsGCzTBbOz0MM8hQEGlyqDT1iUiAYnaPaUp" "L2mRK0rcIUYA4qLt5uOw==", uint64_t{0x9a767d5822c7dac4}}, {"0II/" "697p+" "BtLSjxj5989OXI004TogEb94VUnDzOVSgMXie72cuYRvTFNIBgtXlKfkiUjeqVpd4a+" "n5bxNOD1TGrjQtzKU5r7obo=", uint64_t{0xee46254080d6e2db}}, {"E84YZW2qipAlMPmctrg7TKlwLZ68l4L+c0xRDUfyyFrA4MAti0q9sHq3TDFviH0Y+" "Kq3tEE5srWFA8LM9oomtmvm5PYxoaarWPLc", uint64_t{0xbbb669588d8bf398}}, {"x3pa4HIElyZG0Nj7Vdy9IdJIR4izLmypXw5PCmZB5y68QQ4uRaVVi3UthsoJROvbjDJkP2D" "Q6L/eN8pFeLFzNPKBYzcmuMOb5Ull7w==", uint64_t{0xdc2afaa529beef44}}, {"jVDKGYIuWOP/" "QKLdd2wi8B2VJA8Wh0c8PwrXJVM8FOGM3voPDVPyDJOU6QsBDPseoR8uuKd19OZ/" "zAvSCB+zlf6upAsBlheUKgCfKww=", uint64_t{0xf1f67391d45013a8}}, {"mkquunhmYe1aR2wmUz4vcvLEcKBoe6H+kjUok9VUn2+eTSkWs4oDDtJvNCWtY5efJwg/" "j4PgjRYWtqnrCkhaqJaEvkkOwVfgMIwF3e+d", uint64_t{0x16fce2b8c65a3429}}, {"fRelvKYonTQ+s+rnnvQw+JzGfFoPixtna0vzcSjiDqX5s2Kg2 "UGrK+AVCyMUhO98WoB1DDbrsOYSw2QzrcPe0+3ck9sePvb+Q/IRaHbw==", uint64_t{0xf4b096699f49fe67}}, {"DUwXFJzagljo44QeJ7/" "6ZKw4QXV18lhkYT2jglMr8WB3CHUU4vdsytvw6AKv42ZcG6fRkZkq9fpnmXy6xG0aO3WPT1" "eHuyFirAlkW+zKtwg=", uint64_t{0xca584c4bc8198682}}, {"cYmZCrOOBBongNTr7e4nYn52uQUy2mfe48s50JXx2AZ6cRAt/" "xRHJ5QbEoEJOeOHsJyM4nbzwFm++SlT6gFZZHJpkXJ92JkR86uS/eV1hJUR", uint64_t{0xed269fc3818b6aad}}, {"EXeHBDfhwzAKFhsMcH9+2RHwV+mJaN01+9oacF6vgm8mCXRd6jeN9U2oAb0of5c5cO4i+" "Vb/LlHZSMI490SnHU0bejhSCC2gsC5d2K30ER3iNA==", uint64_t{0x33f253cbb8fe66a8}}, {"FzkzRYoNjkxFhZDso94IHRZaJUP61nFYrh5MwDwv9FNoJ5jyNCY/" "eazPZk+tbmzDyJIGw2h3GxaWZ9bSlsol/vK98SbkMKCQ/wbfrXRLcDzdd/8=", uint64_t{0xd0b76b2c1523d99c}}, {"Re4aXISCMlYY/XsX7zkIFR04ta03u4zkL9dVbLXMa/q6hlY/CImVIIYRN3VKP4pnd0AUr/" "ugkyt36JcstAInb4h9rpAGQ7GMVOgBniiMBZ/MGU7H", uint64_t{0xfd28f0811a2a237f}}, {"ueLyMcqJXX+MhO4UApylCN9WlTQ+" "ltJmItgG7vFUtqs2qNwBMjmAvr5u0sAKd8jpzV0dDPTwchbIeAW5zbtkA2NABJV6hFM48ib" "4/J3A5mseA3cS8w==", uint64_t{0x6261fb136482e84}}, {"6Si7Yi11L+jZMkwaN+GUuzXMrlvEqviEkGOilNq0h8TdQyYKuFXzkYc/" "q74gP3pVCyiwz9KpVGMM9vfnq36riMHRknkmhQutxLZs5fbmOgEO69HglCU=", uint64_t{0x458efc750bca7c3a}}, {"Q6AbOofGuTJOegPh9Clm/" "9crtUMQqylKrTc1fhfJo1tqvpXxhU4k08kntL1RG7woRnFrVh2UoMrL1kjin+s9CanT+" "y4hHwLqRranl9FjvxfVKm3yvg68", uint64_t{0xa7e69ff84e5e7c27}}, {"ieQEbIPvqY2YfIjHnqfJiO1/MIVRk0RoaG/WWi3kFrfIGiNLCczYoklgaecHMm/" "1sZ96AjO+a5stQfZbJQwS7Sc1ODABEdJKcTsxeW2hbh9A6CFzpowP1A==", uint64_t{0x3c59bfd0c29efe9e}}, {"zQUv8hFB3zh2GGl3KTvCmnfzE+" "SUgQPVaSVIELFX5H9cE3FuVFGmymkPQZJLAyzC90Cmi8GqYCvPqTuAAB "XTJxy4bCcVArgZG9zJXpjowpNBfr3ngWrSE=", uint64_t{0x10befacc6afd298d}}, {"US4hcC1+op5JKGC7eIs8CUgInjKWKlvKQkapulxW262E/" "B2ye79QxOexf188u2mFwwe3WTISJHRZzS61IwljqAWAWoBAqkUnW8SHmIDwHUP31J0p5sGd" "P47L", uint64_t{0x41d5320b0a38efa7}}, {"9bHUWFna2LNaGF6fQLlkx1Hkt24nrkLE2CmFdWgTQV3FFbUe747SSqYw6ebpTa07MWSpWRP" "sHesVo2B9tqHbe7eQmqYebPDFnNqrhSdZwFm9arLQVs+7a3Ic6A==", uint64_t{0x58db1c7450fe17f3}}, {"Kb3DpHRUPhtyqgs3RuXjzA08jGb59hjKTOeFt1qhoINfYyfTt2buKhD6YVffRCPsgK9SeqZ" "qRPJSyaqsa0ovyq1WnWW8jI/NhvAkZTVHUrX2pC+cD3OPYT05Dag=", uint64_t{0x6098c055a335b7a6}}, {"gzxyMJIPlU+bJBwhFUCHSofZ/" "319LxqMoqnt3+L6h2U2+ZXJCSsYpE80xmR0Ta77Jq54o92SMH87HV8dGOaCTuAYF+" "lDL42SY1P316Cl0sZTS2ow3ZqwGbcPNs/1", uint64_t{0x1bbacec67845a801}}, {"uR7V0TW+FGVMpsifnaBAQ3IGlr1wx5sKd7TChuqRe6OvUXTlD4hKWy8S+" "8yyOw8lQabism19vOQxfmocEOW/" "vzY0pEa87qHrAZy4s9fH2Bltu8vaOIe+agYohhYORQ==", uint64_t{0xc419cfc7442190}}, {"1UR5eoo2aCwhacjZHaCh9bkOsITp6QunUxHQ2SfeHv0imHetzt/" "Z70mhyWZBalv6eAx+YfWKCUib2SHDtz/" "A2dc3hqUWX5VfAV7FQsghPUAtu6IiRatq4YSLpDvKZBQ=", uint64_t{0xc95e510d94ba270c}}, {"opubR7H63BH7OtY+Avd7QyQ25UZ8kLBdFDsBTwZlY6gA/" "u+x+" "czC9AaZMgmQrUy15DH7YMGsvdXnviTtI4eVI4aF1H9Rl3NXMKZgwFOsdTfdcZeeHVRzBBKX" "8jUfh1il", uint64_t{0xff1ae05c98089c3f}}, {"DC0kXcSXtfQ9FbSRwirIn5tgPri0sbzHSa78aDZVDUKCMaBGyFU6BmrulywYX8yzvwprdLs" "oOwTWN2wMjHlPDqrvVHNEjnmufRDblW+nSS+xtKNs3N5xsxXdv6JXDrAB/Q==", uint64_t{0x90c02b8dceced493}}, {"BXRBk+3wEP3Lpm1y75wjoz+PgB0AMzLe8tQ1AYU2/" "oqrQB2YMC6W+9QDbcOfkGbeH+b7IBkt/" "gwCMw2HaQsRFEsurXtcQ3YwRuPz5XNaw5NAvrNa67Fm7eRzdE1+hWLKtA8=", uint64_t{0x9f8a76697ab1aa36}}, {"RRBSvEGYnzR9E45Aps/+WSnpCo/X7gJLO4DRnUqFrJCV/kzWlusLE/" "6ZU6RoUf2ROwcgEvUiXTGjLs7ts3t9SXnJHxC1KiOzxHdYLMhVvgNd3hVSAXODpKFSkVXND" "55G2L1W", uint64_t{0x6ba1bf3d811a531d}}, {"jeh6Qazxmdi57pa9S3XSnnZFIRrnc6s8QLrah5OX3SB/V2ErSPoEAumavzQPkdKF1/" "SfvmdL+qgF1C+Yawy562QaFqwVGq7+tW0yxP8FStb56ZRgNI4IOmI30s1Ei7iops9Uuw==", uint64_t{0x6a418974109c67b4}}, {"6QO5nnDrY2/" "wrUXpltlKy2dSBcmK15fOY092CR7KxAjNfaY+" "aAmtWbbzQk3MjBg03x39afSUN1fkrWACdyQKRaGxgwq6MGNxI6W+8DLWJBHzIXrntrE/" "ml6fnNXEpxplWJ1vEs4=", uint64_t{0x8472f1c2b3d230a3}}, {"0oPxeEHhqhcFuwonNfLd5jF3RNATGZS6NPoS0WklnzyokbTqcl4BeBkMn07+fDQv83j/" "BpGUwcWO05f3+DYzocfnizpFjLJemFGsls3gxcBYxcbqWYev51tG3lN9EvRE+X9+Pwww", uint64_t{0x5e06068f884e73a7}}, {"naSBSjtOKgAOg8XVbR5cHAW3Y+QL4Pb/JO9/" "oy6L08wvVRZqo0BrssMwhzBP401Um7A4ppAupbQeJFdMrysY34AuSSNvtNUy5VxjNECwiNt" "gwYHw7yakDUv8WvonctmnoSPKENegQg==", uint64_t{0x55290b1a8f170f59}}, {"vPyl8DxVeRe1OpilKb9KNwpGkQRtA94UpAHetNh+" "95V7nIW38v7PpzhnTWIml5kw3So1Si0TXtIUPIbsu32BNhoH7QwFvLM+" "JACgSpc5e3RjsL6Qwxxi11npwxRmRUqATDeMUfRAjxg=", uint64_t{0x5501cfd83dfe706a}}, {"QC9i2GjdTMuNC1xQJ74ngKfrlA4w3o58FhvNCltdIpuMhHP1YsDA78scQPLbZ3OCUgeQguY" "f/vw6zAaVKSgwtaykqg5ka/4vhz4hYqWU5ficdXqClHl+zkWEY26slCNYOM5nnDlly8Cj", uint64_t{0xe43ed13d13a66990}}, {"7CNIgQhAHX27nxI0HeB5oUTnTdgKpRDYDKwRcXfSFGP1XeT9nQF6WKCMjL1tBV6x7KuJ91G" "Zz11F4c+8s+MfqEAEpd4FHzamrMNjGcjCyrVtU6y+7HscMVzr7Q/" "ODLcPEFztFnwjvCjmHw==", uint64_t{0xdf43bc375cf5283f}}, {"Qa/hC2RPXhANSospe+gUaPfjdK/yhQvfm4cCV6/pdvCYWPv8p1kMtKOX3h5/" "8oZ31fsmx4Axphu5qXJokuhZKkBUJueuMpxRyXpwSWz2wELx5glxF7CM0Fn+" "OevnkhUn5jsPlG2r5jYlVn8=", uint64_t{0x8112b806d288d7b5}}, {"kUw/0z4l3a89jTwN5jpG0SHY5km/" "IVhTjgM5xCiPRLncg40aqWrJ5vcF891AOq5hEpSq0bUCJUMFXgct7kvnys905HjerV7Vs1G" "y84tgVJ70/2+pAZTsB/PzNOE/G6sOj4+GbTzkQu819OLB", uint64_t{0xd52a18abb001cb46}}, {"VDdfSDbO8Tdj3T5W0XM3EI7iHh5xpIutiM6dvcJ/fhe23V/srFEkDy5iZf/" "VnA9kfi2C79ENnFnbOReeuZW1b3MUXB9lgC6U4pOTuC+" "jHK3Qnpyiqzj7h3ISJSuo2pob7vY6VHZo6Fn7exEqHg==", uint64_t{0xe12b76a2433a1236}}, {"Ldfvy3ORdquM/R2fIkhH/ONi69mcP1AEJ6n/" "oropwecAsLJzQSgezSY8bEiEs0VnFTBBsW+RtZY6tDj03fnb3amNUOq1b7jbqyQkL9hpl+" "2Z2J8IaVSeownWl+bQcsR5/xRktIMckC5AtF4YHfU=", uint64_t{0x175bf7319cf1fa00}}, {"BrbNpb42+" "VzZAjJw6QLirXzhweCVRfwlczzZ0VX2xluskwBqyfnGovz5EuX79JJ31VNXa5hTkAyQat3l" "YKRADTdAdwE5PqM1N7YaMqqsqoAAAeuYVXuk5eWCykYmClNdSspegwgCuT+403JigBzi", uint64_t{0xd63d57b3f67525ae}}, {"gB3NGHJJvVcuPyF0ZSvHwnWSIfmaI7La24VMPQVoIIWF7Z74NltPZZpx2f+cocESM+" "ILzQW9p+BC8x5IWz7N4Str2WLGKMdgmaBfNkEhSHQDU0IJEOnpUt0HmjhFaBlx0/" "LTmhua+rQ6Wup8ezLwfg==", uint64_t{0x933faea858832b73}}, {"hTKHlRxx6Pl4gjG+6ksvvj0CWFicUg3WrPdSJypDpq91LUWRni2KF6+" "81ZoHBFhEBrCdogKqeK+hy9bLDnx7g6rAFUjtn1+cWzQ2YjiOpz4+" "ROBB7lnwjyTGWzJD1rXtlso1g2qVH8XJVigC5M9AIxM=", uint64_t{0x53d061e5f8e7c04f}}, {"IWQBelSQnhrr0F3BhUpXUIDauhX6f95Qp+A0diFXiUK7irwPG1oqBiqHyK/SH/" "9S+" "rln9DlFROAmeFdH0OCJi2tFm4afxYzJTFR4HnR4cG4x12JqHaZLQx6iiu6CE3rtWBVz99oA" "wCZUOEXIsLU24o2Y", uint64_t{0xdb4124556dd515e0}}, {"TKo+l+" "1dOXdLvIrFqeLaHdm0HZnbcdEgOoLVcGRiCbAMR0j5pIFw8D36tefckAS1RCFOH5IgP8yiF" "T0Gd0a2hI3+" "fTKA7iK96NekxWeoeqzJyctc6QsoiyBlkZerRxs5RplrxoeNg29kKDTM0K94mnhD9g==", uint64_t{0x4fb31a0dd681ee71}}, {"YU4e7G6EfQYvxCFoCrrT0EFgVLHFfOWRTJQJ5gxM3G2b+" "1kJf9YPrpsxF6Xr6nYtS8reEEbDoZJYqnlk9lXSkVArm88Cqn6d25VCx3+" "49MqC0trIlXtb7SXUUhwpJK16T0hJUfPH7s5cMZXc6YmmbFuBNPE=", uint64_t{0x27cc72eefa138e4c}}, {"/I/" "eImMwPo1U6wekNFD1Jxjk9XQVi1D+" "FPdqcHifYXQuP5aScNQfxMAmaPR2XhuOQhADV5tTVbBKwCDCX4E3jcDNHzCiPvViZF1W27t" "xaf2BbFQdwKrNCmrtzcluBFYu0XZfc7RU1RmxK/RtnF1qHsq/O4pp", uint64_t{0x44bc2dfba4bd3ced}}, {"CJTT9WGcY2XykTdo8KodRIA29qsqY0iHzWZRjKHb9alwyJ7RZAE3V5Juv4MY3MeYEr1EPCC" "MxO7yFXqT8XA8YTjaMp3bafRt17Pw8JC4iKJ1zN+WWKOESrj+" "3aluGQqn8z1EzqY4PH7rLG575PYeWsP98BugdA==", uint64_t{0x242da1e3a439bed8}}, {"ZlhyQwLhXQyIUEnMH/" "AEW27vh9xrbNKJxpWGtrEmKhd+nFqAfbeNBQjW0SfG1YI0xQkQMHXjuTt4P/" "EpZRtA47ibZDVS8TtaxwyBjuIDwqcN09eCtpC+Ls+" "vWDTLmBeDM3u4hmzz4DQAYsLiZYSJcldg9Q3wszw=", uint64_t{0xdc559c746e35c139}}, {"v2KU8y0sCrBghmnm8lzGJlwo6D6ObccAxCf10heoDtYLosk4ztTpLlpSFEyu23MLA1tJkcg" "Rko04h19QMG0mOw/" "wc93EXAweriBqXfvdaP85sZABwiKO+6rtS9pacRVpYYhHJeVTQ5NzrvBvi1huxAr+" "xswhVMfL", uint64_t{0xd0b0350275b9989}}, {"QhKlnIS6BuVCTQsnoE67E/" "yrgogE8EwO7xLaEGei26m0gEU4OksefJgppDh3X0x0Cs78Dr9IHK5b977CmZlrTRmwhlP8p" "M+UzXPNRNIZuN3ntOum/QhUWP8SGpirheXENWsXMQ/" "nxtxakyEtrNkKk471Oov9juP8oQ==", uint64_t{0xb04489e41d17730c}}, {"/ZRMgnoRt+Uo6fUPr9FqQvKX7syhgVqWu+" "WUSsiQ68UlN0efSP6Eced5gJZL6tg9gcYJIkhjuQNITU0Q3TjVAnAcobgbJikCn6qZ6pRxK" "BY4MTiAlfGD3T7R7hwJwx554MAy++Zb/YUFlnCaCJiwQMnowF7aQzwYFCo=", uint64_t{0x2217285eb4572156}}, {"NB7tU5fNE8nI+SXGfipc7sRkhnSkUF1krjeo6k+8FITaAtdyz+" "o7mONgXmGLulBPH9bEwyYhKNVY0L+njNQrZ9YC2aXsFD3PdZsxAFaBT3VXEzh+" "NGBTjDASNL3mXyS8Yv1iThGfHoY7T4aR0NYGJ+k+pR6f+KrPC96M", uint64_t{0x12c2e8e68aede73b}}, {"8T6wrqCtEO6/rwxF6lvMeyuigVOLwPipX/FULvwyu+1wa5sQGav/" "2FsLHUVn6cGSi0LlFwLewGHPFJDLR0u4t7ZUyM "x6da0sWgOa5hzDqjsVGmjxEHXiaXKW3i4iSZNuxoNbMQkIbVML+" "DkYu9ND0O2swg4itGeVSzXA==", uint64_t{0x4d612125bdc4fd00}}, {"Ntf1bMRdondtMv1CYr3G80iDJ4WSAlKy5H34XdGruQiCrnRGDBa+" "eUi7vKp4gp3BBcVGl8eYSasVQQjn7MLvb3BjtXx6c/" "bCL7JtpzQKaDnPr9GWRxpBXVxKREgMM7d8lm35EODv0w+" "hQLfVSh8OGs7fsBb68nNWPLeeSOo=", uint64_t{0x81826b553954464e}}, {"VsSAw72Ro6xks02kaiLuiTEIWBC5bgqr4WDnmP8vglXzAhixk7td926rm9jNimL+" "kroPSygZ9gl63aF5DCPOACXmsbmhDrAQuUzoh9ZKhWgElLQsrqo1KIjWoZT5b5QfVUXY9lS" "IBg3U75SqORoTPq7HalxxoIT5diWOcJQi", uint64_t{0xc2e5d345dc0ddd2d}}, {"j+loZ+C87+" "bJxNVebg94gU0mSLeDulcHs84tQT7BZM2rzDSLiCNxUedHr1ZWJ9ejTiBa0dqy2I2ABc++" "xzOLcv+ "O6xO+XOBhOWAQ+IHJVHf7wZnDxIXB8AUHsnjEISKj7823biqXjyP3g==", uint64_t{0x3da6830a9e32631e}}, {"f3LlpcPElMkspNtDq5xXyWU62erEaKn7RWKlo540gR6mZsNpK1czV/" "sOmqaq8XAQLEn68LKj6/" "cFkJukxRzCa4OF1a7cCAXYFp9+wZDu0bw4y63qbpjhdCl8GO6Z2lkcXy7KOzbPE01ukg7+" "gN+7uKpoohgAhIwpAKQXmX5xtd0=", uint64_t{0xc9ae5c8759b4877a}}, }; #if defined(ABSL_IS_BIG_ENDIAN) constexpr uint64_t kGolden[kNumGoldenOutputs] = { 0x4c34aacf38f6eee4, 0x88b1366815e50b88, 0x1a36bd0c6150fb9c, 0xa783aba8a67366c7, 0x5e4a92123ae874f2, 0x0cc9ecf27067ee9a, 0xbe77aa94940527f9, 0x7ea5c12f2669fe31, 0xa33eed8737d946b9, 0x310aec5b1340bb36, 0x354e400861c5d8ff, 0x15be98166adcf42f, 0xc51910b62a90ae51, 0x539d47fc7fdf6a1f, 0x3ebba9daa46eef93, 0xd96bcd3a9113c17f, 0xc78eaf6256ded15a, 0x98902ed321c2f0d9, 0x75a4ac96414b954a, 0x2cb90e00a39e307b, 0x46539574626c3637, 0x186ec89a2be3ff45, 0x972a3bf7531519d2, 0xa14df0d25922364b, 0xa351e19d22752109, 0x08bd311d8fed4f82, 0xea2b52ddc6af54f9, 0x5f20549941338336, 0xd43b07422dc2782e, 0x377c68e2acda4835, 0x1b31a0a663b1d7b3, 0x7388ba5d68058a1a, 0xe382794ea816f032, 0xd4c3fe7889276ee0, 0x2833030545582ea9, 0x554d32a55e55df32, 0x8d6d33d7e17b424d, 0xe51a193d03ae1e34, 0xabb6a80835bd66b3, 0x0e4ba5293f9ce9b7, 0x1ebd8642cb762cdf, 0xcb54b555850888ee, 0x1e4195e4717c701f, 0x6235a13937f6532a, 0xd460960741e845c0, 0x2a72168a2d6af7b1, 0x6be38fbbfc5b17de, 0x4ee97cffa0d0fb39, 0xfdf1119ad5e71a55, 0x0dff7f66b3070727, 0x812d791d6ed62744, 0x60962919074b70b8, 0x956fa5c7d6872547, 0xee892daa58aae597, 0xeeda546e998ee369, 0x454481f5eb9b1fa8, 0x1054394634c98b1b, 0x55bb425415f591fb, 0x9601fa97416232c4, 0xd7a18506519daad7, 0x90935cb5de039acf, 0xe64054c5146ed359, 0xe5b323fb1e866c09, 0x10a472555f5ba1bc, 0xe3c0cd57d26e0972, 0x7ca3db7c121da3e8, 0x7004a89c800bb466, 0x865f69c1a1ff7f39, 0xbe0edd48f0cf2b99, 0x10e5e4ba3cc400f5, 0xafc2b91a220eef50, 0x6f04a259289b24f1, 0x2179a8070e880ef0, 0xd6a9a3d023a740c2, 0x96e6d7954755d9b8, 0xc8e4bddecce5af9f, 0x93941f0fbc724c92, 0xbef5fb15bf76a479, 0x534dca8f5da86529, 0x70789790feec116b, 0x2a296e167eea1fe9, 0x54cb1efd2a3ec7ea, 0x357b43897dfeb9f7, 0xd1eda89bc7ff89d3, 0x434f2e10cbb83c98, 0xeec4cdac46ca69ce, 0xd46aafd52a303206, 0x4bf05968ff50a5c9, 0x71c533747a6292df, 0xa40bd0d16a36118c, 0x597b4ee310c395ab, 0xc5b3e3e386172583, 0x12ca0b32284e6c70, 0xb48995fadcf35630, 0x0646368454cd217d, 0xa21c168e40d765b5, 0x4260d3811337da30, 0xb72728a01cff78e4, 0x8586920947f4756f, 0xc21e5f853cae7dc1, 0xf08c9533be9de285, 0x72df06653b4256d6, 0xf7b7f937f8db1779, 0x976db27dd0418127, 0x9ce863b7bc3f9e00, 0xebb679854fcf3a0a, 0x2ccebabbcf1afa99, 0x44201d6be451dac5, 0xb4af71c0e9a537d1, 0xad8fe9bb33ed2681, 0xcb30128bb68df43b, 0x154d8328903e8d07, 0x5844276dabeabdff, 0xd99017d7d36d930b, 0xabb0b4774fb261ca, 0x0a43f075d62e67e0, 0x8df7b371355ada6b, 0xf4c7a40d06513dcf, 0x257a3615955a0372, 0x987ac410bba74c06, 0xa011a46f25a632a2, 0xa14384b963ddd995, 0xf51b6b8cf9d50ba7, 0x3acdb91ee3abf18d, 0x34e799be08920e8c, 0x8766748a31304b36, 0x0aa239d5d0092f2e, 0xadf473ed26628594, 0xc4094b798eb4b79b, 0xe04ee5f33cd130f4, 0x85045d098c341d46, 0xf936cdf115a890ec, 0x51d137b6d8d2eb4f, 0xd10738bb2fccc1ef, }; #else constexpr uint64_t kGolden[kNumGoldenOutputs] = { 0x4c34aacf38f6eee4, 0x88b1366815e50b88, 0x1a36bd0c6150fb9c, 0xa783aba8a67366c7, 0xbc89ebdc622314e4, 0x632bc3cfcc7544d8, 0xbe77aa94940527f9, 0x7ea5c12f2669fe31, 0xa33eed8737d946b9, 0x74d832ea11fd18ab, 0x49c0487486246cdc, 0x3fdd986c87ddb0a0, 0xac3fa52a64d7c09a, 0xbff0e330196e7ed2, 0x8c8138d3ad7d3cce, 0x968c7d4b48e93778, 0xa04c78d3a421f529, 0x8854bc9c3c3c0241, 0xcccfcdf5a41113fe, 0xe6fc63dc543d984d, 0x00a39ff89e903c05, 0xaf7e9da25f9a26f9, 0x6e269a13d01a43df, 0x846d2300ce2ecdf8, 0xe7ea8c8f08478260, 0x9a2db0d62f6232f3, 0x6f66c761d168c59f, 0x55f9feacaae82043, 0x518084043700f614, 0xb0c8cfc11bead99f, 0xe4a68fdab6359d80, 0x97b17caa8f92236e, 0x96edf5e8363643dc, 0x9b3fbcd8d5b254cd, 0x22a263621d9b3a8b, 0xde90bf6f81800a6d, 0x1b51cae38c2e9513, 0x689215b3c414ef21, 0x064dc85afae8f557, 0xa2f3a8b51f408378, 0x6907c197ec1f6a3b, 0xfe83a42ef5c1cf13, 0x9b8b1d8f7a20cc13, 0x1f1681d52ca895d0, 0xd7b1670bf28e0f96, 0xb32f20f82d8b038a, 0x6a61d030fb2f5253, 0x8eb2bb0bc29ebb39, 0x144f36f7a9eef95c, 0xe77aa47d29808d8c, 0xf14d34c1fc568bad, 0x9796dcd4383f3c73, 0xa2f685fc1be7225b, 0xf3791295b16068b1, 0xb6b8f63424618948, 0x8ac4fd587045db19, 0x7e2aec2c34feb72e, 0x72e135a6910ccbb1, 0x661ff16f3c904e6f, 0xdf92cf9d67ca092d, 0x98a9953d79722eef, 0xe0649ed2181d1707, 0xcd8b8478636a297b, 0x9516258709c8471b, 0xc703b675b51f4394, 0xdb740eae020139f3, 0x57d1499ac4212ff2, 0x355cc03713d43825, 0x0e71ac9b8b1e101e, 0x8029fa72258ff559, 0xa2159726b4c16a50, 0x04e61582fba43007, 0xdab25af835be8cce, 0x13510b1b184705ee, 0xabdbc9e53666fdeb, 0x94a788fcb8173cef, 0x750d5e031286e722, 0x02559e72f4f5b497, 0x7d6e0e5996a646fa, 0x66e871b73b014132, 0x2ec170083f8b784f, 0x34ac9540cfce3fd9, 0x75c5622c6aad1295, 0xf799a6bb2651acc1, 0x8f6bcd3145bdc452, 0xddd9d326eb584a04, 0x5411af1e3532f8dc, 0xeb34722f2ad0f509, 0x835bc952a82298cc, 0xeb3839ff60ea92ad, 0x70bddf1bcdc8a4bc, 0x4bfb3ee86fcde525, 0xc7b3b93b81dfa386, 0xe66db544d57997e8, 0xf68a1b83fd363187, 0xe9b99bec615b171b, 0x093fba04d04ad28a, 0xba6117ed4231a303, 0x594bef25f9d4e206, 0x0a8cba60578b8f67, 0x88f6c7ca10b06019, 0x32a74082aef17b08, 0xe758222f971e22df, 0x4af14ff4a593e51e, 0xdba651e16cb09044, 0x3f3ac837d181eaac, 0xa5589a3f89610c01, 0xd409a7c3a18d5643, 0x8a89444f82962f26, 0x22eb62a13b9771b9, 0xd3a617615256ddd8, 0x7089b990c4bba297, 0x7d752893783eac4f, 0x1f2fcbb79372c915, 0x67a4446b17eb9839, 0x70d11df5cae46788, 0x52621e1780b47d0f, 0xcf63b93a6e590ee6, 0xb6bc96b58ee064b8, 0x2587f8d635ca9c75, 0xc6bddd62ec5e5d01, 0x957398ad3009cdb7, 0x05b6890b20bcd0d3, 0xbe6e965ff837222e, 0x47383a87d2b04b1a, 0x7d42207e6d8d7950, 0x7e981ed12a7f4aa3, 0xdebb05b30769441a, 0xaac5d86f4ff76c49, 0x384f195ca3248331, 0xec4c4b855e909ca1, 0x6a7eeb5a657d73d5, 0x9efbebe2fa9c2791, 0x19e7fa0546900c4d, }; #endif #if UPDATE_GOLDEN (void)kGolden; for (size_t i = 0; i < kNumGoldenOutputs; ++i) { std::string str; ASSERT_TRUE(absl::Base64Unescape(cases[i].base64_data, &str)); uint64_t h = absl::hash_internal::LowLevelHash(str.data(), str.size(), cases[i].seed, kSalt); printf("0x%016" PRIx64 ", ", h); if (i % 3 == 2) { printf("\n"); } } printf("\n\n\n"); EXPECT_FALSE(true); #else for (size_t i = 0; i < kNumGoldenOutputs; ++i) { SCOPED_TRACE(::testing::Message() << "i = " << i << "; input = " << cases[i].base64_data); std::string str; ASSERT_TRUE(absl::Base64Unescape(cases[i].base64_data, &str)); EXPECT_EQ(absl::hash_internal::LowLevelHash(str.data(), str.size(), cases[i].seed, kSalt), kGolden[i]); } #endif } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/hash/internal/low_level_hash.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/hash/internal/low_level_hash_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
28dc5ec3-deef-479b-9dd9-8be3d29407df
cpp
abseil/abseil-cpp
hash
absl/hash/internal/hash.cc
absl/hash/hash_test.cc
#include "absl/hash/internal/hash.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace hash_internal { uint64_t MixingHashState::CombineLargeContiguousImpl32( uint64_t state, const unsigned char* first, size_t len) { while (len >= PiecewiseChunkSize()) { state = Mix(state, hash_internal::CityHash32(reinterpret_cast<const char*>(first), PiecewiseChunkSize())); len -= PiecewiseChunkSize(); first += PiecewiseChunkSize(); } return CombineContiguousImpl(state, first, len, std::integral_constant<int, 4>{}); } uint64_t MixingHashState::CombineLargeContiguousImpl64( uint64_t state, const unsigned char* first, size_t len) { while (len >= PiecewiseChunkSize()) { state = Mix(state, Hash64(first, PiecewiseChunkSize())); len -= PiecewiseChunkSize(); first += PiecewiseChunkSize(); } return CombineContiguousImpl(state, first, len, std::integral_constant<int, 8>{}); } ABSL_CONST_INIT const void* const MixingHashState::kSeed = &kSeed; constexpr uint64_t kHashSalt[5] = { uint64_t{0x243F6A8885A308D3}, uint64_t{0x13198A2E03707344}, uint64_t{0xA4093822299F31D0}, uint64_t{0x082EFA98EC4E6C89}, uint64_t{0x452821E638D01377}, }; uint64_t MixingHashState::LowLevelHashImpl(const unsigned char* data, size_t len) { return LowLevelHashLenGt16(data, len, Seed(), kHashSalt); } } ABSL_NAMESPACE_END }
#include "absl/hash/hash.h" #include <algorithm> #include <array> #include <bitset> #include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> #include <functional> #include <initializer_list> #include <ios> #include <limits> #include <memory> #include <ostream> #include <set> #include <string> #include <tuple> #include <type_traits> #include <unordered_map> #include <utility> #include <vector> #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/container/flat_hash_set.h" #include "absl/hash/hash_testing.h" #include "absl/hash/internal/hash_test.h" #include "absl/hash/internal/spy_hash_state.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/strings/cord_test_helpers.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/types/variant.h" #ifdef ABSL_INTERNAL_STD_FILESYSTEM_PATH_HASH_AVAILABLE #include <filesystem> #endif #ifdef ABSL_HAVE_STD_STRING_VIEW #include <string_view> #endif namespace { using ::absl::hash_test_internal::is_hashable; using ::absl::hash_test_internal::TypeErasedContainer; using ::absl::hash_test_internal::TypeErasedValue; template <typename T> using TypeErasedVector = TypeErasedContainer<std::vector<T>>; using absl::Hash; using absl::hash_internal::SpyHashState; template <typename T> class HashValueIntTest : public testing::Test { }; TYPED_TEST_SUITE_P(HashValueIntTest); template <typename T> SpyHashState SpyHash(const T& value) { return SpyHashState::combine(SpyHashState(), value); } TYPED_TEST_P(HashValueIntTest, BasicUsage) { EXPECT_TRUE((is_hashable<TypeParam>::value)); TypeParam n = 42; EXPECT_EQ(SpyHash(n), SpyHash(TypeParam{42})); EXPECT_NE(SpyHash(n), SpyHash(TypeParam{0})); EXPECT_NE(SpyHash(std::numeric_limits<TypeParam>::max()), SpyHash(std::numeric_limits<TypeParam>::min())); } TYPED_TEST_P(HashValueIntTest, FastPath) { TypeParam n = 42; EXPECT_EQ(absl::Hash<TypeParam>{}(n), absl::Hash<std::tuple<TypeParam>>{}(std::tuple<TypeParam>(n))); } REGISTER_TYPED_TEST_SUITE_P(HashValueIntTest, BasicUsage, FastPath); using IntTypes = testing::Types<unsigned char, char, int, int32_t, int64_t, uint32_t, uint64_t, size_t>; INSTANTIATE_TYPED_TEST_SUITE_P(My, HashValueIntTest, IntTypes); enum LegacyEnum { kValue1, kValue2, kValue3 }; enum class EnumClass { kValue4, kValue5, kValue6 }; TEST(HashValueTest, EnumAndBool) { EXPECT_TRUE((is_hashable<LegacyEnum>::value)); EXPECT_TRUE((is_hashable<EnumClass>::value)); EXPECT_TRUE((is_hashable<bool>::value)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( LegacyEnum::kValue1, LegacyEnum::kValue2, LegacyEnum::kValue3))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( EnumClass::kValue4, EnumClass::kValue5, EnumClass::kValue6))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(true, false))); } TEST(HashValueTest, FloatingPoint) { EXPECT_TRUE((is_hashable<float>::value)); EXPECT_TRUE((is_hashable<double>::value)); EXPECT_TRUE((is_hashable<long double>::value)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(42.f, 0.f, -0.f, std::numeric_limits<float>::infinity(), -std::numeric_limits<float>::infinity()))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(42., 0., -0., std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity()))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( .5L, 1.L, 2.L, 4.L, 42.L, 0.L, -0.L, 17 * static_cast<long double>(std::numeric_limits<double>::max()), std::numeric_limits<long double>::infinity(), -std::numeric_limits<long double>::infinity()))); } TEST(HashValueTest, Pointer) { EXPECT_TRUE((is_hashable<int*>::value)); EXPECT_TRUE((is_hashable<int(*)(char, float)>::value)); EXPECT_TRUE((is_hashable<void(*)(int, int, ...)>::value)); int i; int* ptr = &i; int* n = nullptr; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(&i, ptr, nullptr, ptr + 1, n))); } TEST(HashValueTest, PointerAlignment) { constexpr size_t kTotalSize = 1 << 20; std::unique_ptr<char[]> data(new char[kTotalSize]); constexpr size_t kLog2NumValues = 5; constexpr size_t kNumValues = 1 << kLog2NumValues; for (size_t align = 1; align < kTotalSize / kNumValues; align < 8 ? align += 1 : align < 1024 ? align += 8 : align += 32) { SCOPED_TRACE(align); ASSERT_LE(align * kNumValues, kTotalSize); size_t bits_or = 0; size_t bits_and = ~size_t{}; for (size_t i = 0; i < kNumValues; ++i) { size_t hash = absl::Hash<void*>()(data.get() + i * align); bits_or |= hash; bits_and &= hash; } constexpr size_t kMask = (1 << (kLog2NumValues + 7)) - 1; size_t stuck_bits = (~bits_or | bits_and) & kMask; EXPECT_EQ(stuck_bits, 0u) << "0x" << std::hex << stuck_bits; } } TEST(HashValueTest, PointerToMember) { struct Bass { void q() {} }; struct A : Bass { virtual ~A() = default; virtual void vfa() {} static auto pq() -> void (A::*)() { return &A::q; } }; struct B : Bass { virtual ~B() = default; virtual void vfb() {} static auto pq() -> void (B::*)() { return &B::q; } }; struct Foo : A, B { void f1() {} void f2() const {} int g1() & { return 0; } int g2() const & { return 0; } int g3() && { return 0; } int g4() const && { return 0; } int h1() & { return 0; } int h2() const & { return 0; } int h3() && { return 0; } int h4() const && { return 0; } int a; int b; const int c = 11; const int d = 22; }; EXPECT_TRUE((is_hashable<float Foo::*>::value)); EXPECT_TRUE((is_hashable<double (Foo::*)(int, int)&&>::value)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(&Foo::a, &Foo::b, static_cast<int Foo::*>(nullptr)))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(&Foo::c, &Foo::d, static_cast<const int Foo::*>(nullptr), &Foo::a, &Foo::b))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( &Foo::f1, static_cast<void (Foo::*)()>(nullptr)))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( &Foo::f2, static_cast<void (Foo::*)() const>(nullptr)))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( &Foo::g1, &Foo::h1, static_cast<int (Foo::*)() &>(nullptr)))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( &Foo::g2, &Foo::h2, static_cast<int (Foo::*)() const &>(nullptr)))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( &Foo::g3, &Foo::h3, static_cast<int (Foo::*)() &&>(nullptr)))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( &Foo::g4, &Foo::h4, static_cast<int (Foo::*)() const &&>(nullptr)))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(static_cast<void (Foo::*)()>(&Foo::vfa), static_cast<void (Foo::*)()>(&Foo::vfb), static_cast<void (Foo::*)()>(nullptr)))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(static_cast<void (Foo::*)()>(Foo::A::pq()), static_cast<void (Foo::*)()>(Foo::B::pq()), static_cast<void (Foo::*)()>(nullptr)))); } TEST(HashValueTest, PairAndTuple) { EXPECT_TRUE((is_hashable<std::pair<int, int>>::value)); EXPECT_TRUE((is_hashable<std::pair<const int&, const int&>>::value)); EXPECT_TRUE((is_hashable<std::tuple<int&, int&>>::value)); EXPECT_TRUE((is_hashable<std::tuple<int&&, int&&>>::value)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( std::make_pair(0, 42), std::make_pair(0, 42), std::make_pair(42, 0), std::make_pair(0, 0), std::make_pair(42, 42), std::make_pair(1, 42)))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(std::make_tuple(0, 0, 0), std::make_tuple(0, 0, 42), std::make_tuple(0, 23, 0), std::make_tuple(17, 0, 0), std::make_tuple(42, 0, 0), std::make_tuple(3, 9, 9), std::make_tuple(0, 0, -42)))); int a = 0, b = 1, c = 17, d = 23; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( std::tie(a, a), std::tie(a, b), std::tie(b, c), std::tie(c, d)))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( std::forward_as_tuple(0, 0, 0), std::forward_as_tuple(0, 0, 42), std::forward_as_tuple(0, 23, 0), std::forward_as_tuple(17, 0, 0), std::forward_as_tuple(42, 0, 0), std::forward_as_tuple(3, 9, 9), std::forward_as_tuple(0, 0, -42)))); } TEST(HashValueTest, CombineContiguousWorks) { std::vector<std::tuple<int>> v1 = {std::make_tuple(1), std::make_tuple(3)}; std::vector<std::tuple<int>> v2 = {std::make_tuple(1), std::make_tuple(2)}; auto vh1 = SpyHash(v1); auto vh2 = SpyHash(v2); EXPECT_NE(vh1, vh2); } struct DummyDeleter { template <typename T> void operator() (T* ptr) {} }; struct SmartPointerEq { template <typename T, typename U> bool operator()(const T& t, const U& u) const { return GetPtr(t) == GetPtr(u); } template <typename T> static auto GetPtr(const T& t) -> decltype(&*t) { return t ? &*t : nullptr; } static std::nullptr_t GetPtr(std::nullptr_t) { return nullptr; } }; TEST(HashValueTest, SmartPointers) { EXPECT_TRUE((is_hashable<std::unique_ptr<int>>::value)); EXPECT_TRUE((is_hashable<std::unique_ptr<int, DummyDeleter>>::value)); EXPECT_TRUE((is_hashable<std::shared_ptr<int>>::value)); int i, j; std::unique_ptr<int, DummyDeleter> unique1(&i); std::unique_ptr<int, DummyDeleter> unique2(&i); std::unique_ptr<int, DummyDeleter> unique_other(&j); std::unique_ptr<int, DummyDeleter> unique_null; std::shared_ptr<int> shared1(&i, DummyDeleter()); std::shared_ptr<int> shared2(&i, DummyDeleter()); std::shared_ptr<int> shared_other(&j, DummyDeleter()); std::shared_ptr<int> shared_null; ASSERT_TRUE(SmartPointerEq{}(unique1, shared1)); ASSERT_FALSE(SmartPointerEq{}(unique1, shared_other)); ASSERT_TRUE(SmartPointerEq{}(unique_null, nullptr)); ASSERT_FALSE(SmartPointerEq{}(shared2, nullptr)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::forward_as_tuple(&i, nullptr, unique1, unique2, unique_null, absl::make_unique<int>(), shared1, shared2, shared_null, std::make_shared<int>()), SmartPointerEq{})); } TEST(HashValueTest, FunctionPointer) { using Func = int (*)(); EXPECT_TRUE(is_hashable<Func>::value); Func p1 = [] { return 2; }, p2 = [] { return 1; }; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(p1, p2, nullptr))); } struct WrapInTuple { template <typename T> std::tuple<int, T, size_t> operator()(const T& t) const { return std::make_tuple(7, t, 0xdeadbeef); } }; absl::Cord FlatCord(absl::string_view sv) { absl::Cord c(sv); c.Flatten(); return c; } absl::Cord FragmentedCord(absl::string_view sv) { if (sv.size() < 2) { return absl::Cord(sv); } size_t halfway = sv.size() / 2; std::vector<absl::string_view> parts = {sv.substr(0, halfway), sv.substr(halfway)}; return absl::MakeFragmentedCord(parts); } TEST(HashValueTest, Strings) { EXPECT_TRUE((is_hashable<std::string>::value)); const std::string small = "foo"; const std::string dup = "foofoo"; const std::string large = std::string(2048, 'x'); const std::string huge = std::string(5000, 'a'); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( std::string(), absl::string_view(), absl::Cord(), std::string(""), absl::string_view(""), absl::Cord(""), std::string(small), absl::string_view(small), absl::Cord(small), std::string(dup), absl::string_view(dup), absl::Cord(dup), std::string(large), absl::string_view(large), absl::Cord(large), std::string(huge), absl::string_view(huge), FlatCord(huge), FragmentedCord(huge)))); const WrapInTuple t{}; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( t(std::string()), t(absl::string_view()), t(absl::Cord()), t(std::string("")), t(absl::string_view("")), t(absl::Cord("")), t(std::string(small)), t(absl::string_view(small)), t(absl::Cord(small)), t(std::string(dup)), t(absl::string_view(dup)), t(absl::Cord(dup)), t(std::string(large)), t(absl::string_view(large)), t(absl::Cord(large)), t(std::string(huge)), t(absl::string_view(huge)), t(FlatCord(huge)), t(FragmentedCord(huge))))); EXPECT_NE(SpyHash(static_cast<const char*>("ABC")), SpyHash(absl::string_view("ABC"))); } TEST(HashValueTest, WString) { EXPECT_TRUE((is_hashable<std::wstring>::value)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( std::wstring(), std::wstring(L"ABC"), std::wstring(L"ABC"), std::wstring(L"Some other different string"), std::wstring(L"Iñtërnâtiônàlizætiøn")))); } TEST(HashValueTest, U16String) { EXPECT_TRUE((is_hashable<std::u16string>::value)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( std::u16string(), std::u16string(u"ABC"), std::u16string(u"ABC"), std::u16string(u"Some other different string"), std::u16string(u"Iñtërnâtiônàlizætiøn")))); } TEST(HashValueTest, U32String) { EXPECT_TRUE((is_hashable<std::u32string>::value)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( std::u32string(), std::u32string(U"ABC"), std::u32string(U"ABC"), std::u32string(U"Some other different string"), std::u32string(U"Iñtërnâtiônàlizætiøn")))); } TEST(HashValueTest, WStringView) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else EXPECT_TRUE((is_hashable<std::wstring_view>::value)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( std::wstring_view(), std::wstring_view(L"ABC"), std::wstring_view(L"ABC"), std::wstring_view(L"Some other different string_view"), std::wstring_view(L"Iñtërnâtiônàlizætiøn")))); #endif } TEST(HashValueTest, U16StringView) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else EXPECT_TRUE((is_hashable<std::u16string_view>::value)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(std::u16string_view(), std::u16string_view(u"ABC"), std::u16string_view(u"ABC"), std::u16string_view(u"Some other different string_view"), std::u16string_view(u"Iñtërnâtiônàlizætiøn")))); #endif } TEST(HashValueTest, U32StringView) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else EXPECT_TRUE((is_hashable<std::u32string_view>::value)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(std::u32string_view(), std::u32string_view(U"ABC"), std::u32string_view(U"ABC"), std::u32string_view(U"Some other different string_view"), std::u32string_view(U"Iñtërnâtiônàlizætiøn")))); #endif } TEST(HashValueTest, StdFilesystemPath) { #ifndef ABSL_INTERNAL_STD_FILESYSTEM_PATH_HASH_AVAILABLE GTEST_SKIP() << "std::filesystem::path is unavailable on this platform"; #else EXPECT_TRUE((is_hashable<std::filesystem::path>::value)); const auto kTestCases = std::make_tuple( std::filesystem::path(), std::filesystem::path("/"), #ifndef __GLIBCXX__ std::filesystem::path(" #endif std::filesystem::path("/a/b"), std::filesystem::path("/a std::filesystem::path("a/b"), std::filesystem::path("a/b/"), std::filesystem::path("a std::filesystem::path("a std::filesystem::path("c:/"), std::filesystem::path("c:\\"), std::filesystem::path("c:\\/"), std::filesystem::path("c:\\ std::filesystem::path("c: std::filesystem::path("c: std::filesystem::path("/e/p"), std::filesystem::path("/s/../e/p"), std::filesystem::path("e/p"), std::filesystem::path("s/../e/p")); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(kTestCases)); #endif } TEST(HashValueTest, StdArray) { EXPECT_TRUE((is_hashable<std::array<int, 3>>::value)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(std::array<int, 3>{}, std::array<int, 3>{{0, 23, 42}}))); } TEST(HashValueTest, StdBitset) { EXPECT_TRUE((is_hashable<std::bitset<257>>::value)); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( {std::bitset<2>("00"), std::bitset<2>("01"), std::bitset<2>("10"), std::bitset<2>("11")})); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( {std::bitset<5>("10101"), std::bitset<5>("10001"), std::bitset<5>()})); constexpr int kNumBits = 256; std::array<std::string, 6> bit_strings; bit_strings.fill(std::string(kNumBits, '1')); bit_strings[1][0] = '0'; bit_strings[2][1] = '0'; bit_strings[3][kNumBits / 3] = '0'; bit_strings[4][kNumBits - 2] = '0'; bit_strings[5][kNumBits - 1] = '0'; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( {std::bitset<kNumBits>(bit_strings[0].c_str()), std::bitset<kNumBits>(bit_strings[1].c_str()), std::bitset<kNumBits>(bit_strings[2].c_str()), std::bitset<kNumBits>(bit_strings[3].c_str()), std::bitset<kNumBits>(bit_strings[4].c_str()), std::bitset<kNumBits>(bit_strings[5].c_str())})); } struct Private { int i; template <typename H> friend H AbslHashValue(H h, Private p) { return H::combine(std::move(h), std::abs(p.i)); } friend bool operator==(Private a, Private b) { return std::abs(a.i) == std::abs(b.i); } friend std::ostream& operator<<(std::ostream& o, Private p) { return o << p.i; } }; class PiecewiseHashTester { public: explicit PiecewiseHashTester(absl::string_view buf) : buf_(buf), piecewise_(false), split_locations_() {} PiecewiseHashTester(absl::string_view buf, std::set<size_t> split_locations) : buf_(buf), piecewise_(true), split_locations_(std::move(split_locations)) {} template <typename H> friend H AbslHashValue(H h, const PiecewiseHashTester& p) { if (!p.piecewise_) { return H::combine_contiguous(std::move(h), p.buf_.data(), p.buf_.size()); } absl::hash_internal::PiecewiseCombiner combiner; if (p.split_locations_.empty()) { h = combiner.add_buffer(std::move(h), p.buf_.data(), p.buf_.size()); return combiner.finalize(std::move(h)); } size_t begin = 0; for (size_t next : p.split_locations_) { absl::string_view chunk = p.buf_.substr(begin, next - begin); h = combiner.add_buffer(std::move(h), chunk.data(), chunk.size()); begin = next; } absl::string_view last_chunk = p.buf_.substr(begin); if (!last_chunk.empty()) { h = combiner.add_buffer(std::move(h), last_chunk.data(), last_chunk.size()); } return combiner.finalize(std::move(h)); } private: absl::string_view buf_; bool piecewise_; std::set<size_t> split_locations_; }; struct DummyFooBar { template <typename H> friend H AbslHashValue(H h, const DummyFooBar&) { const char* foo = "foo"; const char* bar = "bar"; h = H::combine_contiguous(std::move(h), foo, 3); h = H::combine_contiguous(std::move(h), bar, 3); return h; } }; TEST(HashValueTest, CombinePiecewiseBuffer) { absl::Hash<PiecewiseHashTester> hash; EXPECT_EQ(hash(PiecewiseHashTester("")), hash(PiecewiseHashTester("", {}))); EXPECT_EQ(hash(PiecewiseHashTester("foobar")), hash(PiecewiseHashTester("foobar", {}))); EXPECT_EQ(hash(PiecewiseHashTester("foobar")), hash(PiecewiseHashTester("foobar", {3}))); EXPECT_NE(hash(PiecewiseHashTester("foobar", {3})), absl::Hash<DummyFooBar>()(DummyFooBar{})); for (size_t big_buffer_size : {1024u * 2 + 512u, 1024u * 3}) { SCOPED_TRACE(big_buffer_size); std::string big_buffer; for (size_t i = 0; i < big_buffer_size; ++i) { big_buffer.push_back(32 + (i * (i / 3)) % 64); } auto big_buffer_hash = hash(PiecewiseHashTester(big_buffer)); const int possible_breaks = 9; size_t breaks[possible_breaks] = {1, 512, 1023, 1024, 1025, 1536, 2047, 2048, 2049}; for (unsigned test_mask = 0; test_mask < (1u << possible_breaks); ++test_mask) { SCOPED_TRACE(test_mask); std::set<size_t> break_locations; for (int j = 0; j < possible_breaks; ++j) { if (test_mask & (1u << j)) { break_locations.insert(breaks[j]); } } EXPECT_EQ( hash(PiecewiseHashTester(big_buffer, std::move(break_locations))), big_buffer_hash); } } } TEST(HashValueTest, PrivateSanity) { EXPECT_TRUE(is_hashable<Private>::value); EXPECT_NE(SpyHash(Private{0}), SpyHash(Private{1})); EXPECT_EQ(SpyHash(Private{1}), SpyHash(Private{1})); } TEST(HashValueTest, Optional) { EXPECT_TRUE(is_hashable<absl::optional<Private>>::value); using O = absl::optional<Private>; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(O{}, O{{1}}, O{{-1}}, O{{10}}))); } TEST(HashValueTest, Variant) { using V = absl::variant<Private, std::string>; EXPECT_TRUE(is_hashable<V>::value); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( V(Private{1}), V(Private{-1}), V(Private{2}), V("ABC"), V("BCD")))); #if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ struct S {}; EXPECT_FALSE(is_hashable<absl::variant<S>>::value); #endif } TEST(HashValueTest, ReferenceWrapper) { EXPECT_TRUE(is_hashable<std::reference_wrapper<Private>>::value); Private p1{1}, p10{10}; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( p1, p10, std::ref(p1), std::ref(p10), std::cref(p1), std::cref(p10)))); EXPECT_TRUE(is_hashable<std::reference_wrapper<int>>::value); int one = 1, ten = 10; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( one, ten, std::ref(one), std::ref(ten), std::cref(one), std::cref(ten)))); EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( std::make_tuple(std::tuple<std::reference_wrapper<int>>(std::ref(one)), std::tuple<std::reference_wrapper<int>>(std::ref(ten)), std::tuple<int>(one), std::tuple<int>(ten)))); } template <typename T, typename = void> struct IsHashCallable : std::false_type {}; template <typename T> struct IsHashCallable<T, absl::void_t<decltype(std::declval<absl::Hash<T>>()( std::declval<const T&>()))>> : std::true_type {}; template <typename T, typename = void> struct IsAggregateInitializable : std::false_type {}; template <typename T> struct IsAggregateInitializable<T, absl::void_t<decltype(T{})>> : std::true_type {}; TEST(IsHashableTest, ValidHash) { EXPECT_TRUE((is_hashable<int>::value)); EXPECT_TRUE(std::is_default_constructible<absl::Hash<int>>::value); EXPECT_TRUE(std::is_copy_constructible<absl::Hash<int>>::value); EXPECT_TRUE(std::is_move_constructible<absl::Hash<int>>::value); EXPECT_TRUE(absl::is_copy_assignable<absl::Hash<int>>::value); EXPECT_TRUE(absl::is_move_assignable<absl::Hash<int>>::value); EXPECT_TRUE(IsHashCallable<int>::value); EXPECT_TRUE(IsAggregateInitializable<absl::Hash<int>>::value); } #if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ TEST(IsHashableTest, PoisonHash) { struct X {}; EXPECT_FALSE((is_hashable<X>::value)); EXPECT_FALSE(std::is_default_constructible<absl::Hash<X>>::value); EXPECT_FALSE(std::is_copy_constructible<absl::Hash<X>>::value); EXPECT_FALSE(std::is_move_constructible<absl::Hash<X>>::value); EXPECT_FALSE(absl::is_copy_assignable<absl::Hash<X>>::value); EXPECT_FALSE(absl::is_move_assignable<absl::Hash<X>>::value); EXPECT_FALSE(IsHashCallable<X>::value); #if !defined(__GNUC__) || defined(__clang__) EXPECT_FALSE(IsAggregateInitializable<absl::Hash<X>>::value); #endif } #endif struct NoOp { template <typename HashCode> friend HashCode AbslHashValue(HashCode h, NoOp n) { return h; } }; struct EmptyCombine { template <typename HashCode> friend HashCode AbslHashValue(HashCode h, EmptyCombine e) { return HashCode::combine(std::move(h)); } }; template <typename Int> struct CombineIterative { template <typename HashCode> friend HashCode AbslHashValue(HashCode h, CombineIterative c) { for (int i = 0; i < 5; ++i) { h = HashCode::combine(std::move(h), Int(i)); } return h; } }; template <typename Int> struct CombineVariadic { template <typename HashCode> friend HashCode AbslHashValue(HashCode h, CombineVariadic c) { return HashCode::combine(std::move(h), Int(0), Int(1), Int(2), Int(3), Int(4)); } }; enum class InvokeTag { kUniquelyRepresented, kHashValue, #if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_ kLegacyHash, #endif kStdHash, kNone }; template <InvokeTag T> using InvokeTagConstant = std::integral_constant<InvokeTag, T>; template <InvokeTag... Tags> struct MinTag; template <InvokeTag a, InvokeTag b, InvokeTag... Tags> struct MinTag<a, b, Tags...> : MinTag<(a < b ? a : b), Tags...> {}; template <InvokeTag a> struct MinTag<a> : InvokeTagConstant<a> {}; template <InvokeTag... Tags> struct CustomHashType { explicit CustomHashType(size_t val) : value(val) {} size_t value; }; template <InvokeTag allowed, InvokeTag... tags> struct EnableIfContained : std::enable_if<absl::disjunction< std::integral_constant<bool, allowed == tags>...>::value> {}; template < typename H, InvokeTag... Tags, typename = typename EnableIfContained<InvokeTag::kHashValue, Tags...>::type> H AbslHashValue(H state, CustomHashType<Tags...> t) { static_assert(MinTag<Tags...>::value == InvokeTag::kHashValue, ""); return H::combine(std::move(state), t.value + static_cast<int>(InvokeTag::kHashValue)); } } namespace absl { ABSL_NAMESPACE_BEGIN namespace hash_internal { template <InvokeTag... Tags> struct is_uniquely_represented< CustomHashType<Tags...>, typename EnableIfContained<InvokeTag::kUniquelyRepresented, Tags...>::type> : std::true_type {}; } ABSL_NAMESPACE_END } #if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_ namespace ABSL_INTERNAL_LEGACY_HASH_NAMESPACE { template <InvokeTag... Tags> struct hash<CustomHashType<Tags...>> { template <InvokeTag... TagsIn, typename = typename EnableIfContained< InvokeTag::kLegacyHash, TagsIn...>::type> size_t operator()(CustomHashType<TagsIn...> t) const { static_assert(MinTag<Tags...>::value == InvokeTag::kLegacyHash, ""); return t.value + static_cast<int>(InvokeTag::kLegacyHash); } }; } #endif namespace std { template <InvokeTag... Tags> struct hash<CustomHashType<Tags...>> { template <InvokeTag... TagsIn, typename = typename EnableIfContained< InvokeTag::kStdHash, TagsIn...>::type> size_t operator()(CustomHashType<TagsIn...> t) const { static_assert(MinTag<Tags...>::value == InvokeTag::kStdHash, ""); return t.value + static_cast<int>(InvokeTag::kStdHash); } }; } namespace { template <typename... T> void TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>, T...) { using type = CustomHashType<T::value...>; SCOPED_TRACE(testing::PrintToString(std::vector<InvokeTag>{T::value...})); EXPECT_TRUE(is_hashable<type>()); EXPECT_TRUE(is_hashable<const type>()); EXPECT_TRUE(is_hashable<const type&>()); const size_t offset = static_cast<int>(std::min({T::value...})); EXPECT_EQ(SpyHash(type(7)), SpyHash(size_t{7 + offset})); } void TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>) { #if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ using type = CustomHashType<>; EXPECT_FALSE(is_hashable<type>()); EXPECT_FALSE(is_hashable<const type>()); EXPECT_FALSE(is_hashable<const type&>()); #endif } template <InvokeTag Tag, typename... T> void TestCustomHashType(InvokeTagConstant<Tag> tag, T... t) { constexpr auto next = static_cast<InvokeTag>(static_cast<int>(Tag) + 1); TestCustomHashType(InvokeTagConstant<next>(), tag, t...); TestCustomHashType(InvokeTagConstant<next>(), t...); } TEST(HashTest, CustomHashType) { TestCustomHashType(InvokeTagConstant<InvokeTag{}>()); } TEST(HashTest, NoOpsAreEquivalent) { EXPECT_EQ(Hash<NoOp>()({}), Hash<NoOp>()({})); EXPECT_EQ(Hash<NoOp>()({}), Hash<EmptyCombine>()({})); } template <typename T> class HashIntTest : public testing::Test { }; TYPED_TEST_SUITE_P(HashIntTest); TYPED_TEST_P(HashIntTest, BasicUsage) { EXPECT_NE(Hash<NoOp>()({}), Hash<TypeParam>()(0)); EXPECT_NE(Hash<NoOp>()({}), Hash<TypeParam>()(std::numeric_limits<TypeParam>::max())); if (std::numeric_limits<TypeParam>::min() != 0) { EXPECT_NE(Hash<NoOp>()({}), Hash<TypeParam>()(std::numeric_limits<TypeParam>::min())); } EXPECT_EQ(Hash<CombineIterative<TypeParam>>()({}), Hash<CombineVariadic<TypeParam>>()({})); } REGISTER_TYPED_TEST_SUITE_P(HashIntTest, BasicUsage); using IntTypes = testing::Types<unsigned char, char, int, int32_t, int64_t, uint32_t, uint64_t, size_t>; INSTANTIATE_TYPED_TEST_SUITE_P(My, HashIntTest, IntTypes); struct StructWithPadding { char c; int i; template <typename H> friend H AbslHashValue(H hash_state, const StructWithPadding& s) { return H::combine(std::move(hash_state), s.c, s.i); } }; static_assert(sizeof(StructWithPadding) > sizeof(char) + sizeof(int), "StructWithPadding doesn't have padding"); static_assert(std::is_standard_layout<StructWithPadding>::value, ""); template <typename T> struct ArraySlice { T* begin; T* end; template <typename H> friend H AbslHashValue(H hash_state, const ArraySlice& slice) { for (auto t = slice.begin; t != slice.end; ++t) { hash_state = H::combine(std::move(hash_state), *t); } return hash_state; } }; TEST(HashTest, HashNonUniquelyRepresentedType) { static const size_t kNumStructs = 10; unsigned char buffer1[kNumStructs * sizeof(StructWithPadding)]; std::memset(buffer1, 0, sizeof(buffer1)); auto* s1 = reinterpret_cast<StructWithPadding*>(buffer1); unsigned char buffer2[kNumStructs * sizeof(StructWithPadding)]; std::memset(buffer2, 255, sizeof(buffer2)); auto* s2 = reinterpret_cast<StructWithPadding*>(buffer2); for (size_t i = 0; i < kNumStructs; ++i) { SCOPED_TRACE(i); s1[i].c = s2[i].c = static_cast<char>('0' + i); s1[i].i = s2[i].i = static_cast<int>(i); ASSERT_FALSE(memcmp(buffer1 + i * sizeof(StructWithPadding), buffer2 + i * sizeof(StructWithPadding), sizeof(StructWithPadding)) == 0) << "Bug in test code: objects do not have unequal" << " object representations"; } EXPECT_EQ(Hash<StructWithPadding>()(s1[0]), Hash<StructWithPadding>()(s2[0])); EXPECT_EQ(Hash<ArraySlice<StructWithPadding>>()({s1, s1 + kNumStructs}), Hash<ArraySlice<StructWithPadding>>()({s2, s2 + kNumStructs})); } TEST(HashTest, StandardHashContainerUsage) { std::unordered_map<int, std::string, Hash<int>> map = {{0, "foo"}, {42, "bar"}}; EXPECT_NE(map.find(0), map.end()); EXPECT_EQ(map.find(1), map.end()); EXPECT_NE(map.find(0u), map.end()); } struct ConvertibleFromNoOp { ConvertibleFromNoOp(NoOp) {} template <typename H> friend H AbslHashValue(H hash_state, ConvertibleFromNoOp) { return H::combine(std::move(hash_state), 1); } }; TEST(HashTest, HeterogeneousCall) { EXPECT_NE(Hash<ConvertibleFromNoOp>()(NoOp()), Hash<NoOp>()(NoOp())); } TEST(IsUniquelyRepresentedTest, SanityTest) { using absl::hash_internal::is_uniquely_represented; EXPECT_TRUE(is_uniquely_represented<unsigned char>::value); EXPECT_TRUE(is_uniquely_represented<int>::value); EXPECT_FALSE(is_uniquely_represented<bool>::value); EXPECT_FALSE(is_uniquely_represented<int*>::value); } struct IntAndString { int i; std::string s; template <typename H> friend H AbslHashValue(H hash_state, IntAndString int_and_string) { return H::combine(std::move(hash_state), int_and_string.s, int_and_string.i); } }; TEST(HashTest, SmallValueOn64ByteBoundary) { Hash<IntAndString>()(IntAndString{0, std::string(63, '0')}); } TEST(HashTest, TypeErased) { EXPECT_TRUE((is_hashable<TypeErasedValue<size_t>>::value)); EXPECT_TRUE((is_hashable<std::pair<TypeErasedValue<size_t>, int>>::value)); EXPECT_EQ(SpyHash(TypeErasedValue<size_t>(7)), SpyHash(size_t{7})); EXPECT_NE(SpyHash(TypeErasedValue<size_t>(7)), SpyHash(size_t{13})); EXPECT_EQ(SpyHash(std::make_pair(TypeErasedValue<size_t>(7), 17)), SpyHash(std::make_pair(size_t{7}, 17))); absl::flat_hash_set<absl::flat_hash_set<int>> ss = {{1, 2}, {3, 4}}; TypeErasedContainer<absl::flat_hash_set<absl::flat_hash_set<int>>> es = { absl::flat_hash_set<int>{1, 2}, {3, 4}}; absl::flat_hash_set<TypeErasedContainer<absl::flat_hash_set<int>>> se = { {1, 2}, {3, 4}}; EXPECT_EQ(SpyHash(ss), SpyHash(es)); EXPECT_EQ(SpyHash(ss), SpyHash(se)); } struct ValueWithBoolConversion { operator bool() const { return false; } int i; }; } namespace std { template <> struct hash<ValueWithBoolConversion> { size_t operator()(ValueWithBoolConversion v) { return static_cast<size_t>(v.i); } }; } namespace { TEST(HashTest, DoesNotUseImplicitConversionsToBool) { EXPECT_NE(absl::Hash<ValueWithBoolConversion>()(ValueWithBoolConversion{0}), absl::Hash<ValueWithBoolConversion>()(ValueWithBoolConversion{1})); } TEST(HashOf, MatchesHashForSingleArgument) { std::string s = "forty two"; double d = 42.0; std::tuple<int, int> t{4, 2}; int i = 42; int neg_i = -42; int16_t i16 = 42; int16_t neg_i16 = -42; int8_t i8 = 42; int8_t neg_i8 = -42; EXPECT_EQ(absl::HashOf(s), absl::Hash<std::string>{}(s)); EXPECT_EQ(absl::HashOf(d), absl::Hash<double>{}(d)); EXPECT_EQ(absl::HashOf(t), (absl::Hash<std::tuple<int, int>>{}(t))); EXPECT_EQ(absl::HashOf(i), absl::Hash<int>{}(i)); EXPECT_EQ(absl::HashOf(neg_i), absl::Hash<int>{}(neg_i)); EXPECT_EQ(absl::HashOf(i16), absl::Hash<int16_t>{}(i16)); EXPECT_EQ(absl::HashOf(neg_i16), absl::Hash<int16_t>{}(neg_i16)); EXPECT_EQ(absl::HashOf(i8), absl::Hash<int8_t>{}(i8)); EXPECT_EQ(absl::HashOf(neg_i8), absl::Hash<int8_t>{}(neg_i8)); } TEST(HashOf, MatchesHashOfTupleForMultipleArguments) { std::string hello = "hello"; std::string world = "world"; EXPECT_EQ(absl::HashOf(), absl::HashOf(std::make_tuple())); EXPECT_EQ(absl::HashOf(hello), absl::HashOf(std::make_tuple(hello))); EXPECT_EQ(absl::HashOf(hello, world), absl::HashOf(std::make_tuple(hello, world))); } template <typename T> std::true_type HashOfExplicitParameter(decltype(absl::HashOf<T>(0))) { return {}; } template <typename T> std::false_type HashOfExplicitParameter(size_t) { return {}; } TEST(HashOf, CantPassExplicitTemplateParameters) { EXPECT_FALSE(HashOfExplicitParameter<int>(0)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/hash/internal/hash.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/hash/hash_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
e93d8c14-5b23-430f-b0da-3ba1cd3e21b0
cpp
abseil/abseil-cpp
city
absl/hash/internal/city.cc
absl/hash/internal/city_test.cc
#include "absl/hash/internal/city.h" #include <string.h> #include <algorithm> #include "absl/base/config.h" #include "absl/base/internal/endian.h" #include "absl/base/internal/unaligned_access.h" #include "absl/base/optimization.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace hash_internal { #ifdef ABSL_IS_BIG_ENDIAN #define uint32_in_expected_order(x) (absl::gbswap_32(x)) #define uint64_in_expected_order(x) (absl::gbswap_64(x)) #else #define uint32_in_expected_order(x) (x) #define uint64_in_expected_order(x) (x) #endif static uint64_t Fetch64(const char *p) { return uint64_in_expected_order(ABSL_INTERNAL_UNALIGNED_LOAD64(p)); } static uint32_t Fetch32(const char *p) { return uint32_in_expected_order(ABSL_INTERNAL_UNALIGNED_LOAD32(p)); } static const uint64_t k0 = 0xc3a5c85c97cb3127ULL; static const uint64_t k1 = 0xb492b66fbe98f273ULL; static const uint64_t k2 = 0x9ae16a3b2f90404fULL; static const uint32_t c1 = 0xcc9e2d51; static const uint32_t c2 = 0x1b873593; static uint32_t fmix(uint32_t h) { h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } static uint32_t Rotate32(uint32_t val, int shift) { return shift == 0 ? val : ((val >> shift) | (val << (32 - shift))); } #undef PERMUTE3 #define PERMUTE3(a, b, c) \ do { \ std::swap(a, b); \ std::swap(a, c); \ } while (0) static uint32_t Mur(uint32_t a, uint32_t h) { a *= c1; a = Rotate32(a, 17); a *= c2; h ^= a; h = Rotate32(h, 19); return h * 5 + 0xe6546b64; } static uint32_t Hash32Len13to24(const char *s, size_t len) { uint32_t a = Fetch32(s - 4 + (len >> 1)); uint32_t b = Fetch32(s + 4); uint32_t c = Fetch32(s + len - 8); uint32_t d = Fetch32(s + (len >> 1)); uint32_t e = Fetch32(s); uint32_t f = Fetch32(s + len - 4); uint32_t h = static_cast<uint32_t>(len); return fmix(Mur(f, Mur(e, Mur(d, Mur(c, Mur(b, Mur(a, h))))))); } static uint32_t Hash32Len0to4(const char *s, size_t len) { uint32_t b = 0; uint32_t c = 9; for (size_t i = 0; i < len; i++) { signed char v = static_cast<signed char>(s[i]); b = b * c1 + static_cast<uint32_t>(v); c ^= b; } return fmix(Mur(b, Mur(static_cast<uint32_t>(len), c))); } static uint32_t Hash32Len5to12(const char *s, size_t len) { uint32_t a = static_cast<uint32_t>(len), b = a * 5, c = 9, d = b; a += Fetch32(s); b += Fetch32(s + len - 4); c += Fetch32(s + ((len >> 1) & 4)); return fmix(Mur(c, Mur(b, Mur(a, d)))); } uint32_t CityHash32(const char *s, size_t len) { if (len <= 24) { return len <= 12 ? (len <= 4 ? Hash32Len0to4(s, len) : Hash32Len5to12(s, len)) : Hash32Len13to24(s, len); } uint32_t h = static_cast<uint32_t>(len), g = c1 * h, f = g; uint32_t a0 = Rotate32(Fetch32(s + len - 4) * c1, 17) * c2; uint32_t a1 = Rotate32(Fetch32(s + len - 8) * c1, 17) * c2; uint32_t a2 = Rotate32(Fetch32(s + len - 16) * c1, 17) * c2; uint32_t a3 = Rotate32(Fetch32(s + len - 12) * c1, 17) * c2; uint32_t a4 = Rotate32(Fetch32(s + len - 20) * c1, 17) * c2; h ^= a0; h = Rotate32(h, 19); h = h * 5 + 0xe6546b64; h ^= a2; h = Rotate32(h, 19); h = h * 5 + 0xe6546b64; g ^= a1; g = Rotate32(g, 19); g = g * 5 + 0xe6546b64; g ^= a3; g = Rotate32(g, 19); g = g * 5 + 0xe6546b64; f += a4; f = Rotate32(f, 19); f = f * 5 + 0xe6546b64; size_t iters = (len - 1) / 20; do { uint32_t b0 = Rotate32(Fetch32(s) * c1, 17) * c2; uint32_t b1 = Fetch32(s + 4); uint32_t b2 = Rotate32(Fetch32(s + 8) * c1, 17) * c2; uint32_t b3 = Rotate32(Fetch32(s + 12) * c1, 17) * c2; uint32_t b4 = Fetch32(s + 16); h ^= b0; h = Rotate32(h, 18); h = h * 5 + 0xe6546b64; f += b1; f = Rotate32(f, 19); f = f * c1; g += b2; g = Rotate32(g, 18); g = g * 5 + 0xe6546b64; h ^= b3 + b1; h = Rotate32(h, 19); h = h * 5 + 0xe6546b64; g ^= b4; g = absl::gbswap_32(g) * 5; h += b4 * 5; h = absl::gbswap_32(h); f += b0; PERMUTE3(f, h, g); s += 20; } while (--iters != 0); g = Rotate32(g, 11) * c1; g = Rotate32(g, 17) * c1; f = Rotate32(f, 11) * c1; f = Rotate32(f, 17) * c1; h = Rotate32(h + g, 19); h = h * 5 + 0xe6546b64; h = Rotate32(h, 17) * c1; h = Rotate32(h + f, 19); h = h * 5 + 0xe6546b64; h = Rotate32(h, 17) * c1; return h; } static uint64_t Rotate(uint64_t val, int shift) { return shift == 0 ? val : ((val >> shift) | (val << (64 - shift))); } static uint64_t ShiftMix(uint64_t val) { return val ^ (val >> 47); } static uint64_t HashLen16(uint64_t u, uint64_t v, uint64_t mul) { uint64_t a = (u ^ v) * mul; a ^= (a >> 47); uint64_t b = (v ^ a) * mul; b ^= (b >> 47); b *= mul; return b; } static uint64_t HashLen16(uint64_t u, uint64_t v) { const uint64_t kMul = 0x9ddfea08eb382d69ULL; return HashLen16(u, v, kMul); } static uint64_t HashLen0to16(const char *s, size_t len) { if (len >= 8) { uint64_t mul = k2 + len * 2; uint64_t a = Fetch64(s) + k2; uint64_t b = Fetch64(s + len - 8); uint64_t c = Rotate(b, 37) * mul + a; uint64_t d = (Rotate(a, 25) + b) * mul; return HashLen16(c, d, mul); } if (len >= 4) { uint64_t mul = k2 + len * 2; uint64_t a = Fetch32(s); return HashLen16(len + (a << 3), Fetch32(s + len - 4), mul); } if (len > 0) { uint8_t a = static_cast<uint8_t>(s[0]); uint8_t b = static_cast<uint8_t>(s[len >> 1]); uint8_t c = static_cast<uint8_t>(s[len - 1]); uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8); uint32_t z = static_cast<uint32_t>(len) + (static_cast<uint32_t>(c) << 2); return ShiftMix(y * k2 ^ z * k0) * k2; } return k2; } static uint64_t HashLen17to32(const char *s, size_t len) { uint64_t mul = k2 + len * 2; uint64_t a = Fetch64(s) * k1; uint64_t b = Fetch64(s + 8); uint64_t c = Fetch64(s + len - 8) * mul; uint64_t d = Fetch64(s + len - 16) * k2; return HashLen16(Rotate(a + b, 43) + Rotate(c, 30) + d, a + Rotate(b + k2, 18) + c, mul); } static std::pair<uint64_t, uint64_t> WeakHashLen32WithSeeds( uint64_t w, uint64_t x, uint64_t y, uint64_t z, uint64_t a, uint64_t b) { a += w; b = Rotate(b + a + z, 21); uint64_t c = a; a += x; a += y; b += Rotate(a, 44); return std::make_pair(a + z, b + c); } static std::pair<uint64_t, uint64_t> WeakHashLen32WithSeeds(const char *s, uint64_t a, uint64_t b) { return WeakHashLen32WithSeeds(Fetch64(s), Fetch64(s + 8), Fetch64(s + 16), Fetch64(s + 24), a, b); } static uint64_t HashLen33to64(const char *s, size_t len) { uint64_t mul = k2 + len * 2; uint64_t a = Fetch64(s) * k2; uint64_t b = Fetch64(s + 8); uint64_t c = Fetch64(s + len - 24); uint64_t d = Fetch64(s + len - 32); uint64_t e = Fetch64(s + 16) * k2; uint64_t f = Fetch64(s + 24) * 9; uint64_t g = Fetch64(s + len - 8); uint64_t h = Fetch64(s + len - 16) * mul; uint64_t u = Rotate(a + g, 43) + (Rotate(b, 30) + c) * 9; uint64_t v = ((a + g) ^ d) + f + 1; uint64_t w = absl::gbswap_64((u + v) * mul) + h; uint64_t x = Rotate(e + f, 42) + c; uint64_t y = (absl::gbswap_64((v + w) * mul) + g) * mul; uint64_t z = e + f + c; a = absl::gbswap_64((x + z) * mul + y) + b; b = ShiftMix((z + a) * mul + d + h) * mul; return b + x; } uint64_t CityHash64(const char *s, size_t len) { if (len <= 32) { if (len <= 16) { return HashLen0to16(s, len); } else { return HashLen17to32(s, len); } } else if (len <= 64) { return HashLen33to64(s, len); } uint64_t x = Fetch64(s + len - 40); uint64_t y = Fetch64(s + len - 16) + Fetch64(s + len - 56); uint64_t z = HashLen16(Fetch64(s + len - 48) + len, Fetch64(s + len - 24)); std::pair<uint64_t, uint64_t> v = WeakHashLen32WithSeeds(s + len - 64, len, z); std::pair<uint64_t, uint64_t> w = WeakHashLen32WithSeeds(s + len - 32, y + k1, x); x = x * k1 + Fetch64(s); len = (len - 1) & ~static_cast<size_t>(63); do { x = Rotate(x + y + v.first + Fetch64(s + 8), 37) * k1; y = Rotate(y + v.second + Fetch64(s + 48), 42) * k1; x ^= w.second; y += v.first + Fetch64(s + 40); z = Rotate(z + w.first, 33) * k1; v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first); w = WeakHashLen32WithSeeds(s + 32, z + w.second, y + Fetch64(s + 16)); std::swap(z, x); s += 64; len -= 64; } while (len != 0); return HashLen16(HashLen16(v.first, w.first) + ShiftMix(y) * k1 + z, HashLen16(v.second, w.second) + x); } uint64_t CityHash64WithSeed(const char *s, size_t len, uint64_t seed) { return CityHash64WithSeeds(s, len, k2, seed); } uint64_t CityHash64WithSeeds(const char *s, size_t len, uint64_t seed0, uint64_t seed1) { return HashLen16(CityHash64(s, len) - seed0, seed1); } } ABSL_NAMESPACE_END }
#include "absl/hash/internal/city.h" #include <string.h> #include <cstdio> #include <iostream> #include "gtest/gtest.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace hash_internal { namespace { static const uint64_t k0 = 0xc3a5c85c97cb3127ULL; static const uint64_t kSeed0 = 1234567; static const uint64_t kSeed1 = k0; static const int kDataSize = 1 << 20; static const int kTestSize = 300; static char data[kDataSize]; void setup() { uint64_t a = 9; uint64_t b = 777; for (int i = 0; i < kDataSize; i++) { a += b; b += a; a = (a ^ (a >> 41)) * k0; b = (b ^ (b >> 41)) * k0 + i; uint8_t u = b >> 37; memcpy(data + i, &u, 1); } } #define C(x) 0x##x##ULL static const uint64_t testdata[kTestSize][4] = { {C(9ae16a3b2f90404f), C(75106db890237a4a), C(3feac5f636039766), C(dc56d17a)}, {C(541150e87f415e96), C(1aef0d24b3148a1a), C(bacc300e1e82345a), C(99929334)}, {C(f3786a4b25827c1), C(34ee1a2bf767bd1c), C(2f15ca2ebfb631f2), C(4252edb7)}, {C(ef923a7a1af78eab), C(79163b1e1e9a9b18), C(df3b2aca6e1e4a30), C(ebc34f3c)}, {C(11df592596f41d88), C(843ec0bce9042f9c), C(cce2ea1e08b1eb30), C(26f2b463)}, {C(831f448bdc5600b3), C(62a24be3120a6919), C(1b44098a41e010da), C(b042c047)}, {C(3eca803e70304894), C(d80de767e4a920a), C(a51cfbb292efd53d), C(e73bb0a8)}, {C(1b5a063fb4c7f9f1), C(318dbc24af66dee9), C(10ef7b32d5c719af), C(91dfdd75)}, {C(a0f10149a0e538d6), C(69d008c20f87419f), C(41b36376185b3e9e), C(c87f95de)}, {C(fb8d9c70660b910b), C(a45b0cc3476bff1b), C(b28d1996144f0207), C(3f5538ef)}, {C(236827beae282a46), C(e43970221139c946), C(4f3ac6faa837a3aa), C(70eb1a1f)}, {C(c385e435136ecf7c), C(d9d17368ff6c4a08), C(1b31eed4e5251a67), C(cfd63b83)}, {C(e3f6828b6017086d), C(21b4d1900554b3b0), C(bef38be1809e24f1), C(894a52ef)}, {C(851fff285561dca0), C(4d1277d73cdf416f), C(28ccffa61010ebe2), C(9cde6a54)}, {C(61152a63595a96d9), C(d1a3a91ef3a7ba45), C(443b6bb4a493ad0c), C(6c4898d5)}, {C(44473e03be306c88), C(30097761f872472a), C(9fd1b669bfad82d7), C(13e1978e)}, {C(3ead5f21d344056), C(fb6420393cfb05c3), C(407932394cbbd303), C(51b4ba8)}, {C(6abbfde37ee03b5b), C(83febf188d2cc113), C(cda7b62d94d5b8ee), C(b6b06e40)}, {C(943e7ed63b3c080), C(1ef207e9444ef7f8), C(ef4a9f9f8c6f9b4a), C(240a2f2)}, {C(d72ce05171ef8a1a), C(c6bd6bd869203894), C(c760e6396455d23a), C(5dcefc30)}, {C(4182832b52d63735), C(337097e123eea414), C(b5a72ca0456df910), C(7a48b105)}, {C(d6cdae892584a2cb), C(58de0fa4eca17dcd), C(43df30b8f5f1cb00), C(fd55007b)}, {C(5c8e90bc267c5ee4), C(e9ae044075d992d9), C(f234cbfd1f0a1e59), C(6b95894c)}, {C(bbd7f30ac310a6f3), C(b23b570d2666685f), C(fb13fb08c9814fe7), C(3360e827)}, {C(36a097aa49519d97), C(8204380a73c4065), C(77c2004bdd9e276a), C(45177e0b)}, {C(dc78cb032c49217), C(112464083f83e03a), C(96ae53e28170c0f5), C(7c6fffe4)}, {C(441593e0da922dfe), C(936ef46061469b32), C(204a1921197ddd87), C(bbc78da4)}, {C(2ba3883d71cc2133), C(72f2bbb32bed1a3c), C(27e1bd96d4843251), C(c5c25d39)}, {C(f2b6d2adf8423600), C(7514e2f016a48722), C(43045743a50396ba), C(b6e5d06e)}, {C(38fffe7f3680d63c), C(d513325255a7a6d1), C(31ed47790f6ca62f), C(6178504e)}, {C(b7477bf0b9ce37c6), C(63b1c580a7fd02a4), C(f6433b9f10a5dac), C(bd4c3637)}, {C(55bdb0e71e3edebd), C(c7ab562bcf0568bc), C(43166332f9ee684f), C(6e7ac474)}, {C(782fa1b08b475e7), C(fb7138951c61b23b), C(9829105e234fb11e), C(1fb4b518)}, {C(c5dc19b876d37a80), C(15ffcff666cfd710), C(e8c30c72003103e2), C(31d13d6d)}, {C(5e1141711d2d6706), C(b537f6dee8de6933), C(3af0a1fbbe027c54), C(26fa72e3)}, {C(782edf6da001234f), C(f48cbd5c66c48f3), C(808754d1e64e2a32), C(6a7433bf)}, {C(d26285842ff04d44), C(8f38d71341eacca9), C(5ca436f4db7a883c), C(4e6df758)}, {C(c6ab830865a6bae6), C(6aa8e8dd4b98815c), C(efe3846713c371e5), C(d57f63ea)}, {C(44b3a1929232892), C(61dca0e914fc217), C(a607cc142096b964), C(52ef73b3)}, {C(4b603d7932a8de4f), C(fae64c464b8a8f45), C(8fafab75661d602a), C(3cb36c3)}, {C(4ec0b54cf1566aff), C(30d2c7269b206bf4), C(77c22e82295e1061), C(72c39bea)}, {C(ed8b7a4b34954ff7), C(56432de31f4ee757), C(85bd3abaa572b155), C(a65aa25c)}, {C(5d28b43694176c26), C(714cc8bc12d060ae), C(3437726273a83fe6), C(74740539)}, {C(6a1ef3639e1d202e), C(919bc1bd145ad928), C(30f3f7e48c28a773), C(c3ae3c26)}, {C(159f4d9e0307b111), C(3e17914a5675a0c), C(af849bd425047b51), C(f29db8a2)}, {C(cc0a840725a7e25b), C(57c69454396e193a), C(976eaf7eee0b4540), C(1ef4cbf4)}, {C(a2b27ee22f63c3f1), C(9ebde0ce1b3976b2), C(2fe6a92a257af308), C(a9be6c41)}, {C(d8f2f234899bcab3), C(b10b037297c3a168), C(debea2c510ceda7f), C(fa31801)}, {C(584f28543864844f), C(d7cee9fc2d46f20d), C(a38dca5657387205), C(8331c5d8)}, {C(a94be46dd9aa41af), C(a57e5b7723d3f9bd), C(34bf845a52fd2f), C(e9876db8)}, {C(9a87bea227491d20), C(a468657e2b9c43e7), C(af9ba60db8d89ef7), C(27b0604e)}, {C(27688c24958d1a5c), C(e3b4a1c9429cf253), C(48a95811f70d64bc), C(dcec07f2)}, {C(5d1d37790a1873ad), C(ed9cd4bcc5fa1090), C(ce51cde05d8cd96a), C(cff0a82a)}, {C(1f03fd18b711eea9), C(566d89b1946d381a), C(6e96e83fc92563ab), C(fec83621)}, {C(f0316f286cf527b6), C(f84c29538de1aa5a), C(7612ed3c923d4a71), C(743d8dc)}, {C(297008bcb3e3401d), C(61a8e407f82b0c69), C(a4a35bff0524fa0e), C(64d41d26)}, {C(43c6252411ee3be), C(b4ca1b8077777168), C(2746dc3f7da1737f), C(acd90c81)}, {C(ce38a9a54fad6599), C(6d6f4a90b9e8755e), C(c3ecc79ff105de3f), C(7c746a4b)}, {C(270a9305fef70cf), C(600193999d884f3a), C(f4d49eae09ed8a1), C(b1047e99)}, {C(e71be7c28e84d119), C(eb6ace59932736e6), C(70c4397807ba12c5), C(d1fd1068)}, {C(b5b58c24b53aaa19), C(d2a6ab0773dd897f), C(ef762fe01ecb5b97), C(56486077)}, {C(44dd59bd301995cf), C(3ccabd76493ada1a), C(540db4c87d55ef23), C(6069be80)}, {C(b4d4789eb6f2630b), C(bf6973263ce8ef0e), C(d1c75c50844b9d3), C(2078359b)}, {C(12807833c463737c), C(58e927ea3b3776b4), C(72dd20ef1c2f8ad0), C(9ea21004)}, {C(e88419922b87176f), C(bcf32f41a7ddbf6f), C(d6ebefd8085c1a0f), C(9c9cfe88)}, {C(105191e0ec8f7f60), C(5918dbfcca971e79), C(6b285c8a944767b9), C(b70a6ddd)}, {C(a5b88bf7399a9f07), C(fca3ddfd96461cc4), C(ebe738fdc0282fc6), C(dea37298)}, {C(d08c3f5747d84f50), C(4e708b27d1b6f8ac), C(70f70fd734888606), C(8f480819)}, {C(2f72d12a40044b4b), C(889689352fec53de), C(f03e6ad87eb2f36), C(30b3b16)}, {C(aa1f61fdc5c2e11e), C(c2c56cd11277ab27), C(a1e73069fdf1f94f), C(f31bc4e8)}, {C(9489b36fe2246244), C(3355367033be74b8), C(5f57c2277cbce516), C(419f953b)}, {C(358d7c0476a044cd), C(e0b7b47bcbd8854f), C(ffb42ec696705519), C(20e9e76d)}, {C(b0c48df14275265a), C(9da4448975905efa), C(d716618e414ceb6d), C(646f0ff8)}, {C(daa70bb300956588), C(410ea6883a240c6d), C(f5c8239fb5673eb3), C(eeb7eca8)}, {C(4ec97a20b6c4c7c2), C(5913b1cd454f29fd), C(a9629f9daf06d685), C(8112bb9)}, {C(5c3323628435a2e8), C(1bea45ce9e72a6e3), C(904f0a7027ddb52e), C(85a6d477)}, {C(c1ef26bea260abdb), C(6ee423f2137f9280), C(df2118b946ed0b43), C(56f76c84)}, {C(6be7381b115d653a), C(ed046190758ea511), C(de6a45ffc3ed1159), C(9af45d55)}, {C(ae3eece1711b2105), C(14fd3f4027f81a4a), C(abb7e45177d151db), C(d1c33760)}, {C(376c28588b8fb389), C(6b045e84d8491ed2), C(4e857effb7d4e7dc), C(c56bbf69)}, {C(58d943503bb6748f), C(419c6c8e88ac70f6), C(586760cbf3d3d368), C(abecfb9b)}, {C(dfff5989f5cfd9a1), C(bcee2e7ea3a96f83), C(681c7874adb29017), C(8de13255)}, {C(7fb19eb1a496e8f5), C(d49e5dfdb5c0833f), C(c0d5d7b2f7c48dc7), C(a98ee299)}, {C(5dba5b0dadccdbaa), C(4ba8da8ded87fcdc), C(f693fdd25badf2f0), C(3015f556)}, {C(688bef4b135a6829), C(8d31d82abcd54e8e), C(f95f8a30d55036d7), C(5a430e29)}, {C(d8323be05433a412), C(8d48fa2b2b76141d), C(3d346f23978336a5), C(2797add0)}, {C(3b5404278a55a7fc), C(23ca0b327c2d0a81), C(a6d65329571c892c), C(27d55016)}, {C(2a96a3f96c5e9bbc), C(8caf8566e212dda8), C(904de559ca16e45e), C(84945a82)}, {C(22bebfdcc26d18ff), C(4b4d8dcb10807ba1), C(40265eee30c6b896), C(3ef7e224)}, {C(627a2249ec6bbcc2), C(c0578b462a46735a), C(4974b8ee1c2d4f1f), C(35ed8dc8)}, {C(3abaf1667ba2f3e0), C(ee78476b5eeadc1), C(7e56ac0a6ca4f3f4), C(6a75e43d)}, {C(3931ac68c5f1b2c9), C(efe3892363ab0fb0), C(40b707268337cd36), C(235d9805)}, {C(b98fb0606f416754), C(46a6e5547ba99c1e), C(c909d82112a8ed2), C(f7d69572)}, {C(7f7729a33e58fcc4), C(2e4bc1e7a023ead4), C(e707008ea7ca6222), C(bacd0199)}, {C(42a0aa9ce82848b3), C(57232730e6bee175), C(f89bb3f370782031), C(e428f50e)}, {C(6b2c6d38408a4889), C(de3ef6f68fb25885), C(20754f456c203361), C(81eaaad3)}, {C(930380a3741e862a), C(348d28638dc71658), C(89dedcfd1654ea0d), C(addbd3e3)}, {C(94808b5d2aa25f9a), C(cec72968128195e0), C(d9f4da2bdc1e130f), C(e66dbca0)}, {C(b31abb08ae6e3d38), C(9eb9a95cbd9e8223), C(8019e79b7ee94ea9), C(afe11fd5)}, {C(dccb5534a893ea1a), C(ce71c398708c6131), C(fe2396315457c164), C(a71a406f)}, {C(6369163565814de6), C(8feb86fb38d08c2f), C(4976933485cc9a20), C(9d90eaf5)}, {C(edee4ff253d9f9b3), C(96ef76fb279ef0ad), C(a4d204d179db2460), C(6665db10)}, {C(941993df6e633214), C(929bc1beca5b72c6), C(141fc52b8d55572d), C(9c977cbf)}, {C(859838293f64cd4c), C(484403b39d44ad79), C(bf674e64d64b9339), C(ee83ddd4)}, {C(c19b5648e0d9f555), C(328e47b2b7562993), C(e756b92ba4bd6a51), C(26519cc)}, {C(f963b63b9006c248), C(9e9bf727ffaa00bc), C(c73bacc75b917e3a), C(a485a53f)}, {C(6a8aa0852a8c1f3b), C(c8f1e5e206a21016), C(2aa554aed1ebb524), C(f62bc412)}, {C(740428b4d45e5fb8), C(4c95a4ce922cb0a5), C(e99c3ba78feae796), C(8975a436)}, {C(658b883b3a872b86), C(2f0e303f0f64827a), C(975337e23dc45e1), C(94ff7f41)}, {C(6df0a977da5d27d4), C(891dd0e7cb19508), C(fd65434a0b71e680), C(760aa031)}, {C(a900275464ae07ef), C(11f2cfda34beb4a3), C(9abf91e5a1c38e4), C(3bda76df)}, {C(810bc8aa0c40bcb0), C(448a019568d01441), C(f60ec52f60d3aeae), C(498e2e65)}, {C(22036327deb59ed7), C(adc05ceb97026a02), C(48bff0654262672b), C(d38deb48)}, {C(7d14dfa9772b00c8), C(595735efc7eeaed7), C(29872854f94c3507), C(82b3fb6b)}, {C(2d777cddb912675d), C(278d7b10722a13f9), C(f5c02bfb7cc078af), C(e500e25f)}, {C(f2ec98824e8aa613), C(5eb7e3fb53fe3bed), C(12c22860466e1dd4), C(bd2bb07c)}, {C(5e763988e21f487f), C(24189de8065d8dc5), C(d1519d2403b62aa0), C(3a2b431d)}, {C(48949dc327bb96ad), C(e1fd21636c5c50b4), C(3f6eb7f13a8712b4), C(7322a83d)}, {C(b7c4209fb24a85c5), C(b35feb319c79ce10), C(f0d3de191833b922), C(a645ca1c)}, {C(9c9e5be0943d4b05), C(b73dc69e45201cbb), C(aab17180bfe5083d), C(8909a45a)}, {C(3898bca4dfd6638d), C(f911ff35efef0167), C(24bdf69e5091fc88), C(bd30074c)}, {C(5b5d2557400e68e7), C(98d610033574cee), C(dfd08772ce385deb), C(c17cf001)}, {C(a927ed8b2bf09bb6), C(606e52f10ae94eca), C(71c2203feb35a9ee), C(26ffd25a)}, {C(8d25746414aedf28), C(34b1629d28b33d3a), C(4d5394aea5f82d7b), C(f1d8ce3c)}, {C(b5bbdb73458712f2), C(1ff887b3c2a35137), C(7f7231f702d0ace9), C(3ee8fb17)}, {C(3d32a26e3ab9d254), C(fc4070574dc30d3a), C(f02629579c2b27c9), C(a77acc2a)}, {C(9371d3c35fa5e9a5), C(42967cf4d01f30), C(652d1eeae704145c), C(f4556dee)}, {C(cbaa3cb8f64f54e0), C(76c3b48ee5c08417), C(9f7d24e87e61ce9), C(de287a64)}, {C(b2e23e8116c2ba9f), C(7e4d9c0060101151), C(3310da5e5028f367), C(878e55b9)}, {C(8aa77f52d7868eb9), C(4d55bd587584e6e2), C(d2db37041f495f5), C(7648486)}, {C(858fea922c7fe0c3), C(cfe8326bf733bc6f), C(4e5e2018cf8f7dfc), C(57ac0fb1)}, {C(46ef25fdec8392b1), C(e48d7b6d42a5cd35), C(56a6fe1c175299ca), C(d01967ca)}, {C(8d078f726b2df464), C(b50ee71cdcabb299), C(f4af300106f9c7ba), C(96ecdf74)}, {C(35ea86e6960ca950), C(34fe1fe234fc5c76), C(a00207a3dc2a72b7), C(779f5506)}, {C(8aee9edbc15dd011), C(51f5839dc8462695), C(b2213e17c37dca2d), C(3c94c2de)}, {C(c3e142ba98432dda), C(911d060cab126188), C(b753fbfa8365b844), C(39f98faf)}, {C(123ba6b99c8cd8db), C(448e582672ee07c4), C(cebe379292db9e65), C(7af31199)}, {C(ba87acef79d14f53), C(b3e0fcae63a11558), C(d5ac313a593a9f45), C(e341a9d6)}, {C(bcd3957d5717dc3), C(2da746741b03a007), C(873816f4b1ece472), C(ca24aeeb)}, {C(61442ff55609168e), C(6447c5fc76e8c9cf), C(6a846de83ae15728), C(b2252b57)}, {C(dbe4b1b2d174757f), C(506512da18712656), C(6857f3e0b8dd95f), C(72c81da1)}, {C(531e8e77b363161c), C(eece0b43e2dae030), C(8294b82c78f34ed1), C(6b9fce95)}, {C(f71e9c926d711e2b), C(d77af2853a4ceaa1), C(9aa0d6d76a36fae7), C(19399857)}, {C(cb20ac28f52df368), C(e6705ee7880996de), C(9b665cc3ec6972f2), C(3c57a994)}, {C(e4a794b4acb94b55), C(89795358057b661b), C(9c4cdcec176d7a70), C(c053e729)}, {C(cb942e91443e7208), C(e335de8125567c2a), C(d4d74d268b86df1f), C(51cbbba7)}, {C(ecca7563c203f7ba), C(177ae2423ef34bb2), C(f60b7243400c5731), C(1acde79a)}, {C(1652cb940177c8b5), C(8c4fe7d85d2a6d6d), C(f6216ad097e54e72), C(2d160d13)}, {C(31fed0fc04c13ce8), C(3d5d03dbf7ff240a), C(727c5c9b51581203), C(787f5801)}, {C(e7b668947590b9b3), C(baa41ad32938d3fa), C(abcbc8d4ca4b39e4), C(c9629828)}, {C(1de2119923e8ef3c), C(6ab27c096cf2fe14), C(8c3658edca958891), C(be139231)}, {C(1269df1e69e14fa7), C(992f9d58ac5041b7), C(e97fcf695a7cbbb4), C(7df699ef)}, {C(820826d7aba567ff), C(1f73d28e036a52f3), C(41c4c5a73f3b0893), C(8ce6b96d)}, {C(ffe0547e4923cef9), C(3534ed49b9da5b02), C(548a273700fba03d), C(6f9ed99c)}, {C(72da8d1b11d8bc8b), C(ba94b56b91b681c6), C(4e8cc51bd9b0fc8c), C(e0244796)}, {C(d62ab4e3f88fc797), C(ea86c7aeb6283ae4), C(b5b93e09a7fe465), C(4ccf7e75)}, {C(d0f06c28c7b36823), C(1008cb0874de4bb8), C(d6c7ff816c7a737b), C(915cef86)}, {C(99b7042460d72ec6), C(2a53e5e2b8e795c2), C(53a78132d9e1b3e3), C(5cb59482)}, {C(4f4dfcfc0ec2bae5), C(841233148268a1b8), C(9248a76ab8be0d3), C(6ca3f532)}, {C(fe86bf9d4422b9ae), C(ebce89c90641ef9c), C(1c84e2292c0b5659), C(e24f3859)}, {C(a90d81060932dbb0), C(8acfaa88c5fbe92b), C(7c6f3447e90f7f3f), C(adf5a9c7)}, {C(17938a1b0e7f5952), C(22cadd2f56f8a4be), C(84b0d1183d5ed7c1), C(32264b75)}, {C(de9e0cb0e16f6e6d), C(238e6283aa4f6594), C(4fb9c914c2f0a13b), C(a64b3376)}, {C(6d4b876d9b146d1a), C(aab2d64ce8f26739), C(d315f93600e83fe5), C(d33890e)}, {C(e698fa3f54e6ea22), C(bd28e20e7455358c), C(9ace161f6ea76e66), C(926d4b63)}, {C(7bc0deed4fb349f7), C(1771aff25dc722fa), C(19ff0644d9681917), C(d51ba539)}, {C(db4b15e88533f622), C(256d6d2419b41ce9), C(9d7c5378396765d5), C(7f37636d)}, {C(922834735e86ecb2), C(363382685b88328e), C(e9c92960d7144630), C(b98026c0)}, {C(30f1d72c812f1eb8), C(b567cd4a69cd8989), C(820b6c992a51f0bc), C(b877767e)}, {C(168884267f3817e9), C(5b376e050f637645), C(1c18314abd34497a), C(aefae77)}, {C(82e78596ee3e56a7), C(25697d9c87f30d98), C(7600a8342834924d), C(f686911)}, {C(aa2d6cf22e3cc252), C(9b4dec4f5e179f16), C(76fb0fba1d99a99a), C(3deadf12)}, {C(7bf5ffd7f69385c7), C(fc077b1d8bc82879), C(9c04e36f9ed83a24), C(ccf02a4e)}, {C(e89c8ff9f9c6e34b), C(f54c0f669a49f6c4), C(fc3e46f5d846adef), C(176c1722)}, {C(a18fbcdccd11e1f4), C(8248216751dfd65e), C(40c089f208d89d7c), C(26f82ad)}, {C(2d54f40cc4088b17), C(59d15633b0cd1399), C(a8cc04bb1bffd15b), C(b5244f42)}, {C(69276946cb4e87c7), C(62bdbe6183be6fa9), C(3ba9773dac442a1a), C(49a689e5)}, {C(668174a3f443df1d), C(407299392da1ce86), C(c2a3f7d7f2c5be28), C(59fcdd3)}, {C(5e29be847bd5046), C(b561c7f19c8f80c3), C(5e5abd5021ccaeaf), C(4f4b04e9)}, {C(cd0d79f2164da014), C(4c386bb5c5d6ca0c), C(8e771b03647c3b63), C(8b00f891)}, {C(e0e6fc0b1628af1d), C(29be5fb4c27a2949), C(1c3f781a604d3630), C(16e114f3)}, {C(2058927664adfd93), C(6e8f968c7963baa5), C(af3dced6fff7c394), C(d6b6dadc)}, {C(dc107285fd8e1af7), C(a8641a0609321f3f), C(db06e89ffdc54466), C(897e20ac)}, {C(fbba1afe2e3280f1), C(755a5f392f07fce), C(9e44a9a15402809a), C(f996e05d)}, {C(bfa10785ddc1011b), C(b6e1c4d2f670f7de), C(517d95604e4fcc1f), C(c4306af6)}, {C(534cc35f0ee1eb4e), C(b703820f1f3b3dce), C(884aa164cf22363), C(6dcad433)}, {C(7ca6e3933995dac), C(fd118c77daa8188), C(3aceb7b5e7da6545), C(3c07374d)}, {C(f0d6044f6efd7598), C(e044d6ba4369856e), C(91968e4f8c8a1a4c), C(f0f4602c)}, {C(3d69e52049879d61), C(76610636ea9f74fe), C(e9bf5602f89310c0), C(3e1ea071)}, {C(79da242a16acae31), C(183c5f438e29d40), C(6d351710ae92f3de), C(67580f0c)}, {C(461c82656a74fb57), C(d84b491b275aa0f7), C(8f262cb29a6eb8b2), C(4e109454)}, {C(53c1a66d0b13003), C(731f060e6fe797fc), C(daa56811791371e3), C(88a474a7)}, {C(d3a2efec0f047e9), C(1cabce58853e58ea), C(7a17b2eae3256be4), C(5b5bedd)}, {C(43c64d7484f7f9b2), C(5da002b64aafaeb7), C(b576c1e45800a716), C(1aaddfa7)}, {C(a7dec6ad81cf7fa1), C(180c1ab708683063), C(95e0fd7008d67cff), C(5be07fd8)}, {C(5408a1df99d4aff), C(b9565e588740f6bd), C(abf241813b08006e), C(cbca8606)}, {C(a8b27a6bcaeeed4b), C(aec1eeded6a87e39), C(9daf246d6fed8326), C(bde64d01)}, {C(9a952a8246fdc269), C(d0dcfcac74ef278c), C(250f7139836f0f1f), C(ee90cf33)}, {C(c930841d1d88684f), C(5eb66eb18b7f9672), C(e455d413008a2546), C(4305c3ce)}, {C(94dc6971e3cf071a), C(994c7003b73b2b34), C(ea16e85978694e5), C(4b3a1d76)}, {C(7fc98006e25cac9), C(77fee0484cda86a7), C(376ec3d447060456), C(a8bb6d80)}, {C(bd781c4454103f6), C(612197322f49c931), C(b9cf17fd7e5462d5), C(1f9fa607)}, {C(da60e6b14479f9df), C(3bdccf69ece16792), C(18ebf45c4fecfdc9), C(8d0e4ed2)}, {C(4ca56a348b6c4d3), C(60618537c3872514), C(2fbb9f0e65871b09), C(1bf31347)}, {C(ebd22d4b70946401), C(6863602bf7139017), C(c0b1ac4e11b00666), C(1ae3fc5b)}, {C(3cc4693d6cbcb0c), C(501689ea1c70ffa), C(10a4353e9c89e364), C(459c3930)}, {C(38908e43f7ba5ef0), C(1ab035d4e7781e76), C(41d133e8c0a68ff7), C(e00c4184)}, {C(34983ccc6aa40205), C(21802cad34e72bc4), C(1943e8fb3c17bb8), C(ffc7a781)}, {C(86215c45dcac9905), C(ea546afe851cae4b), C(d85b6457e489e374), C(6a125480)}, {C(420fc255c38db175), C(d503cd0f3c1208d1), C(d4684e74c825a0bc), C(88a1512b)}, {C(1d7a31f5bc8fe2f9), C(4763991092dcf836), C(ed695f55b97416f4), C(549bbbe5)}, {C(94129a84c376a26e), C(c245e859dc231933), C(1b8f74fecf917453), C(c133d38c)}, {C(1d3a9809dab05c8d), C(adddeb4f71c93e8), C(ef342eb36631edb), C(fcace348)}, {C(90fa3ccbd60848da), C(dfa6e0595b569e11), C(e585d067a1f5135d), C(ed7b6f9a)}, {C(2dbb4fc71b554514), C(9650e04b86be0f82), C(60f2304fba9274d3), C(6d907dda)}, {C(b98bf4274d18374a), C(1b669fd4c7f9a19a), C(b1f5972b88ba2b7a), C(7a4d48d5)}, {C(d6781d0b5e18eb68), C(b992913cae09b533), C(58f6021caaee3a40), C(e686f3db)}, {C(226651cf18f4884c), C(595052a874f0f51c), C(c9b75162b23bab42), C(cce7c55)}, {C(a734fb047d3162d6), C(e523170d240ba3a5), C(125a6972809730e8), C(f58b96b)}, {C(c6df6364a24f75a3), C(c294e2c84c4f5df8), C(a88df65c6a89313b), C(1bbf6f60)}, {C(d8d1364c1fbcd10), C(2d7cc7f54832deaa), C(4e22c876a7c57625), C(ce5e0cc2)}, {C(aae06f9146db885f), C(3598736441e280d9), C(fba339b117083e55), C(584cfd6f)}, {C(8955ef07631e3bcc), C(7d70965ea3926f83), C(39aed4134f8b2db6), C(8f9bbc33)}, {C(ad611c609cfbe412), C(d3c00b18bf253877), C(90b2172e1f3d0bfd), C(d7640d95)}, {C(d5339adc295d5d69), C(b633cc1dcb8b586a), C(ee84184cf5b1aeaf), C(3d12a2b)}, {C(40d0aeff521375a8), C(77ba1ad7ecebd506), C(547c6f1a7d9df427), C(aaeafed0)}, {C(8b2d54ae1a3df769), C(11e7adaee3216679), C(3483781efc563e03), C(95b9b814)}, {C(99c175819b4eae28), C(932e8ff9f7a40043), C(ec78dcab07ca9f7c), C(45fbe66e)}, {C(2a418335779b82fc), C(af0295987849a76b), C(c12bc5ff0213f46e), C(b4baa7a8)}, {C(3b1fc6a3d279e67d), C(70ea1e49c226396), C(25505adcf104697c), C(83e962fe)}, {C(d97eacdf10f1c3c9), C(b54f4654043a36e0), C(b128f6eb09d1234), C(aac3531c)}, {C(293a5c1c4e203cd4), C(6b3329f1c130cefe), C(f2e32f8ec76aac91), C(2b1db7cc)}, {C(4290e018ffaedde7), C(a14948545418eb5e), C(72d851b202284636), C(cf00cd31)}, {C(f919a59cbde8bf2f), C(a56d04203b2dc5a5), C(38b06753ac871e48), C(7d3c43b8)}, {C(1d70a3f5521d7fa4), C(fb97b3fdc5891965), C(299d49bbbe3535af), C(cbd5fac6)}, {C(6af98d7b656d0d7c), C(d2e99ae96d6b5c0c), C(f63bd1603ef80627), C(76d0fec4)}, {C(395b7a8adb96ab75), C(582df7165b20f4a), C(e52bd30e9ff657f9), C(405e3402)}, {C(3822dd82c7df012f), C(b9029b40bd9f122b), C(fd25b988468266c4), C(c732c481)}, {C(79f7efe4a80b951a), C(dd3a3fddfc6c9c41), C(ab4c812f9e27aa40), C(a8d123c9)}, {C(ae6e59f5f055921a), C(e9d9b7bf68e82), C(5ce4e4a5b269cc59), C(1e80ad7d)}, {C(8959dbbf07387d36), C(b4658afce48ea35d), C(8f3f82437d8cb8d6), C(52aeb863)}, {C(4739613234278a49), C(99ea5bcd340bf663), C(258640912e712b12), C(ef7c0c18)}, {C(420e6c926bc54841), C(96dbbf6f4e7c75cd), C(d8d40fa70c3c67bb), C(b6ad4b68)}, {C(c8601bab561bc1b7), C(72b26272a0ff869a), C(56fdfc986d6bc3c4), C(c1e46b17)}, {C(b2d294931a0e20eb), C(284ffd9a0815bc38), C(1f8a103aac9bbe6), C(57b8df25)}, {C(7966f53c37b6c6d7), C(8e6abcfb3aa2b88f), C(7f2e5e0724e5f345), C(e9fa36d6)}, {C(be9bb0abd03b7368), C(13bca93a3031be55), C(e864f4f52b55b472), C(8f8daefc)}, {C(a08d128c5f1649be), C(a8166c3dbbe19aad), C(cb9f914f829ec62c), C(6e1bb7e)}, {C(7c386f0ffe0465ac), C(530419c9d843dbf3), C(7450e3a4f72b8d8c), C(fd0076f0)}, {C(bb362094e7ef4f8), C(ff3c2a48966f9725), C(55152803acd4a7fe), C(899b17b6)}, {C(cd80dea24321eea4), C(52b4fdc8130c2b15), C(f3ea100b154bfb82), C(e3e84e31)}, {C(d599a04125372c3a), C(313136c56a56f363), C(1e993c3677625832), C(eef79b6b)}, {C(dbbf541e9dfda0a), C(1479fceb6db4f844), C(31ab576b59062534), C(868e3315)}, {C(c2ee3288be4fe2bf), C(c65d2f5ddf32b92), C(af6ecdf121ba5485), C(4639a426)}, {C(d86603ced1ed4730), C(f9de718aaada7709), C(db8b9755194c6535), C(f3213646)}, {C(915263c671b28809), C(a815378e7ad762fd), C(abec6dc9b669f559), C(17f148e9)}, {C(2b67cdd38c307a5e), C(cb1d45bb5c9fe1c), C(800baf2a02ec18ad), C(bfd94880)}, {C(2d107419073b9cd0), C(a96db0740cef8f54), C(ec41ee91b3ecdc1b), C(bb1fa7f3)}, {C(f3e9487ec0e26dfc), C(1ab1f63224e837fa), C(119983bb5a8125d8), C(88816b1)}, {C(1160987c8fe86f7d), C(879e6db1481eb91b), C(d7dcb802bfe6885d), C(5c2faeb3)}, {C(eab8112c560b967b), C(97f550b58e89dbae), C(846ed506d304051f), C(51b5fc6f)}, {C(1addcf0386d35351), C(b5f436561f8f1484), C(85d38e22181c9bb1), C(33d94752)}, {C(d445ba84bf803e09), C(1216c2497038f804), C(2293216ea2237207), C(b0c92948)}, {C(37235a096a8be435), C(d9b73130493589c2), C(3b1024f59378d3be), C(c7171590)}, {C(763ad6ea2fe1c99d), C(cf7af5368ac1e26b), C(4d5e451b3bb8d3d4), C(240a67fb)}, {C(ea627fc84cd1b857), C(85e372494520071f), C(69ec61800845780b), C(e1843cd5)}, {C(1f2ffd79f2cdc0c8), C(726a1bc31b337aaa), C(678b7f275ef96434), C(fda1452b)}, {C(39a9e146ec4b3210), C(f63f75802a78b1ac), C(e2e22539c94741c3), C(a2cad330)}, {C(74cba303e2dd9d6d), C(692699b83289fad1), C(dfb9aa7874678480), C(53467e16)}, {C(4cbc2b73a43071e0), C(56c5db4c4ca4e0b7), C(1b275a162f46bd3d), C(da14a8d0)}, {C(875638b9715d2221), C(d9ba0615c0c58740), C(616d4be2dfe825aa), C(67333551)}, {C(fb686b2782994a8d), C(edee60693756bb48), C(e6bc3cae0ded2ef5), C(a0ebd66e)}, {C(ab21d81a911e6723), C(4c31b07354852f59), C(835da384c9384744), C(4b769593)}, {C(33d013cc0cd46ecf), C(3de726423aea122c), C(116af51117fe21a9), C(6aa75624)}, {C(8ca92c7cd39fae5d), C(317e620e1bf20f1), C(4f0b33bf2194b97f), C(602a3f96)}, {C(fdde3b03f018f43e), C(38f932946c78660), C(c84084ce946851ee), C(cd183c4d)}, {C(9c8502050e9c9458), C(d6d2a1a69964beb9), C(1675766f480229b5), C(960a4d07)}, {C(348176ca2fa2fdd2), C(3a89c514cc360c2d), C(9f90b8afb318d6d0), C(9ae998c4)}, {C(4a3d3dfbbaea130b), C(4e221c920f61ed01), C(553fd6cd1304531f), C(74e2179d)}, {C(b371f768cdf4edb9), C(bdef2ace6d2de0f0), C(e05b4100f7f1baec), C(ee9bae25)}, {C(7a1d2e96934f61f), C(eb1760ae6af7d961), C(887eb0da063005df), C(b66edf10)}, {C(8be53d466d4728f2), C(86a5ac8e0d416640), C(984aa464cdb5c8bb), C(d6209737)}, {C(829677eb03abf042), C(43cad004b6bc2c0), C(f2f224756803971a), C(b994a88)}, {C(754435bae3496fc), C(5707fc006f094dcf), C(8951c86ab19d8e40), C(a05d43c0)}, {C(fda9877ea8e3805f), C(31e868b6ffd521b7), C(b08c90681fb6a0fd), C(c79f73a8)}, {C(2e36f523ca8f5eb5), C(8b22932f89b27513), C(331cd6ecbfadc1bb), C(a490aff5)}, {C(21a378ef76828208), C(a5c13037fa841da2), C(506d22a53fbe9812), C(dfad65b4)}, {C(ccdd5600054b16ca), C(f78846e84204cb7b), C(1f9faec82c24eac9), C(1d07dfb)}, {C(7854468f4e0cabd0), C(3a3f6b4f098d0692), C(ae2423ec7799d30d), C(416df9a0)}, {C(7f88db5346d8f997), C(88eac9aacc653798), C(68a4d0295f8eefa1), C(1f8fb9cc)}, {C(bb3fb5fb01d60fcf), C(1b7cc0847a215eb6), C(1246c994437990a1), C(7abf48e3)}, {C(2e783e1761acd84d), C(39158042bac975a0), C(1cd21c5a8071188d), C(dea4e3dd)}, {C(392058251cf22acc), C(944ec4475ead4620), C(b330a10b5cb94166), C(c6064f22)}, {C(adf5c1e5d6419947), C(2a9747bc659d28aa), C(95c5b8cb1f5d62c), C(743bed9c)}, {C(6bc1db2c2bee5aba), C(e63b0ed635307398), C(7b2eca111f30dbbc), C(fce254d5)}, {C(b00f898229efa508), C(83b7590ad7f6985c), C(2780e70a0592e41d), C(e47ec9d1)}, {C(b56eb769ce0d9a8c), C(ce196117bfbcaf04), C(b26c3c3797d66165), C(334a145c)}, {C(70c0637675b94150), C(259e1669305b0a15), C(46e1dd9fd387a58d), C(adec1e3c)}, {C(74c0b8a6821faafe), C(abac39d7491370e7), C(faf0b2a48a4e6aed), C(f6a9fbf8)}, {C(5fb5e48ac7b7fa4f), C(a96170f08f5acbc7), C(bbf5c63d4f52a1e5), C(5398210c)}, }; void TestUnchanging(const uint64_t* expected, int offset, int len) { EXPECT_EQ(expected[0], CityHash64(data + offset, len)); EXPECT_EQ(expected[3], CityHash32(data + offset, len)); EXPECT_EQ(expected[1], CityHash64WithSeed(data + offset, len, kSeed0)); EXPECT_EQ(expected[2], CityHash64WithSeeds(data + offset, len, kSeed0, kSeed1)); } TEST(CityHashTest, Unchanging) { setup(); int i = 0; for (; i < kTestSize - 1; i++) { TestUnchanging(testdata[i], i * i, i); } TestUnchanging(testdata[i], 0, kDataSize); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/hash/internal/city.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/hash/internal/city_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
5528a023-e75d-4b6a-999a-1b9a9e6e728f
cpp
abseil/abseil-cpp
symbolize
absl/debugging/symbolize.cc
absl/debugging/symbolize_test.cc
#include "absl/debugging/symbolize.h" #ifdef _WIN32 #include <winapifamily.h> #if !(WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)) || \ WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #define ABSL_INTERNAL_HAVE_SYMBOLIZE_WIN32 #endif #endif #if defined(__EMSCRIPTEN__) && !defined(STANDALONE_WASM) #define ABSL_INTERNAL_HAVE_SYMBOLIZE_WASM #endif #if defined(ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE) #include "absl/debugging/symbolize_elf.inc" #elif defined(ABSL_INTERNAL_HAVE_SYMBOLIZE_WIN32) #include "absl/debugging/symbolize_win32.inc" #elif defined(__APPLE__) #include "absl/debugging/symbolize_darwin.inc" #elif defined(ABSL_INTERNAL_HAVE_SYMBOLIZE_WASM) #include "absl/debugging/symbolize_emscripten.inc" #else #include "absl/debugging/symbolize_unimplemented.inc" #endif
#include "absl/debugging/symbolize.h" #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif #ifndef _WIN32 #include <fcntl.h> #include <sys/mman.h> #endif #include <cstring> #include <iostream> #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/casts.h" #include "absl/base/config.h" #include "absl/base/internal/per_thread_tls.h" #include "absl/base/optimization.h" #include "absl/debugging/internal/stack_consumption.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS) #define MAP_ANONYMOUS MAP_ANON #endif using testing::Contains; #ifdef _WIN32 #define ABSL_SYMBOLIZE_TEST_NOINLINE __declspec(noinline) #else #define ABSL_SYMBOLIZE_TEST_NOINLINE ABSL_ATTRIBUTE_NOINLINE #endif extern "C" { ABSL_SYMBOLIZE_TEST_NOINLINE void nonstatic_func() { volatile int x = __LINE__; static_cast<void>(x); ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); } ABSL_SYMBOLIZE_TEST_NOINLINE static void static_func() { volatile int x = __LINE__; static_cast<void>(x); ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); } } struct Foo { static void func(int x); }; ABSL_SYMBOLIZE_TEST_NOINLINE void Foo::func(int) { volatile int x = __LINE__; static_cast<void>(x); ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); } int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.unlikely) unlikely_func() { return 0; } int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.hot) hot_func() { return 0; } int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.startup) startup_func() { return 0; } int ABSL_ATTRIBUTE_SECTION_VARIABLE(.text.exit) exit_func() { return 0; } int regular_func() { return 0; } #if ABSL_PER_THREAD_TLS static ABSL_PER_THREAD_TLS_KEYWORD char symbolize_test_thread_small[1]; static ABSL_PER_THREAD_TLS_KEYWORD char symbolize_test_thread_big[2 * 1024 * 1024]; #endif #if !defined(__EMSCRIPTEN__) static void *GetPCFromFnPtr(void *ptr) { return ptr; } static volatile bool volatile_bool = false; static constexpr size_t kHpageSize = 1 << 21; const char kHpageTextPadding[kHpageSize * 4] ABSL_ATTRIBUTE_SECTION_VARIABLE( .text) = ""; #else static void *GetPCFromFnPtr(void *ptr) { return EM_ASM_PTR( { return wasmOffsetConverter.convert(wasmTable.get($0).name, 0); }, ptr); } #endif static char try_symbolize_buffer[4096]; static const char *TrySymbolizeWithLimit(void *pc, int limit) { CHECK_LE(limit, sizeof(try_symbolize_buffer)) << "try_symbolize_buffer is too small"; auto heap_buffer = absl::make_unique<char[]>(sizeof(try_symbolize_buffer)); bool found = absl::Symbolize(pc, heap_buffer.get(), limit); if (found) { CHECK_LT(static_cast<int>( strnlen(heap_buffer.get(), static_cast<size_t>(limit))), limit) << "absl::Symbolize() did not properly terminate the string"; strncpy(try_symbolize_buffer, heap_buffer.get(), sizeof(try_symbolize_buffer) - 1); try_symbolize_buffer[sizeof(try_symbolize_buffer) - 1] = '\0'; } return found ? try_symbolize_buffer : nullptr; } static const char *TrySymbolize(void *pc) { return TrySymbolizeWithLimit(pc, sizeof(try_symbolize_buffer)); } #if defined(ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE) || \ defined(ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE) || \ defined(ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE) void ABSL_ATTRIBUTE_NOINLINE TestWithReturnAddress() { #if defined(ABSL_HAVE_ATTRIBUTE_NOINLINE) void *return_address = __builtin_return_address(0); const char *symbol = TrySymbolize(return_address); ASSERT_NE(symbol, nullptr) << "TestWithReturnAddress failed"; EXPECT_STREQ(symbol, "main") << "TestWithReturnAddress failed"; #endif } TEST(Symbolize, Cached) { EXPECT_STREQ("nonstatic_func", TrySymbolize(GetPCFromFnPtr((void *)(&nonstatic_func)))); const char *static_func_symbol = TrySymbolize(GetPCFromFnPtr((void *)(&static_func))); EXPECT_TRUE(strcmp("static_func", static_func_symbol) == 0 || strcmp("static_func()", static_func_symbol) == 0); EXPECT_TRUE(nullptr == TrySymbolize(nullptr)); } TEST(Symbolize, Truncation) { constexpr char kNonStaticFunc[] = "nonstatic_func"; EXPECT_STREQ("nonstatic_func", TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)), strlen(kNonStaticFunc) + 1)); EXPECT_STREQ("nonstatic_...", TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)), strlen(kNonStaticFunc) + 0)); EXPECT_STREQ("nonstatic...", TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)), strlen(kNonStaticFunc) - 1)); EXPECT_STREQ("n...", TrySymbolizeWithLimit( GetPCFromFnPtr((void *)(&nonstatic_func)), 5)); EXPECT_STREQ("...", TrySymbolizeWithLimit( GetPCFromFnPtr((void *)(&nonstatic_func)), 4)); EXPECT_STREQ("..", TrySymbolizeWithLimit( GetPCFromFnPtr((void *)(&nonstatic_func)), 3)); EXPECT_STREQ( ".", TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)), 2)); EXPECT_STREQ( "", TrySymbolizeWithLimit(GetPCFromFnPtr((void *)(&nonstatic_func)), 1)); EXPECT_EQ(nullptr, TrySymbolizeWithLimit( GetPCFromFnPtr((void *)(&nonstatic_func)), 0)); } TEST(Symbolize, SymbolizeWithDemangling) { Foo::func(100); #ifdef __EMSCRIPTEN__ EXPECT_STREQ("Foo::func(int)", TrySymbolize(GetPCFromFnPtr((void *)(&Foo::func)))); #else EXPECT_STREQ("Foo::func()", TrySymbolize(GetPCFromFnPtr((void *)(&Foo::func)))); #endif } TEST(Symbolize, SymbolizeSplitTextSections) { EXPECT_STREQ("unlikely_func()", TrySymbolize(GetPCFromFnPtr((void *)(&unlikely_func)))); EXPECT_STREQ("hot_func()", TrySymbolize(GetPCFromFnPtr((void *)(&hot_func)))); EXPECT_STREQ("startup_func()", TrySymbolize(GetPCFromFnPtr((void *)(&startup_func)))); EXPECT_STREQ("exit_func()", TrySymbolize(GetPCFromFnPtr((void *)(&exit_func)))); EXPECT_STREQ("regular_func()", TrySymbolize(GetPCFromFnPtr((void *)(&regular_func)))); } #ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION static void *g_pc_to_symbolize; static char g_symbolize_buffer[4096]; static char *g_symbolize_result; static void SymbolizeSignalHandler(int signo) { if (absl::Symbolize(g_pc_to_symbolize, g_symbolize_buffer, sizeof(g_symbolize_buffer))) { g_symbolize_result = g_symbolize_buffer; } else { g_symbolize_result = nullptr; } } static const char *SymbolizeStackConsumption(void *pc, int *stack_consumed) { g_pc_to_symbolize = pc; *stack_consumed = absl::debugging_internal::GetSignalHandlerStackConsumption( SymbolizeSignalHandler); return g_symbolize_result; } static int GetStackConsumptionUpperLimit() { int stack_consumption_upper_limit = 2048; #if defined(ABSL_HAVE_ADDRESS_SANITIZER) || \ defined(ABSL_HAVE_MEMORY_SANITIZER) || defined(ABSL_HAVE_THREAD_SANITIZER) stack_consumption_upper_limit *= 5; #endif return stack_consumption_upper_limit; } TEST(Symbolize, SymbolizeStackConsumption) { int stack_consumed = 0; const char *symbol = SymbolizeStackConsumption((void *)(&nonstatic_func), &stack_consumed); EXPECT_STREQ("nonstatic_func", symbol); EXPECT_GT(stack_consumed, 0); EXPECT_LT(stack_consumed, GetStackConsumptionUpperLimit()); symbol = SymbolizeStackConsumption((void *)(&static_func), &stack_consumed); EXPECT_TRUE(strcmp("static_func", symbol) == 0 || strcmp("static_func()", symbol) == 0); EXPECT_GT(stack_consumed, 0); EXPECT_LT(stack_consumed, GetStackConsumptionUpperLimit()); } TEST(Symbolize, SymbolizeWithDemanglingStackConsumption) { Foo::func(100); int stack_consumed = 0; const char *symbol = SymbolizeStackConsumption((void *)(&Foo::func), &stack_consumed); EXPECT_STREQ("Foo::func()", symbol); EXPECT_GT(stack_consumed, 0); EXPECT_LT(stack_consumed, GetStackConsumptionUpperLimit()); } #endif #if !defined(ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE) && \ !defined(ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE) const size_t kPageSize = 64 << 10; const char kPadding0[kPageSize * 4] ABSL_ATTRIBUTE_SECTION_VARIABLE(.text) = ""; const char kPadding1[kPageSize * 4] ABSL_ATTRIBUTE_SECTION_VARIABLE(.text) = ""; static int FilterElfHeader(struct dl_phdr_info *info, size_t size, void *data) { for (int i = 0; i < info->dlpi_phnum; i++) { if (info->dlpi_phdr[i].p_type == PT_LOAD && info->dlpi_phdr[i].p_flags == (PF_R | PF_X)) { const void *const vaddr = absl::bit_cast<void *>(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr); const auto segsize = info->dlpi_phdr[i].p_memsz; const char *self_exe; if (info->dlpi_name != nullptr && info->dlpi_name[0] != '\0') { self_exe = info->dlpi_name; } else { self_exe = "/proc/self/exe"; } absl::debugging_internal::RegisterFileMappingHint( vaddr, reinterpret_cast<const char *>(vaddr) + segsize, info->dlpi_phdr[i].p_offset, self_exe); return 1; } } return 1; } TEST(Symbolize, SymbolizeWithMultipleMaps) { if (volatile_bool) { LOG(INFO) << kPadding0; LOG(INFO) << kPadding1; } char buf[512]; memset(buf, 0, sizeof(buf)); absl::Symbolize(kPadding0, buf, sizeof(buf)); EXPECT_STREQ("kPadding0", buf); memset(buf, 0, sizeof(buf)); absl::Symbolize(kPadding1, buf, sizeof(buf)); EXPECT_STREQ("kPadding1", buf); dl_iterate_phdr(FilterElfHeader, nullptr); const char *ptrs[] = {kPadding0, kPadding1}; for (const char *ptr : ptrs) { const int kMapFlags = MAP_ANONYMOUS | MAP_PRIVATE; void *addr = mmap(nullptr, kPageSize, PROT_READ, kMapFlags, 0, 0); ASSERT_NE(addr, MAP_FAILED); void *remapped = reinterpret_cast<void *>( reinterpret_cast<uintptr_t>(ptr + kPageSize) & ~(kPageSize - 1ULL)); const int kMremapFlags = (MREMAP_MAYMOVE | MREMAP_FIXED); void *ret = mremap(addr, kPageSize, kPageSize, kMremapFlags, remapped); ASSERT_NE(ret, MAP_FAILED); } absl::Symbolize(nullptr, buf, sizeof(buf)); const char *expected[] = {"kPadding0", "kPadding1"}; const size_t offsets[] = {0, kPageSize, 2 * kPageSize, 3 * kPageSize}; for (int i = 0; i < 2; i++) { for (size_t offset : offsets) { memset(buf, 0, sizeof(buf)); absl::Symbolize(ptrs[i] + offset, buf, sizeof(buf)); EXPECT_STREQ(expected[i], buf); } } } static void DummySymbolDecorator( const absl::debugging_internal::SymbolDecoratorArgs *args) { std::string *message = static_cast<std::string *>(args->arg); strncat(args->symbol_buf, message->c_str(), args->symbol_buf_size - strlen(args->symbol_buf) - 1); } TEST(Symbolize, InstallAndRemoveSymbolDecorators) { int ticket_a; std::string a_message("a"); EXPECT_GE(ticket_a = absl::debugging_internal::InstallSymbolDecorator( DummySymbolDecorator, &a_message), 0); int ticket_b; std::string b_message("b"); EXPECT_GE(ticket_b = absl::debugging_internal::InstallSymbolDecorator( DummySymbolDecorator, &b_message), 0); int ticket_c; std::string c_message("c"); EXPECT_GE(ticket_c = absl::debugging_internal::InstallSymbolDecorator( DummySymbolDecorator, &c_message), 0); char *address = reinterpret_cast<char *>(4); EXPECT_STREQ("abc", TrySymbolize(address)); EXPECT_TRUE(absl::debugging_internal::RemoveSymbolDecorator(ticket_b)); EXPECT_STREQ("ac", TrySymbolize(address + 4)); EXPECT_TRUE(absl::debugging_internal::RemoveSymbolDecorator(ticket_a)); EXPECT_TRUE(absl::debugging_internal::RemoveSymbolDecorator(ticket_c)); } static int in_data_section = 1; TEST(Symbolize, ForEachSection) { int fd = TEMP_FAILURE_RETRY(open("/proc/self/exe", O_RDONLY)); ASSERT_NE(fd, -1); std::vector<std::string> sections; ASSERT_TRUE(absl::debugging_internal::ForEachSection( fd, [&sections](const absl::string_view name, const ElfW(Shdr) &) { sections.emplace_back(name); return true; })); EXPECT_THAT(sections, Contains(".text")); EXPECT_THAT(sections, Contains(".rodata")); EXPECT_THAT(sections, Contains(".bss")); ++in_data_section; EXPECT_THAT(sections, Contains(".data")); close(fd); } #endif extern "C" { inline void *ABSL_ATTRIBUTE_ALWAYS_INLINE inline_func() { void *pc = nullptr; #if defined(__i386__) __asm__ __volatile__("call 1f;\n 1: pop %[PC]" : [PC] "=r"(pc)); #elif defined(__x86_64__) __asm__ __volatile__("leaq 0(%%rip),%[PC];\n" : [PC] "=r"(pc)); #endif return pc; } void *ABSL_ATTRIBUTE_NOINLINE non_inline_func() { void *pc = nullptr; #if defined(__i386__) __asm__ __volatile__("call 1f;\n 1: pop %[PC]" : [PC] "=r"(pc)); #elif defined(__x86_64__) __asm__ __volatile__("leaq 0(%%rip),%[PC];\n" : [PC] "=r"(pc)); #endif return pc; } void ABSL_ATTRIBUTE_NOINLINE TestWithPCInsideNonInlineFunction() { #if defined(ABSL_HAVE_ATTRIBUTE_NOINLINE) && \ (defined(__i386__) || defined(__x86_64__)) void *pc = non_inline_func(); const char *symbol = TrySymbolize(pc); ASSERT_NE(symbol, nullptr) << "TestWithPCInsideNonInlineFunction failed"; EXPECT_STREQ(symbol, "non_inline_func") << "TestWithPCInsideNonInlineFunction failed"; #endif } void ABSL_ATTRIBUTE_NOINLINE TestWithPCInsideInlineFunction() { #if defined(ABSL_HAVE_ATTRIBUTE_ALWAYS_INLINE) && \ (defined(__i386__) || defined(__x86_64__)) void *pc = inline_func(); const char *symbol = TrySymbolize(pc); ASSERT_NE(symbol, nullptr) << "TestWithPCInsideInlineFunction failed"; EXPECT_STREQ(symbol, __FUNCTION__) << "TestWithPCInsideInlineFunction failed"; #endif } } #if defined(__arm__) && ABSL_HAVE_ATTRIBUTE(target) && \ ((__ARM_ARCH >= 7) || !defined(__ARM_PCS_VFP)) __attribute__((target("thumb"))) int ArmThumbOverlapThumb(int x) { return x * x * x; } __attribute__((target("arm"))) int ArmThumbOverlapArm(int x) { return x * x * x; } void ABSL_ATTRIBUTE_NOINLINE TestArmThumbOverlap() { #if defined(ABSL_HAVE_ATTRIBUTE_NOINLINE) const char *symbol = TrySymbolize((void *)&ArmThumbOverlapArm); ASSERT_NE(symbol, nullptr) << "TestArmThumbOverlap failed"; EXPECT_STREQ("ArmThumbOverlapArm()", symbol) << "TestArmThumbOverlap failed"; #endif } #endif #elif defined(_WIN32) #if !defined(ABSL_CONSUME_DLL) TEST(Symbolize, Basics) { EXPECT_STREQ("nonstatic_func", TrySymbolize((void *)(&nonstatic_func))); const char *static_func_symbol = TrySymbolize((void *)(&static_func)); ASSERT_TRUE(static_func_symbol != nullptr); EXPECT_TRUE(strstr(static_func_symbol, "static_func") != nullptr); EXPECT_TRUE(nullptr == TrySymbolize(nullptr)); } TEST(Symbolize, Truncation) { constexpr char kNonStaticFunc[] = "nonstatic_func"; EXPECT_STREQ("nonstatic_func", TrySymbolizeWithLimit((void *)(&nonstatic_func), strlen(kNonStaticFunc) + 1)); EXPECT_STREQ("nonstatic_...", TrySymbolizeWithLimit((void *)(&nonstatic_func), strlen(kNonStaticFunc) + 0)); EXPECT_STREQ("nonstatic...", TrySymbolizeWithLimit((void *)(&nonstatic_func), strlen(kNonStaticFunc) - 1)); EXPECT_STREQ("n...", TrySymbolizeWithLimit((void *)(&nonstatic_func), 5)); EXPECT_STREQ("...", TrySymbolizeWithLimit((void *)(&nonstatic_func), 4)); EXPECT_STREQ("..", TrySymbolizeWithLimit((void *)(&nonstatic_func), 3)); EXPECT_STREQ(".", TrySymbolizeWithLimit((void *)(&nonstatic_func), 2)); EXPECT_STREQ("", TrySymbolizeWithLimit((void *)(&nonstatic_func), 1)); EXPECT_EQ(nullptr, TrySymbolizeWithLimit((void *)(&nonstatic_func), 0)); } TEST(Symbolize, SymbolizeWithDemangling) { const char *result = TrySymbolize((void *)(&Foo::func)); ASSERT_TRUE(result != nullptr); EXPECT_TRUE(strstr(result, "Foo::func") != nullptr) << result; } #endif #else TEST(Symbolize, Unimplemented) { char buf[64]; EXPECT_FALSE(absl::Symbolize((void *)(&nonstatic_func), buf, sizeof(buf))); EXPECT_FALSE(absl::Symbolize((void *)(&static_func), buf, sizeof(buf))); EXPECT_FALSE(absl::Symbolize((void *)(&Foo::func), buf, sizeof(buf))); } #endif int main(int argc, char **argv) { #if !defined(__EMSCRIPTEN__) if (volatile_bool) { LOG(INFO) << kHpageTextPadding; } #endif #if ABSL_PER_THREAD_TLS symbolize_test_thread_small[0] = 0; symbolize_test_thread_big[0] = 0; #endif absl::InitializeSymbolizer(argv[0]); testing::InitGoogleTest(&argc, argv); #if defined(ABSL_INTERNAL_HAVE_ELF_SYMBOLIZE) || \ defined(ABSL_INTERNAL_HAVE_EMSCRIPTEN_SYMBOLIZE) || \ defined(ABSL_INTERNAL_HAVE_DARWIN_SYMBOLIZE) TestWithPCInsideInlineFunction(); TestWithPCInsideNonInlineFunction(); TestWithReturnAddress(); #if defined(__arm__) && ABSL_HAVE_ATTRIBUTE(target) && \ ((__ARM_ARCH >= 7) || !defined(__ARM_PCS_VFP)) TestArmThumbOverlap(); #endif #endif return RUN_ALL_TESTS(); }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/symbolize.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/symbolize_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
aa714b00-9f09-4f1f-a469-890581529792
cpp
abseil/abseil-cpp
failure_signal_handler
absl/debugging/failure_signal_handler.cc
absl/debugging/failure_signal_handler_test.cc
#include "absl/debugging/failure_signal_handler.h" #include "absl/base/config.h" #ifdef _WIN32 #include <windows.h> #else #include <sched.h> #include <unistd.h> #endif #ifdef __APPLE__ #include <TargetConditionals.h> #endif #ifdef ABSL_HAVE_MMAP #include <sys/mman.h> #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS) #define MAP_ANONYMOUS MAP_ANON #endif #endif #ifdef __linux__ #include <sys/prctl.h> #endif #include <algorithm> #include <atomic> #include <cerrno> #include <csignal> #include <cstdio> #include <cstring> #include <ctime> #include "absl/base/attributes.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/sysinfo.h" #include "absl/debugging/internal/examine_stack.h" #include "absl/debugging/stacktrace.h" #if !defined(_WIN32) && !defined(__wasi__) #define ABSL_HAVE_SIGACTION #if !(defined(TARGET_OS_OSX) && TARGET_OS_OSX) && \ !(defined(TARGET_OS_WATCH) && TARGET_OS_WATCH) && \ !(defined(TARGET_OS_TV) && TARGET_OS_TV) && !defined(__QNX__) #define ABSL_HAVE_SIGALTSTACK #endif #endif namespace absl { ABSL_NAMESPACE_BEGIN ABSL_CONST_INIT static FailureSignalHandlerOptions fsh_options; static void RaiseToDefaultHandler(int signo) { signal(signo, SIG_DFL); raise(signo); } struct FailureSignalData { const int signo; const char* const as_string; #ifdef ABSL_HAVE_SIGACTION struct sigaction previous_action; using StructSigaction = struct sigaction; #define FSD_PREVIOUS_INIT FailureSignalData::StructSigaction() #else void (*previous_handler)(int); #define FSD_PREVIOUS_INIT SIG_DFL #endif }; ABSL_CONST_INIT static FailureSignalData failure_signal_data[] = { {SIGSEGV, "SIGSEGV", FSD_PREVIOUS_INIT}, {SIGILL, "SIGILL", FSD_PREVIOUS_INIT}, {SIGFPE, "SIGFPE", FSD_PREVIOUS_INIT}, {SIGABRT, "SIGABRT", FSD_PREVIOUS_INIT}, {SIGTERM, "SIGTERM", FSD_PREVIOUS_INIT}, #ifndef _WIN32 {SIGBUS, "SIGBUS", FSD_PREVIOUS_INIT}, {SIGTRAP, "SIGTRAP", FSD_PREVIOUS_INIT}, #endif }; #undef FSD_PREVIOUS_INIT static void RaiseToPreviousHandler(int signo) { for (const auto& it : failure_signal_data) { if (it.signo == signo) { #ifdef ABSL_HAVE_SIGACTION sigaction(signo, &it.previous_action, nullptr); #else signal(signo, it.previous_handler); #endif raise(signo); return; } } RaiseToDefaultHandler(signo); } namespace debugging_internal { const char* FailureSignalToString(int signo) { for (const auto& it : failure_signal_data) { if (it.signo == signo) { return it.as_string; } } return ""; } } #ifdef ABSL_HAVE_SIGALTSTACK static bool SetupAlternateStackOnce() { #if defined(__wasm__) || defined(__asjms__) const size_t page_mask = getpagesize() - 1; #else const size_t page_mask = static_cast<size_t>(sysconf(_SC_PAGESIZE)) - 1; #endif size_t stack_size = (std::max(static_cast<size_t>(SIGSTKSZ), size_t{65536}) + page_mask) & ~page_mask; #if defined(ABSL_HAVE_ADDRESS_SANITIZER) || \ defined(ABSL_HAVE_MEMORY_SANITIZER) || defined(ABSL_HAVE_THREAD_SANITIZER) stack_size *= 5; #endif stack_t sigstk; memset(&sigstk, 0, sizeof(sigstk)); sigstk.ss_size = stack_size; #ifdef ABSL_HAVE_MMAP #ifndef MAP_STACK #define MAP_STACK 0 #endif sigstk.ss_sp = mmap(nullptr, sigstk.ss_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0); if (sigstk.ss_sp == MAP_FAILED) { ABSL_RAW_LOG(FATAL, "mmap() for alternate signal stack failed"); } #else sigstk.ss_sp = malloc(sigstk.ss_size); if (sigstk.ss_sp == nullptr) { ABSL_RAW_LOG(FATAL, "malloc() for alternate signal stack failed"); } #endif if (sigaltstack(&sigstk, nullptr) != 0) { ABSL_RAW_LOG(FATAL, "sigaltstack() failed with errno=%d", errno); } #ifdef __linux__ #if defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME) prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, sigstk.ss_sp, sigstk.ss_size, "absl-signalstack"); #endif #endif return true; } #endif #ifdef ABSL_HAVE_SIGACTION static int MaybeSetupAlternateStack() { #ifdef ABSL_HAVE_SIGALTSTACK ABSL_ATTRIBUTE_UNUSED static const bool kOnce = SetupAlternateStackOnce(); return SA_ONSTACK; #else return 0; #endif } static void InstallOneFailureHandler(FailureSignalData* data, void (*handler)(int, siginfo_t*, void*)) { struct sigaction act; memset(&act, 0, sizeof(act)); sigemptyset(&act.sa_mask); act.sa_flags |= SA_SIGINFO; act.sa_flags |= SA_NODEFER; if (fsh_options.use_alternate_stack) { act.sa_flags |= MaybeSetupAlternateStack(); } act.sa_sigaction = handler; ABSL_RAW_CHECK(sigaction(data->signo, &act, &data->previous_action) == 0, "sigaction() failed"); } #else static void InstallOneFailureHandler(FailureSignalData* data, void (*handler)(int)) { data->previous_handler = signal(data->signo, handler); ABSL_RAW_CHECK(data->previous_handler != SIG_ERR, "signal() failed"); } #endif static void WriteSignalMessage(int signo, int cpu, void (*writerfn)(const char*)) { char buf[96]; char on_cpu[32] = {0}; if (cpu != -1) { snprintf(on_cpu, sizeof(on_cpu), " on cpu %d", cpu); } const char* const signal_string = debugging_internal::FailureSignalToString(signo); if (signal_string != nullptr && signal_string[0] != '\0') { snprintf(buf, sizeof(buf), "*** %s received at time=%ld%s ***\n", signal_string, static_cast<long>(time(nullptr)), on_cpu); } else { snprintf(buf, sizeof(buf), "*** Signal %d received at time=%ld%s ***\n", signo, static_cast<long>(time(nullptr)), on_cpu); } writerfn(buf); } struct WriterFnStruct { void (*writerfn)(const char*); }; static void WriterFnWrapper(const char* data, void* arg) { static_cast<WriterFnStruct*>(arg)->writerfn(data); } ABSL_ATTRIBUTE_NOINLINE static void WriteStackTrace( void* ucontext, bool symbolize_stacktrace, void (*writerfn)(const char*, void*), void* writerfn_arg) { constexpr int kNumStackFrames = 32; void* stack[kNumStackFrames]; int frame_sizes[kNumStackFrames]; int min_dropped_frames; int depth = absl::GetStackFramesWithContext( stack, frame_sizes, kNumStackFrames, 1, ucontext, &min_dropped_frames); absl::debugging_internal::DumpPCAndFrameSizesAndStackTrace( absl::debugging_internal::GetProgramCounter(ucontext), stack, frame_sizes, depth, min_dropped_frames, symbolize_stacktrace, writerfn, writerfn_arg); } static void WriteFailureInfo(int signo, void* ucontext, int cpu, void (*writerfn)(const char*)) { WriterFnStruct writerfn_struct{writerfn}; WriteSignalMessage(signo, cpu, writerfn); WriteStackTrace(ucontext, fsh_options.symbolize_stacktrace, WriterFnWrapper, &writerfn_struct); } static void PortableSleepForSeconds(int seconds) { #ifdef _WIN32 Sleep(static_cast<DWORD>(seconds * 1000)); #else struct timespec sleep_time; sleep_time.tv_sec = seconds; sleep_time.tv_nsec = 0; while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) { } #endif } #ifdef ABSL_HAVE_ALARM static void ImmediateAbortSignalHandler(int) { RaiseToDefaultHandler(SIGABRT); } #endif using GetTidType = decltype(absl::base_internal::GetTID()); ABSL_CONST_INIT static std::atomic<GetTidType> failed_tid(0); #ifndef ABSL_HAVE_SIGACTION static void AbslFailureSignalHandler(int signo) { void* ucontext = nullptr; #else static void AbslFailureSignalHandler(int signo, siginfo_t*, void* ucontext) { #endif const GetTidType this_tid = absl::base_internal::GetTID(); GetTidType previous_failed_tid = 0; if (!failed_tid.compare_exchange_strong(previous_failed_tid, this_tid, std::memory_order_acq_rel, std::memory_order_relaxed)) { ABSL_RAW_LOG( ERROR, "Signal %d raised at PC=%p while already in AbslFailureSignalHandler()", signo, absl::debugging_internal::GetProgramCounter(ucontext)); if (this_tid != previous_failed_tid) { PortableSleepForSeconds(3); RaiseToDefaultHandler(signo); return; } } int my_cpu = -1; #ifdef ABSL_HAVE_SCHED_GETCPU my_cpu = sched_getcpu(); #endif #ifdef ABSL_HAVE_ALARM if (fsh_options.alarm_on_failure_secs > 0) { alarm(0); signal(SIGALRM, ImmediateAbortSignalHandler); alarm(static_cast<unsigned int>(fsh_options.alarm_on_failure_secs)); } #endif WriteFailureInfo( signo, ucontext, my_cpu, +[](const char* data) { absl::raw_log_internal::AsyncSignalSafeWriteError(data, strlen(data)); }); if (fsh_options.writerfn != nullptr) { WriteFailureInfo(signo, ucontext, my_cpu, fsh_options.writerfn); fsh_options.writerfn(nullptr); } if (fsh_options.call_previous_handler) { RaiseToPreviousHandler(signo); } else { RaiseToDefaultHandler(signo); } } void InstallFailureSignalHandler(const FailureSignalHandlerOptions& options) { fsh_options = options; for (auto& it : failure_signal_data) { InstallOneFailureHandler(&it, AbslFailureSignalHandler); } } ABSL_NAMESPACE_END }
#include "absl/debugging/failure_signal_handler.h" #include <csignal> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/internal/raw_logging.h" #include "absl/debugging/stacktrace.h" #include "absl/debugging/symbolize.h" #include "absl/log/check.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" namespace { using testing::StartsWith; #if GTEST_HAS_DEATH_TEST using FailureSignalHandlerDeathTest = ::testing::TestWithParam<int>; void InstallHandlerAndRaise(int signo) { absl::InstallFailureSignalHandler(absl::FailureSignalHandlerOptions()); raise(signo); } TEST_P(FailureSignalHandlerDeathTest, AbslFailureSignal) { const int signo = GetParam(); std::string exit_regex = absl::StrCat( "\\*\\*\\* ", absl::debugging_internal::FailureSignalToString(signo), " received at time="); #ifndef _WIN32 EXPECT_EXIT(InstallHandlerAndRaise(signo), testing::KilledBySignal(signo), exit_regex); #else EXPECT_DEATH_IF_SUPPORTED(InstallHandlerAndRaise(signo), exit_regex); #endif } ABSL_CONST_INIT FILE* error_file = nullptr; void WriteToErrorFile(const char* msg) { if (msg != nullptr) { ABSL_RAW_CHECK(fwrite(msg, strlen(msg), 1, error_file) == 1, "fwrite() failed"); } ABSL_RAW_CHECK(fflush(error_file) == 0, "fflush() failed"); } std::string GetTmpDir() { static const char* const kTmpEnvVars[] = {"TEST_TMPDIR", "TMPDIR", "TEMP", "TEMPDIR", "TMP"}; for (const char* const var : kTmpEnvVars) { const char* tmp_dir = std::getenv(var); if (tmp_dir != nullptr) { return tmp_dir; } } return "/tmp"; } void InstallHandlerWithWriteToFileAndRaise(const char* file, int signo) { error_file = fopen(file, "w"); CHECK_NE(error_file, nullptr) << "Failed create error_file"; absl::FailureSignalHandlerOptions options; options.writerfn = WriteToErrorFile; absl::InstallFailureSignalHandler(options); raise(signo); } TEST_P(FailureSignalHandlerDeathTest, AbslFatalSignalsWithWriterFn) { const int signo = GetParam(); std::string tmp_dir = GetTmpDir(); std::string file = absl::StrCat(tmp_dir, "/signo_", signo); std::string exit_regex = absl::StrCat( "\\*\\*\\* ", absl::debugging_internal::FailureSignalToString(signo), " received at time="); #ifndef _WIN32 EXPECT_EXIT(InstallHandlerWithWriteToFileAndRaise(file.c_str(), signo), testing::KilledBySignal(signo), exit_regex); #else EXPECT_DEATH_IF_SUPPORTED( InstallHandlerWithWriteToFileAndRaise(file.c_str(), signo), exit_regex); #endif std::fstream error_output(file); ASSERT_TRUE(error_output.is_open()) << file; std::string error_line; std::getline(error_output, error_line); EXPECT_THAT( error_line, StartsWith(absl::StrCat( "*** ", absl::debugging_internal::FailureSignalToString(signo), " received at "))); #if defined(__linux__) EXPECT_THAT(error_line, testing::HasSubstr(" on cpu ")); #endif if (absl::debugging_internal::StackTraceWorksForTest()) { std::getline(error_output, error_line); EXPECT_THAT(error_line, StartsWith("PC: ")); } } constexpr int kFailureSignals[] = { SIGSEGV, SIGILL, SIGFPE, SIGABRT, SIGTERM, #ifndef _WIN32 SIGBUS, SIGTRAP, #endif }; std::string SignalParamToString(const ::testing::TestParamInfo<int>& info) { std::string result = absl::debugging_internal::FailureSignalToString(info.param); if (result.empty()) { result = absl::StrCat(info.param); } return result; } INSTANTIATE_TEST_SUITE_P(AbslDeathTest, FailureSignalHandlerDeathTest, ::testing::ValuesIn(kFailureSignals), SignalParamToString); #endif } int main(int argc, char** argv) { absl::InitializeSymbolizer(argv[0]); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/failure_signal_handler.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/failure_signal_handler_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
c592c6a0-9729-40a5-b62b-7619780bc1a4
cpp
abseil/abseil-cpp
leak_check
absl/debugging/leak_check.cc
absl/debugging/leak_check_test.cc
#include "absl/debugging/leak_check.h" #include "absl/base/attributes.h" #include "absl/base/config.h" #if defined(ABSL_HAVE_LEAK_SANITIZER) #include <sanitizer/lsan_interface.h> #if ABSL_HAVE_ATTRIBUTE_WEAK extern "C" ABSL_ATTRIBUTE_WEAK int __lsan_is_turned_off(); #endif namespace absl { ABSL_NAMESPACE_BEGIN bool HaveLeakSanitizer() { return true; } #if ABSL_HAVE_ATTRIBUTE_WEAK bool LeakCheckerIsActive() { return !(&__lsan_is_turned_off && __lsan_is_turned_off()); } #else bool LeakCheckerIsActive() { return true; } #endif bool FindAndReportLeaks() { return __lsan_do_recoverable_leak_check() != 0; } void DoIgnoreLeak(const void* ptr) { __lsan_ignore_object(ptr); } void RegisterLivePointers(const void* ptr, size_t size) { __lsan_register_root_region(ptr, size); } void UnRegisterLivePointers(const void* ptr, size_t size) { __lsan_unregister_root_region(ptr, size); } LeakCheckDisabler::LeakCheckDisabler() { __lsan_disable(); } LeakCheckDisabler::~LeakCheckDisabler() { __lsan_enable(); } ABSL_NAMESPACE_END } #else namespace absl { ABSL_NAMESPACE_BEGIN bool HaveLeakSanitizer() { return false; } bool LeakCheckerIsActive() { return false; } void DoIgnoreLeak(const void*) { } void RegisterLivePointers(const void*, size_t) { } void UnRegisterLivePointers(const void*, size_t) { } LeakCheckDisabler::LeakCheckDisabler() = default; LeakCheckDisabler::~LeakCheckDisabler() = default; ABSL_NAMESPACE_END } #endif
#include <string> #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/debugging/leak_check.h" #include "absl/log/log.h" namespace { TEST(LeakCheckTest, IgnoreLeakSuppressesLeakedMemoryErrors) { if (!absl::LeakCheckerIsActive()) { GTEST_SKIP() << "LeakChecker is not active"; } auto foo = absl::IgnoreLeak(new std::string("some ignored leaked string")); LOG(INFO) << "Ignoring leaked string " << foo; } TEST(LeakCheckTest, LeakCheckDisablerIgnoresLeak) { if (!absl::LeakCheckerIsActive()) { GTEST_SKIP() << "LeakChecker is not active"; } absl::LeakCheckDisabler disabler; auto foo = new std::string("some string leaked while checks are disabled"); LOG(INFO) << "Ignoring leaked string " << foo; } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/leak_check.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/leak_check_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
03fd3fca-6046-4159-b19f-540a358fdd4f
cpp
abseil/abseil-cpp
stacktrace
absl/debugging/stacktrace.cc
absl/debugging/stacktrace_test.cc
#include "absl/debugging/stacktrace.h" #include <atomic> #include "absl/base/attributes.h" #include "absl/base/port.h" #include "absl/debugging/internal/stacktrace_config.h" #if defined(ABSL_STACKTRACE_INL_HEADER) #include ABSL_STACKTRACE_INL_HEADER #else # error Cannot calculate stack trace: will need to write for your environment # include "absl/debugging/internal/stacktrace_aarch64-inl.inc" # include "absl/debugging/internal/stacktrace_arm-inl.inc" # include "absl/debugging/internal/stacktrace_emscripten-inl.inc" # include "absl/debugging/internal/stacktrace_generic-inl.inc" # include "absl/debugging/internal/stacktrace_powerpc-inl.inc" # include "absl/debugging/internal/stacktrace_riscv-inl.inc" # include "absl/debugging/internal/stacktrace_unimplemented-inl.inc" # include "absl/debugging/internal/stacktrace_win32-inl.inc" # include "absl/debugging/internal/stacktrace_x86-inl.inc" #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace { typedef int (*Unwinder)(void**, int*, int, int, const void*, int*); std::atomic<Unwinder> custom; template <bool IS_STACK_FRAMES, bool IS_WITH_CONTEXT> ABSL_ATTRIBUTE_ALWAYS_INLINE inline int Unwind(void** result, int* sizes, int max_depth, int skip_count, const void* uc, int* min_dropped_frames) { Unwinder f = &UnwindImpl<IS_STACK_FRAMES, IS_WITH_CONTEXT>; Unwinder g = custom.load(std::memory_order_acquire); if (g != nullptr) f = g; int size = (*f)(result, sizes, max_depth, skip_count + 1, uc, min_dropped_frames); ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); return size; } } ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL int GetStackFrames( void** result, int* sizes, int max_depth, int skip_count) { return Unwind<true, false>(result, sizes, max_depth, skip_count, nullptr, nullptr); } ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL int GetStackFramesWithContext(void** result, int* sizes, int max_depth, int skip_count, const void* uc, int* min_dropped_frames) { return Unwind<true, true>(result, sizes, max_depth, skip_count, uc, min_dropped_frames); } ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL int GetStackTrace( void** result, int max_depth, int skip_count) { return Unwind<false, false>(result, nullptr, max_depth, skip_count, nullptr, nullptr); } ABSL_ATTRIBUTE_NOINLINE ABSL_ATTRIBUTE_NO_TAIL_CALL int GetStackTraceWithContext(void** result, int max_depth, int skip_count, const void* uc, int* min_dropped_frames) { return Unwind<false, true>(result, nullptr, max_depth, skip_count, uc, min_dropped_frames); } void SetStackUnwinder(Unwinder w) { custom.store(w, std::memory_order_release); } int DefaultStackUnwinder(void** pcs, int* sizes, int depth, int skip, const void* uc, int* min_dropped_frames) { skip++; Unwinder f = nullptr; if (sizes == nullptr) { if (uc == nullptr) { f = &UnwindImpl<false, false>; } else { f = &UnwindImpl<false, true>; } } else { if (uc == nullptr) { f = &UnwindImpl<true, false>; } else { f = &UnwindImpl<true, true>; } } volatile int x = 0; int n = (*f)(pcs, sizes, depth, skip, uc, min_dropped_frames); x = 1; (void) x; return n; } ABSL_NAMESPACE_END }
#include "absl/debugging/stacktrace.h" #include "gtest/gtest.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" namespace { #if defined(__linux__) && (defined(__x86_64__) || defined(__aarch64__)) ABSL_ATTRIBUTE_NOINLINE void Unwind(void* p) { ABSL_ATTRIBUTE_UNUSED static void* volatile sink = p; constexpr int kSize = 16; void* stack[kSize]; int frames[kSize]; absl::GetStackTrace(stack, kSize, 0); absl::GetStackFrames(stack, frames, kSize, 0); } ABSL_ATTRIBUTE_NOINLINE void HugeFrame() { char buffer[1 << 20]; Unwind(buffer); ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); } TEST(StackTrace, HugeFrame) { HugeFrame(); ABSL_BLOCK_TAIL_CALL_OPTIMIZATION(); } #endif }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/stacktrace.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/stacktrace_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
e94359c1-9f65-4511-82da-655ef1410361
cpp
abseil/abseil-cpp
utf8_for_code_point
absl/debugging/internal/utf8_for_code_point.cc
absl/debugging/internal/utf8_for_code_point_test.cc
#include "absl/debugging/internal/utf8_for_code_point.h" #include <cstdint> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { namespace { constexpr uint32_t kMinSurrogate = 0xd800, kMaxSurrogate = 0xdfff; constexpr uint32_t kMax1ByteCodePoint = 0x7f; constexpr uint32_t kMax2ByteCodePoint = 0x7ff; constexpr uint32_t kMax3ByteCodePoint = 0xffff; constexpr uint32_t kMaxCodePoint = 0x10ffff; } Utf8ForCodePoint::Utf8ForCodePoint(uint64_t code_point) { if (code_point <= kMax1ByteCodePoint) { length = 1; bytes[0] = static_cast<char>(code_point); return; } if (code_point <= kMax2ByteCodePoint) { length = 2; bytes[0] = static_cast<char>(0xc0 | (code_point >> 6)); bytes[1] = static_cast<char>(0x80 | (code_point & 0x3f)); return; } if (kMinSurrogate <= code_point && code_point <= kMaxSurrogate) return; if (code_point <= kMax3ByteCodePoint) { length = 3; bytes[0] = static_cast<char>(0xe0 | (code_point >> 12)); bytes[1] = static_cast<char>(0x80 | ((code_point >> 6) & 0x3f)); bytes[2] = static_cast<char>(0x80 | (code_point & 0x3f)); return; } if (code_point > kMaxCodePoint) return; length = 4; bytes[0] = static_cast<char>(0xf0 | (code_point >> 18)); bytes[1] = static_cast<char>(0x80 | ((code_point >> 12) & 0x3f)); bytes[2] = static_cast<char>(0x80 | ((code_point >> 6) & 0x3f)); bytes[3] = static_cast<char>(0x80 | (code_point & 0x3f)); } } ABSL_NAMESPACE_END }
#include "absl/debugging/internal/utf8_for_code_point.h" #include <cstdint> #include "gtest/gtest.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { namespace { TEST(Utf8ForCodePointTest, RecognizesTheSmallestCodePoint) { Utf8ForCodePoint utf8(uint64_t{0}); ASSERT_EQ(utf8.length, 1); EXPECT_EQ(utf8.bytes[0], '\0'); } TEST(Utf8ForCodePointTest, RecognizesAsciiSmallA) { Utf8ForCodePoint utf8(uint64_t{'a'}); ASSERT_EQ(utf8.length, 1); EXPECT_EQ(utf8.bytes[0], 'a'); } TEST(Utf8ForCodePointTest, RecognizesTheLargestOneByteCodePoint) { Utf8ForCodePoint utf8(uint64_t{0x7f}); ASSERT_EQ(utf8.length, 1); EXPECT_EQ(utf8.bytes[0], '\x7f'); } TEST(Utf8ForCodePointTest, RecognizesTheSmallestTwoByteCodePoint) { Utf8ForCodePoint utf8(uint64_t{0x80}); ASSERT_EQ(utf8.length, 2); EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xc2)); EXPECT_EQ(utf8.bytes[1], static_cast<char>(0x80)); } TEST(Utf8ForCodePointTest, RecognizesSmallNWithTilde) { Utf8ForCodePoint utf8(uint64_t{0xf1}); ASSERT_EQ(utf8.length, 2); const char* want = "ñ"; EXPECT_EQ(utf8.bytes[0], want[0]); EXPECT_EQ(utf8.bytes[1], want[1]); } TEST(Utf8ForCodePointTest, RecognizesCapitalPi) { Utf8ForCodePoint utf8(uint64_t{0x3a0}); ASSERT_EQ(utf8.length, 2); const char* want = "Π"; EXPECT_EQ(utf8.bytes[0], want[0]); EXPECT_EQ(utf8.bytes[1], want[1]); } TEST(Utf8ForCodePointTest, RecognizesTheLargestTwoByteCodePoint) { Utf8ForCodePoint utf8(uint64_t{0x7ff}); ASSERT_EQ(utf8.length, 2); EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xdf)); EXPECT_EQ(utf8.bytes[1], static_cast<char>(0xbf)); } TEST(Utf8ForCodePointTest, RecognizesTheSmallestThreeByteCodePoint) { Utf8ForCodePoint utf8(uint64_t{0x800}); ASSERT_EQ(utf8.length, 3); EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xe0)); EXPECT_EQ(utf8.bytes[1], static_cast<char>(0xa0)); EXPECT_EQ(utf8.bytes[2], static_cast<char>(0x80)); } TEST(Utf8ForCodePointTest, RecognizesTheChineseCharacterZhong1AsInZhong1Wen2) { Utf8ForCodePoint utf8(uint64_t{0x4e2d}); ASSERT_EQ(utf8.length, 3); const char* want = "中"; EXPECT_EQ(utf8.bytes[0], want[0]); EXPECT_EQ(utf8.bytes[1], want[1]); EXPECT_EQ(utf8.bytes[2], want[2]); } TEST(Utf8ForCodePointTest, RecognizesOneBeforeTheSmallestSurrogate) { Utf8ForCodePoint utf8(uint64_t{0xd7ff}); ASSERT_EQ(utf8.length, 3); EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xed)); EXPECT_EQ(utf8.bytes[1], static_cast<char>(0x9f)); EXPECT_EQ(utf8.bytes[2], static_cast<char>(0xbf)); } TEST(Utf8ForCodePointTest, RejectsTheSmallestSurrogate) { Utf8ForCodePoint utf8(uint64_t{0xd800}); EXPECT_EQ(utf8.length, 0); } TEST(Utf8ForCodePointTest, RejectsTheLargestSurrogate) { Utf8ForCodePoint utf8(uint64_t{0xdfff}); EXPECT_EQ(utf8.length, 0); } TEST(Utf8ForCodePointTest, RecognizesOnePastTheLargestSurrogate) { Utf8ForCodePoint utf8(uint64_t{0xe000}); ASSERT_EQ(utf8.length, 3); EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xee)); EXPECT_EQ(utf8.bytes[1], static_cast<char>(0x80)); EXPECT_EQ(utf8.bytes[2], static_cast<char>(0x80)); } TEST(Utf8ForCodePointTest, RecognizesTheLargestThreeByteCodePoint) { Utf8ForCodePoint utf8(uint64_t{0xffff}); ASSERT_EQ(utf8.length, 3); EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xef)); EXPECT_EQ(utf8.bytes[1], static_cast<char>(0xbf)); EXPECT_EQ(utf8.bytes[2], static_cast<char>(0xbf)); } TEST(Utf8ForCodePointTest, RecognizesTheSmallestFourByteCodePoint) { Utf8ForCodePoint utf8(uint64_t{0x10000}); ASSERT_EQ(utf8.length, 4); EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xf0)); EXPECT_EQ(utf8.bytes[1], static_cast<char>(0x90)); EXPECT_EQ(utf8.bytes[2], static_cast<char>(0x80)); EXPECT_EQ(utf8.bytes[3], static_cast<char>(0x80)); } TEST(Utf8ForCodePointTest, RecognizesTheJackOfHearts) { Utf8ForCodePoint utf8(uint64_t{0x1f0bb}); ASSERT_EQ(utf8.length, 4); const char* want = "🂻"; EXPECT_EQ(utf8.bytes[0], want[0]); EXPECT_EQ(utf8.bytes[1], want[1]); EXPECT_EQ(utf8.bytes[2], want[2]); EXPECT_EQ(utf8.bytes[3], want[3]); } TEST(Utf8ForCodePointTest, RecognizesTheLargestFourByteCodePoint) { Utf8ForCodePoint utf8(uint64_t{0x10ffff}); ASSERT_EQ(utf8.length, 4); EXPECT_EQ(utf8.bytes[0], static_cast<char>(0xf4)); EXPECT_EQ(utf8.bytes[1], static_cast<char>(0x8f)); EXPECT_EQ(utf8.bytes[2], static_cast<char>(0xbf)); EXPECT_EQ(utf8.bytes[3], static_cast<char>(0xbf)); } TEST(Utf8ForCodePointTest, RejectsTheSmallestOverlargeCodePoint) { Utf8ForCodePoint utf8(uint64_t{0x110000}); EXPECT_EQ(utf8.length, 0); } TEST(Utf8ForCodePointTest, RejectsAThroughlyOverlargeCodePoint) { Utf8ForCodePoint utf8(uint64_t{0xffffffff00000000}); EXPECT_EQ(utf8.length, 0); } TEST(Utf8ForCodePointTest, OkReturnsTrueForAValidCodePoint) { EXPECT_TRUE(Utf8ForCodePoint(uint64_t{0}).ok()); } TEST(Utf8ForCodePointTest, OkReturnsFalseForAnInvalidCodePoint) { EXPECT_FALSE(Utf8ForCodePoint(uint64_t{0xffffffff00000000}).ok()); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/internal/utf8_for_code_point.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/internal/utf8_for_code_point_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
dcdef421-b677-448b-ba64-e6868f89a248
cpp
abseil/abseil-cpp
stack_consumption
absl/debugging/internal/stack_consumption.cc
absl/debugging/internal/stack_consumption_test.cc
#include "absl/debugging/internal/stack_consumption.h" #ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION #include <signal.h> #include <string.h> #include <sys/mman.h> #include <unistd.h> #include "absl/base/attributes.h" #include "absl/base/internal/raw_logging.h" #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS) #define MAP_ANONYMOUS MAP_ANON #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { namespace { #if defined(__i386__) || defined(__x86_64__) || defined(__ppc__) || \ defined(__aarch64__) || defined(__riscv) constexpr bool kStackGrowsDown = true; #else #error Need to define kStackGrowsDown #endif void EmptySignalHandler(int) {} constexpr int kAlternateStackSize = 64 << 10; constexpr int kSafetyMargin = 32; constexpr char kAlternateStackFillValue = 0x55; int GetStackConsumption(const void* const altstack) { const char* begin; int increment; if (kStackGrowsDown) { begin = reinterpret_cast<const char*>(altstack); increment = 1; } else { begin = reinterpret_cast<const char*>(altstack) + kAlternateStackSize - 1; increment = -1; } for (int usage_count = kAlternateStackSize; usage_count > 0; --usage_count) { if (*begin != kAlternateStackFillValue) { ABSL_RAW_CHECK(usage_count <= kAlternateStackSize - kSafetyMargin, "Buffer has overflowed or is about to overflow"); return usage_count; } begin += increment; } ABSL_RAW_LOG(FATAL, "Unreachable code"); return -1; } } int GetSignalHandlerStackConsumption(void (*signal_handler)(int)) { void* altstack = mmap(nullptr, kAlternateStackSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); ABSL_RAW_CHECK(altstack != MAP_FAILED, "mmap() failed"); stack_t sigstk; memset(&sigstk, 0, sizeof(sigstk)); sigstk.ss_sp = altstack; sigstk.ss_size = kAlternateStackSize; sigstk.ss_flags = 0; stack_t old_sigstk; memset(&old_sigstk, 0, sizeof(old_sigstk)); ABSL_RAW_CHECK(sigaltstack(&sigstk, &old_sigstk) == 0, "sigaltstack() failed"); struct sigaction sa; memset(&sa, 0, sizeof(sa)); struct sigaction old_sa1, old_sa2; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_ONSTACK; sa.sa_handler = EmptySignalHandler; ABSL_RAW_CHECK(sigaction(SIGUSR1, &sa, &old_sa1) == 0, "sigaction() failed"); sa.sa_handler = signal_handler; ABSL_RAW_CHECK(sigaction(SIGUSR2, &sa, &old_sa2) == 0, "sigaction() failed"); ABSL_RAW_CHECK(kill(getpid(), SIGUSR1) == 0, "kill() failed"); memset(altstack, kAlternateStackFillValue, kAlternateStackSize); ABSL_RAW_CHECK(kill(getpid(), SIGUSR1) == 0, "kill() failed"); int base_stack_consumption = GetStackConsumption(altstack); ABSL_RAW_CHECK(kill(getpid(), SIGUSR2) == 0, "kill() failed"); int signal_handler_stack_consumption = GetStackConsumption(altstack); if (old_sigstk.ss_sp == nullptr && old_sigstk.ss_size == 0 && (old_sigstk.ss_flags & SS_DISABLE)) { old_sigstk.ss_size = static_cast<size_t>(MINSIGSTKSZ); } ABSL_RAW_CHECK(sigaltstack(&old_sigstk, nullptr) == 0, "sigaltstack() failed"); ABSL_RAW_CHECK(sigaction(SIGUSR1, &old_sa1, nullptr) == 0, "sigaction() failed"); ABSL_RAW_CHECK(sigaction(SIGUSR2, &old_sa2, nullptr) == 0, "sigaction() failed"); ABSL_RAW_CHECK(munmap(altstack, kAlternateStackSize) == 0, "munmap() failed"); if (signal_handler_stack_consumption != -1 && base_stack_consumption != -1) { return signal_handler_stack_consumption - base_stack_consumption; } return -1; } } ABSL_NAMESPACE_END } #else #ifdef __APPLE__ namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { extern const char kAvoidEmptyStackConsumptionLibraryWarning; const char kAvoidEmptyStackConsumptionLibraryWarning = 0; } ABSL_NAMESPACE_END } #endif #endif
#include "absl/debugging/internal/stack_consumption.h" #ifdef ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION #include <string.h> #include "gtest/gtest.h" #include "absl/log/log.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { namespace { static void SimpleSignalHandler(int signo) { char buf[100]; memset(buf, 'a', sizeof(buf)); if (signo == 0) { LOG(INFO) << static_cast<void*>(buf); } } TEST(SignalHandlerStackConsumptionTest, MeasuresStackConsumption) { EXPECT_GE(GetSignalHandlerStackConsumption(SimpleSignalHandler), 100); } } } ABSL_NAMESPACE_END } #endif
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/internal/stack_consumption.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/internal/stack_consumption_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
0f329122-8f19-41a9-81b2-7b068f84edbb
cpp
abseil/abseil-cpp
decode_rust_punycode
absl/debugging/internal/decode_rust_punycode.cc
absl/debugging/internal/decode_rust_punycode_test.cc
#include "absl/debugging/internal/decode_rust_punycode.h" #include <cstddef> #include <cstdint> #include <cstring> #include "absl/base/config.h" #include "absl/base/nullability.h" #include "absl/debugging/internal/bounded_utf8_length_sequence.h" #include "absl/debugging/internal/utf8_for_code_point.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { namespace { constexpr uint32_t kMaxChars = 256; constexpr uint32_t kBase = 36, kTMin = 1, kTMax = 26, kSkew = 38, kDamp = 700; constexpr uint32_t kMaxCodePoint = 0x10ffff; constexpr uint32_t kMaxI = 1 << 30; bool ConsumeOptionalAsciiPrefix(const char*& punycode_begin, const char* const punycode_end, char* const out_begin, char* const out_end, uint32_t& num_ascii_chars) { num_ascii_chars = 0; int last_underscore = -1; for (int i = 0; i < punycode_end - punycode_begin; ++i) { const char c = punycode_begin[i]; if (c == '_') { last_underscore = i; continue; } if ('a' <= c && c <= 'z') continue; if ('A' <= c && c <= 'Z') continue; if ('0' <= c && c <= '9') continue; return false; } if (last_underscore < 0) return true; if (last_underscore == 0) return false; if (last_underscore + 1 > out_end - out_begin) return false; num_ascii_chars = static_cast<uint32_t>(last_underscore); std::memcpy(out_begin, punycode_begin, num_ascii_chars); out_begin[num_ascii_chars] = '\0'; punycode_begin += num_ascii_chars + 1; return true; } int DigitValue(char c) { if ('0' <= c && c <= '9') return c - '0' + 26; if ('a' <= c && c <= 'z') return c - 'a'; if ('A' <= c && c <= 'Z') return c - 'A'; return -1; } bool ScanNextDelta(const char*& punycode_begin, const char* const punycode_end, uint32_t bias, uint32_t& i) { uint64_t w = 1; for (uint32_t k = kBase; punycode_begin != punycode_end; k += kBase) { const int digit_value = DigitValue(*punycode_begin++); if (digit_value < 0) return false; const uint64_t new_i = i + static_cast<uint64_t>(digit_value) * w; static_assert( kMaxI >= kMaxChars * kMaxCodePoint, "kMaxI is too small to prevent spurious failures on good input"); if (new_i > kMaxI) return false; static_assert( kMaxI < (uint64_t{1} << 32), "Make kMaxI smaller or i 64 bits wide to prevent silent wraparound"); i = static_cast<uint32_t>(new_i); uint32_t t; if (k <= bias + kTMin) { t = kTMin; } else if (k >= bias + kTMax) { t = kTMax; } else { t = k - bias; } if (static_cast<uint32_t>(digit_value) < t) return true; w *= kBase - t; } return false; } } absl::Nullable<char*> DecodeRustPunycode(DecodeRustPunycodeOptions options) { const char* punycode_begin = options.punycode_begin; const char* const punycode_end = options.punycode_end; char* const out_begin = options.out_begin; char* const out_end = options.out_end; const size_t out_size = static_cast<size_t>(out_end - out_begin); if (out_size == 0) return nullptr; *out_begin = '\0'; uint32_t n = 128, i = 0, bias = 72, num_chars = 0; if (!ConsumeOptionalAsciiPrefix(punycode_begin, punycode_end, out_begin, out_end, num_chars)) { return nullptr; } uint32_t total_utf8_bytes = num_chars; BoundedUtf8LengthSequence<kMaxChars> utf8_lengths; while (punycode_begin != punycode_end) { if (num_chars >= kMaxChars) return nullptr; const uint32_t old_i = i; if (!ScanNextDelta(punycode_begin, punycode_end, bias, i)) return nullptr; uint32_t delta = i - old_i; delta /= (old_i == 0 ? kDamp : 2); delta += delta/(num_chars + 1); bias = 0; while (delta > ((kBase - kTMin) * kTMax)/2) { delta /= kBase - kTMin; bias += kBase; } bias += ((kBase - kTMin + 1) * delta)/(delta + kSkew); static_assert( kMaxI + kMaxCodePoint < (uint64_t{1} << 32), "Make kMaxI smaller or n 64 bits wide to prevent silent wraparound"); n += i/(num_chars + 1); i %= num_chars + 1; Utf8ForCodePoint utf8_for_code_point(n); if (!utf8_for_code_point.ok()) return nullptr; if (total_utf8_bytes + utf8_for_code_point.length + 1 > out_size) { return nullptr; } uint32_t n_index = utf8_lengths.InsertAndReturnSumOfPredecessors( i, utf8_for_code_point.length); std::memmove( out_begin + n_index + utf8_for_code_point.length, out_begin + n_index, total_utf8_bytes + 1 - n_index); std::memcpy(out_begin + n_index, utf8_for_code_point.bytes, utf8_for_code_point.length); total_utf8_bytes += utf8_for_code_point.length; ++num_chars; ++i; } return out_begin + total_utf8_bytes; } } ABSL_NAMESPACE_END }
#include "absl/debugging/internal/decode_rust_punycode.h" #include <cstddef> #include <cstring> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { namespace { using ::testing::AllOf; using ::testing::Eq; using ::testing::IsNull; using ::testing::Pointee; using ::testing::ResultOf; using ::testing::StrEq; class DecodeRustPunycodeTest : public ::testing::Test { protected: void FillBufferWithNonzeroBytes() { std::memset(buffer_storage_, 0xab, sizeof(buffer_storage_)); } DecodeRustPunycodeOptions WithAmpleSpace() { FillBufferWithNonzeroBytes(); DecodeRustPunycodeOptions options; options.punycode_begin = punycode_.data(); options.punycode_end = punycode_.data() + punycode_.size(); options.out_begin = buffer_storage_; options.out_end = buffer_storage_ + sizeof(buffer_storage_); return options; } DecodeRustPunycodeOptions WithJustEnoughSpace() { FillBufferWithNonzeroBytes(); const size_t begin_offset = sizeof(buffer_storage_) - plaintext_.size() - 1; DecodeRustPunycodeOptions options; options.punycode_begin = punycode_.data(); options.punycode_end = punycode_.data() + punycode_.size(); options.out_begin = buffer_storage_ + begin_offset; options.out_end = buffer_storage_ + sizeof(buffer_storage_); return options; } DecodeRustPunycodeOptions WithOneByteTooFew() { FillBufferWithNonzeroBytes(); const size_t begin_offset = sizeof(buffer_storage_) - plaintext_.size(); DecodeRustPunycodeOptions options; options.punycode_begin = punycode_.data(); options.punycode_end = punycode_.data() + punycode_.size(); options.out_begin = buffer_storage_ + begin_offset; options.out_end = buffer_storage_ + sizeof(buffer_storage_); return options; } auto PointsToTheNulAfter(const std::string& golden) { const size_t golden_size = golden.size(); return AllOf( Pointee(Eq('\0')), ResultOf("preceding string body", [golden_size](const char* p) { return p - golden_size; }, StrEq(golden))); } std::string punycode_; std::string plaintext_; char buffer_storage_[1024]; }; TEST_F(DecodeRustPunycodeTest, MapsEmptyToEmpty) { punycode_ = ""; plaintext_ = ""; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, StripsTheTrailingDelimiterFromAPureRunOfBasicChars) { punycode_ = "foo_"; plaintext_ = "foo"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, TreatsTheLastUnderscoreAsTheDelimiter) { punycode_ = "foo_bar_"; plaintext_ = "foo_bar"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsALeadingUnderscoreIfNotTheDelimiter) { punycode_ = "_foo_"; plaintext_ = "_foo"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, RejectsALeadingUnderscoreDelimiter) { punycode_ = "_foo"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); } TEST_F(DecodeRustPunycodeTest, RejectsEmbeddedNul) { punycode_ = std::string("foo\0bar_", 8); EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); } TEST_F(DecodeRustPunycodeTest, RejectsAsciiCharsOtherThanIdentifierChars) { punycode_ = "foo\007_"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); punycode_ = "foo-_"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); punycode_ = "foo;_"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); punycode_ = "foo\177_"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); } TEST_F(DecodeRustPunycodeTest, RejectsRawNonAsciiChars) { punycode_ = "\x80"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); punycode_ = "\x80_"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); punycode_ = "\xff"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); punycode_ = "\xff_"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); } TEST_F(DecodeRustPunycodeTest, RecognizesU0080) { punycode_ = "a"; plaintext_ = "\xc2\x80"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, OneByteDeltaSequencesMustBeA) { punycode_ = "b"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); punycode_ = "z"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); punycode_ = "0"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); punycode_ = "9"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsDeltaSequenceBA) { punycode_ = "ba"; plaintext_ = "\xc2\x81"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsOtherDeltaSequencesWithSecondByteA) { punycode_ = "ca"; plaintext_ = "\xc2\x82"; EXPECT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); punycode_ = "za"; plaintext_ = "\xc2\x99"; EXPECT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); punycode_ = "0a"; plaintext_ = "\xc2\x9a"; EXPECT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); punycode_ = "1a"; plaintext_ = "\xc2\x9b"; EXPECT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); punycode_ = "9a"; plaintext_ = "£"; EXPECT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); } TEST_F(DecodeRustPunycodeTest, RejectsDeltaWhereTheSecondAndLastDigitIsNotA) { punycode_ = "bb"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); punycode_ = "zz"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); punycode_ = "00"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); punycode_ = "99"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsDeltasWithSecondByteBFollowedByA) { punycode_ = "bba"; plaintext_ = "¤"; EXPECT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); punycode_ = "cba"; plaintext_ = "¥"; EXPECT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); punycode_ = "zba"; plaintext_ = "¼"; EXPECT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); punycode_ = "0ba"; plaintext_ = "½"; EXPECT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); punycode_ = "1ba"; plaintext_ = "¾"; EXPECT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); punycode_ = "9ba"; plaintext_ = "Æ"; EXPECT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); } TEST_F(DecodeRustPunycodeTest, AcceptsTwoByteCharAlone) { punycode_ = "0ca"; plaintext_ = "à"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsTwoByteCharBeforeBasicChars) { punycode_ = "_la_mode_yya"; plaintext_ = "à_la_mode"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsTwoByteCharAmidBasicChars) { punycode_ = "verre__vin_m4a"; plaintext_ = "verre_à_vin"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsTwoByteCharAfterBasicChars) { punycode_ = "belt_3na"; plaintext_ = "beltà"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsRepeatedTwoByteChar) { punycode_ = "0caaaa"; plaintext_ = "àààà"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsNearbyTwoByteCharsInOrder) { punycode_ = "3camsuz"; plaintext_ = "ãéïôù"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsNearbyTwoByteCharsOutOfOrder) { punycode_ = "3caltsx"; plaintext_ = "ùéôãï"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsThreeByteCharAlone) { punycode_ = "fiq"; plaintext_ = "中"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsRepeatedThreeByteChar) { punycode_ = "fiqaaaa"; plaintext_ = "中中中中中"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsThreeByteCharsInOrder) { punycode_ = "fiq228c"; plaintext_ = "中文"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsNearbyThreeByteCharsOutOfOrder) { punycode_ = "fiq128c"; plaintext_ = "文中"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsFourByteCharAlone) { punycode_ = "uy7h"; plaintext_ = "🂻"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsFourByteCharBeforeBasicChars) { punycode_ = "jack__uh63d"; plaintext_ = "jack_🂻"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsFourByteCharAmidBasicChars) { punycode_ = "jack__of_hearts_ki37n"; plaintext_ = "jack_🂻_of_hearts"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsFourByteCharAfterBasicChars) { punycode_ = "_of_hearts_kz45i"; plaintext_ = "🂻_of_hearts"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsRepeatedFourByteChar) { punycode_ = "uy7haaaa"; plaintext_ = "🂻🂻🂻🂻🂻"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsNearbyFourByteCharsInOrder) { punycode_ = "8x7hcjmf"; plaintext_ = "🂦🂧🂪🂭🂮"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsNearbyFourByteCharsOutOfOrder) { punycode_ = "8x7hcild"; plaintext_ = "🂮🂦🂭🂪🂧"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, AcceptsAMixtureOfByteLengths) { punycode_ = "3caltsx2079ivf8aiuy7cja3a6ak"; plaintext_ = "ùéôãï中文🂮🂦🂭🂪🂧"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, RejectsOverlargeDeltas) { punycode_ = "123456789a"; EXPECT_THAT(DecodeRustPunycode(WithAmpleSpace()), IsNull()); } TEST_F(DecodeRustPunycodeTest, Beowulf) { punycode_ = "hwt_we_gardena_in_geardagum_" "eodcyninga_rym_gefrunon_" "hu_a_elingas_ellen_fremedon_hxg9c70do9alau"; plaintext_ = "hwæt_we_gardena_in_geardagum_" "þeodcyninga_þrym_gefrunon_" "hu_ða_æþelingas_ellen_fremedon"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, MengHaoran) { punycode_ = "gmq4ss0cfvao1e2wg8mcw8b0wkl9a7tt90a8riuvbk7t8kbv9a66ogofvzlf6" "3d01ybn1u28dyqi5q2cxyyxnk5d2gx1ks9ddvfm17bk6gbsd6wftrav60u4ta"; plaintext_ = "故人具雞黍" "邀我至田家" "綠樹村邊合" "青山郭外斜" "開軒面場圃" "把酒話桑麻" "待到重陽日" "還來就菊花"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, YamanoueNoOkura) { punycode_ = "48jdaa3a6ccpepjrsmlb0q4bwcdtid8fg6c0cai9822utqeruk3om0u4f2wbp0" "em23do0op23cc2ff70mb6tae8aq759gja"; plaintext_ = "瓜食めば" "子ども思ほゆ" "栗食めば" "まして偲はゆ" "何処より" "来りしものそ" "眼交に" "もとな懸りて" "安眠し寝さぬ"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } TEST_F(DecodeRustPunycodeTest, EshmunazarSarcophagus) { punycode_ = "wj9caaabaabbaaohcacxvhdc7bgxbccbdcjeacddcedcdlddbdbddcdbdcknfcee" "ifel8del2a7inq9fhcpxikms7a4a9ac9ataaa0g"; plaintext_ = "𐤁𐤉𐤓𐤇𐤁𐤋𐤁𐤔𐤍𐤕𐤏𐤎𐤓" "𐤅𐤀𐤓𐤁𐤏𐤗𐤖𐤖𐤖𐤖𐤋𐤌𐤋𐤊𐤉𐤌𐤋𐤊" "𐤀𐤔𐤌𐤍𐤏𐤆𐤓𐤌𐤋𐤊𐤑𐤃𐤍𐤌" "𐤁𐤍𐤌𐤋𐤊𐤕𐤁𐤍𐤕𐤌𐤋𐤊𐤑𐤃𐤍𐤌" "𐤃𐤁𐤓𐤌𐤋𐤊𐤀𐤔𐤌𐤍𐤏𐤆𐤓𐤌𐤋𐤊" "𐤑𐤃𐤍𐤌𐤋𐤀𐤌𐤓𐤍𐤂𐤆𐤋𐤕"; ASSERT_THAT(DecodeRustPunycode(WithAmpleSpace()), PointsToTheNulAfter(plaintext_)); ASSERT_THAT(DecodeRustPunycode(WithJustEnoughSpace()), PointsToTheNulAfter(plaintext_)); EXPECT_THAT(DecodeRustPunycode(WithOneByteTooFew()), IsNull()); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/internal/decode_rust_punycode.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/internal/decode_rust_punycode_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
e6ebaeca-4ac3-439a-8640-7976da5c568c
cpp
abseil/abseil-cpp
demangle_rust
absl/debugging/internal/demangle_rust.cc
absl/debugging/internal/demangle_rust_test.cc
#include "absl/debugging/internal/demangle_rust.h" #include <cstddef> #include <cstdint> #include <cstring> #include <limits> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/debugging/internal/decode_rust_punycode.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { namespace { constexpr int kMaxReturns = 1 << 17; bool IsDigit(char c) { return '0' <= c && c <= '9'; } bool IsLower(char c) { return 'a' <= c && c <= 'z'; } bool IsUpper(char c) { return 'A' <= c && c <= 'Z'; } bool IsAlpha(char c) { return IsLower(c) || IsUpper(c); } bool IsIdentifierChar(char c) { return IsAlpha(c) || IsDigit(c) || c == '_'; } bool IsLowerHexDigit(char c) { return IsDigit(c) || ('a' <= c && c <= 'f'); } const char* BasicTypeName(char c) { switch (c) { case 'a': return "i8"; case 'b': return "bool"; case 'c': return "char"; case 'd': return "f64"; case 'e': return "str"; case 'f': return "f32"; case 'h': return "u8"; case 'i': return "isize"; case 'j': return "usize"; case 'l': return "i32"; case 'm': return "u32"; case 'n': return "i128"; case 'o': return "u128"; case 'p': return "_"; case 's': return "i16"; case 't': return "u16"; case 'u': return "()"; case 'v': return "..."; case 'x': return "i64"; case 'y': return "u64"; case 'z': return "!"; } return nullptr; } class RustSymbolParser { public: RustSymbolParser(const char* encoding, char* out, char* const out_end) : encoding_(encoding), out_(out), out_end_(out_end) { if (out_ != out_end_) *out_ = '\0'; } ABSL_MUST_USE_RESULT bool Parse() && { #define ABSL_DEMANGLER_RECURSE(callee, caller) \ do { \ if (recursion_depth_ == kStackSize) return false; \ \ recursion_stack_[recursion_depth_++] = caller; \ goto callee; \ \ case caller: {} \ } while (0) int iter = 0; goto whole_encoding; for (; iter < kMaxReturns && recursion_depth_ > 0; ++iter) { switch (recursion_stack_[--recursion_depth_]) { whole_encoding: if (!Eat('_') || !Eat('R')) return false; ABSL_DEMANGLER_RECURSE(path, kInstantiatingCrate); if (IsAlpha(Peek())) { ++silence_depth_; ABSL_DEMANGLER_RECURSE(path, kVendorSpecificSuffix); } switch (Take()) { case '.': case '$': case '\0': return true; } return false; path: switch (Take()) { case 'C': goto crate_root; case 'M': goto inherent_impl; case 'X': goto trait_impl; case 'Y': goto trait_definition; case 'N': goto nested_path; case 'I': goto generic_args; case 'B': goto path_backref; default: return false; } crate_root: if (!ParseIdentifier()) return false; continue; inherent_impl: if (!Emit("<")) return false; ABSL_DEMANGLER_RECURSE(impl_path, kInherentImplType); ABSL_DEMANGLER_RECURSE(type, kInherentImplEnding); if (!Emit(">")) return false; continue; trait_impl: if (!Emit("<")) return false; ABSL_DEMANGLER_RECURSE(impl_path, kTraitImplType); ABSL_DEMANGLER_RECURSE(type, kTraitImplInfix); if (!Emit(" as ")) return false; ABSL_DEMANGLER_RECURSE(path, kTraitImplEnding); if (!Emit(">")) return false; continue; impl_path: ++silence_depth_; { int ignored_disambiguator; if (!ParseDisambiguator(ignored_disambiguator)) return false; } ABSL_DEMANGLER_RECURSE(path, kImplPathEnding); --silence_depth_; continue; trait_definition: if (!Emit("<")) return false; ABSL_DEMANGLER_RECURSE(type, kTraitDefinitionInfix); if (!Emit(" as ")) return false; ABSL_DEMANGLER_RECURSE(path, kTraitDefinitionEnding); if (!Emit(">")) return false; continue; nested_path: if (IsUpper(Peek())) { if (!PushNamespace(Take())) return false; ABSL_DEMANGLER_RECURSE(path, kIdentifierInUppercaseNamespace); if (!Emit("::")) return false; if (!ParseIdentifier(PopNamespace())) return false; continue; } if (IsLower(Take())) { ABSL_DEMANGLER_RECURSE(path, kIdentifierInLowercaseNamespace); if (!Emit("::")) return false; if (!ParseIdentifier()) return false; continue; } return false; type: if (IsLower(Peek())) { const char* type_name = BasicTypeName(Take()); if (type_name == nullptr || !Emit(type_name)) return false; continue; } if (Eat('A')) { if (!Emit("[")) return false; ABSL_DEMANGLER_RECURSE(type, kArraySize); if (!Emit("; ")) return false; ABSL_DEMANGLER_RECURSE(constant, kFinishArray); if (!Emit("]")) return false; continue; } if (Eat('S')) { if (!Emit("[")) return false; ABSL_DEMANGLER_RECURSE(type, kSliceEnding); if (!Emit("]")) return false; continue; } if (Eat('T')) goto tuple_type; if (Eat('R')) { if (!Emit("&")) return false; if (!ParseOptionalLifetime()) return false; goto type; } if (Eat('Q')) { if (!Emit("&mut ")) return false; if (!ParseOptionalLifetime()) return false; goto type; } if (Eat('P')) { if (!Emit("*const ")) return false; goto type; } if (Eat('O')) { if (!Emit("*mut ")) return false; goto type; } if (Eat('F')) goto fn_type; if (Eat('D')) goto dyn_trait_type; if (Eat('B')) goto type_backref; goto path; tuple_type: if (!Emit("(")) return false; if (Eat('E')) { if (!Emit(")")) return false; continue; } ABSL_DEMANGLER_RECURSE(type, kAfterFirstTupleElement); if (Eat('E')) { if (!Emit(",)")) return false; continue; } if (!Emit(", ")) return false; ABSL_DEMANGLER_RECURSE(type, kAfterSecondTupleElement); if (Eat('E')) { if (!Emit(")")) return false; continue; } if (!Emit(", ")) return false; ABSL_DEMANGLER_RECURSE(type, kAfterThirdTupleElement); if (Eat('E')) { if (!Emit(")")) return false; continue; } if (!Emit(", ...)")) return false; ++silence_depth_; while (!Eat('E')) { ABSL_DEMANGLER_RECURSE(type, kAfterSubsequentTupleElement); } --silence_depth_; continue; fn_type: if (!Emit("fn...")) return false; ++silence_depth_; if (!ParseOptionalBinder()) return false; (void)Eat('U'); if (Eat('K')) { if (!Eat('C') && !ParseUndisambiguatedIdentifier()) return false; } while (!Eat('E')) { ABSL_DEMANGLER_RECURSE(type, kContinueParameterList); } ABSL_DEMANGLER_RECURSE(type, kFinishFn); --silence_depth_; continue; dyn_trait_type: if (!Emit("dyn ")) return false; if (!ParseOptionalBinder()) return false; if (!Eat('E')) { ABSL_DEMANGLER_RECURSE(dyn_trait, kBeginAutoTraits); while (!Eat('E')) { if (!Emit(" + ")) return false; ABSL_DEMANGLER_RECURSE(dyn_trait, kContinueAutoTraits); } } if (!ParseRequiredLifetime()) return false; continue; dyn_trait: ABSL_DEMANGLER_RECURSE(path, kContinueDynTrait); if (Peek() == 'p') { if (!Emit("<>")) return false; ++silence_depth_; while (Eat('p')) { if (!ParseUndisambiguatedIdentifier()) return false; ABSL_DEMANGLER_RECURSE(type, kContinueAssocBinding); } --silence_depth_; } continue; constant: if (Eat('B')) goto const_backref; if (Eat('p')) { if (!Emit("_")) return false; continue; } ++silence_depth_; ABSL_DEMANGLER_RECURSE(type, kConstData); --silence_depth_; if (Eat('n') && !EmitChar('-')) return false; if (!Emit("0x")) return false; if (Eat('0')) { if (!EmitChar('0')) return false; if (!Eat('_')) return false; continue; } while (IsLowerHexDigit(Peek())) { if (!EmitChar(Take())) return false; } if (!Eat('_')) return false; continue; generic_args: ABSL_DEMANGLER_RECURSE(path, kBeginGenericArgList); if (!Emit("::<>")) return false; ++silence_depth_; while (!Eat('E')) { ABSL_DEMANGLER_RECURSE(generic_arg, kContinueGenericArgList); } --silence_depth_; continue; generic_arg: if (Peek() == 'L') { if (!ParseOptionalLifetime()) return false; continue; } if (Eat('K')) goto constant; goto type; path_backref: if (!BeginBackref()) return false; if (silence_depth_ == 0) { ABSL_DEMANGLER_RECURSE(path, kPathBackrefEnding); } EndBackref(); continue; type_backref: if (!BeginBackref()) return false; if (silence_depth_ == 0) { ABSL_DEMANGLER_RECURSE(type, kTypeBackrefEnding); } EndBackref(); continue; const_backref: if (!BeginBackref()) return false; if (silence_depth_ == 0) { ABSL_DEMANGLER_RECURSE(constant, kConstantBackrefEnding); } EndBackref(); continue; } } return false; } private: enum ReturnAddress : uint8_t { kInstantiatingCrate, kVendorSpecificSuffix, kIdentifierInUppercaseNamespace, kIdentifierInLowercaseNamespace, kInherentImplType, kInherentImplEnding, kTraitImplType, kTraitImplInfix, kTraitImplEnding, kImplPathEnding, kTraitDefinitionInfix, kTraitDefinitionEnding, kArraySize, kFinishArray, kSliceEnding, kAfterFirstTupleElement, kAfterSecondTupleElement, kAfterThirdTupleElement, kAfterSubsequentTupleElement, kContinueParameterList, kFinishFn, kBeginAutoTraits, kContinueAutoTraits, kContinueDynTrait, kContinueAssocBinding, kConstData, kBeginGenericArgList, kContinueGenericArgList, kPathBackrefEnding, kTypeBackrefEnding, kConstantBackrefEnding, }; enum { kStackSize = 256, kNamespaceStackSize = 64, kPositionStackSize = 16, }; char Peek() const { return encoding_[pos_]; } char Take() { return encoding_[pos_++]; } ABSL_MUST_USE_RESULT bool Eat(char want) { if (encoding_[pos_] != want) return false; ++pos_; return true; } ABSL_MUST_USE_RESULT bool EmitChar(char c) { if (silence_depth_ > 0) return true; if (out_end_ - out_ < 2) return false; *out_++ = c; *out_ = '\0'; return true; } ABSL_MUST_USE_RESULT bool Emit(const char* token) { if (silence_depth_ > 0) return true; const size_t token_length = std::strlen(token); const size_t bytes_to_copy = token_length + 1; if (static_cast<size_t>(out_end_ - out_) < bytes_to_copy) return false; std::memcpy(out_, token, bytes_to_copy); out_ += token_length; return true; } ABSL_MUST_USE_RESULT bool EmitDisambiguator(int disambiguator) { if (disambiguator < 0) return EmitChar('?'); if (disambiguator == 0) return EmitChar('0'); char digits[3 * sizeof(disambiguator)] = {}; size_t leading_digit_index = sizeof(digits) - 1; for (; disambiguator > 0; disambiguator /= 10) { digits[--leading_digit_index] = static_cast<char>('0' + disambiguator % 10); } return Emit(digits + leading_digit_index); } ABSL_MUST_USE_RESULT bool ParseDisambiguator(int& value) { value = -1; if (!Eat('s')) { value = 0; return true; } int base_62_value = 0; if (!ParseBase62Number(base_62_value)) return false; value = base_62_value < 0 ? -1 : base_62_value + 1; return true; } ABSL_MUST_USE_RESULT bool ParseBase62Number(int& value) { value = -1; if (Eat('_')) { value = 0; return true; } int encoded_number = 0; bool overflowed = false; while (IsAlpha(Peek()) || IsDigit(Peek())) { const char c = Take(); if (encoded_number >= std::numeric_limits<int>::max()/62) { overflowed = true; } else { int digit; if (IsDigit(c)) { digit = c - '0'; } else if (IsLower(c)) { digit = c - 'a' + 10; } else { digit = c - 'A' + 36; } encoded_number = 62 * encoded_number + digit; } } if (!Eat('_')) return false; if (!overflowed) value = encoded_number + 1; return true; } ABSL_MUST_USE_RESULT bool ParseIdentifier(char uppercase_namespace = '\0') { int disambiguator = 0; if (!ParseDisambiguator(disambiguator)) return false; return ParseUndisambiguatedIdentifier(uppercase_namespace, disambiguator); } ABSL_MUST_USE_RESULT bool ParseUndisambiguatedIdentifier( char uppercase_namespace = '\0', int disambiguator = 0) { const bool is_punycoded = Eat('u'); if (!IsDigit(Peek())) return false; int num_bytes = 0; if (!ParseDecimalNumber(num_bytes)) return false; (void)Eat('_'); if (is_punycoded) { DecodeRustPunycodeOptions options; options.punycode_begin = &encoding_[pos_]; options.punycode_end = &encoding_[pos_] + num_bytes; options.out_begin = out_; options.out_end = out_end_; out_ = DecodeRustPunycode(options); if (out_ == nullptr) return false; pos_ += static_cast<size_t>(num_bytes); } if (uppercase_namespace != '\0') { switch (uppercase_namespace) { case 'C': if (!Emit("{closure")) return false; break; case 'S': if (!Emit("{shim")) return false; break; default: if (!EmitChar('{') || !EmitChar(uppercase_namespace)) return false; break; } if (num_bytes > 0 && !Emit(":")) return false; } if (!is_punycoded) { for (int i = 0; i < num_bytes; ++i) { const char c = Take(); if (!IsIdentifierChar(c) && (c & 0x80) == 0) { return false; } if (!EmitChar(c)) return false; } } if (uppercase_namespace != '\0') { if (!EmitChar('#')) return false; if (!EmitDisambiguator(disambiguator)) return false; if (!EmitChar('}')) return false; } return true; } ABSL_MUST_USE_RESULT bool ParseDecimalNumber(int& value) { value = -1; if (!IsDigit(Peek())) return false; int encoded_number = Take() - '0'; if (encoded_number == 0) { value = 0; return true; } while (IsDigit(Peek()) && encoded_number < std::numeric_limits<int>::max()/10) { encoded_number = 10 * encoded_number + (Take() - '0'); } if (IsDigit(Peek())) return false; value = encoded_number; return true; } ABSL_MUST_USE_RESULT bool ParseOptionalBinder() { if (!Eat('G')) return true; int ignored_binding_count; return ParseBase62Number(ignored_binding_count); } ABSL_MUST_USE_RESULT bool ParseOptionalLifetime() { if (!Eat('L')) return true; int ignored_de_bruijn_index; return ParseBase62Number(ignored_de_bruijn_index); } ABSL_MUST_USE_RESULT bool ParseRequiredLifetime() { if (Peek() != 'L') return false; return ParseOptionalLifetime(); } ABSL_MUST_USE_RESULT bool PushNamespace(char ns) { if (namespace_depth_ == kNamespaceStackSize) return false; namespace_stack_[namespace_depth_++] = ns; return true; } char PopNamespace() { return namespace_stack_[--namespace_depth_]; } ABSL_MUST_USE_RESULT bool PushPosition(int position) { if (position_depth_ == kPositionStackSize) return false; position_stack_[position_depth_++] = position; return true; } int PopPosition() { return position_stack_[--position_depth_]; } ABSL_MUST_USE_RESULT bool BeginBackref() { int offset = 0; const int offset_of_this_backref = pos_ - 2 - 1 ; if (!ParseBase62Number(offset) || offset < 0 || offset >= offset_of_this_backref) { return false; } offset += 2; if (!PushPosition(pos_)) return false; pos_ = offset; return true; } void EndBackref() { pos_ = PopPosition(); } ReturnAddress recursion_stack_[kStackSize] = {}; int recursion_depth_ = 0; char namespace_stack_[kNamespaceStackSize] = {}; int namespace_depth_ = 0; int position_stack_[kPositionStackSize] = {}; int position_depth_ = 0; int silence_depth_ = 0; int pos_ = 0; const char* encoding_ = nullptr; char* out_ = nullptr; char* out_end_ = nullptr; }; } bool DemangleRustSymbolEncoding(const char* mangled, char* out, size_t out_size) { return RustSymbolParser(mangled, out, out + out_size).Parse(); } } ABSL_NAMESPACE_END }
#include "absl/debugging/internal/demangle_rust.h" #include <cstddef> #include <string> #include "gtest/gtest.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { namespace { std::string ResultOfDemangling(const char* mangled, size_t buffer_size) { std::string buffer(buffer_size + 1, '~'); constexpr char kCanaryCharacter = 0x7f; buffer[buffer_size] = kCanaryCharacter; if (!DemangleRustSymbolEncoding(mangled, &buffer[0], buffer_size)) { return "Failed parse"; } if (buffer[buffer_size] != kCanaryCharacter) { return "Buffer overrun by output: " + buffer.substr(0, buffer_size + 1) + "..."; } return buffer.data(); } #define EXPECT_DEMANGLING(mangled, plaintext) \ do { \ [] { \ constexpr size_t plenty_of_space = sizeof(plaintext) + 128; \ constexpr size_t just_enough_space = sizeof(plaintext); \ constexpr size_t one_byte_too_few = sizeof(plaintext) - 1; \ const char* expected_plaintext = plaintext; \ const char* expected_error = "Failed parse"; \ ASSERT_EQ(ResultOfDemangling(mangled, plenty_of_space), \ expected_plaintext); \ ASSERT_EQ(ResultOfDemangling(mangled, just_enough_space), \ expected_plaintext); \ ASSERT_EQ(ResultOfDemangling(mangled, one_byte_too_few), \ expected_error); \ }(); \ } while (0) #define EXPECT_DEMANGLING_FAILS(mangled) \ do { \ constexpr size_t plenty_of_space = 1024; \ const char* expected_error = "Failed parse"; \ EXPECT_EQ(ResultOfDemangling(mangled, plenty_of_space), expected_error); \ } while (0) TEST(DemangleRust, EmptyDemangling) { EXPECT_TRUE(DemangleRustSymbolEncoding("_RC0", nullptr, 0)); } TEST(DemangleRust, FunctionAtCrateLevel) { EXPECT_DEMANGLING("_RNvC10crate_name9func_name", "crate_name::func_name"); EXPECT_DEMANGLING( "_RNvCs09azAZ_10crate_name9func_name", "crate_name::func_name"); } TEST(DemangleRust, TruncationsOfFunctionAtCrateLevel) { EXPECT_DEMANGLING_FAILS("_R"); EXPECT_DEMANGLING_FAILS("_RN"); EXPECT_DEMANGLING_FAILS("_RNvC"); EXPECT_DEMANGLING_FAILS("_RNvC10"); EXPECT_DEMANGLING_FAILS("_RNvC10crate_nam"); EXPECT_DEMANGLING_FAILS("_RNvC10crate_name"); EXPECT_DEMANGLING_FAILS("_RNvC10crate_name9"); EXPECT_DEMANGLING_FAILS("_RNvC10crate_name9func_nam"); EXPECT_DEMANGLING_FAILS("_RNvCs"); EXPECT_DEMANGLING_FAILS("_RNvCs09azAZ"); EXPECT_DEMANGLING_FAILS("_RNvCs09azAZ_"); } TEST(DemangleRust, VendorSuffixes) { EXPECT_DEMANGLING("_RNvC10crate_name9func_name.!@#", "crate_name::func_name"); EXPECT_DEMANGLING("_RNvC10crate_name9func_name$!@#", "crate_name::func_name"); } TEST(DemangleRust, UnicodeIdentifiers) { EXPECT_DEMANGLING("_RNvC7ice_cap17Eyjafjallajökull", "ice_cap::Eyjafjallajökull"); EXPECT_DEMANGLING("_RNvC7ice_caps_u19Eyjafjallajkull_jtb", "ice_cap::Eyjafjallajökull"); } TEST(DemangleRust, FunctionInModule) { EXPECT_DEMANGLING("_RNvNtCs09azAZ_10crate_name11module_name9func_name", "crate_name::module_name::func_name"); } TEST(DemangleRust, FunctionInFunction) { EXPECT_DEMANGLING( "_RNvNvCs09azAZ_10crate_name15outer_func_name15inner_func_name", "crate_name::outer_func_name::inner_func_name"); } TEST(DemangleRust, ClosureInFunction) { EXPECT_DEMANGLING( "_RNCNvCs09azAZ_10crate_name9func_name0", "crate_name::func_name::{closure#0}"); EXPECT_DEMANGLING( "_RNCNvCs09azAZ_10crate_name9func_name0Cs123_12client_crate", "crate_name::func_name::{closure#0}"); } TEST(DemangleRust, ClosureNumbering) { EXPECT_DEMANGLING( "_RNCNvCs09azAZ_10crate_name9func_names_0Cs123_12client_crate", "crate_name::func_name::{closure#1}"); EXPECT_DEMANGLING( "_RNCNvCs09azAZ_10crate_name9func_names0_0Cs123_12client_crate", "crate_name::func_name::{closure#2}"); EXPECT_DEMANGLING( "_RNCNvCs09azAZ_10crate_name9func_names9_0Cs123_12client_crate", "crate_name::func_name::{closure#11}"); EXPECT_DEMANGLING( "_RNCNvCs09azAZ_10crate_name9func_namesa_0Cs123_12client_crate", "crate_name::func_name::{closure#12}"); EXPECT_DEMANGLING( "_RNCNvCs09azAZ_10crate_name9func_namesz_0Cs123_12client_crate", "crate_name::func_name::{closure#37}"); EXPECT_DEMANGLING( "_RNCNvCs09azAZ_10crate_name9func_namesA_0Cs123_12client_crate", "crate_name::func_name::{closure#38}"); EXPECT_DEMANGLING( "_RNCNvCs09azAZ_10crate_name9func_namesZ_0Cs123_12client_crate", "crate_name::func_name::{closure#63}"); EXPECT_DEMANGLING( "_RNCNvCs09azAZ_10crate_name9func_names10_0Cs123_12client_crate", "crate_name::func_name::{closure#64}"); EXPECT_DEMANGLING( "_RNCNvCs09azAZ_10crate_name9func_namesg6_0Cs123_12client_crate", "crate_name::func_name::{closure#1000}"); } TEST(DemangleRust, ClosureNumberOverflowingInt) { EXPECT_DEMANGLING( "_RNCNvCs09azAZ_10crate_name9func_names1234567_0Cs123_12client_crate", "crate_name::func_name::{closure#?}"); } TEST(DemangleRust, UnexpectedlyNamedClosure) { EXPECT_DEMANGLING( "_RNCNvCs123_10crate_name9func_name12closure_nameCs456_12client_crate", "crate_name::func_name::{closure:closure_name#0}"); EXPECT_DEMANGLING( "_RNCNvCs123_10crate_name9func_names2_12closure_nameCs456_12client_crate", "crate_name::func_name::{closure:closure_name#4}"); } TEST(DemangleRust, ItemNestedInsideClosure) { EXPECT_DEMANGLING( "_RNvNCNvCs123_10crate_name9func_name015inner_func_nameCs_12client_crate", "crate_name::func_name::{closure#0}::inner_func_name"); } TEST(DemangleRust, Shim) { EXPECT_DEMANGLING( "_RNSNvCs123_10crate_name9func_name6vtableCs456_12client_crate", "crate_name::func_name::{shim:vtable#0}"); } TEST(DemangleRust, UnknownUppercaseNamespace) { EXPECT_DEMANGLING( "_RNXNvCs123_10crate_name9func_name14mystery_objectCs456_12client_crate", "crate_name::func_name::{X:mystery_object#0}"); } TEST(DemangleRust, NestedUppercaseNamespaces) { EXPECT_DEMANGLING( "_RNCNXNYCs123_10crate_names0_1ys1_1xs2_0Cs456_12client_crate", "crate_name::{Y:y#2}::{X:x#3}::{closure#4}"); } TEST(DemangleRust, TraitDefinition) { EXPECT_DEMANGLING( "_RNvYNtC7crate_a9my_structNtC7crate_b8my_trait1f", "<crate_a::my_struct as crate_b::my_trait>::f"); } TEST(DemangleRust, BasicTypeNames) { EXPECT_DEMANGLING("_RNvYaNtC1c1t1f", "<i8 as c::t>::f"); EXPECT_DEMANGLING("_RNvYbNtC1c1t1f", "<bool as c::t>::f"); EXPECT_DEMANGLING("_RNvYcNtC1c1t1f", "<char as c::t>::f"); EXPECT_DEMANGLING("_RNvYdNtC1c1t1f", "<f64 as c::t>::f"); EXPECT_DEMANGLING("_RNvYeNtC1c1t1f", "<str as c::t>::f"); EXPECT_DEMANGLING("_RNvYfNtC1c1t1f", "<f32 as c::t>::f"); EXPECT_DEMANGLING("_RNvYhNtC1c1t1f", "<u8 as c::t>::f"); EXPECT_DEMANGLING("_RNvYiNtC1c1t1f", "<isize as c::t>::f"); EXPECT_DEMANGLING("_RNvYjNtC1c1t1f", "<usize as c::t>::f"); EXPECT_DEMANGLING("_RNvYlNtC1c1t1f", "<i32 as c::t>::f"); EXPECT_DEMANGLING("_RNvYmNtC1c1t1f", "<u32 as c::t>::f"); EXPECT_DEMANGLING("_RNvYnNtC1c1t1f", "<i128 as c::t>::f"); EXPECT_DEMANGLING("_RNvYoNtC1c1t1f", "<u128 as c::t>::f"); EXPECT_DEMANGLING("_RNvYpNtC1c1t1f", "<_ as c::t>::f"); EXPECT_DEMANGLING("_RNvYsNtC1c1t1f", "<i16 as c::t>::f"); EXPECT_DEMANGLING("_RNvYtNtC1c1t1f", "<u16 as c::t>::f"); EXPECT_DEMANGLING("_RNvYuNtC1c1t1f", "<() as c::t>::f"); EXPECT_DEMANGLING("_RNvYvNtC1c1t1f", "<... as c::t>::f"); EXPECT_DEMANGLING("_RNvYxNtC1c1t1f", "<i64 as c::t>::f"); EXPECT_DEMANGLING("_RNvYyNtC1c1t1f", "<u64 as c::t>::f"); EXPECT_DEMANGLING("_RNvYzNtC1c1t1f", "<! as c::t>::f"); EXPECT_DEMANGLING_FAILS("_RNvYkNtC1c1t1f"); } TEST(DemangleRust, SliceTypes) { EXPECT_DEMANGLING("_RNvYSlNtC1c1t1f", "<[i32] as c::t>::f"); EXPECT_DEMANGLING("_RNvYSNtC1d1sNtC1c1t1f", "<[d::s] as c::t>::f"); } TEST(DemangleRust, ImmutableReferenceTypes) { EXPECT_DEMANGLING("_RNvYRlNtC1c1t1f", "<&i32 as c::t>::f"); EXPECT_DEMANGLING("_RNvYRNtC1d1sNtC1c1t1f", "<&d::s as c::t>::f"); } TEST(DemangleRust, MutableReferenceTypes) { EXPECT_DEMANGLING("_RNvYQlNtC1c1t1f", "<&mut i32 as c::t>::f"); EXPECT_DEMANGLING("_RNvYQNtC1d1sNtC1c1t1f", "<&mut d::s as c::t>::f"); } TEST(DemangleRust, ConstantRawPointerTypes) { EXPECT_DEMANGLING("_RNvYPlNtC1c1t1f", "<*const i32 as c::t>::f"); EXPECT_DEMANGLING("_RNvYPNtC1d1sNtC1c1t1f", "<*const d::s as c::t>::f"); } TEST(DemangleRust, MutableRawPointerTypes) { EXPECT_DEMANGLING("_RNvYOlNtC1c1t1f", "<*mut i32 as c::t>::f"); EXPECT_DEMANGLING("_RNvYONtC1d1sNtC1c1t1f", "<*mut d::s as c::t>::f"); } TEST(DemangleRust, TupleLength0) { EXPECT_DEMANGLING("_RNvYTENtC1c1t1f", "<() as c::t>::f"); } TEST(DemangleRust, TupleLength1) { EXPECT_DEMANGLING("_RNvYTlENtC1c1t1f", "<(i32,) as c::t>::f"); EXPECT_DEMANGLING("_RNvYTNtC1d1sENtC1c1t1f", "<(d::s,) as c::t>::f"); } TEST(DemangleRust, TupleLength2) { EXPECT_DEMANGLING("_RNvYTlmENtC1c1t1f", "<(i32, u32) as c::t>::f"); EXPECT_DEMANGLING("_RNvYTNtC1d1xNtC1e1yENtC1c1t1f", "<(d::x, e::y) as c::t>::f"); } TEST(DemangleRust, TupleLength3) { EXPECT_DEMANGLING("_RNvYTlmnENtC1c1t1f", "<(i32, u32, i128) as c::t>::f"); EXPECT_DEMANGLING("_RNvYTNtC1d1xNtC1e1yNtC1f1zENtC1c1t1f", "<(d::x, e::y, f::z) as c::t>::f"); } TEST(DemangleRust, LongerTuplesAbbreviated) { EXPECT_DEMANGLING("_RNvYTlmnoENtC1c1t1f", "<(i32, u32, i128, ...) as c::t>::f"); EXPECT_DEMANGLING("_RNvYTlmnNtC1d1xNtC1e1yENtC1c1t1f", "<(i32, u32, i128, ...) as c::t>::f"); } TEST(DemangleRust, PathBackrefToCrate) { EXPECT_DEMANGLING("_RNvYNtC8my_crate9my_structNtB4_8my_trait1f", "<my_crate::my_struct as my_crate::my_trait>::f"); } TEST(DemangleRust, PathBackrefToNestedPath) { EXPECT_DEMANGLING("_RNvYNtNtC1c1m1sNtB4_1t1f", "<c::m::s as c::m::t>::f"); } TEST(DemangleRust, PathBackrefAsInstantiatingCrate) { EXPECT_DEMANGLING("_RNCNvC8my_crate7my_func0B3_", "my_crate::my_func::{closure#0}"); } TEST(DemangleRust, TypeBackrefsNestedInTuple) { EXPECT_DEMANGLING("_RNvYTTRlB4_ERB3_ENtC1c1t1f", "<((&i32, &i32), &(&i32, &i32)) as c::t>::f"); } TEST(DemangleRust, NoInfiniteLoopOnBackrefToTheWhole) { EXPECT_DEMANGLING_FAILS("_RB_"); EXPECT_DEMANGLING_FAILS("_RNvB_1sNtC1c1t1f"); } TEST(DemangleRust, NoCrashOnForwardBackref) { EXPECT_DEMANGLING_FAILS("_RB0_"); EXPECT_DEMANGLING_FAILS("_RB1_"); EXPECT_DEMANGLING_FAILS("_RB2_"); EXPECT_DEMANGLING_FAILS("_RB3_"); EXPECT_DEMANGLING_FAILS("_RB4_"); } TEST(DemangleRust, PathBackrefsDoNotRecurseDuringSilence) { EXPECT_DEMANGLING("_RNvYTlmnNtB_1sENtC1c1t1f", "<(i32, u32, i128, ...) as c::t>::f"); } TEST(DemangleRust, TypeBackrefsDoNotRecurseDuringSilence) { EXPECT_DEMANGLING("_RNvYTlmnB2_ENtC1c1t1f", "<(i32, u32, i128, ...) as c::t>::f"); } TEST(DemangleRust, ConstBackrefsDoNotRecurseDuringSilence) { EXPECT_DEMANGLING("_RINvC1c1fAlB_E", "c::f::<>"); } TEST(DemangleRust, ReturnFromBackrefToInputPosition256) { EXPECT_DEMANGLING("_RNvYNtC1c238very_long_type_" "ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij" "ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij" "ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij" "ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij" "ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij" "ABCDEFGHIJabcdefghijABC" "NtB4_1t1f", "<c::very_long_type_" "ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij" "ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij" "ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij" "ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij" "ABCDEFGHIJabcdefghijABCDEFGHIJabcdefghij" "ABCDEFGHIJabcdefghijABC" " as c::t>::f"); } TEST(DemangleRust, EmptyGenericArgs) { EXPECT_DEMANGLING("_RINvC1c1fE", "c::f::<>"); } TEST(DemangleRust, OneSimpleTypeInGenericArgs) { EXPECT_DEMANGLING("_RINvC1c1flE", "c::f::<>"); } TEST(DemangleRust, OneTupleInGenericArgs) { EXPECT_DEMANGLING("_RINvC1c1fTlmEE", "c::f::<>"); } TEST(DemangleRust, OnePathInGenericArgs) { EXPECT_DEMANGLING("_RINvC1c1fNtC1d1sE", "c::f::<>"); } TEST(DemangleRust, LongerGenericArgs) { EXPECT_DEMANGLING("_RINvC1c1flmRNtC1d1sE", "c::f::<>"); } TEST(DemangleRust, BackrefInGenericArgs) { EXPECT_DEMANGLING("_RINvC1c1fRlB7_NtB2_1sE", "c::f::<>"); } TEST(DemangleRust, NestedGenericArgs) { EXPECT_DEMANGLING("_RINvC1c1fINtB2_1slEmE", "c::f::<>"); } TEST(DemangleRust, MonomorphicEntityNestedInsideGeneric) { EXPECT_DEMANGLING("_RNvINvC1c1fppE1g", "c::f::<>::g"); } TEST(DemangleRust, ArrayTypeWithSimpleElementType) { EXPECT_DEMANGLING("_RNvYAlj1f_NtC1c1t1f", "<[i32; 0x1f] as c::t>::f"); } TEST(DemangleRust, ArrayTypeWithComplexElementType) { EXPECT_DEMANGLING("_RNvYAINtC1c1slEj1f_NtB6_1t1f", "<[c::s::<>; 0x1f] as c::t>::f"); } TEST(DemangleRust, NestedArrayType) { EXPECT_DEMANGLING("_RNvYAAlj1f_j2e_NtC1c1t1f", "<[[i32; 0x1f]; 0x2e] as c::t>::f"); } TEST(DemangleRust, BackrefArraySize) { EXPECT_DEMANGLING("_RNvYAAlj1f_B5_NtC1c1t1f", "<[[i32; 0x1f]; 0x1f] as c::t>::f"); } TEST(DemangleRust, ZeroArraySize) { EXPECT_DEMANGLING("_RNvYAlj0_NtC1c1t1f", "<[i32; 0x0] as c::t>::f"); } TEST(DemangleRust, SurprisingMinusesInArraySize) { EXPECT_DEMANGLING("_RNvYAljn0_NtC1c1t1f", "<[i32; -0x0] as c::t>::f"); EXPECT_DEMANGLING("_RNvYAljn42_NtC1c1t1f", "<[i32; -0x42] as c::t>::f"); } TEST(DemangleRust, NumberAsGenericArg) { EXPECT_DEMANGLING("_RINvC1c1fKl8_E", "c::f::<>"); } TEST(DemangleRust, NumberAsFirstOfTwoGenericArgs) { EXPECT_DEMANGLING("_RINvC1c1fKl8_mE", "c::f::<>"); } TEST(DemangleRust, NumberAsSecondOfTwoGenericArgs) { EXPECT_DEMANGLING("_RINvC1c1fmKl8_E", "c::f::<>"); } TEST(DemangleRust, NumberPlaceholder) { EXPECT_DEMANGLING("_RNvINvC1c1fKpE1g", "c::f::<>::g"); } TEST(DemangleRust, InherentImplWithoutDisambiguator) { EXPECT_DEMANGLING("_RNvMNtC8my_crate6my_modNtB2_9my_struct7my_func", "<my_crate::my_mod::my_struct>::my_func"); } TEST(DemangleRust, InherentImplWithDisambiguator) { EXPECT_DEMANGLING("_RNvMs_NtC8my_crate6my_modNtB4_9my_struct7my_func", "<my_crate::my_mod::my_struct>::my_func"); } TEST(DemangleRust, TraitImplWithoutDisambiguator) { EXPECT_DEMANGLING("_RNvXC8my_crateNtB2_9my_structNtB2_8my_trait7my_func", "<my_crate::my_struct as my_crate::my_trait>::my_func"); } TEST(DemangleRust, TraitImplWithDisambiguator) { EXPECT_DEMANGLING("_RNvXs_C8my_crateNtB4_9my_structNtB4_8my_trait7my_func", "<my_crate::my_struct as my_crate::my_trait>::my_func"); } TEST(DemangleRust, TraitImplWithNonpathSelfType) { EXPECT_DEMANGLING("_RNvXC8my_crateRlNtB2_8my_trait7my_func", "<&i32 as my_crate::my_trait>::my_func"); } TEST(DemangleRust, ThunkType) { EXPECT_DEMANGLING("_RNvYFEuNtC1c1t1f", "<fn... as c::t>::f"); } TEST(DemangleRust, NontrivialFunctionReturnType) { EXPECT_DEMANGLING( "_RNvYFERTlmENtC1c1t1f", "<fn... as c::t>::f"); } TEST(DemangleRust, OneParameterType) { EXPECT_DEMANGLING("_RNvYFlEuNtC1c1t1f", "<fn... as c::t>::f"); } TEST(DemangleRust, TwoParameterTypes) { EXPECT_DEMANGLING("_RNvYFlmEuNtC1c1t1f", "<fn... as c::t>::f"); } TEST(DemangleRust, ExternC) { EXPECT_DEMANGLING("_RNvYFKCEuNtC1c1t1f", "<fn... as c::t>::f"); } TEST(DemangleRust, ExternOther) { EXPECT_DEMANGLING( "_RNvYFK5not_CEuNtC1c1t1f", "<fn... as c::t>::f"); } TEST(DemangleRust, Unsafe) { EXPECT_DEMANGLING("_RNvYFUEuNtC1c1t1f", "<fn... as c::t>::f"); } TEST(DemangleRust, Binder) { EXPECT_DEMANGLING( "_RNvYFG_RL0_lEB5_NtC1c1t1f", "<fn... as c::t>::f"); } TEST(DemangleRust, AllFnSigFeaturesInOrder) { EXPECT_DEMANGLING( "_RNvYFG_UKCRL0_lEB8_NtC1c1t1f", "<fn... as c::t>::f"); } TEST(DemangleRust, LifetimeInGenericArgs) { EXPECT_DEMANGLING("_RINvC1c1fINtB2_1sL_EE", "c::f::<>"); } TEST(DemangleRust, EmptyDynTrait) { EXPECT_DEMANGLING("_RNvYDEL_NtC1c1t1f", "<dyn as c::t>::f"); } TEST(DemangleRust, SimpleDynTrait) { EXPECT_DEMANGLING("_RNvYDNtC1c1tEL_NtC1d1u1f", "<dyn c::t as d::u>::f"); } TEST(DemangleRust, DynTraitWithOneAssociatedType) { EXPECT_DEMANGLING( "_RNvYDNtC1c1tp1xlEL_NtC1d1u1f", "<dyn c::t<> as d::u>::f"); } TEST(DemangleRust, DynTraitWithTwoAssociatedTypes) { EXPECT_DEMANGLING( "_RNvYDNtC1c1tp1xlp1ymEL_NtC1d1u1f", "<dyn c::t<> as d::u>::f"); } TEST(DemangleRust, DynTraitPlusAutoTrait) { EXPECT_DEMANGLING( "_RNvYDNtC1c1tNtNtC3std6marker4SendEL_NtC1d1u1f", "<dyn c::t + std::marker::Send as d::u>::f"); } TEST(DemangleRust, DynTraitPlusTwoAutoTraits) { EXPECT_DEMANGLING( "_RNvYDNtC1c1tNtNtC3std6marker4CopyNtBc_4SyncEL_NtC1d1u1f", "<dyn c::t + std::marker::Copy + std::marker::Sync as d::u>::f"); } TEST(DemangleRust, HigherRankedDynTrait) { EXPECT_DEMANGLING( "_RNvYDG_INtC1c1tRL0_lEEL_NtC1d1u1f", "<dyn c::t::<> as d::u>::f"); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/internal/demangle_rust.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/internal/demangle_rust_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
93cba225-8871-4b50-9f3e-4bab934cf0ac
cpp
abseil/abseil-cpp
demangle
absl/debugging/internal/demangle.cc
absl/debugging/internal/demangle_test.cc
#include "absl/debugging/internal/demangle.h" #include <cstddef> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <limits> #include <string> #include "absl/base/config.h" #include "absl/debugging/internal/demangle_rust.h" #if ABSL_INTERNAL_HAS_CXA_DEMANGLE #include <cxxabi.h> #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { typedef struct { const char *abbrev; const char *real_name; int arity; } AbbrevPair; static const AbbrevPair kOperatorList[] = { {"nw", "new", 0}, {"na", "new[]", 0}, {"dl", "delete", 1}, {"da", "delete[]", 1}, {"aw", "co_await", 1}, {"ps", "+", 1}, {"ng", "-", 1}, {"ad", "&", 1}, {"de", "*", 1}, {"co", "~", 1}, {"pl", "+", 2}, {"mi", "-", 2}, {"ml", "*", 2}, {"dv", "/", 2}, {"rm", "%", 2}, {"an", "&", 2}, {"or", "|", 2}, {"eo", "^", 2}, {"aS", "=", 2}, {"pL", "+=", 2}, {"mI", "-=", 2}, {"mL", "*=", 2}, {"dV", "/=", 2}, {"rM", "%=", 2}, {"aN", "&=", 2}, {"oR", "|=", 2}, {"eO", "^=", 2}, {"ls", "<<", 2}, {"rs", ">>", 2}, {"lS", "<<=", 2}, {"rS", ">>=", 2}, {"ss", "<=>", 2}, {"eq", "==", 2}, {"ne", "!=", 2}, {"lt", "<", 2}, {"gt", ">", 2}, {"le", "<=", 2}, {"ge", ">=", 2}, {"nt", "!", 1}, {"aa", "&&", 2}, {"oo", "||", 2}, {"pp", "++", 1}, {"mm", "--", 1}, {"cm", ",", 2}, {"pm", "->*", 2}, {"pt", "->", 0}, {"cl", "()", 0}, {"ix", "[]", 2}, {"qu", "?", 3}, {"st", "sizeof", 0}, {"sz", "sizeof", 1}, {"sZ", "sizeof...", 0}, {nullptr, nullptr, 0}, }; static const AbbrevPair kBuiltinTypeList[] = { {"v", "void", 0}, {"w", "wchar_t", 0}, {"b", "bool", 0}, {"c", "char", 0}, {"a", "signed char", 0}, {"h", "unsigned char", 0}, {"s", "short", 0}, {"t", "unsigned short", 0}, {"i", "int", 0}, {"j", "unsigned int", 0}, {"l", "long", 0}, {"m", "unsigned long", 0}, {"x", "long long", 0}, {"y", "unsigned long long", 0}, {"n", "__int128", 0}, {"o", "unsigned __int128", 0}, {"f", "float", 0}, {"d", "double", 0}, {"e", "long double", 0}, {"g", "__float128", 0}, {"z", "ellipsis", 0}, {"De", "decimal128", 0}, {"Dd", "decimal64", 0}, {"Dc", "decltype(auto)", 0}, {"Da", "auto", 0}, {"Dn", "std::nullptr_t", 0}, {"Df", "decimal32", 0}, {"Di", "char32_t", 0}, {"Du", "char8_t", 0}, {"Ds", "char16_t", 0}, {"Dh", "float16", 0}, {nullptr, nullptr, 0}, }; static const AbbrevPair kSubstitutionList[] = { {"St", "", 0}, {"Sa", "allocator", 0}, {"Sb", "basic_string", 0}, {"Ss", "string", 0}, {"Si", "istream", 0}, {"So", "ostream", 0}, {"Sd", "iostream", 0}, {nullptr, nullptr, 0}, }; typedef struct { int mangled_idx; int out_cur_idx; int prev_name_idx; unsigned int prev_name_length : 16; signed int nest_level : 15; unsigned int append : 1; } ParseState; static_assert(sizeof(ParseState) == 4 * sizeof(int), "unexpected size of ParseState"); typedef struct { const char *mangled_begin; char *out; int out_end_idx; int recursion_depth; int steps; ParseState parse_state; #ifdef ABSL_INTERNAL_DEMANGLE_RECORDS_HIGH_WATER_MARK int high_water_mark; bool too_complex; #endif } State; namespace { #ifdef ABSL_INTERNAL_DEMANGLE_RECORDS_HIGH_WATER_MARK void UpdateHighWaterMark(State *state) { if (state->high_water_mark < state->parse_state.mangled_idx) { state->high_water_mark = state->parse_state.mangled_idx; } } void ReportHighWaterMark(State *state) { const size_t input_length = std::strlen(state->mangled_begin); if (input_length + 6 > static_cast<size_t>(state->out_end_idx) || state->too_complex) { if (state->out_end_idx > 0) state->out[0] = '\0'; return; } const size_t high_water_mark = static_cast<size_t>(state->high_water_mark); std::memcpy(state->out, state->mangled_begin, high_water_mark); std::memcpy(state->out + high_water_mark, "--!--", 5); std::memcpy(state->out + high_water_mark + 5, state->mangled_begin + high_water_mark, input_length - high_water_mark); state->out[input_length + 5] = '\0'; } #else void UpdateHighWaterMark(State *) {} void ReportHighWaterMark(State *) {} #endif class ComplexityGuard { public: explicit ComplexityGuard(State *state) : state_(state) { ++state->recursion_depth; ++state->steps; } ~ComplexityGuard() { --state_->recursion_depth; } static constexpr int kRecursionDepthLimit = 256; static constexpr int kParseStepsLimit = 1 << 17; bool IsTooComplex() const { if (state_->recursion_depth > kRecursionDepthLimit || state_->steps > kParseStepsLimit) { #ifdef ABSL_INTERNAL_DEMANGLE_RECORDS_HIGH_WATER_MARK state_->too_complex = true; #endif return true; } return false; } private: State *state_; }; } static size_t StrLen(const char *str) { size_t len = 0; while (*str != '\0') { ++str; ++len; } return len; } static bool AtLeastNumCharsRemaining(const char *str, size_t n) { for (size_t i = 0; i < n; ++i) { if (str[i] == '\0') { return false; } } return true; } static bool StrPrefix(const char *str, const char *prefix) { size_t i = 0; while (str[i] != '\0' && prefix[i] != '\0' && str[i] == prefix[i]) { ++i; } return prefix[i] == '\0'; } static void InitState(State* state, const char* mangled, char* out, size_t out_size) { state->mangled_begin = mangled; state->out = out; state->out_end_idx = static_cast<int>(out_size); state->recursion_depth = 0; state->steps = 0; #ifdef ABSL_INTERNAL_DEMANGLE_RECORDS_HIGH_WATER_MARK state->high_water_mark = 0; state->too_complex = false; #endif state->parse_state.mangled_idx = 0; state->parse_state.out_cur_idx = 0; state->parse_state.prev_name_idx = 0; state->parse_state.prev_name_length = 0; state->parse_state.nest_level = -1; state->parse_state.append = true; } static inline const char *RemainingInput(State *state) { return &state->mangled_begin[state->parse_state.mangled_idx]; } static bool ParseOneCharToken(State *state, const char one_char_token) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (RemainingInput(state)[0] == one_char_token) { ++state->parse_state.mangled_idx; UpdateHighWaterMark(state); return true; } return false; } static bool ParseTwoCharToken(State *state, const char *two_char_token) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (RemainingInput(state)[0] == two_char_token[0] && RemainingInput(state)[1] == two_char_token[1]) { state->parse_state.mangled_idx += 2; UpdateHighWaterMark(state); return true; } return false; } static bool ParseThreeCharToken(State *state, const char *three_char_token) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (RemainingInput(state)[0] == three_char_token[0] && RemainingInput(state)[1] == three_char_token[1] && RemainingInput(state)[2] == three_char_token[2]) { state->parse_state.mangled_idx += 3; UpdateHighWaterMark(state); return true; } return false; } static bool ParseLongToken(State *state, const char *long_token) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; int i = 0; for (; long_token[i] != '\0'; ++i) { if (RemainingInput(state)[i] != long_token[i]) return false; } state->parse_state.mangled_idx += i; UpdateHighWaterMark(state); return true; } static bool ParseCharClass(State *state, const char *char_class) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (RemainingInput(state)[0] == '\0') { return false; } const char *p = char_class; for (; *p != '\0'; ++p) { if (RemainingInput(state)[0] == *p) { ++state->parse_state.mangled_idx; UpdateHighWaterMark(state); return true; } } return false; } static bool ParseDigit(State *state, int *digit) { char c = RemainingInput(state)[0]; if (ParseCharClass(state, "0123456789")) { if (digit != nullptr) { *digit = c - '0'; } return true; } return false; } static bool Optional(bool ) { return true; } typedef bool (*ParseFunc)(State *); static bool OneOrMore(ParseFunc parse_func, State *state) { if (parse_func(state)) { while (parse_func(state)) { } return true; } return false; } static bool ZeroOrMore(ParseFunc parse_func, State *state) { while (parse_func(state)) { } return true; } static void Append(State *state, const char *const str, const size_t length) { for (size_t i = 0; i < length; ++i) { if (state->parse_state.out_cur_idx + 1 < state->out_end_idx) { state->out[state->parse_state.out_cur_idx++] = str[i]; } else { state->parse_state.out_cur_idx = state->out_end_idx + 1; break; } } if (state->parse_state.out_cur_idx < state->out_end_idx) { state->out[state->parse_state.out_cur_idx] = '\0'; } } static bool IsLower(char c) { return c >= 'a' && c <= 'z'; } static bool IsAlpha(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } static bool IsDigit(char c) { return c >= '0' && c <= '9'; } static bool IsFunctionCloneSuffix(const char *str) { size_t i = 0; while (str[i] != '\0') { bool parsed = false; if (str[i] == '.' && (IsAlpha(str[i + 1]) || str[i + 1] == '_')) { parsed = true; i += 2; while (IsAlpha(str[i]) || str[i] == '_') { ++i; } } if (str[i] == '.' && IsDigit(str[i + 1])) { parsed = true; i += 2; while (IsDigit(str[i])) { ++i; } } if (!parsed) return false; } return true; } static bool EndsWith(State *state, const char chr) { return state->parse_state.out_cur_idx > 0 && state->parse_state.out_cur_idx < state->out_end_idx && chr == state->out[state->parse_state.out_cur_idx - 1]; } static void MaybeAppendWithLength(State *state, const char *const str, const size_t length) { if (state->parse_state.append && length > 0) { if (str[0] == '<' && EndsWith(state, '<')) { Append(state, " ", 1); } if (state->parse_state.out_cur_idx < state->out_end_idx && (IsAlpha(str[0]) || str[0] == '_')) { state->parse_state.prev_name_idx = state->parse_state.out_cur_idx; state->parse_state.prev_name_length = static_cast<unsigned int>(length); } Append(state, str, length); } } static bool MaybeAppendDecimal(State *state, int val) { constexpr size_t kMaxLength = 20; char buf[kMaxLength]; if (state->parse_state.append) { char *p = &buf[kMaxLength]; do { *--p = static_cast<char>((val % 10) + '0'); val /= 10; } while (p > buf && val != 0); Append(state, p, kMaxLength - static_cast<size_t>(p - buf)); } return true; } static bool MaybeAppend(State *state, const char *const str) { if (state->parse_state.append) { size_t length = StrLen(str); MaybeAppendWithLength(state, str, length); } return true; } static bool EnterNestedName(State *state) { state->parse_state.nest_level = 0; return true; } static bool LeaveNestedName(State *state, int16_t prev_value) { state->parse_state.nest_level = prev_value; return true; } static bool DisableAppend(State *state) { state->parse_state.append = false; return true; } static bool RestoreAppend(State *state, bool prev_value) { state->parse_state.append = prev_value; return true; } static void MaybeIncreaseNestLevel(State *state) { if (state->parse_state.nest_level > -1) { ++state->parse_state.nest_level; } } static void MaybeAppendSeparator(State *state) { if (state->parse_state.nest_level >= 1) { MaybeAppend(state, "::"); } } static void MaybeCancelLastSeparator(State *state) { if (state->parse_state.nest_level >= 1 && state->parse_state.append && state->parse_state.out_cur_idx >= 2) { state->parse_state.out_cur_idx -= 2; state->out[state->parse_state.out_cur_idx] = '\0'; } } static bool IdentifierIsAnonymousNamespace(State *state, size_t length) { static const char anon_prefix[] = "_GLOBAL__N_"; return (length > (sizeof(anon_prefix) - 1) && StrPrefix(RemainingInput(state), anon_prefix)); } static bool ParseMangledName(State *state); static bool ParseEncoding(State *state); static bool ParseName(State *state); static bool ParseUnscopedName(State *state); static bool ParseNestedName(State *state); static bool ParsePrefix(State *state); static bool ParseUnqualifiedName(State *state); static bool ParseSourceName(State *state); static bool ParseLocalSourceName(State *state); static bool ParseUnnamedTypeName(State *state); static bool ParseNumber(State *state, int *number_out); static bool ParseFloatNumber(State *state); static bool ParseSeqId(State *state); static bool ParseIdentifier(State *state, size_t length); static bool ParseOperatorName(State *state, int *arity); static bool ParseConversionOperatorType(State *state); static bool ParseSpecialName(State *state); static bool ParseCallOffset(State *state); static bool ParseNVOffset(State *state); static bool ParseVOffset(State *state); static bool ParseAbiTags(State *state); static bool ParseCtorDtorName(State *state); static bool ParseDecltype(State *state); static bool ParseType(State *state); static bool ParseCVQualifiers(State *state); static bool ParseExtendedQualifier(State *state); static bool ParseBuiltinType(State *state); static bool ParseVendorExtendedType(State *state); static bool ParseFunctionType(State *state); static bool ParseBareFunctionType(State *state); static bool ParseOverloadAttribute(State *state); static bool ParseClassEnumType(State *state); static bool ParseArrayType(State *state); static bool ParsePointerToMemberType(State *state); static bool ParseTemplateParam(State *state); static bool ParseTemplateParamDecl(State *state); static bool ParseTemplateTemplateParam(State *state); static bool ParseTemplateArgs(State *state); static bool ParseTemplateArg(State *state); static bool ParseBaseUnresolvedName(State *state); static bool ParseUnresolvedName(State *state); static bool ParseUnresolvedQualifierLevel(State *state); static bool ParseUnionSelector(State* state); static bool ParseFunctionParam(State* state); static bool ParseBracedExpression(State *state); static bool ParseExpression(State *state); static bool ParseInitializer(State *state); static bool ParseExprPrimary(State *state); static bool ParseExprCastValueAndTrailingE(State *state); static bool ParseQRequiresClauseExpr(State *state); static bool ParseRequirement(State *state); static bool ParseTypeConstraint(State *state); static bool ParseLocalName(State *state); static bool ParseLocalNameSuffix(State *state); static bool ParseDiscriminator(State *state); static bool ParseSubstitution(State *state, bool accept_std); static bool ParseMangledName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; return ParseTwoCharToken(state, "_Z") && ParseEncoding(state); } static bool ParseEncoding(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (ParseName(state)) { if (!ParseBareFunctionType(state)) { return true; } ParseQRequiresClauseExpr(state); return true; } if (ParseSpecialName(state)) { return true; } return false; } static bool ParseName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (ParseNestedName(state) || ParseLocalName(state)) { return true; } ParseState copy = state->parse_state; if (ParseSubstitution(state, false) && ParseTemplateArgs(state)) { return true; } state->parse_state = copy; return ParseUnscopedName(state) && Optional(ParseTemplateArgs(state)); } static bool ParseUnscopedName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (ParseUnqualifiedName(state)) { return true; } ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "St") && MaybeAppend(state, "std::") && ParseUnqualifiedName(state)) { return true; } state->parse_state = copy; return false; } static inline bool ParseRefQualifier(State *state) { return ParseCharClass(state, "OR"); } static bool ParseNestedName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'N') && EnterNestedName(state) && Optional(ParseCVQualifiers(state)) && Optional(ParseRefQualifier(state)) && ParsePrefix(state) && LeaveNestedName(state, copy.nest_level) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; return false; } static bool ParsePrefix(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; bool has_something = false; while (true) { MaybeAppendSeparator(state); if (ParseTemplateParam(state) || ParseDecltype(state) || ParseSubstitution(state, true) || ParseVendorExtendedType(state) || ParseUnscopedName(state) || (ParseOneCharToken(state, 'M') && ParseUnnamedTypeName(state))) { has_something = true; MaybeIncreaseNestLevel(state); continue; } MaybeCancelLastSeparator(state); if (has_something && ParseTemplateArgs(state)) { return ParsePrefix(state); } else { break; } } return true; } static bool ParseUnqualifiedName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (ParseOperatorName(state, nullptr) || ParseCtorDtorName(state) || ParseSourceName(state) || ParseLocalSourceName(state) || ParseUnnamedTypeName(state)) { return ParseAbiTags(state); } ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "DC") && OneOrMore(ParseSourceName, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (ParseOneCharToken(state, 'F') && MaybeAppend(state, "friend ") && (ParseSourceName(state) || ParseOperatorName(state, nullptr))) { return true; } state->parse_state = copy; return false; } static bool ParseAbiTags(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; while (ParseOneCharToken(state, 'B')) { ParseState copy = state->parse_state; MaybeAppend(state, "[abi:"); if (!ParseSourceName(state)) { state->parse_state = copy; return false; } MaybeAppend(state, "]"); } return true; } static bool ParseSourceName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; int length = -1; if (ParseNumber(state, &length) && ParseIdentifier(state, static_cast<size_t>(length))) { return true; } state->parse_state = copy; return false; } static bool ParseLocalSourceName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'L') && ParseSourceName(state) && Optional(ParseDiscriminator(state))) { return true; } state->parse_state = copy; return false; } static bool ParseUnnamedTypeName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; int which = -1; if (ParseTwoCharToken(state, "Ut") && Optional(ParseNumber(state, &which)) && which <= std::numeric_limits<int>::max() - 2 && ParseOneCharToken(state, '_')) { MaybeAppend(state, "{unnamed type#"); MaybeAppendDecimal(state, 2 + which); MaybeAppend(state, "}"); return true; } state->parse_state = copy; which = -1; if (ParseTwoCharToken(state, "Ul") && DisableAppend(state) && ZeroOrMore(ParseTemplateParamDecl, state) && OneOrMore(ParseType, state) && RestoreAppend(state, copy.append) && ParseOneCharToken(state, 'E') && Optional(ParseNumber(state, &which)) && which <= std::numeric_limits<int>::max() - 2 && ParseOneCharToken(state, '_')) { MaybeAppend(state, "{lambda()#"); MaybeAppendDecimal(state, 2 + which); MaybeAppend(state, "}"); return true; } state->parse_state = copy; return false; } static bool ParseNumber(State *state, int *number_out) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; bool negative = false; if (ParseOneCharToken(state, 'n')) { negative = true; } const char *p = RemainingInput(state); uint64_t number = 0; for (; *p != '\0'; ++p) { if (IsDigit(*p)) { number = number * 10 + static_cast<uint64_t>(*p - '0'); } else { break; } } if (negative) { number = ~number + 1; } if (p != RemainingInput(state)) { state->parse_state.mangled_idx += p - RemainingInput(state); UpdateHighWaterMark(state); if (number_out != nullptr) { *number_out = static_cast<int>(number); } return true; } return false; } static bool ParseFloatNumber(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; const char *p = RemainingInput(state); for (; *p != '\0'; ++p) { if (!IsDigit(*p) && !(*p >= 'a' && *p <= 'f')) { break; } } if (p != RemainingInput(state)) { state->parse_state.mangled_idx += p - RemainingInput(state); UpdateHighWaterMark(state); return true; } return false; } static bool ParseSeqId(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; const char *p = RemainingInput(state); for (; *p != '\0'; ++p) { if (!IsDigit(*p) && !(*p >= 'A' && *p <= 'Z')) { break; } } if (p != RemainingInput(state)) { state->parse_state.mangled_idx += p - RemainingInput(state); UpdateHighWaterMark(state); return true; } return false; } static bool ParseIdentifier(State *state, size_t length) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (!AtLeastNumCharsRemaining(RemainingInput(state), length)) { return false; } if (IdentifierIsAnonymousNamespace(state, length)) { MaybeAppend(state, "(anonymous namespace)"); } else { MaybeAppendWithLength(state, RemainingInput(state), length); } state->parse_state.mangled_idx += length; UpdateHighWaterMark(state); return true; } static bool ParseOperatorName(State *state, int *arity) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (!AtLeastNumCharsRemaining(RemainingInput(state), 2)) { return false; } ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "cv") && MaybeAppend(state, "operator ") && EnterNestedName(state) && ParseConversionOperatorType(state) && LeaveNestedName(state, copy.nest_level)) { if (arity != nullptr) { *arity = 1; } return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "li") && MaybeAppend(state, "operator\"\" ") && ParseSourceName(state)) { return true; } state->parse_state = copy; if (ParseOneCharToken(state, 'v') && ParseDigit(state, arity) && ParseSourceName(state)) { return true; } state->parse_state = copy; if (!(IsLower(RemainingInput(state)[0]) && IsAlpha(RemainingInput(state)[1]))) { return false; } const AbbrevPair *p; for (p = kOperatorList; p->abbrev != nullptr; ++p) { if (RemainingInput(state)[0] == p->abbrev[0] && RemainingInput(state)[1] == p->abbrev[1]) { if (arity != nullptr) { *arity = p->arity; } MaybeAppend(state, "operator"); if (IsLower(*p->real_name)) { MaybeAppend(state, " "); } MaybeAppend(state, p->real_name); state->parse_state.mangled_idx += 2; UpdateHighWaterMark(state); return true; } } return false; } static bool ParseConversionOperatorType(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; const char* begin_simple_prefixes = RemainingInput(state); while (ParseCharClass(state, "OPRCGrVK")) {} const char* end_simple_prefixes = RemainingInput(state); if (!ParseType(state)) { state->parse_state = copy; return false; } while (begin_simple_prefixes != end_simple_prefixes) { switch (*--end_simple_prefixes) { case 'P': MaybeAppend(state, "*"); break; case 'R': MaybeAppend(state, "&"); break; case 'O': MaybeAppend(state, "&&"); break; case 'C': MaybeAppend(state, " _Complex"); break; case 'G': MaybeAppend(state, " _Imaginary"); break; case 'r': MaybeAppend(state, " restrict"); break; case 'V': MaybeAppend(state, " volatile"); break; case 'K': MaybeAppend(state, " const"); break; } } return true; } static bool ParseSpecialName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "TW")) { MaybeAppend(state, "thread-local wrapper routine for "); if (ParseName(state)) return true; state->parse_state = copy; return false; } if (ParseTwoCharToken(state, "TH")) { MaybeAppend(state, "thread-local initialization routine for "); if (ParseName(state)) return true; state->parse_state = copy; return false; } if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "VTIS") && ParseType(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "Tc") && ParseCallOffset(state) && ParseCallOffset(state) && ParseEncoding(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "GV") && ParseName(state)) { return true; } state->parse_state = copy; if (ParseOneCharToken(state, 'T') && ParseCallOffset(state) && ParseEncoding(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "TC") && ParseType(state) && ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') && DisableAppend(state) && ParseType(state)) { RestoreAppend(state, copy.append); return true; } state->parse_state = copy; if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "FJ") && ParseType(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "GR")) { MaybeAppend(state, "reference temporary for "); if (!ParseName(state)) { state->parse_state = copy; return false; } const bool has_seq_id = ParseSeqId(state); const bool has_underscore = ParseOneCharToken(state, '_'); if (has_seq_id && !has_underscore) { state->parse_state = copy; return false; } return true; } if (ParseTwoCharToken(state, "GA") && ParseEncoding(state)) { return true; } state->parse_state = copy; if (ParseThreeCharToken(state, "GTt") && MaybeAppend(state, "transaction clone for ") && ParseEncoding(state)) { return true; } state->parse_state = copy; if (ParseOneCharToken(state, 'T') && ParseCharClass(state, "hv") && ParseCallOffset(state) && ParseEncoding(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "TA")) { bool append = state->parse_state.append; DisableAppend(state); if (ParseTemplateArg(state)) { RestoreAppend(state, append); MaybeAppend(state, "template parameter object"); return true; } } state->parse_state = copy; return false; } static bool ParseCallOffset(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'h') && ParseNVOffset(state) && ParseOneCharToken(state, '_')) { return true; } state->parse_state = copy; if (ParseOneCharToken(state, 'v') && ParseVOffset(state) && ParseOneCharToken(state, '_')) { return true; } state->parse_state = copy; return false; } static bool ParseNVOffset(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; return ParseNumber(state, nullptr); } static bool ParseVOffset(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') && ParseNumber(state, nullptr)) { return true; } state->parse_state = copy; return false; } static bool ParseCtorDtorName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'C')) { if (ParseCharClass(state, "1234")) { const char *const prev_name = state->out + state->parse_state.prev_name_idx; MaybeAppendWithLength(state, prev_name, state->parse_state.prev_name_length); return true; } else if (ParseOneCharToken(state, 'I') && ParseCharClass(state, "12") && ParseClassEnumType(state)) { return true; } } state->parse_state = copy; if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "0124")) { const char *const prev_name = state->out + state->parse_state.prev_name_idx; MaybeAppend(state, "~"); MaybeAppendWithLength(state, prev_name, state->parse_state.prev_name_length); return true; } state->parse_state = copy; return false; } static bool ParseDecltype(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'D') && ParseCharClass(state, "tT") && ParseExpression(state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; return false; } static bool ParseType(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseCVQualifiers(state)) { const bool result = ParseType(state); if (!result) state->parse_state = copy; return result; } state->parse_state = copy; if (ParseCharClass(state, "OPRCG")) { const bool result = ParseType(state); if (!result) state->parse_state = copy; return result; } state->parse_state = copy; if (ParseTwoCharToken(state, "Dp") && ParseType(state)) { return true; } state->parse_state = copy; if (ParseBuiltinType(state) || ParseFunctionType(state) || ParseClassEnumType(state) || ParseArrayType(state) || ParsePointerToMemberType(state) || ParseDecltype(state) || ParseSubstitution(state, false)) { return true; } if (ParseTemplateTemplateParam(state) && ParseTemplateArgs(state)) { return true; } state->parse_state = copy; if (ParseTemplateParam(state)) { return true; } if (ParseTwoCharToken(state, "Dv") && ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') && ParseType(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "Dv") && ParseExpression(state) && ParseOneCharToken(state, '_') && ParseType(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "Dk") && ParseTypeConstraint(state)) { return true; } state->parse_state = copy; return ParseLongToken(state, "_SUBSTPACK_"); } static bool ParseCVQualifiers(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; int num_cv_qualifiers = 0; while (ParseExtendedQualifier(state)) ++num_cv_qualifiers; num_cv_qualifiers += ParseOneCharToken(state, 'r'); num_cv_qualifiers += ParseOneCharToken(state, 'V'); num_cv_qualifiers += ParseOneCharToken(state, 'K'); return num_cv_qualifiers > 0; } static bool ParseExtendedQualifier(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (!ParseOneCharToken(state, 'U')) return false; bool append = state->parse_state.append; DisableAppend(state); if (!ParseSourceName(state)) { state->parse_state = copy; return false; } Optional(ParseTemplateArgs(state)); RestoreAppend(state, append); return true; } static bool ParseBuiltinType(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "DB") || (ParseTwoCharToken(state, "DU") && MaybeAppend(state, "unsigned "))) { bool append = state->parse_state.append; DisableAppend(state); int number = -1; if (!ParseNumber(state, &number) && !ParseExpression(state)) { state->parse_state = copy; return false; } RestoreAppend(state, append); if (!ParseOneCharToken(state, '_')) { state->parse_state = copy; return false; } MaybeAppend(state, "_BitInt("); if (number >= 0) { MaybeAppendDecimal(state, number); } else { MaybeAppend(state, "?"); } MaybeAppend(state, ")"); return true; } if (ParseTwoCharToken(state, "DF")) { if (ParseThreeCharToken(state, "16b")) { MaybeAppend(state, "std::bfloat16_t"); return true; } int number = 0; if (!ParseNumber(state, &number)) { state->parse_state = copy; return false; } MaybeAppend(state, "_Float"); MaybeAppendDecimal(state, number); if (ParseOneCharToken(state, 'x')) { MaybeAppend(state, "x"); return true; } if (ParseOneCharToken(state, '_')) return true; state->parse_state = copy; return false; } for (const AbbrevPair *p = kBuiltinTypeList; p->abbrev != nullptr; ++p) { if (p->abbrev[1] == '\0') { if (ParseOneCharToken(state, p->abbrev[0])) { MaybeAppend(state, p->real_name); return true; } } else if (p->abbrev[2] == '\0' && ParseTwoCharToken(state, p->abbrev)) { MaybeAppend(state, p->real_name); return true; } } return ParseVendorExtendedType(state); } static bool ParseVendorExtendedType(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'u') && ParseSourceName(state) && Optional(ParseTemplateArgs(state))) { return true; } state->parse_state = copy; return false; } static bool ParseExceptionSpec(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (ParseTwoCharToken(state, "Do")) return true; ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "DO") && ParseExpression(state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "Dw") && OneOrMore(ParseType, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; return false; } static bool ParseFunctionType(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; Optional(ParseExceptionSpec(state)); Optional(ParseTwoCharToken(state, "Dx")); if (!ParseOneCharToken(state, 'F')) { state->parse_state = copy; return false; } Optional(ParseOneCharToken(state, 'Y')); if (!ParseBareFunctionType(state)) { state->parse_state = copy; return false; } Optional(ParseCharClass(state, "RO")); if (!ParseOneCharToken(state, 'E')) { state->parse_state = copy; return false; } return true; } static bool ParseBareFunctionType(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; DisableAppend(state); if (ZeroOrMore(ParseOverloadAttribute, state) && OneOrMore(ParseType, state)) { RestoreAppend(state, copy.append); MaybeAppend(state, "()"); return true; } state->parse_state = copy; return false; } static bool ParseOverloadAttribute(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "Ua") && ParseName(state)) { return true; } state->parse_state = copy; return false; } static bool ParseClassEnumType(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (Optional(ParseTwoCharToken(state, "Ts") || ParseTwoCharToken(state, "Tu") || ParseTwoCharToken(state, "Te")) && ParseName(state)) { return true; } state->parse_state = copy; return false; } static bool ParseArrayType(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'A') && ParseNumber(state, nullptr) && ParseOneCharToken(state, '_') && ParseType(state)) { return true; } state->parse_state = copy; if (ParseOneCharToken(state, 'A') && Optional(ParseExpression(state)) && ParseOneCharToken(state, '_') && ParseType(state)) { return true; } state->parse_state = copy; return false; } static bool ParsePointerToMemberType(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'M') && ParseType(state) && ParseType(state)) { return true; } state->parse_state = copy; return false; } static bool ParseTemplateParam(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (ParseTwoCharToken(state, "T_")) { MaybeAppend(state, "?"); return true; } ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'T') && ParseNumber(state, nullptr) && ParseOneCharToken(state, '_')) { MaybeAppend(state, "?"); return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "TL") && ParseNumber(state, nullptr)) { if (ParseTwoCharToken(state, "__")) { MaybeAppend(state, "?"); return true; } if (ParseOneCharToken(state, '_') && ParseNumber(state, nullptr) && ParseOneCharToken(state, '_')) { MaybeAppend(state, "?"); return true; } } state->parse_state = copy; return false; } static bool ParseTemplateParamDecl(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "Ty")) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "Tk") && ParseName(state) && Optional(ParseTemplateArgs(state))) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "Tn") && ParseType(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "Tt") && ZeroOrMore(ParseTemplateParamDecl, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "Tp") && ParseTemplateParamDecl(state)) { return true; } state->parse_state = copy; return false; } static bool ParseTemplateTemplateParam(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; return (ParseTemplateParam(state) || ParseSubstitution(state, false)); } static bool ParseTemplateArgs(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; DisableAppend(state); if (ParseOneCharToken(state, 'I') && OneOrMore(ParseTemplateArg, state) && Optional(ParseQRequiresClauseExpr(state)) && ParseOneCharToken(state, 'E')) { RestoreAppend(state, copy.append); MaybeAppend(state, "<>"); return true; } state->parse_state = copy; return false; } static bool ParseTemplateArg(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'J') && ZeroOrMore(ParseTemplateArg, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (ParseLocalSourceName(state) && Optional(ParseTemplateArgs(state))) { copy = state->parse_state; if (ParseExprCastValueAndTrailingE(state)) { return true; } state->parse_state = copy; return true; } if (ParseType(state) || ParseExprPrimary(state)) { return true; } state->parse_state = copy; if (ParseOneCharToken(state, 'X') && ParseExpression(state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (ParseTemplateParamDecl(state) && ParseTemplateArg(state)) { return true; } state->parse_state = copy; return false; } static inline bool ParseUnresolvedType(State *state) { return (ParseTemplateParam(state) && Optional(ParseTemplateArgs(state))) || ParseDecltype(state) || ParseSubstitution(state, false); } static inline bool ParseSimpleId(State *state) { return ParseSourceName(state) && Optional(ParseTemplateArgs(state)); } static bool ParseBaseUnresolvedName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (ParseSimpleId(state)) { return true; } ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "on") && ParseOperatorName(state, nullptr) && Optional(ParseTemplateArgs(state))) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "dn") && (ParseUnresolvedType(state) || ParseSimpleId(state))) { return true; } state->parse_state = copy; return false; } static bool ParseUnresolvedName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (Optional(ParseTwoCharToken(state, "gs")) && ParseBaseUnresolvedName(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "sr") && ParseUnresolvedType(state) && ParseBaseUnresolvedName(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "sr") && ParseOneCharToken(state, 'N') && ParseUnresolvedType(state) && OneOrMore(ParseUnresolvedQualifierLevel, state) && ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) { return true; } state->parse_state = copy; if (Optional(ParseTwoCharToken(state, "gs")) && ParseTwoCharToken(state, "sr") && OneOrMore(ParseUnresolvedQualifierLevel, state) && ParseOneCharToken(state, 'E') && ParseBaseUnresolvedName(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "sr") && ParseTwoCharToken(state, "St") && ParseSimpleId(state) && ParseSimpleId(state)) { return true; } state->parse_state = copy; return false; } static bool ParseUnresolvedQualifierLevel(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (ParseSimpleId(state)) return true; ParseState copy = state->parse_state; if (ParseSubstitution(state, false) && ParseTemplateArgs(state)) { return true; } state->parse_state = copy; return false; } static bool ParseUnionSelector(State *state) { return ParseOneCharToken(state, '_') && Optional(ParseNumber(state, nullptr)); } static bool ParseFunctionParam(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "fp") && Optional(ParseCVQualifiers(state)) && Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "fL") && Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, 'p') && Optional(ParseCVQualifiers(state)) && Optional(ParseNumber(state, nullptr)) && ParseOneCharToken(state, '_')) { return true; } state->parse_state = copy; return ParseThreeCharToken(state, "fpT"); } static bool ParseBracedExpression(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "di") && ParseSourceName(state) && ParseBracedExpression(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "dx") && ParseExpression(state) && ParseBracedExpression(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "dX") && ParseExpression(state) && ParseExpression(state) && ParseBracedExpression(state)) { return true; } state->parse_state = copy; return ParseExpression(state); } static bool ParseExpression(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (ParseTemplateParam(state) || ParseExprPrimary(state)) { return true; } ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "cl") && OneOrMore(ParseExpression, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if ((ParseThreeCharToken(state, "pp_") || ParseThreeCharToken(state, "mm_")) && ParseExpression(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "cp") && ParseSimpleId(state) && ZeroOrMore(ParseExpression, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "so") && ParseType(state) && ParseExpression(state) && Optional(ParseNumber(state, nullptr)) && ZeroOrMore(ParseUnionSelector, state) && Optional(ParseOneCharToken(state, 'p')) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (ParseFunctionParam(state)) return true; state->parse_state = copy; if (ParseTwoCharToken(state, "tl") && ParseType(state) && ZeroOrMore(ParseBracedExpression, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "il") && ZeroOrMore(ParseBracedExpression, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (Optional(ParseTwoCharToken(state, "gs")) && (ParseTwoCharToken(state, "nw") || ParseTwoCharToken(state, "na")) && ZeroOrMore(ParseExpression, state) && ParseOneCharToken(state, '_') && ParseType(state) && (ParseOneCharToken(state, 'E') || ParseInitializer(state))) { return true; } state->parse_state = copy; if (Optional(ParseTwoCharToken(state, "gs")) && (ParseTwoCharToken(state, "dl") || ParseTwoCharToken(state, "da")) && ParseExpression(state)) { return true; } state->parse_state = copy; if (ParseCharClass(state, "dscr") && ParseOneCharToken(state, 'c') && ParseType(state) && ParseExpression(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "cv")) { if (ParseType(state)) { ParseState copy2 = state->parse_state; if (ParseOneCharToken(state, '_') && ZeroOrMore(ParseExpression, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy2; if (ParseExpression(state)) { return true; } } } else { int arity = -1; if (ParseOperatorName(state, &arity) && arity > 0 && (arity < 3 || ParseExpression(state)) && (arity < 2 || ParseExpression(state)) && (arity < 1 || ParseExpression(state))) { return true; } } state->parse_state = copy; if (ParseTwoCharToken(state, "ti") && ParseType(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "te") && ParseExpression(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "st") && ParseType(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "at") && ParseType(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "az") && ParseExpression(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "nx") && ParseExpression(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "sZ") && (ParseFunctionParam(state) || ParseTemplateParam(state))) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "sP") && ZeroOrMore(ParseTemplateArg, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if ((ParseTwoCharToken(state, "fl") || ParseTwoCharToken(state, "fr")) && ParseOperatorName(state, nullptr) && ParseExpression(state)) { return true; } state->parse_state = copy; if ((ParseTwoCharToken(state, "fL") || ParseTwoCharToken(state, "fR")) && ParseOperatorName(state, nullptr) && ParseExpression(state) && ParseExpression(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "tw") && ParseExpression(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "tr")) return true; if ((ParseTwoCharToken(state, "dt") || ParseTwoCharToken(state, "pt")) && ParseExpression(state) && ParseUnresolvedName(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "ds") && ParseExpression(state) && ParseExpression(state)) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "sp") && ParseExpression(state)) { return true; } state->parse_state = copy; if (ParseOneCharToken(state, 'u') && ParseSourceName(state) && ZeroOrMore(ParseTemplateArg, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "rq") && OneOrMore(ParseRequirement, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "rQ") && ParseBareFunctionType(state) && ParseOneCharToken(state, '_') && OneOrMore(ParseRequirement, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; return ParseUnresolvedName(state); } static bool ParseInitializer(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "pi") && ZeroOrMore(ParseExpression, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (ParseTwoCharToken(state, "il") && ZeroOrMore(ParseBracedExpression, state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; return false; } static bool ParseExprPrimary(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseTwoCharToken(state, "LZ")) { if (ParseEncoding(state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; return false; } if (ParseOneCharToken(state, 'L')) { if (ParseThreeCharToken(state, "DnE")) return true; if (RemainingInput(state)[0] == 'A' ) { if (ParseType(state) && ParseOneCharToken(state, 'E')) return true; state->parse_state = copy; return false; } if (ParseType(state) && ParseExprCastValueAndTrailingE(state)) { return true; } } state->parse_state = copy; if (ParseOneCharToken(state, 'L') && ParseMangledName(state) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; return false; } static bool ParseExprCastValueAndTrailingE(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseNumber(state, nullptr) && ParseOneCharToken(state, 'E')) { return true; } state->parse_state = copy; if (ParseFloatNumber(state)) { if (ParseOneCharToken(state, 'E')) return true; if (ParseOneCharToken(state, '_') && ParseFloatNumber(state) && ParseOneCharToken(state, 'E')) { return true; } } state->parse_state = copy; return false; } static bool ParseQRequiresClauseExpr(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; DisableAppend(state); if (ParseOneCharToken(state, 'Q') && ParseExpression(state)) { RestoreAppend(state, copy.append); return true; } state->parse_state = copy; return false; } static bool ParseRequirement(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'X') && ParseExpression(state) && Optional(ParseOneCharToken(state, 'N')) && (!ParseOneCharToken(state, 'R') || ParseTypeConstraint(state))) { return true; } state->parse_state = copy; if (ParseOneCharToken(state, 'T') && ParseType(state)) return true; state->parse_state = copy; if (ParseOneCharToken(state, 'Q') && ParseExpression(state)) return true; state->parse_state = copy; return false; } static bool ParseTypeConstraint(State *state) { return ParseName(state); } static bool ParseLocalNameSuffix(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'd') && (IsDigit(RemainingInput(state)[0]) || RemainingInput(state)[0] == '_')) { int number = -1; Optional(ParseNumber(state, &number)); if (number < -1 || number > 2147483645) { number = -1; } number += 2; MaybeAppend(state, "::{default arg#"); MaybeAppendDecimal(state, number); MaybeAppend(state, "}::"); if (ParseOneCharToken(state, '_') && ParseName(state)) return true; state->parse_state = copy; if (state->parse_state.append) { state->out[state->parse_state.out_cur_idx] = '\0'; } return false; } state->parse_state = copy; if (MaybeAppend(state, "::") && ParseName(state) && Optional(ParseDiscriminator(state))) { return true; } state->parse_state = copy; if (state->parse_state.append) { state->out[state->parse_state.out_cur_idx] = '\0'; } return ParseOneCharToken(state, 's') && Optional(ParseDiscriminator(state)); } static bool ParseLocalName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'Z') && ParseEncoding(state) && ParseOneCharToken(state, 'E') && ParseLocalNameSuffix(state)) { return true; } state->parse_state = copy; return false; } static bool ParseDiscriminator(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; ParseState copy = state->parse_state; if (!ParseOneCharToken(state, '_')) return false; if (ParseDigit(state, nullptr)) return true; if (ParseOneCharToken(state, '_') && ParseNumber(state, nullptr) && ParseOneCharToken(state, '_')) { return true; } state->parse_state = copy; return false; } static bool ParseSubstitution(State *state, bool accept_std) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (ParseTwoCharToken(state, "S_")) { MaybeAppend(state, "?"); return true; } ParseState copy = state->parse_state; if (ParseOneCharToken(state, 'S') && ParseSeqId(state) && ParseOneCharToken(state, '_')) { MaybeAppend(state, "?"); return true; } state->parse_state = copy; if (ParseOneCharToken(state, 'S')) { const AbbrevPair *p; for (p = kSubstitutionList; p->abbrev != nullptr; ++p) { if (RemainingInput(state)[0] == p->abbrev[1] && (accept_std || p->abbrev[1] != 't')) { MaybeAppend(state, "std"); if (p->real_name[0] != '\0') { MaybeAppend(state, "::"); MaybeAppend(state, p->real_name); } ++state->parse_state.mangled_idx; UpdateHighWaterMark(state); return true; } } } state->parse_state = copy; return false; } static bool ParseTopLevelMangledName(State *state) { ComplexityGuard guard(state); if (guard.IsTooComplex()) return false; if (ParseMangledName(state)) { if (RemainingInput(state)[0] != '\0') { if (IsFunctionCloneSuffix(RemainingInput(state))) { return true; } if (RemainingInput(state)[0] == '@') { MaybeAppend(state, RemainingInput(state)); return true; } ReportHighWaterMark(state); return false; } return true; } ReportHighWaterMark(state); return false; } static bool Overflowed(const State *state) { return state->parse_state.out_cur_idx >= state->out_end_idx; } bool Demangle(const char* mangled, char* out, size_t out_size) { if (mangled[0] == '_' && mangled[1] == 'R') { return DemangleRustSymbolEncoding(mangled, out, out_size); } State state; InitState(&state, mangled, out, out_size); return ParseTopLevelMangledName(&state) && !Overflowed(&state) && state.parse_state.out_cur_idx > 0; } std::string DemangleString(const char* mangled) { std::string out; int status = 0; char* demangled = nullptr; #if ABSL_INTERNAL_HAS_CXA_DEMANGLE demangled = abi::__cxa_demangle(mangled, nullptr, nullptr, &status); #endif if (status == 0 && demangled != nullptr) { out.append(demangled); free(demangled); } else { out.append(mangled); } return out; } } ABSL_NAMESPACE_END }
#include "absl/debugging/internal/demangle.h" #include <cstdlib> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/debugging/internal/stack_consumption.h" #include "absl/log/log.h" #include "absl/memory/memory.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { namespace { using ::testing::ContainsRegex; TEST(Demangle, FunctionTemplate) { char tmp[100]; ASSERT_TRUE(Demangle("_Z3fooIiEiT_", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo<>()"); } TEST(Demangle, FunctionTemplateWithNesting) { char tmp[100]; ASSERT_TRUE(Demangle("_Z3fooI7WrapperIiEEiT_", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo<>()"); } TEST(Demangle, FunctionTemplateWithNonTypeParamConstraint) { char tmp[100]; ASSERT_TRUE(Demangle("_Z3fooITkSt8integraliEiT_", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo<>()"); } TEST(Demangle, FunctionTemplateWithFunctionRequiresClause) { char tmp[100]; ASSERT_TRUE(Demangle("_Z3fooIiEivQsr3stdE8integralIT_E", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo<>()"); } TEST(Demangle, FunctionWithTemplateParamRequiresClause) { char tmp[100]; ASSERT_TRUE(Demangle("_Z3fooIiQsr3stdE8integralIT_EEiv", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo<>()"); } TEST(Demangle, FunctionWithTemplateParamAndFunctionRequiresClauses) { char tmp[100]; ASSERT_TRUE(Demangle("_Z3fooIiQsr3stdE8integralIT_EEivQsr3stdE8integralIS0_E", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo<>()"); } TEST(Demangle, FunctionTemplateBacktracksOnMalformedRequiresClause) { char tmp[100]; ASSERT_FALSE(Demangle("_Z3fooIiQEiT_", tmp, sizeof(tmp))); } TEST(Demangle, FunctionTemplateWithAutoParam) { char tmp[100]; ASSERT_TRUE(Demangle("_Z3fooITnDaLi1EEvv", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo<>()"); } TEST(Demangle, FunctionTemplateWithNonTypeParamPack) { char tmp[100]; ASSERT_TRUE(Demangle("_Z3fooITpTnRiJEiEvT0_", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo<>()"); } TEST(Demangle, FunctionTemplateTemplateParamWithConstrainedArg) { char tmp[100]; ASSERT_TRUE(Demangle("_Z3fooITtTyE5FooerEvv", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo<>()"); } TEST(Demangle, ConstrainedAutoInFunctionTemplate) { char tmp[100]; ASSERT_TRUE(Demangle("_Z1fITnDk1CLi0EEvv", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "f<>()"); } TEST(Demangle, ConstrainedFriendFunctionTemplate) { char tmp[100]; ASSERT_TRUE(Demangle("_ZN2ns1YIiEF1yES1_QLb1E", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "ns::Y<>::friend y()"); } TEST(Demangle, ConstrainedFriendOperatorTemplate) { char tmp[100]; ASSERT_TRUE(Demangle("_ZN2ns1YIiEFdeES1_QLb1E", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "ns::Y<>::friend operator*()"); } TEST(Demangle, NonTemplateBuiltinType) { char tmp[100]; ASSERT_TRUE(Demangle("_Z3foou17__my_builtin_type", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo()"); } TEST(Demangle, SingleArgTemplateBuiltinType) { char tmp[100]; ASSERT_TRUE(Demangle("_Z3fooIiEu17__my_builtin_typeIT_Ev", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo<>()"); } TEST(Demangle, TwoArgTemplateBuiltinType) { char tmp[100]; ASSERT_TRUE( Demangle("_Z3fooIicEu17__my_builtin_typeIT_T0_Ev", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo<>()"); } TEST(Demangle, TypeNestedUnderTemplatedBuiltinType) { char tmp[100]; ASSERT_TRUE(Demangle("_Z1fIRK1CENu20__remove_reference_tIT_E4typeES3_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, TemplateTemplateParamSubstitution) { char tmp[100]; ASSERT_TRUE(Demangle("_Z3fooITtTyTnTL0__E8FoolableEvv", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "foo<>()"); } TEST(Demangle, TemplateParamSubstitutionWithGenericLambda) { char tmp[100]; ASSERT_TRUE( Demangle("_ZN5FooerIiE3fooIiEEvNS0_UlTL0__TL0_0_E_E", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "Fooer<>::foo<>()"); } TEST(Demangle, LambdaRequiresTrue) { char tmp[100]; ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QLb1E", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "$_0::operator()<>()"); } TEST(Demangle, LambdaRequiresSimpleExpression) { char tmp[100]; ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QeqplLi2ELi2ELi4E", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "$_0::operator()<>()"); } TEST(Demangle, LambdaRequiresRequiresExpressionContainingTrue) { char tmp[100]; ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqXLb1EE", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "$_0::operator()<>()"); } TEST(Demangle, LambdaRequiresRequiresExpressionContainingConcept) { char tmp[100]; ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqXsr3stdE7same_asIDtfp_EiEE", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "$_0::operator()<>()"); } TEST(Demangle, LambdaRequiresRequiresExpressionContainingNoexceptExpression) { char tmp[100]; ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqXplfp_fp_NE", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "$_0::operator()<>()"); } TEST(Demangle, LambdaRequiresRequiresExpressionContainingReturnTypeConstraint) { char tmp[100]; ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqXplfp_fp_RNSt7same_asIDtfp_EEEE", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "$_0::operator()<>()"); } TEST(Demangle, LambdaRequiresRequiresExpressionWithBothNoexceptAndReturnType) { char tmp[100]; ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqXplfp_fp_NRNSt7same_asIDtfp_EEEE", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "$_0::operator()<>()"); } TEST(Demangle, LambdaRequiresRequiresExpressionContainingType) { char tmp[100]; ASSERT_TRUE(Demangle("_ZNK3$_0clI1SEEDaT_QrqTNS2_1TEE", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "$_0::operator()<>()"); } TEST(Demangle, LambdaRequiresRequiresExpressionNestingAnotherRequires) { char tmp[100]; ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqQLb1EE", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "$_0::operator()<>()"); } TEST(Demangle, LambdaRequiresRequiresExpressionContainingTwoRequirements) { char tmp[100]; ASSERT_TRUE(Demangle("_ZNK3$_0clIiEEDaT_QrqXLb1EXeqplLi2ELi2ELi4EE", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "$_0::operator()<>()"); } TEST(Demangle, RequiresExpressionWithItsOwnParameter) { char tmp[100]; ASSERT_TRUE(Demangle("_Z1fIiE1SIXrQT__XplfL0p_fp_EEES1_", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "f<>()"); } TEST(Demangle, LambdaWithExplicitTypeArgument) { char tmp[100]; ASSERT_TRUE(Demangle("_ZZ1fIiET_S0_ENKUlTyS0_E_clIiEEDaS0_", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "f<>()::{lambda()#1}::operator()<>()"); } TEST(Demangle, LambdaWithExplicitPackArgument) { char tmp[100]; ASSERT_TRUE(Demangle("_ZZ1fIiET_S0_ENKUlTpTyDpT_E_clIJiEEEDaS2_", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "f<>()::{lambda()#1}::operator()<>()"); } TEST(Demangle, LambdaInClassMemberDefaultArgument) { char tmp[100]; ASSERT_TRUE(Demangle("_ZZN1S1fEPFvvEEd_NKUlvE_clEv", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "S::f()::{default arg#1}::{lambda()#1}::operator()()"); ASSERT_TRUE(Demangle("_ZZN1S1fEPFvvEEd0_NKUlvE_clEv", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "S::f()::{default arg#2}::{lambda()#1}::operator()()"); ASSERT_FALSE(Demangle("_ZZN1S1fEPFvvEEdn1_NKUlvE_clEv", tmp, sizeof(tmp))); } TEST(Demangle, AvoidSignedOverflowForUnfortunateParameterNumbers) { char tmp[100]; ASSERT_TRUE(Demangle("_ZZN1S1fEPFvvEEd2147483645_NKUlvE_clEv", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "S::f()::{default arg#2147483647}::{lambda()#1}::operator()()"); ASSERT_TRUE(Demangle("_ZZN1S1fEPFvvEEd2147483646_NKUlvE_clEv", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "S::f()::{default arg#1}::{lambda()#1}::operator()()"); ASSERT_TRUE(Demangle("_ZZN1S1fEPFvvEEd2147483647_NKUlvE_clEv", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "S::f()::{default arg#1}::{lambda()#1}::operator()()"); ASSERT_TRUE(Demangle("_ZZN1S1fEPFvvEEd2147483648_NKUlvE_clEv", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "S::f()::{default arg#1}::{lambda()#1}::operator()()"); } TEST(Demangle, SubstpackNotationForTroublesomeTemplatePack) { char tmp[100]; ASSERT_TRUE(Demangle("_ZN1AIJEE1fIJEEEvDpO1BI_SUBSTPACK_T_E", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "A<>::f<>()"); } TEST(Demangle, TemplateTemplateParamAppearingAsBackrefFollowedByTemplateArgs) { char tmp[100]; ASSERT_TRUE(Demangle("_ZN1WI1SE1fIiEEDTclsrS0_IT_EE1mEEv", tmp, sizeof(tmp))); EXPECT_STREQ(tmp, "W<>::f<>()"); } TEST(Demangle, CornerCases) { char tmp[10]; EXPECT_TRUE(Demangle("_Z6foobarv", tmp, sizeof(tmp))); EXPECT_STREQ("foobar()", tmp); EXPECT_TRUE(Demangle("_Z6foobarv", tmp, 9)); EXPECT_STREQ("foobar()", tmp); EXPECT_FALSE(Demangle("_Z6foobarv", tmp, 8)); EXPECT_FALSE(Demangle("_Z6foobarv", tmp, 1)); EXPECT_FALSE(Demangle("_Z6foobarv", tmp, 0)); EXPECT_FALSE(Demangle("_Z6foobarv", nullptr, 0)); EXPECT_FALSE(Demangle("_Z1000000", tmp, 9)); } TEST(Demangle, Clones) { char tmp[20]; EXPECT_TRUE(Demangle("_ZL3Foov", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.clone.3", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.constprop.80", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.isra.18", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.isra.2.constprop.18", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.__uniq.12345", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.__uniq.12345.isra.2.constprop.18", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.clo", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.123", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.clone.foo", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.clone.123.456", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_TRUE(Demangle("_ZL3Foov.part.9.165493.constprop.775.31805", tmp, sizeof(tmp))); EXPECT_STREQ("Foo()", tmp); EXPECT_FALSE(Demangle("_ZL3Foov.", tmp, sizeof(tmp))); EXPECT_FALSE(Demangle("_ZL3Foov.abc123", tmp, sizeof(tmp))); EXPECT_FALSE(Demangle("_ZL3Foov.clone.", tmp, sizeof(tmp))); EXPECT_FALSE(Demangle("_ZL3Foov.isra.2.constprop.", tmp, sizeof(tmp))); } TEST(Demangle, Discriminators) { char tmp[80]; EXPECT_TRUE(Demangle("_ZZ1fvEN1S1gEv", tmp, sizeof(tmp))); EXPECT_STREQ("f()::S::g()", tmp); EXPECT_TRUE(Demangle("_ZZ1fvEN1S1gE_0v", tmp, sizeof(tmp))); EXPECT_STREQ("f()::S::g()", tmp); EXPECT_TRUE(Demangle("_ZZ1fvEN1S1gE_9v", tmp, sizeof(tmp))); EXPECT_STREQ("f()::S::g()", tmp); EXPECT_TRUE(Demangle("_ZZ1fvEN1S1gE__10_v", tmp, sizeof(tmp))); EXPECT_STREQ("f()::S::g()", tmp); } TEST(Demangle, SingleDigitDiscriminatorFollowedByADigit) { char tmp[80]; EXPECT_TRUE(Demangle("_ZZ1fvEN1S1gE_911return_type", tmp, sizeof(tmp))); EXPECT_STREQ("f()::S::g()", tmp); } TEST(Demangle, LiteralOfGlobalNamespaceEnumType) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIL1E42EEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, NullptrLiterals) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fILDnEEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fILDn0EEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, StringLiterals) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fILA42_KcEEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, ComplexFloatingPointLiterals) { char tmp[80]; EXPECT_TRUE(Demangle( "_Z1fIiEvRAszpltlCdstT_ELS0_0000000000000000_4010000000000000E_c", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, Float128) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvDF128_Ev", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator _Float128()", tmp); } TEST(Demangle, Float128x) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvDF128xEv", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator _Float128x()", tmp); } TEST(Demangle, Bfloat16) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvDF16bEv", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator std::bfloat16_t()", tmp); } TEST(Demangle, SimpleSignedBitInt) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvDB256_Ev", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator _BitInt(256)()", tmp); } TEST(Demangle, SimpleUnsignedBitInt) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvDU256_Ev", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator unsigned _BitInt(256)()", tmp); } TEST(Demangle, DependentBitInt) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvDBT__ILi256EEEv", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator _BitInt(?)<>()", tmp); } TEST(Demangle, ConversionToPointerType) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvPiEv", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator int*()", tmp); } TEST(Demangle, ConversionToLvalueReferenceType) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvRiEv", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator int&()", tmp); } TEST(Demangle, ConversionToRvalueReferenceType) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvOiEv", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator int&&()", tmp); } TEST(Demangle, ConversionToComplexFloatingPointType) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvCfEv", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator float _Complex()", tmp); } TEST(Demangle, ConversionToImaginaryFloatingPointType) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvGfEv", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator float _Imaginary()", tmp); } TEST(Demangle, ConversionToPointerToCvQualifiedType) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvPrVKiEv", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator int const volatile restrict*()", tmp); } TEST(Demangle, ConversionToLayeredPointerType) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvPKPKiEv", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator int const* const*()", tmp); } TEST(Demangle, ConversionToTypeWithExtendedQualifier) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1ScvPU5AS128KiEv", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator int*()", tmp); } TEST(Demangle, GlobalInitializers) { char tmp[80]; EXPECT_TRUE(Demangle("_ZGR1v", tmp, sizeof(tmp))); EXPECT_STREQ("reference temporary for v", tmp); EXPECT_TRUE(Demangle("_ZGR1v_", tmp, sizeof(tmp))); EXPECT_STREQ("reference temporary for v", tmp); EXPECT_TRUE(Demangle("_ZGR1v0_", tmp, sizeof(tmp))); EXPECT_STREQ("reference temporary for v", tmp); EXPECT_TRUE(Demangle("_ZGR1v1Z_", tmp, sizeof(tmp))); EXPECT_STREQ("reference temporary for v", tmp); } TEST(Demangle, StructuredBindings) { char tmp[80]; EXPECT_TRUE(Demangle("_ZDC1x1yE", tmp, sizeof(tmp))); EXPECT_TRUE(Demangle("_ZGRDC1x1yE_", tmp, sizeof(tmp))); } TEST(Demangle, AbiTags) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1aB3abc", tmp, sizeof(tmp))); EXPECT_STREQ("a[abi:abc]", tmp); EXPECT_TRUE(Demangle("_ZN1BC2B3xyzEv", tmp, sizeof(tmp))); EXPECT_STREQ("B::B[abi:xyz]()", tmp); EXPECT_TRUE(Demangle("_Z1CB3barB3foov", tmp, sizeof(tmp))); EXPECT_STREQ("C[abi:bar][abi:foo]()", tmp); } TEST(Demangle, SimpleGnuVectorSize) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fDv8_i", tmp, sizeof(tmp))); EXPECT_STREQ("f()", tmp); } TEST(Demangle, GnuVectorSizeIsATemplateParameter) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fILi32EEvDvT__i", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, GnuVectorSizeIsADependentOperatorExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fILi32EEvDvmlLi2ET__i", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, SimpleAddressSpace) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fPU5AS128Ki", tmp, sizeof(tmp))); EXPECT_STREQ("f()", tmp); } TEST(Demangle, DependentAddressSpace) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fILi128EEvPU2ASIT_Ei", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, TransactionSafeEntryPoint) { char tmp[80]; EXPECT_TRUE(Demangle("_ZGTt1fv", tmp, sizeof(tmp))); EXPECT_STREQ("transaction clone for f()", tmp); } TEST(Demangle, TransactionSafeFunctionType) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fPDxFvvE", tmp, sizeof(tmp))); EXPECT_STREQ("f()", tmp); } TEST(Demangle, TemplateParameterObject) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIXtl1SLi1ELi2EEEXadL_ZTAXtlS0_Li1ELi2EEEEEEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_ZTAXtl1SLi1ELi2EEE", tmp, sizeof(tmp))); EXPECT_STREQ("template parameter object", tmp); } TEST(Demangle, EnableIfAttributeOnGlobalFunction) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fUa9enable_ifIXgefL0p_Li0EEEl", tmp, sizeof(tmp))); EXPECT_STREQ("f()", tmp); } TEST(Demangle, EnableIfAttributeOnNamespaceScopeFunction) { char tmp[80]; EXPECT_TRUE(Demangle("_ZN2ns1fEUa9enable_ifIXgefL0p_Li0EEEl", tmp, sizeof(tmp))); EXPECT_STREQ("ns::f()", tmp); } TEST(Demangle, EnableIfAttributeOnFunctionTemplate) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEUa9enable_ifIXgefL0p_tliEEET_S0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, ThisPointerInDependentSignature) { char tmp[80]; EXPECT_TRUE(Demangle("_ZN1S1fIiEEDTcl1gIT_EfpTEEv", tmp, sizeof(tmp))); EXPECT_STREQ("S::f<>()", tmp); } TEST(Demangle, DependentMemberOperatorCall) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fI1CEDTcldtfp_onclEET_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, TypeNestedUnderDecltype) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiENDTtl1SIT_EEE1tEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, ElaboratedTypes) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEvTsN1SIT_E1CE", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fIiEvTuN1SIT_E1CE", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fIiEvTeN1SIT_E1CE", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, SubobjectAddresses) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIXsoKcL_Z1aE123EEEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fIXadsoKcL_Z1aEEEEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fIXadsoKcL_Z1aE123EEEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fIXadsoKcL_Z1aE123pEEEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fIXadsoKcL_Z1aE__1_234EEEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fIXadsoKcL_Z1aE123_456pEEEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, Preincrement) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_pp_fp_EES0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, Postincrement) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_ppfp_EES0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, Predecrement) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_mm_fp_EES0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, Postdecrement) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_mmfp_EES0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, UnaryFoldExpressions) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIJilEE1SIXfrooeqstT_Li4EEEDpS1_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fIJilEE1SIXflooeqstT_Li4EEEDpS1_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, BinaryFoldExpressions) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIJilEE1SIXfRooeqstT_Li4ELb0EEEDpS1_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fIJilEE1SIXfLooLb0EeqstT_Li4EEEDpS1_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, SizeofPacks) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIJilEE1SIXsZT_EEDpT_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1gIJilEE1SIXsZfp_EEDpT_", tmp, sizeof(tmp))); EXPECT_STREQ("g<>()", tmp); } TEST(Demangle, SizeofPackInvolvingAnAliasTemplate) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIJiEEvRAsPDpT_iE_Kc", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, UserDefinedLiteral) { char tmp[80]; EXPECT_TRUE(Demangle("_Zli4_lity", tmp, sizeof(tmp))); EXPECT_STREQ("operator\"\" _lit()", tmp); } TEST(Demangle, Spaceship) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK1SssERKS_", tmp, sizeof(tmp))); EXPECT_STREQ("S::operator<=>()", tmp); EXPECT_TRUE(Demangle("_Z1gI1SEDTssfp_fp0_ET_S2_", tmp, sizeof(tmp))); EXPECT_STREQ("g<>()", tmp); } TEST(Demangle, CoAwait) { char tmp[80]; EXPECT_TRUE(Demangle("_ZNK2ns9AwaitableawEv", tmp, sizeof(tmp))); EXPECT_STREQ("ns::Awaitable::operator co_await()", tmp); } TEST(Demangle, VendorExtendedExpressions) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIXu3__eEEEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fIXu3__eilEEEvv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, DirectListInitialization) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_EEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1gI3XYZEDTtlT_Li1ELi2ELi3EEEv", tmp, sizeof(tmp))); EXPECT_STREQ("g<>()", tmp); EXPECT_TRUE(Demangle("_Z1hI3XYZEDTtlT_di1xLi1Edi1yLi2Edi1zLi3EEEv", tmp, sizeof(tmp))); EXPECT_STREQ("h<>()", tmp); EXPECT_TRUE(Demangle("_Z1iI1AEDTtlT_di1adxLi2ELi42EEEv", tmp, sizeof(tmp))); EXPECT_STREQ("i<>()", tmp); EXPECT_TRUE(Demangle("_Z1jI1AEDTtlT_di1adXLi1ELi3ELi42EEEv", tmp, sizeof(tmp))); EXPECT_STREQ("j<>()", tmp); } TEST(Demangle, SimpleInitializerLists) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTcl1gIT_EilEEEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fIiEDTcl1gilfp_EEET_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle("_Z1fIiEDTcl1gilfp_fp0_EEET_S1_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, BracedListImplicitlyConstructingAClassObject) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTcl1gildi1vfp_EEET_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, SimpleNewExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_denw_S0_EEEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, NewExpressionWithEmptyParentheses) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_denw_S0_piEEEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, NewExpressionWithNonemptyParentheses) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_denw_S0_piLi42EEEEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, PlacementNewExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_denwadfp__S0_piLi42EEEES0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, GlobalScopeNewExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_degsnw_S0_EEEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, NewExpressionWithEmptyBraces) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_denw_S0_ilEEEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, NewExpressionWithNonemptyBraces) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_denw_S0_ilLi42EEEEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, SimpleArrayNewExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_dena_S0_EEEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, ArrayNewExpressionWithEmptyParentheses) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_dena_S0_piEEEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, ArrayPlacementNewExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_denaadfp__S0_EEES0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, GlobalScopeArrayNewExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_degsna_S0_EEEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, ArrayNewExpressionWithTwoElementsInBraces) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTtlT_dena_S0_ilLi1ELi2EEEEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, SimpleDeleteExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTdlfp_EPT_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, GlobalScopeDeleteExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTgsdlfp_EPT_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, SimpleArrayDeleteExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTdafp_EPT_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, GlobalScopeArrayDeleteExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTgsdafp_EPT_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, ReferenceQualifiedFunctionTypes) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fPKFvvREi", tmp, sizeof(tmp))); EXPECT_STREQ("f()", tmp); EXPECT_TRUE(Demangle("_Z1fPFvvOEi", tmp, sizeof(tmp))); EXPECT_STREQ("f()", tmp); EXPECT_TRUE(Demangle("_Z1fPFvRiREi", tmp, sizeof(tmp))); EXPECT_STREQ("f()", tmp); EXPECT_TRUE(Demangle("_Z1fPFvO1SOEi", tmp, sizeof(tmp))); EXPECT_STREQ("f()", tmp); } TEST(Demangle, DynamicCast) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fI1SEDTdcPKT_fp_EPS1_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, StaticCast) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTscPKT_fp_EPS0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, ConstCast) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTccPKT_fp_EPS0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, ReinterpretCast) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTrcPKT_fp_EPS0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, TypeidType) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTcldttiT_4nameEES0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, TypeidExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEDTcldttetlT_E4nameEES0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, AlignofType) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiET_RAatS0__S0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, AlignofExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiET_RAaztlS0_E_S0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, NoexceptExpression) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIiEvRAnxtlT_E_S0_", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, UnaryThrow) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fILb0EEDTquT_twT_Li0EEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, NullaryThrow) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fILb0EEDTquT_trLi0EEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); } TEST(Demangle, ThreadLocalWrappers) { char tmp[80]; EXPECT_TRUE(Demangle("_ZTWN2ns3varE", tmp, sizeof(tmp))); EXPECT_STREQ("thread-local wrapper routine for ns::var", tmp); EXPECT_TRUE(Demangle("_ZTHN2ns3varE", tmp, sizeof(tmp))); EXPECT_STREQ("thread-local initialization routine for ns::var", tmp); } TEST(Demangle, DubiousSrStSymbols) { char tmp[80]; EXPECT_TRUE(Demangle("_Z1fIcE1SIXsrSt1uIT_E1vEEv", tmp, sizeof(tmp))); EXPECT_STREQ("f<>()", tmp); EXPECT_TRUE(Demangle( "_ZSteqIcEN9__gnu_cxx11__enable_if" "IXsrSt9__is_charIT_E7__valueEbE" "6__typeE" "RKNSt7__cxx1112basic_stringIS3_St11char_traitsIS3_ESaIS3_EEESE_", tmp, sizeof(tmp))); EXPECT_STREQ("std::operator==<>()", tmp); } TEST(Demangle, DelegatesToDemangleRustSymbolEncoding) { char tmp[80]; EXPECT_TRUE(Demangle("_RNvC8my_crate7my_func", tmp, sizeof(tmp))); EXPECT_STREQ("my_crate::my_func", tmp); } #if defined(ABSL_INTERNAL_HAVE_DEBUGGING_STACK_CONSUMPTION) && \ !defined(ABSL_HAVE_ADDRESS_SANITIZER) && \ !defined(ABSL_HAVE_MEMORY_SANITIZER) && \ !defined(ABSL_HAVE_THREAD_SANITIZER) static const char *g_mangled; static char g_demangle_buffer[4096]; static char *g_demangle_result; static void DemangleSignalHandler(int signo) { if (Demangle(g_mangled, g_demangle_buffer, sizeof(g_demangle_buffer))) { g_demangle_result = g_demangle_buffer; } else { g_demangle_result = nullptr; } } static const char *DemangleStackConsumption(const char *mangled, int *stack_consumed) { g_mangled = mangled; *stack_consumed = GetSignalHandlerStackConsumption(DemangleSignalHandler); LOG(INFO) << "Stack consumption of Demangle: " << *stack_consumed; return g_demangle_result; } const int kStackConsumptionUpperLimit = 8192; static std::string NestedMangledName(int depth) { std::string mangled_name = "_Z1a"; if (depth > 0) { mangled_name += "IXL"; mangled_name += NestedMangledName(depth - 1); mangled_name += "EEE"; } return mangled_name; } TEST(Demangle, DemangleStackConsumption) { int stack_consumed = 0; const char *demangled = DemangleStackConsumption("_Z6foobarv", &stack_consumed); EXPECT_STREQ("foobar()", demangled); EXPECT_GT(stack_consumed, 0); EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); const std::string nested_mangled_name0 = NestedMangledName(0); demangled = DemangleStackConsumption(nested_mangled_name0.c_str(), &stack_consumed); EXPECT_STREQ("a", demangled); EXPECT_GT(stack_consumed, 0); EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); const std::string nested_mangled_name1 = NestedMangledName(1); demangled = DemangleStackConsumption(nested_mangled_name1.c_str(), &stack_consumed); EXPECT_STREQ("a<>", demangled); EXPECT_GT(stack_consumed, 0); EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); const std::string nested_mangled_name2 = NestedMangledName(2); demangled = DemangleStackConsumption(nested_mangled_name2.c_str(), &stack_consumed); EXPECT_STREQ("a<>", demangled); EXPECT_GT(stack_consumed, 0); EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); const std::string nested_mangled_name3 = NestedMangledName(3); demangled = DemangleStackConsumption(nested_mangled_name3.c_str(), &stack_consumed); EXPECT_STREQ("a<>", demangled); EXPECT_GT(stack_consumed, 0); EXPECT_LT(stack_consumed, kStackConsumptionUpperLimit); } #endif static void TestOnInput(const char* input) { static const int kOutSize = 1048576; auto out = absl::make_unique<char[]>(kOutSize); Demangle(input, out.get(), kOutSize); } TEST(DemangleRegression, NegativeLength) { TestOnInput("_ZZn4"); } TEST(DemangleRegression, DeeplyNestedArrayType) { const int depth = 100000; std::string data = "_ZStI"; data.reserve(data.size() + 3 * depth + 1); for (int i = 0; i < depth; i++) { data += "A1_"; } TestOnInput(data.c_str()); } struct Base { virtual ~Base() = default; }; struct Derived : public Base {}; TEST(DemangleStringTest, SupportsSymbolNameReturnedByTypeId) { EXPECT_EQ(DemangleString(typeid(int).name()), "int"); EXPECT_THAT( DemangleString(typeid(Base).name()), ContainsRegex("absl.*debugging_internal.*anonymous namespace.*::Base")); EXPECT_THAT(DemangleString(typeid(Derived).name()), ContainsRegex( "absl.*debugging_internal.*anonymous namespace.*::Derived")); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/internal/demangle.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/internal/demangle_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
d9e7938a-62ab-44dd-9d1c-26c951320ef7
cpp
abseil/abseil-cpp
crc32c
absl/crc/crc32c.cc
absl/crc/crc32c_test.cc
#include "absl/crc/crc32c.h" #include <cstdint> #include "absl/crc/internal/crc.h" #include "absl/crc/internal/crc32c.h" #include "absl/crc/internal/crc_memcpy.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { const crc_internal::CRC* CrcEngine() { static const crc_internal::CRC* engine = crc_internal::CRC::Crc32c(); return engine; } constexpr uint32_t kCRC32Xor = 0xffffffffU; } namespace crc_internal { crc32c_t UnextendCrc32cByZeroes(crc32c_t initial_crc, size_t length) { uint32_t crc = static_cast<uint32_t>(initial_crc) ^ kCRC32Xor; CrcEngine()->UnextendByZeroes(&crc, length); return static_cast<crc32c_t>(crc ^ kCRC32Xor); } crc32c_t ExtendCrc32cInternal(crc32c_t initial_crc, absl::string_view buf_to_add) { uint32_t crc = static_cast<uint32_t>(initial_crc) ^ kCRC32Xor; CrcEngine()->Extend(&crc, buf_to_add.data(), buf_to_add.size()); return static_cast<crc32c_t>(crc ^ kCRC32Xor); } } crc32c_t ComputeCrc32c(absl::string_view buf) { return ExtendCrc32c(crc32c_t{0}, buf); } crc32c_t ExtendCrc32cByZeroes(crc32c_t initial_crc, size_t length) { uint32_t crc = static_cast<uint32_t>(initial_crc) ^ kCRC32Xor; CrcEngine()->ExtendByZeroes(&crc, length); return static_cast<crc32c_t>(crc ^ kCRC32Xor); } crc32c_t ConcatCrc32c(crc32c_t lhs_crc, crc32c_t rhs_crc, size_t rhs_len) { uint32_t result = static_cast<uint32_t>(lhs_crc); CrcEngine()->ExtendByZeroes(&result, rhs_len); return crc32c_t{result ^ static_cast<uint32_t>(rhs_crc)}; } crc32c_t RemoveCrc32cPrefix(crc32c_t crc_a, crc32c_t crc_ab, size_t length_b) { return ConcatCrc32c(crc_a, crc_ab, length_b); } crc32c_t MemcpyCrc32c(void* dest, const void* src, size_t count, crc32c_t initial_crc) { return static_cast<crc32c_t>( crc_internal::Crc32CAndCopy(dest, src, count, initial_crc, false)); } crc32c_t RemoveCrc32cSuffix(crc32c_t full_string_crc, crc32c_t suffix_crc, size_t suffix_len) { uint32_t result = static_cast<uint32_t>(full_string_crc) ^ static_cast<uint32_t>(suffix_crc); CrcEngine()->UnextendByZeroes(&result, suffix_len); return crc32c_t{result}; } ABSL_NAMESPACE_END }
#include "absl/crc/crc32c.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <cstring> #include <sstream> #include <string> #include "gtest/gtest.h" #include "absl/crc/internal/crc32c.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" namespace { TEST(CRC32C, RFC3720) { char data[32]; memset(data, 0, sizeof(data)); EXPECT_EQ(absl::ComputeCrc32c(absl::string_view(data, sizeof(data))), absl::crc32c_t{0x8a9136aa}); memset(data, 0xff, sizeof(data)); EXPECT_EQ(absl::ComputeCrc32c(absl::string_view(data, sizeof(data))), absl::crc32c_t{0x62a8ab43}); for (int i = 0; i < 32; ++i) data[i] = static_cast<char>(i); EXPECT_EQ(absl::ComputeCrc32c(absl::string_view(data, sizeof(data))), absl::crc32c_t{0x46dd794e}); for (int i = 0; i < 32; ++i) data[i] = static_cast<char>(31 - i); EXPECT_EQ(absl::ComputeCrc32c(absl::string_view(data, sizeof(data))), absl::crc32c_t{0x113fdb5c}); constexpr uint8_t cmd[48] = { 0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x18, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; EXPECT_EQ(absl::ComputeCrc32c(absl::string_view( reinterpret_cast<const char*>(cmd), sizeof(cmd))), absl::crc32c_t{0xd9963a56}); } std::string TestString(size_t len) { std::string result; result.reserve(len); for (size_t i = 0; i < len; ++i) { result.push_back(static_cast<char>(i % 256)); } return result; } TEST(CRC32C, Compute) { EXPECT_EQ(absl::ComputeCrc32c(""), absl::crc32c_t{0}); EXPECT_EQ(absl::ComputeCrc32c("hello world"), absl::crc32c_t{0xc99465aa}); } TEST(CRC32C, Extend) { uint32_t base = 0xC99465AA; std::string extension = "Extension String"; EXPECT_EQ( absl::ExtendCrc32c(absl::crc32c_t{base}, extension), absl::crc32c_t{0xD2F65090}); } TEST(CRC32C, ExtendByZeroes) { std::string base = "hello world"; absl::crc32c_t base_crc = absl::crc32c_t{0xc99465aa}; constexpr size_t kExtendByValues[] = {100, 10000, 100000}; for (const size_t extend_by : kExtendByValues) { SCOPED_TRACE(extend_by); absl::crc32c_t crc2 = absl::ExtendCrc32cByZeroes(base_crc, extend_by); EXPECT_EQ(crc2, absl::ComputeCrc32c(base + std::string(extend_by, '\0'))); } } TEST(CRC32C, UnextendByZeroes) { constexpr size_t kExtendByValues[] = {2, 200, 20000, 200000, 20000000}; constexpr size_t kUnextendByValues[] = {0, 100, 10000, 100000, 10000000}; for (auto seed_crc : {absl::crc32c_t{0}, absl::crc32c_t{0xc99465aa}}) { SCOPED_TRACE(seed_crc); for (const size_t size_1 : kExtendByValues) { for (const size_t size_2 : kUnextendByValues) { size_t extend_size = std::max(size_1, size_2); size_t unextend_size = std::min(size_1, size_2); SCOPED_TRACE(extend_size); SCOPED_TRACE(unextend_size); absl::crc32c_t crc1 = seed_crc; crc1 = absl::ExtendCrc32cByZeroes(crc1, extend_size); crc1 = absl::crc_internal::UnextendCrc32cByZeroes(crc1, unextend_size); absl::crc32c_t crc2 = seed_crc; crc2 = absl::ExtendCrc32cByZeroes(crc2, extend_size - unextend_size); EXPECT_EQ(crc1, crc2); } } } constexpr size_t kSizes[] = {0, 1, 100, 10000}; for (const size_t size : kSizes) { SCOPED_TRACE(size); std::string string_before = TestString(size); std::string string_after = string_before + std::string(size, '\0'); absl::crc32c_t crc_before = absl::ComputeCrc32c(string_before); absl::crc32c_t crc_after = absl::ComputeCrc32c(string_after); EXPECT_EQ(crc_before, absl::crc_internal::UnextendCrc32cByZeroes(crc_after, size)); } } TEST(CRC32C, Concat) { std::string hello = "Hello, "; std::string world = "world!"; std::string hello_world = absl::StrCat(hello, world); absl::crc32c_t crc_a = absl::ComputeCrc32c(hello); absl::crc32c_t crc_b = absl::ComputeCrc32c(world); absl::crc32c_t crc_ab = absl::ComputeCrc32c(hello_world); EXPECT_EQ(absl::ConcatCrc32c(crc_a, crc_b, world.size()), crc_ab); } TEST(CRC32C, Memcpy) { constexpr size_t kBytesSize[] = {0, 1, 20, 500, 100000}; for (size_t bytes : kBytesSize) { SCOPED_TRACE(bytes); std::string sample_string = TestString(bytes); std::string target_buffer = std::string(bytes, '\0'); absl::crc32c_t memcpy_crc = absl::MemcpyCrc32c(&(target_buffer[0]), sample_string.data(), bytes); absl::crc32c_t compute_crc = absl::ComputeCrc32c(sample_string); EXPECT_EQ(memcpy_crc, compute_crc); EXPECT_EQ(sample_string, target_buffer); } } TEST(CRC32C, RemovePrefix) { std::string hello = "Hello, "; std::string world = "world!"; std::string hello_world = absl::StrCat(hello, world); absl::crc32c_t crc_a = absl::ComputeCrc32c(hello); absl::crc32c_t crc_b = absl::ComputeCrc32c(world); absl::crc32c_t crc_ab = absl::ComputeCrc32c(hello_world); EXPECT_EQ(absl::RemoveCrc32cPrefix(crc_a, crc_ab, world.size()), crc_b); } TEST(CRC32C, RemoveSuffix) { std::string hello = "Hello, "; std::string world = "world!"; std::string hello_world = absl::StrCat(hello, world); absl::crc32c_t crc_a = absl::ComputeCrc32c(hello); absl::crc32c_t crc_b = absl::ComputeCrc32c(world); absl::crc32c_t crc_ab = absl::ComputeCrc32c(hello_world); EXPECT_EQ(absl::RemoveCrc32cSuffix(crc_ab, crc_b, world.size()), crc_a); } TEST(CRC32C, InsertionOperator) { { std::ostringstream buf; buf << absl::crc32c_t{0xc99465aa}; EXPECT_EQ(buf.str(), "c99465aa"); } { std::ostringstream buf; buf << absl::crc32c_t{0}; EXPECT_EQ(buf.str(), "00000000"); } { std::ostringstream buf; buf << absl::crc32c_t{17}; EXPECT_EQ(buf.str(), "00000011"); } } TEST(CRC32C, AbslStringify) { EXPECT_EQ(absl::StrFormat("%v", absl::crc32c_t{0xc99465aa}), "c99465aa"); EXPECT_EQ(absl::StrFormat("%v", absl::crc32c_t{0}), "00000000"); EXPECT_EQ(absl::StrFormat("%v", absl::crc32c_t{17}), "00000011"); EXPECT_EQ(absl::StrCat(absl::crc32c_t{0xc99465aa}), "c99465aa"); EXPECT_EQ(absl::StrCat(absl::crc32c_t{0}), "00000000"); EXPECT_EQ(absl::StrCat(absl::crc32c_t{17}), "00000011"); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/crc/crc32c.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/crc/crc32c_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
7a442277-60e5-4a8a-9580-69dd82e9d0f3
cpp
abseil/abseil-cpp
crc_cord_state
absl/crc/internal/crc_cord_state.cc
absl/crc/internal/crc_cord_state_test.cc
#include "absl/crc/internal/crc_cord_state.h" #include <cassert> #include "absl/base/config.h" #include "absl/base/no_destructor.h" #include "absl/numeric/bits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace crc_internal { CrcCordState::RefcountedRep* CrcCordState::RefSharedEmptyRep() { static absl::NoDestructor<CrcCordState::RefcountedRep> empty; assert(empty->count.load(std::memory_order_relaxed) >= 1); assert(empty->rep.removed_prefix.length == 0); assert(empty->rep.prefix_crc.empty()); Ref(empty.get()); return empty.get(); } CrcCordState::CrcCordState() : refcounted_rep_(new RefcountedRep) {} CrcCordState::CrcCordState(const CrcCordState& other) : refcounted_rep_(other.refcounted_rep_) { Ref(refcounted_rep_); } CrcCordState::CrcCordState(CrcCordState&& other) : refcounted_rep_(other.refcounted_rep_) { other.refcounted_rep_ = RefSharedEmptyRep(); } CrcCordState& CrcCordState::operator=(const CrcCordState& other) { if (this != &other) { Unref(refcounted_rep_); refcounted_rep_ = other.refcounted_rep_; Ref(refcounted_rep_); } return *this; } CrcCordState& CrcCordState::operator=(CrcCordState&& other) { if (this != &other) { Unref(refcounted_rep_); refcounted_rep_ = other.refcounted_rep_; other.refcounted_rep_ = RefSharedEmptyRep(); } return *this; } CrcCordState::~CrcCordState() { Unref(refcounted_rep_); } crc32c_t CrcCordState::Checksum() const { if (rep().prefix_crc.empty()) { return absl::crc32c_t{0}; } if (IsNormalized()) { return rep().prefix_crc.back().crc; } return absl::RemoveCrc32cPrefix( rep().removed_prefix.crc, rep().prefix_crc.back().crc, rep().prefix_crc.back().length - rep().removed_prefix.length); } CrcCordState::PrefixCrc CrcCordState::NormalizedPrefixCrcAtNthChunk( size_t n) const { assert(n < NumChunks()); if (IsNormalized()) { return rep().prefix_crc[n]; } size_t length = rep().prefix_crc[n].length - rep().removed_prefix.length; return PrefixCrc(length, absl::RemoveCrc32cPrefix(rep().removed_prefix.crc, rep().prefix_crc[n].crc, length)); } void CrcCordState::Normalize() { if (IsNormalized() || rep().prefix_crc.empty()) { return; } Rep* r = mutable_rep(); for (auto& prefix_crc : r->prefix_crc) { size_t remaining = prefix_crc.length - r->removed_prefix.length; prefix_crc.crc = absl::RemoveCrc32cPrefix(r->removed_prefix.crc, prefix_crc.crc, remaining); prefix_crc.length = remaining; } r->removed_prefix = PrefixCrc(); } void CrcCordState::Poison() { Rep* rep = mutable_rep(); if (NumChunks() > 0) { for (auto& prefix_crc : rep->prefix_crc) { uint32_t crc = static_cast<uint32_t>(prefix_crc.crc); crc += 0x2e76e41b; crc = absl::rotr(crc, 17); prefix_crc.crc = crc32c_t{crc}; } } else { rep->prefix_crc.emplace_back(0, crc32c_t{1}); } } } ABSL_NAMESPACE_END }
#include "absl/crc/internal/crc_cord_state.h" #include <algorithm> #include <cstdint> #include <string> #include <utility> #include "gtest/gtest.h" #include "absl/crc/crc32c.h" namespace { TEST(CrcCordState, Default) { absl::crc_internal::CrcCordState state; EXPECT_TRUE(state.IsNormalized()); EXPECT_EQ(state.Checksum(), absl::crc32c_t{0}); state.Normalize(); EXPECT_EQ(state.Checksum(), absl::crc32c_t{0}); } TEST(CrcCordState, Normalize) { absl::crc_internal::CrcCordState state; auto* rep = state.mutable_rep(); rep->prefix_crc.push_back( absl::crc_internal::CrcCordState::PrefixCrc(1000, absl::crc32c_t{1000})); rep->prefix_crc.push_back( absl::crc_internal::CrcCordState::PrefixCrc(2000, absl::crc32c_t{2000})); rep->removed_prefix = absl::crc_internal::CrcCordState::PrefixCrc(500, absl::crc32c_t{500}); EXPECT_FALSE(state.IsNormalized()); absl::crc32c_t crc = state.Checksum(); state.Normalize(); EXPECT_TRUE(state.IsNormalized()); EXPECT_EQ(state.Checksum(), crc); EXPECT_EQ(rep->removed_prefix.length, 0); } TEST(CrcCordState, Copy) { absl::crc_internal::CrcCordState state; auto* rep = state.mutable_rep(); rep->prefix_crc.push_back( absl::crc_internal::CrcCordState::PrefixCrc(1000, absl::crc32c_t{1000})); absl::crc_internal::CrcCordState copy = state; EXPECT_EQ(state.Checksum(), absl::crc32c_t{1000}); EXPECT_EQ(copy.Checksum(), absl::crc32c_t{1000}); } TEST(CrcCordState, UnsharedSelfCopy) { absl::crc_internal::CrcCordState state; auto* rep = state.mutable_rep(); rep->prefix_crc.push_back( absl::crc_internal::CrcCordState::PrefixCrc(1000, absl::crc32c_t{1000})); const absl::crc_internal::CrcCordState& ref = state; state = ref; EXPECT_EQ(state.Checksum(), absl::crc32c_t{1000}); } TEST(CrcCordState, Move) { absl::crc_internal::CrcCordState state; auto* rep = state.mutable_rep(); rep->prefix_crc.push_back( absl::crc_internal::CrcCordState::PrefixCrc(1000, absl::crc32c_t{1000})); absl::crc_internal::CrcCordState moved = std::move(state); EXPECT_EQ(moved.Checksum(), absl::crc32c_t{1000}); } TEST(CrcCordState, UnsharedSelfMove) { absl::crc_internal::CrcCordState state; auto* rep = state.mutable_rep(); rep->prefix_crc.push_back( absl::crc_internal::CrcCordState::PrefixCrc(1000, absl::crc32c_t{1000})); absl::crc_internal::CrcCordState& ref = state; state = std::move(ref); EXPECT_EQ(state.Checksum(), absl::crc32c_t{1000}); } TEST(CrcCordState, PoisonDefault) { absl::crc_internal::CrcCordState state; state.Poison(); EXPECT_NE(state.Checksum(), absl::crc32c_t{0}); } TEST(CrcCordState, PoisonData) { absl::crc_internal::CrcCordState state; auto* rep = state.mutable_rep(); rep->prefix_crc.push_back( absl::crc_internal::CrcCordState::PrefixCrc(1000, absl::crc32c_t{1000})); rep->prefix_crc.push_back( absl::crc_internal::CrcCordState::PrefixCrc(2000, absl::crc32c_t{2000})); rep->removed_prefix = absl::crc_internal::CrcCordState::PrefixCrc(500, absl::crc32c_t{500}); absl::crc32c_t crc = state.Checksum(); state.Poison(); EXPECT_NE(state.Checksum(), crc); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/crc/internal/crc_cord_state.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/crc/internal/crc_cord_state_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
8086529a-480b-40f5-ae84-ebac1bbb68bd
cpp
abseil/abseil-cpp
status
absl/status/status.cc
absl/status/status_test.cc
#include "absl/status/status.h" #include <errno.h> #include <atomic> #include <cstddef> #include <cstdint> #include <cstring> #include <memory> #include <ostream> #include <string> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/strerror.h" #include "absl/base/macros.h" #include "absl/base/no_destructor.h" #include "absl/base/nullability.h" #include "absl/debugging/stacktrace.h" #include "absl/debugging/symbolize.h" #include "absl/status/internal/status_internal.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" namespace absl { ABSL_NAMESPACE_BEGIN static_assert( alignof(status_internal::StatusRep) >= 4, "absl::Status assumes it can use the bottom 2 bits of a StatusRep*."); std::string StatusCodeToString(StatusCode code) { switch (code) { case StatusCode::kOk: return "OK"; case StatusCode::kCancelled: return "CANCELLED"; case StatusCode::kUnknown: return "UNKNOWN"; case StatusCode::kInvalidArgument: return "INVALID_ARGUMENT"; case StatusCode::kDeadlineExceeded: return "DEADLINE_EXCEEDED"; case StatusCode::kNotFound: return "NOT_FOUND"; case StatusCode::kAlreadyExists: return "ALREADY_EXISTS"; case StatusCode::kPermissionDenied: return "PERMISSION_DENIED"; case StatusCode::kUnauthenticated: return "UNAUTHENTICATED"; case StatusCode::kResourceExhausted: return "RESOURCE_EXHAUSTED"; case StatusCode::kFailedPrecondition: return "FAILED_PRECONDITION"; case StatusCode::kAborted: return "ABORTED"; case StatusCode::kOutOfRange: return "OUT_OF_RANGE"; case StatusCode::kUnimplemented: return "UNIMPLEMENTED"; case StatusCode::kInternal: return "INTERNAL"; case StatusCode::kUnavailable: return "UNAVAILABLE"; case StatusCode::kDataLoss: return "DATA_LOSS"; default: return ""; } } std::ostream& operator<<(std::ostream& os, StatusCode code) { return os << StatusCodeToString(code); } absl::Nonnull<const std::string*> Status::EmptyString() { static const absl::NoDestructor<std::string> kEmpty; return kEmpty.get(); } #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL constexpr const char Status::kMovedFromString[]; #endif absl::Nonnull<const std::string*> Status::MovedFromString() { static const absl::NoDestructor<std::string> kMovedFrom(kMovedFromString); return kMovedFrom.get(); } Status::Status(absl::StatusCode code, absl::string_view msg) : rep_(CodeToInlinedRep(code)) { if (code != absl::StatusCode::kOk && !msg.empty()) { rep_ = PointerToRep(new status_internal::StatusRep(code, msg, nullptr)); } } absl::Nonnull<status_internal::StatusRep*> Status::PrepareToModify( uintptr_t rep) { if (IsInlined(rep)) { return new status_internal::StatusRep(InlinedRepToCode(rep), absl::string_view(), nullptr); } return RepToPointer(rep)->CloneAndUnref(); } std::string Status::ToStringSlow(uintptr_t rep, StatusToStringMode mode) { if (IsInlined(rep)) { return absl::StrCat(absl::StatusCodeToString(InlinedRepToCode(rep)), ": "); } return RepToPointer(rep)->ToString(mode); } std::ostream& operator<<(std::ostream& os, const Status& x) { os << x.ToString(StatusToStringMode::kWithEverything); return os; } Status AbortedError(absl::string_view message) { return Status(absl::StatusCode::kAborted, message); } Status AlreadyExistsError(absl::string_view message) { return Status(absl::StatusCode::kAlreadyExists, message); } Status CancelledError(absl::string_view message) { return Status(absl::StatusCode::kCancelled, message); } Status DataLossError(absl::string_view message) { return Status(absl::StatusCode::kDataLoss, message); } Status DeadlineExceededError(absl::string_view message) { return Status(absl::StatusCode::kDeadlineExceeded, message); } Status FailedPreconditionError(absl::string_view message) { return Status(absl::StatusCode::kFailedPrecondition, message); } Status InternalError(absl::string_view message) { return Status(absl::StatusCode::kInternal, message); } Status InvalidArgumentError(absl::string_view message) { return Status(absl::StatusCode::kInvalidArgument, message); } Status NotFoundError(absl::string_view message) { return Status(absl::StatusCode::kNotFound, message); } Status OutOfRangeError(absl::string_view message) { return Status(absl::StatusCode::kOutOfRange, message); } Status PermissionDeniedError(absl::string_view message) { return Status(absl::StatusCode::kPermissionDenied, message); } Status ResourceExhaustedError(absl::string_view message) { return Status(absl::StatusCode::kResourceExhausted, message); } Status UnauthenticatedError(absl::string_view message) { return Status(absl::StatusCode::kUnauthenticated, message); } Status UnavailableError(absl::string_view message) { return Status(absl::StatusCode::kUnavailable, message); } Status UnimplementedError(absl::string_view message) { return Status(absl::StatusCode::kUnimplemented, message); } Status UnknownError(absl::string_view message) { return Status(absl::StatusCode::kUnknown, message); } bool IsAborted(const Status& status) { return status.code() == absl::StatusCode::kAborted; } bool IsAlreadyExists(const Status& status) { return status.code() == absl::StatusCode::kAlreadyExists; } bool IsCancelled(const Status& status) { return status.code() == absl::StatusCode::kCancelled; } bool IsDataLoss(const Status& status) { return status.code() == absl::StatusCode::kDataLoss; } bool IsDeadlineExceeded(const Status& status) { return status.code() == absl::StatusCode::kDeadlineExceeded; } bool IsFailedPrecondition(const Status& status) { return status.code() == absl::StatusCode::kFailedPrecondition; } bool IsInternal(const Status& status) { return status.code() == absl::StatusCode::kInternal; } bool IsInvalidArgument(const Status& status) { return status.code() == absl::StatusCode::kInvalidArgument; } bool IsNotFound(const Status& status) { return status.code() == absl::StatusCode::kNotFound; } bool IsOutOfRange(const Status& status) { return status.code() == absl::StatusCode::kOutOfRange; } bool IsPermissionDenied(const Status& status) { return status.code() == absl::StatusCode::kPermissionDenied; } bool IsResourceExhausted(const Status& status) { return status.code() == absl::StatusCode::kResourceExhausted; } bool IsUnauthenticated(const Status& status) { return status.code() == absl::StatusCode::kUnauthenticated; } bool IsUnavailable(const Status& status) { return status.code() == absl::StatusCode::kUnavailable; } bool IsUnimplemented(const Status& status) { return status.code() == absl::StatusCode::kUnimplemented; } bool IsUnknown(const Status& status) { return status.code() == absl::StatusCode::kUnknown; } StatusCode ErrnoToStatusCode(int error_number) { switch (error_number) { case 0: return StatusCode::kOk; case EINVAL: case ENAMETOOLONG: case E2BIG: case EDESTADDRREQ: case EDOM: case EFAULT: case EILSEQ: case ENOPROTOOPT: case ENOTSOCK: case ENOTTY: case EPROTOTYPE: case ESPIPE: return StatusCode::kInvalidArgument; case ETIMEDOUT: return StatusCode::kDeadlineExceeded; case ENODEV: case ENOENT: #ifdef ENOMEDIUM case ENOMEDIUM: #endif case ENXIO: case ESRCH: return StatusCode::kNotFound; case EEXIST: case EADDRNOTAVAIL: case EALREADY: #ifdef ENOTUNIQ case ENOTUNIQ: #endif return StatusCode::kAlreadyExists; case EPERM: case EACCES: #ifdef ENOKEY case ENOKEY: #endif case EROFS: return StatusCode::kPermissionDenied; case ENOTEMPTY: case EISDIR: case ENOTDIR: case EADDRINUSE: case EBADF: #ifdef EBADFD case EBADFD: #endif case EBUSY: case ECHILD: case EISCONN: #ifdef EISNAM case EISNAM: #endif #ifdef ENOTBLK case ENOTBLK: #endif case ENOTCONN: case EPIPE: #ifdef ESHUTDOWN case ESHUTDOWN: #endif case ETXTBSY: #ifdef EUNATCH case EUNATCH: #endif return StatusCode::kFailedPrecondition; case ENOSPC: #ifdef EDQUOT case EDQUOT: #endif case EMFILE: case EMLINK: case ENFILE: case ENOBUFS: case ENOMEM: #ifdef EUSERS case EUSERS: #endif return StatusCode::kResourceExhausted; #ifdef ECHRNG case ECHRNG: #endif case EFBIG: case EOVERFLOW: case ERANGE: return StatusCode::kOutOfRange; #ifdef ENOPKG case ENOPKG: #endif case ENOSYS: case ENOTSUP: case EAFNOSUPPORT: #ifdef EPFNOSUPPORT case EPFNOSUPPORT: #endif case EPROTONOSUPPORT: #ifdef ESOCKTNOSUPPORT case ESOCKTNOSUPPORT: #endif case EXDEV: return StatusCode::kUnimplemented; case EAGAIN: #ifdef ECOMM case ECOMM: #endif case ECONNREFUSED: case ECONNABORTED: case ECONNRESET: case EINTR: #ifdef EHOSTDOWN case EHOSTDOWN: #endif case EHOSTUNREACH: case ENETDOWN: case ENETRESET: case ENETUNREACH: case ENOLCK: case ENOLINK: #ifdef ENONET case ENONET: #endif return StatusCode::kUnavailable; case EDEADLK: #ifdef ESTALE case ESTALE: #endif return StatusCode::kAborted; case ECANCELED: return StatusCode::kCancelled; default: return StatusCode::kUnknown; } } namespace { std::string MessageForErrnoToStatus(int error_number, absl::string_view message) { return absl::StrCat(message, ": ", absl::base_internal::StrError(error_number)); } } Status ErrnoToStatus(int error_number, absl::string_view message) { return Status(ErrnoToStatusCode(error_number), MessageForErrnoToStatus(error_number, message)); } absl::Nonnull<const char*> StatusMessageAsCStr(const Status& status) { auto sv_message = status.message(); return sv_message.empty() ? "" : sv_message.data(); } ABSL_NAMESPACE_END }
#include "absl/status/status.h" #include <errno.h> #include <array> #include <cstddef> #include <sstream> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/cord.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" namespace { using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Optional; using ::testing::UnorderedElementsAreArray; TEST(StatusCode, InsertionOperator) { const absl::StatusCode code = absl::StatusCode::kUnknown; std::ostringstream oss; oss << code; EXPECT_EQ(oss.str(), absl::StatusCodeToString(code)); } struct ErrorTest { absl::StatusCode code; using Creator = absl::Status (*)( absl::string_view ); using Classifier = bool (*)(const absl::Status&); Creator creator; Classifier classifier; }; constexpr ErrorTest kErrorTests[]{ {absl::StatusCode::kCancelled, absl::CancelledError, absl::IsCancelled}, {absl::StatusCode::kUnknown, absl::UnknownError, absl::IsUnknown}, {absl::StatusCode::kInvalidArgument, absl::InvalidArgumentError, absl::IsInvalidArgument}, {absl::StatusCode::kDeadlineExceeded, absl::DeadlineExceededError, absl::IsDeadlineExceeded}, {absl::StatusCode::kNotFound, absl::NotFoundError, absl::IsNotFound}, {absl::StatusCode::kAlreadyExists, absl::AlreadyExistsError, absl::IsAlreadyExists}, {absl::StatusCode::kPermissionDenied, absl::PermissionDeniedError, absl::IsPermissionDenied}, {absl::StatusCode::kResourceExhausted, absl::ResourceExhaustedError, absl::IsResourceExhausted}, {absl::StatusCode::kFailedPrecondition, absl::FailedPreconditionError, absl::IsFailedPrecondition}, {absl::StatusCode::kAborted, absl::AbortedError, absl::IsAborted}, {absl::StatusCode::kOutOfRange, absl::OutOfRangeError, absl::IsOutOfRange}, {absl::StatusCode::kUnimplemented, absl::UnimplementedError, absl::IsUnimplemented}, {absl::StatusCode::kInternal, absl::InternalError, absl::IsInternal}, {absl::StatusCode::kUnavailable, absl::UnavailableError, absl::IsUnavailable}, {absl::StatusCode::kDataLoss, absl::DataLossError, absl::IsDataLoss}, {absl::StatusCode::kUnauthenticated, absl::UnauthenticatedError, absl::IsUnauthenticated}, }; TEST(Status, CreateAndClassify) { for (const auto& test : kErrorTests) { SCOPED_TRACE(absl::StatusCodeToString(test.code)); std::string message = absl::StrCat("error code ", test.code, " test message"); absl::Status status = test.creator( message ); EXPECT_EQ(test.code, status.code()); EXPECT_EQ(message, status.message()); EXPECT_TRUE(test.classifier(status)); for (const auto& other : kErrorTests) { if (other.code != test.code) { EXPECT_FALSE(test.classifier(absl::Status(other.code, ""))) << " other.code = " << other.code; } } } } TEST(Status, DefaultConstructor) { absl::Status status; EXPECT_TRUE(status.ok()); EXPECT_EQ(absl::StatusCode::kOk, status.code()); EXPECT_EQ("", status.message()); } TEST(Status, OkStatus) { absl::Status status = absl::OkStatus(); EXPECT_TRUE(status.ok()); EXPECT_EQ(absl::StatusCode::kOk, status.code()); EXPECT_EQ("", status.message()); } TEST(Status, ConstructorWithCodeMessage) { { absl::Status status(absl::StatusCode::kCancelled, ""); EXPECT_FALSE(status.ok()); EXPECT_EQ(absl::StatusCode::kCancelled, status.code()); EXPECT_EQ("", status.message()); } { absl::Status status(absl::StatusCode::kInternal, "message"); EXPECT_FALSE(status.ok()); EXPECT_EQ(absl::StatusCode::kInternal, status.code()); EXPECT_EQ("message", status.message()); } } TEST(Status, StatusMessageCStringTest) { { absl::Status status = absl::OkStatus(); EXPECT_EQ(status.message(), ""); EXPECT_STREQ(absl::StatusMessageAsCStr(status), ""); EXPECT_EQ(status.message(), absl::StatusMessageAsCStr(status)); EXPECT_NE(absl::StatusMessageAsCStr(status), nullptr); } { absl::Status status; EXPECT_EQ(status.message(), ""); EXPECT_NE(absl::StatusMessageAsCStr(status), nullptr); EXPECT_STREQ(absl::StatusMessageAsCStr(status), ""); } { absl::Status status(absl::StatusCode::kInternal, "message"); EXPECT_FALSE(status.ok()); EXPECT_EQ(absl::StatusCode::kInternal, status.code()); EXPECT_EQ("message", status.message()); EXPECT_STREQ("message", absl::StatusMessageAsCStr(status)); } } TEST(Status, ConstructOutOfRangeCode) { const int kRawCode = 9999; absl::Status status(static_cast<absl::StatusCode>(kRawCode), ""); EXPECT_EQ(absl::StatusCode::kUnknown, status.code()); EXPECT_EQ(kRawCode, status.raw_code()); } constexpr char kUrl1[] = "url.payload.1"; constexpr char kUrl2[] = "url.payload.2"; constexpr char kUrl3[] = "url.payload.3"; constexpr char kUrl4[] = "url.payload.xx"; constexpr char kPayload1[] = "aaaaa"; constexpr char kPayload2[] = "bbbbb"; constexpr char kPayload3[] = "ccccc"; using PayloadsVec = std::vector<std::pair<std::string, absl::Cord>>; TEST(Status, TestGetSetPayload) { absl::Status ok_status = absl::OkStatus(); ok_status.SetPayload(kUrl1, absl::Cord(kPayload1)); ok_status.SetPayload(kUrl2, absl::Cord(kPayload2)); EXPECT_FALSE(ok_status.GetPayload(kUrl1)); EXPECT_FALSE(ok_status.GetPayload(kUrl2)); absl::Status bad_status(absl::StatusCode::kInternal, "fail"); bad_status.SetPayload(kUrl1, absl::Cord(kPayload1)); bad_status.SetPayload(kUrl2, absl::Cord(kPayload2)); EXPECT_THAT(bad_status.GetPayload(kUrl1), Optional(Eq(kPayload1))); EXPECT_THAT(bad_status.GetPayload(kUrl2), Optional(Eq(kPayload2))); EXPECT_FALSE(bad_status.GetPayload(kUrl3)); bad_status.SetPayload(kUrl1, absl::Cord(kPayload3)); EXPECT_THAT(bad_status.GetPayload(kUrl1), Optional(Eq(kPayload3))); bad_status.SetPayload(absl::StrCat(kUrl1, ".1"), absl::Cord(kPayload1)); EXPECT_THAT(bad_status.GetPayload(absl::StrCat(kUrl1, ".1")), Optional(Eq(kPayload1))); } TEST(Status, TestErasePayload) { absl::Status bad_status(absl::StatusCode::kInternal, "fail"); bad_status.SetPayload(kUrl1, absl::Cord(kPayload1)); bad_status.SetPayload(kUrl2, absl::Cord(kPayload2)); bad_status.SetPayload(kUrl3, absl::Cord(kPayload3)); EXPECT_FALSE(bad_status.ErasePayload(kUrl4)); EXPECT_TRUE(bad_status.GetPayload(kUrl2)); EXPECT_TRUE(bad_status.ErasePayload(kUrl2)); EXPECT_FALSE(bad_status.GetPayload(kUrl2)); EXPECT_FALSE(bad_status.ErasePayload(kUrl2)); EXPECT_TRUE(bad_status.ErasePayload(kUrl1)); EXPECT_TRUE(bad_status.ErasePayload(kUrl3)); bad_status.SetPayload(kUrl1, absl::Cord(kPayload1)); EXPECT_TRUE(bad_status.ErasePayload(kUrl1)); } TEST(Status, TestComparePayloads) { absl::Status bad_status1(absl::StatusCode::kInternal, "fail"); bad_status1.SetPayload(kUrl1, absl::Cord(kPayload1)); bad_status1.SetPayload(kUrl2, absl::Cord(kPayload2)); bad_status1.SetPayload(kUrl3, absl::Cord(kPayload3)); absl::Status bad_status2(absl::StatusCode::kInternal, "fail"); bad_status2.SetPayload(kUrl2, absl::Cord(kPayload2)); bad_status2.SetPayload(kUrl3, absl::Cord(kPayload3)); bad_status2.SetPayload(kUrl1, absl::Cord(kPayload1)); EXPECT_EQ(bad_status1, bad_status2); } TEST(Status, TestComparePayloadsAfterErase) { absl::Status payload_status(absl::StatusCode::kInternal, ""); payload_status.SetPayload(kUrl1, absl::Cord(kPayload1)); payload_status.SetPayload(kUrl2, absl::Cord(kPayload2)); absl::Status empty_status(absl::StatusCode::kInternal, ""); EXPECT_NE(payload_status, empty_status); EXPECT_TRUE(payload_status.ErasePayload(kUrl1)); EXPECT_NE(payload_status, empty_status); EXPECT_TRUE(payload_status.ErasePayload(kUrl2)); EXPECT_EQ(payload_status, empty_status); } PayloadsVec AllVisitedPayloads(const absl::Status& s) { PayloadsVec result; s.ForEachPayload([&](absl::string_view type_url, const absl::Cord& payload) { result.push_back(std::make_pair(std::string(type_url), payload)); }); return result; } TEST(Status, TestForEachPayload) { absl::Status bad_status(absl::StatusCode::kInternal, "fail"); bad_status.SetPayload(kUrl1, absl::Cord(kPayload1)); bad_status.SetPayload(kUrl2, absl::Cord(kPayload2)); bad_status.SetPayload(kUrl3, absl::Cord(kPayload3)); int count = 0; bad_status.ForEachPayload( [&count](absl::string_view, const absl::Cord&) { ++count; }); EXPECT_EQ(count, 3); PayloadsVec expected_payloads = {{kUrl1, absl::Cord(kPayload1)}, {kUrl2, absl::Cord(kPayload2)}, {kUrl3, absl::Cord(kPayload3)}}; PayloadsVec visited_payloads = AllVisitedPayloads(bad_status); EXPECT_THAT(visited_payloads, UnorderedElementsAreArray(expected_payloads)); std::vector<absl::Status> scratch; while (true) { scratch.emplace_back(absl::StatusCode::kInternal, "fail"); scratch.back().SetPayload(kUrl1, absl::Cord(kPayload1)); scratch.back().SetPayload(kUrl2, absl::Cord(kPayload2)); scratch.back().SetPayload(kUrl3, absl::Cord(kPayload3)); if (AllVisitedPayloads(scratch.back()) != visited_payloads) { break; } } } TEST(Status, ToString) { absl::Status status(absl::StatusCode::kInternal, "fail"); EXPECT_EQ("INTERNAL: fail", status.ToString()); status.SetPayload("foo", absl::Cord("bar")); EXPECT_EQ("INTERNAL: fail [foo='bar']", status.ToString()); status.SetPayload("bar", absl::Cord("\377")); EXPECT_THAT(status.ToString(), AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"), HasSubstr("[bar='\\xff']"))); } TEST(Status, ToStringMode) { absl::Status status(absl::StatusCode::kInternal, "fail"); status.SetPayload("foo", absl::Cord("bar")); status.SetPayload("bar", absl::Cord("\377")); EXPECT_EQ("INTERNAL: fail", status.ToString(absl::StatusToStringMode::kWithNoExtraData)); EXPECT_THAT(status.ToString(absl::StatusToStringMode::kWithPayload), AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"), HasSubstr("[bar='\\xff']"))); EXPECT_THAT(status.ToString(absl::StatusToStringMode::kWithEverything), AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"), HasSubstr("[bar='\\xff']"))); EXPECT_THAT(status.ToString(~absl::StatusToStringMode::kWithPayload), AllOf(HasSubstr("INTERNAL: fail"), Not(HasSubstr("[foo='bar']")), Not(HasSubstr("[bar='\\xff']")))); } TEST(Status, OstreamOperator) { absl::Status status(absl::StatusCode::kInternal, "fail"); { std::stringstream stream; stream << status; EXPECT_EQ("INTERNAL: fail", stream.str()); } status.SetPayload("foo", absl::Cord("bar")); { std::stringstream stream; stream << status; EXPECT_EQ("INTERNAL: fail [foo='bar']", stream.str()); } status.SetPayload("bar", absl::Cord("\377")); { std::stringstream stream; stream << status; EXPECT_THAT(stream.str(), AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"), HasSubstr("[bar='\\xff']"))); } } TEST(Status, AbslStringify) { absl::Status status(absl::StatusCode::kInternal, "fail"); EXPECT_EQ("INTERNAL: fail", absl::StrCat(status)); EXPECT_EQ("INTERNAL: fail", absl::StrFormat("%v", status)); status.SetPayload("foo", absl::Cord("bar")); EXPECT_EQ("INTERNAL: fail [foo='bar']", absl::StrCat(status)); status.SetPayload("bar", absl::Cord("\377")); EXPECT_THAT(absl::StrCat(status), AllOf(HasSubstr("INTERNAL: fail"), HasSubstr("[foo='bar']"), HasSubstr("[bar='\\xff']"))); } TEST(Status, OstreamEqStringify) { absl::Status status(absl::StatusCode::kUnknown, "fail"); status.SetPayload("foo", absl::Cord("bar")); std::stringstream stream; stream << status; EXPECT_EQ(stream.str(), absl::StrCat(status)); } absl::Status EraseAndReturn(const absl::Status& base) { absl::Status copy = base; EXPECT_TRUE(copy.ErasePayload(kUrl1)); return copy; } TEST(Status, CopyOnWriteForErasePayload) { { absl::Status base(absl::StatusCode::kInvalidArgument, "fail"); base.SetPayload(kUrl1, absl::Cord(kPayload1)); EXPECT_TRUE(base.GetPayload(kUrl1).has_value()); absl::Status copy = EraseAndReturn(base); EXPECT_TRUE(base.GetPayload(kUrl1).has_value()); EXPECT_FALSE(copy.GetPayload(kUrl1).has_value()); } { absl::Status base(absl::StatusCode::kInvalidArgument, "fail"); base.SetPayload(kUrl1, absl::Cord(kPayload1)); absl::Status copy = base; EXPECT_TRUE(base.GetPayload(kUrl1).has_value()); EXPECT_TRUE(copy.GetPayload(kUrl1).has_value()); EXPECT_TRUE(base.ErasePayload(kUrl1)); EXPECT_FALSE(base.GetPayload(kUrl1).has_value()); EXPECT_TRUE(copy.GetPayload(kUrl1).has_value()); } } TEST(Status, CopyConstructor) { { absl::Status status; absl::Status copy(status); EXPECT_EQ(copy, status); } { absl::Status status(absl::StatusCode::kInvalidArgument, "message"); absl::Status copy(status); EXPECT_EQ(copy, status); } { absl::Status status(absl::StatusCode::kInvalidArgument, "message"); status.SetPayload(kUrl1, absl::Cord(kPayload1)); absl::Status copy(status); EXPECT_EQ(copy, status); } } TEST(Status, CopyAssignment) { absl::Status assignee; { absl::Status status; assignee = status; EXPECT_EQ(assignee, status); } { absl::Status status(absl::StatusCode::kInvalidArgument, "message"); assignee = status; EXPECT_EQ(assignee, status); } { absl::Status status(absl::StatusCode::kInvalidArgument, "message"); status.SetPayload(kUrl1, absl::Cord(kPayload1)); assignee = status; EXPECT_EQ(assignee, status); } } TEST(Status, CopyAssignmentIsNotRef) { const absl::Status status_orig(absl::StatusCode::kInvalidArgument, "message"); absl::Status status_copy = status_orig; EXPECT_EQ(status_orig, status_copy); status_copy.SetPayload(kUrl1, absl::Cord(kPayload1)); EXPECT_NE(status_orig, status_copy); } TEST(Status, MoveConstructor) { { absl::Status status; absl::Status copy(absl::Status{}); EXPECT_EQ(copy, status); } { absl::Status status(absl::StatusCode::kInvalidArgument, "message"); absl::Status copy( absl::Status(absl::StatusCode::kInvalidArgument, "message")); EXPECT_EQ(copy, status); } { absl::Status status(absl::StatusCode::kInvalidArgument, "message"); status.SetPayload(kUrl1, absl::Cord(kPayload1)); absl::Status copy1(status); absl::Status copy2(std::move(status)); EXPECT_EQ(copy1, copy2); } } TEST(Status, MoveAssignment) { absl::Status assignee; { absl::Status status; assignee = absl::Status(); EXPECT_EQ(assignee, status); } { absl::Status status(absl::StatusCode::kInvalidArgument, "message"); assignee = absl::Status(absl::StatusCode::kInvalidArgument, "message"); EXPECT_EQ(assignee, status); } { absl::Status status(absl::StatusCode::kInvalidArgument, "message"); status.SetPayload(kUrl1, absl::Cord(kPayload1)); absl::Status copy(status); assignee = std::move(status); EXPECT_EQ(assignee, copy); } { absl::Status status(absl::StatusCode::kInvalidArgument, "message"); absl::Status copy(status); assignee = static_cast<absl::Status&&>(status); EXPECT_EQ(assignee, copy); } } TEST(Status, Update) { absl::Status s; s.Update(absl::OkStatus()); EXPECT_TRUE(s.ok()); const absl::Status a(absl::StatusCode::kCancelled, "message"); s.Update(a); EXPECT_EQ(s, a); const absl::Status b(absl::StatusCode::kInternal, "other message"); s.Update(b); EXPECT_EQ(s, a); s.Update(absl::OkStatus()); EXPECT_EQ(s, a); EXPECT_FALSE(s.ok()); } TEST(Status, Equality) { absl::Status ok; absl::Status no_payload = absl::CancelledError("no payload"); absl::Status one_payload = absl::InvalidArgumentError("one payload"); one_payload.SetPayload(kUrl1, absl::Cord(kPayload1)); absl::Status two_payloads = one_payload; two_payloads.SetPayload(kUrl2, absl::Cord(kPayload2)); const std::array<absl::Status, 4> status_arr = {ok, no_payload, one_payload, two_payloads}; for (int i = 0; i < status_arr.size(); i++) { for (int j = 0; j < status_arr.size(); j++) { if (i == j) { EXPECT_TRUE(status_arr[i] == status_arr[j]); EXPECT_FALSE(status_arr[i] != status_arr[j]); } else { EXPECT_TRUE(status_arr[i] != status_arr[j]); EXPECT_FALSE(status_arr[i] == status_arr[j]); } } } } TEST(Status, Swap) { auto test_swap = [](const absl::Status& s1, const absl::Status& s2) { absl::Status copy1 = s1, copy2 = s2; swap(copy1, copy2); EXPECT_EQ(copy1, s2); EXPECT_EQ(copy2, s1); }; const absl::Status ok; const absl::Status no_payload(absl::StatusCode::kAlreadyExists, "no payload"); absl::Status with_payload(absl::StatusCode::kInternal, "with payload"); with_payload.SetPayload(kUrl1, absl::Cord(kPayload1)); test_swap(ok, no_payload); test_swap(no_payload, ok); test_swap(ok, with_payload); test_swap(with_payload, ok); test_swap(no_payload, with_payload); test_swap(with_payload, no_payload); } TEST(StatusErrno, ErrnoToStatusCode) { EXPECT_EQ(absl::ErrnoToStatusCode(0), absl::StatusCode::kOk); EXPECT_EQ(absl::ErrnoToStatusCode(EINVAL), absl::StatusCode::kInvalidArgument); EXPECT_EQ(absl::ErrnoToStatusCode(ENOENT), absl::StatusCode::kNotFound); EXPECT_EQ(absl::ErrnoToStatusCode(19980927), absl::StatusCode::kUnknown); } TEST(StatusErrno, ErrnoToStatus) { absl::Status status = absl::ErrnoToStatus(ENOENT, "Cannot open 'path'"); EXPECT_EQ(status.code(), absl::StatusCode::kNotFound); EXPECT_EQ(status.message(), "Cannot open 'path': No such file or directory"); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/status/status.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/status/status_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
4e0595d1-6ba2-4742-adc2-e2b72de011da
cpp
abseil/abseil-cpp
statusor
absl/status/statusor.cc
absl/status/statusor_test.cc
#include "absl/status/statusor.h" #include <cstdlib> #include <utility> #include "absl/base/call_once.h" #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/nullability.h" #include "absl/status/internal/statusor_internal.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" namespace absl { ABSL_NAMESPACE_BEGIN BadStatusOrAccess::BadStatusOrAccess(absl::Status status) : status_(std::move(status)) {} BadStatusOrAccess::BadStatusOrAccess(const BadStatusOrAccess& other) : status_(other.status_) {} BadStatusOrAccess& BadStatusOrAccess::operator=( const BadStatusOrAccess& other) { other.InitWhat(); status_ = other.status_; what_ = other.what_; return *this; } BadStatusOrAccess& BadStatusOrAccess::operator=(BadStatusOrAccess&& other) { other.InitWhat(); status_ = std::move(other.status_); what_ = std::move(other.what_); return *this; } BadStatusOrAccess::BadStatusOrAccess(BadStatusOrAccess&& other) : status_(std::move(other.status_)) {} absl::Nonnull<const char*> BadStatusOrAccess::what() const noexcept { InitWhat(); return what_.c_str(); } const absl::Status& BadStatusOrAccess::status() const { return status_; } void BadStatusOrAccess::InitWhat() const { absl::call_once(init_what_, [this] { what_ = absl::StrCat("Bad StatusOr access: ", status_.ToString()); }); } namespace internal_statusor { void Helper::HandleInvalidStatusCtorArg(absl::Nonnull<absl::Status*> status) { const char* kMessage = "An OK status is not a valid constructor argument to StatusOr<T>"; #ifdef NDEBUG ABSL_INTERNAL_LOG(ERROR, kMessage); #else ABSL_INTERNAL_LOG(FATAL, kMessage); #endif *status = absl::InternalError(kMessage); } void Helper::Crash(const absl::Status& status) { ABSL_INTERNAL_LOG( FATAL, absl::StrCat("Attempting to fetch value instead of handling error ", status.ToString())); } void ThrowBadStatusOrAccess(absl::Status status) { #ifdef ABSL_HAVE_EXCEPTIONS throw absl::BadStatusOrAccess(std::move(status)); #else ABSL_INTERNAL_LOG( FATAL, absl::StrCat("Attempting to fetch value instead of handling error ", status.ToString())); std::abort(); #endif } } ABSL_NAMESPACE_END }
#include "absl/status/statusor.h" #include <array> #include <cstddef> #include <initializer_list> #include <map> #include <memory> #include <ostream> #include <sstream> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/casts.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/any.h" #include "absl/types/variant.h" #include "absl/utility/utility.h" namespace { using ::absl_testing::IsOk; using ::absl_testing::IsOkAndHolds; using ::testing::AllOf; using ::testing::AnyOf; using ::testing::AnyWith; using ::testing::ElementsAre; using ::testing::EndsWith; using ::testing::Field; using ::testing::HasSubstr; using ::testing::Ne; using ::testing::Not; using ::testing::Pointee; using ::testing::StartsWith; using ::testing::VariantWith; struct CopyDetector { CopyDetector() = default; explicit CopyDetector(int xx) : x(xx) {} CopyDetector(CopyDetector&& d) noexcept : x(d.x), copied(false), moved(true) {} CopyDetector(const CopyDetector& d) : x(d.x), copied(true), moved(false) {} CopyDetector& operator=(const CopyDetector& c) { x = c.x; copied = true; moved = false; return *this; } CopyDetector& operator=(CopyDetector&& c) noexcept { x = c.x; copied = false; moved = true; return *this; } int x = 0; bool copied = false; bool moved = false; }; testing::Matcher<const CopyDetector&> CopyDetectorHas(int a, bool b, bool c) { return AllOf(Field(&CopyDetector::x, a), Field(&CopyDetector::moved, b), Field(&CopyDetector::copied, c)); } class Base1 { public: virtual ~Base1() {} int pad; }; class Base2 { public: virtual ~Base2() {} int yetotherpad; }; class Derived : public Base1, public Base2 { public: virtual ~Derived() {} int evenmorepad; }; class CopyNoAssign { public: explicit CopyNoAssign(int value) : foo(value) {} CopyNoAssign(const CopyNoAssign& other) : foo(other.foo) {} int foo; private: const CopyNoAssign& operator=(const CopyNoAssign&); }; absl::StatusOr<std::unique_ptr<int>> ReturnUniquePtr() { return absl::make_unique<int>(0); } TEST(StatusOr, ElementType) { static_assert(std::is_same<absl::StatusOr<int>::value_type, int>(), ""); static_assert(std::is_same<absl::StatusOr<char>::value_type, char>(), ""); } TEST(StatusOr, TestMoveOnlyInitialization) { absl::StatusOr<std::unique_ptr<int>> thing(ReturnUniquePtr()); ASSERT_TRUE(thing.ok()); EXPECT_EQ(0, **thing); int* previous = thing->get(); thing = ReturnUniquePtr(); EXPECT_TRUE(thing.ok()); EXPECT_EQ(0, **thing); EXPECT_NE(previous, thing->get()); } TEST(StatusOr, TestMoveOnlyValueExtraction) { absl::StatusOr<std::unique_ptr<int>> thing(ReturnUniquePtr()); ASSERT_TRUE(thing.ok()); std::unique_ptr<int> ptr = *std::move(thing); EXPECT_EQ(0, *ptr); thing = std::move(ptr); ptr = std::move(*thing); EXPECT_EQ(0, *ptr); } TEST(StatusOr, TestMoveOnlyInitializationFromTemporaryByValueOrDie) { std::unique_ptr<int> ptr(*ReturnUniquePtr()); EXPECT_EQ(0, *ptr); } TEST(StatusOr, TestValueOrDieOverloadForConstTemporary) { static_assert( std::is_same< const int&&, decltype(std::declval<const absl::StatusOr<int>&&>().value())>(), "value() for const temporaries should return const T&&"); } TEST(StatusOr, TestMoveOnlyConversion) { absl::StatusOr<std::unique_ptr<const int>> const_thing(ReturnUniquePtr()); EXPECT_TRUE(const_thing.ok()); EXPECT_EQ(0, **const_thing); const int* const_previous = const_thing->get(); const_thing = ReturnUniquePtr(); EXPECT_TRUE(const_thing.ok()); EXPECT_EQ(0, **const_thing); EXPECT_NE(const_previous, const_thing->get()); } TEST(StatusOr, TestMoveOnlyVector) { std::vector<absl::StatusOr<std::unique_ptr<int>>> vec; vec.push_back(ReturnUniquePtr()); vec.resize(2); auto another_vec = std::move(vec); EXPECT_EQ(0, **another_vec[0]); EXPECT_EQ(absl::UnknownError(""), another_vec[1].status()); } TEST(StatusOr, TestDefaultCtor) { absl::StatusOr<int> thing; EXPECT_FALSE(thing.ok()); EXPECT_EQ(thing.status().code(), absl::StatusCode::kUnknown); } TEST(StatusOr, StatusCtorForwards) { absl::Status status(absl::StatusCode::kInternal, "Some error"); EXPECT_EQ(absl::StatusOr<int>(status).status().message(), "Some error"); EXPECT_EQ(status.message(), "Some error"); EXPECT_EQ(absl::StatusOr<int>(std::move(status)).status().message(), "Some error"); EXPECT_NE(status.message(), "Some error"); } TEST(BadStatusOrAccessTest, CopyConstructionWhatOk) { absl::Status error = absl::InternalError("some arbitrary message too big for the sso buffer"); absl::BadStatusOrAccess e1{error}; absl::BadStatusOrAccess e2{e1}; EXPECT_THAT(e1.what(), HasSubstr(error.ToString())); EXPECT_THAT(e2.what(), HasSubstr(error.ToString())); } TEST(BadStatusOrAccessTest, CopyAssignmentWhatOk) { absl::Status error = absl::InternalError("some arbitrary message too big for the sso buffer"); absl::BadStatusOrAccess e1{error}; absl::BadStatusOrAccess e2{absl::InternalError("other")}; e2 = e1; EXPECT_THAT(e1.what(), HasSubstr(error.ToString())); EXPECT_THAT(e2.what(), HasSubstr(error.ToString())); } TEST(BadStatusOrAccessTest, MoveConstructionWhatOk) { absl::Status error = absl::InternalError("some arbitrary message too big for the sso buffer"); absl::BadStatusOrAccess e1{error}; absl::BadStatusOrAccess e2{std::move(e1)}; EXPECT_THAT(e2.what(), HasSubstr(error.ToString())); } TEST(BadStatusOrAccessTest, MoveAssignmentWhatOk) { absl::Status error = absl::InternalError("some arbitrary message too big for the sso buffer"); absl::BadStatusOrAccess e1{error}; absl::BadStatusOrAccess e2{absl::InternalError("other")}; e2 = std::move(e1); EXPECT_THAT(e2.what(), HasSubstr(error.ToString())); } #ifdef ABSL_HAVE_EXCEPTIONS #define EXPECT_DEATH_OR_THROW(statement, status_) \ EXPECT_THROW( \ { \ try { \ statement; \ } catch (const absl::BadStatusOrAccess& e) { \ EXPECT_EQ(e.status(), status_); \ EXPECT_THAT(e.what(), HasSubstr(e.status().ToString())); \ throw; \ } \ }, \ absl::BadStatusOrAccess); #else #define EXPECT_DEATH_OR_THROW(statement, status) \ EXPECT_DEATH_IF_SUPPORTED(statement, status.ToString()); #endif TEST(StatusOrDeathTest, TestDefaultCtorValue) { absl::StatusOr<int> thing; EXPECT_DEATH_OR_THROW(thing.value(), absl::UnknownError("")); const absl::StatusOr<int> thing2; EXPECT_DEATH_OR_THROW(thing2.value(), absl::UnknownError("")); } TEST(StatusOrDeathTest, TestValueNotOk) { absl::StatusOr<int> thing(absl::CancelledError()); EXPECT_DEATH_OR_THROW(thing.value(), absl::CancelledError()); } TEST(StatusOrDeathTest, TestValueNotOkConst) { const absl::StatusOr<int> thing(absl::UnknownError("")); EXPECT_DEATH_OR_THROW(thing.value(), absl::UnknownError("")); } TEST(StatusOrDeathTest, TestPointerDefaultCtorValue) { absl::StatusOr<int*> thing; EXPECT_DEATH_OR_THROW(thing.value(), absl::UnknownError("")); } TEST(StatusOrDeathTest, TestPointerValueNotOk) { absl::StatusOr<int*> thing(absl::CancelledError()); EXPECT_DEATH_OR_THROW(thing.value(), absl::CancelledError()); } TEST(StatusOrDeathTest, TestPointerValueNotOkConst) { const absl::StatusOr<int*> thing(absl::CancelledError()); EXPECT_DEATH_OR_THROW(thing.value(), absl::CancelledError()); } #if GTEST_HAS_DEATH_TEST TEST(StatusOrDeathTest, TestStatusCtorStatusOk) { EXPECT_DEBUG_DEATH( { absl::StatusOr<int> thing(absl::OkStatus()); EXPECT_FALSE(thing.ok()); EXPECT_EQ(thing.status().code(), absl::StatusCode::kInternal); }, "An OK status is not a valid constructor argument"); } TEST(StatusOrDeathTest, TestPointerStatusCtorStatusOk) { EXPECT_DEBUG_DEATH( { absl::StatusOr<int*> thing(absl::OkStatus()); EXPECT_FALSE(thing.ok()); EXPECT_EQ(thing.status().code(), absl::StatusCode::kInternal); }, "An OK status is not a valid constructor argument"); } #endif TEST(StatusOr, ValueAccessor) { const int kIntValue = 110; { absl::StatusOr<int> status_or(kIntValue); EXPECT_EQ(kIntValue, status_or.value()); EXPECT_EQ(kIntValue, std::move(status_or).value()); } { absl::StatusOr<CopyDetector> status_or(kIntValue); EXPECT_THAT(status_or, IsOkAndHolds(CopyDetectorHas(kIntValue, false, false))); CopyDetector copy_detector = status_or.value(); EXPECT_THAT(copy_detector, CopyDetectorHas(kIntValue, false, true)); copy_detector = std::move(status_or).value(); EXPECT_THAT(copy_detector, CopyDetectorHas(kIntValue, true, false)); } } TEST(StatusOr, BadValueAccess) { const absl::Status kError = absl::CancelledError("message"); absl::StatusOr<int> status_or(kError); EXPECT_DEATH_OR_THROW(status_or.value(), kError); } TEST(StatusOr, TestStatusCtor) { absl::StatusOr<int> thing(absl::CancelledError()); EXPECT_FALSE(thing.ok()); EXPECT_EQ(thing.status().code(), absl::StatusCode::kCancelled); } TEST(StatusOr, TestValueCtor) { const int kI = 4; const absl::StatusOr<int> thing(kI); EXPECT_TRUE(thing.ok()); EXPECT_EQ(kI, *thing); } struct Foo { const int x; explicit Foo(int y) : x(y) {} }; TEST(StatusOr, InPlaceConstruction) { EXPECT_THAT(absl::StatusOr<Foo>(absl::in_place, 10), IsOkAndHolds(Field(&Foo::x, 10))); } struct InPlaceHelper { InPlaceHelper(std::initializer_list<int> xs, std::unique_ptr<int> yy) : x(xs), y(std::move(yy)) {} const std::vector<int> x; std::unique_ptr<int> y; }; TEST(StatusOr, InPlaceInitListConstruction) { absl::StatusOr<InPlaceHelper> status_or(absl::in_place, {10, 11, 12}, absl::make_unique<int>(13)); EXPECT_THAT(status_or, IsOkAndHolds(AllOf( Field(&InPlaceHelper::x, ElementsAre(10, 11, 12)), Field(&InPlaceHelper::y, Pointee(13))))); } TEST(StatusOr, Emplace) { absl::StatusOr<Foo> status_or_foo(10); status_or_foo.emplace(20); EXPECT_THAT(status_or_foo, IsOkAndHolds(Field(&Foo::x, 20))); status_or_foo = absl::InvalidArgumentError("msg"); EXPECT_FALSE(status_or_foo.ok()); EXPECT_EQ(status_or_foo.status().code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ(status_or_foo.status().message(), "msg"); status_or_foo.emplace(20); EXPECT_THAT(status_or_foo, IsOkAndHolds(Field(&Foo::x, 20))); } TEST(StatusOr, EmplaceInitializerList) { absl::StatusOr<InPlaceHelper> status_or(absl::in_place, {10, 11, 12}, absl::make_unique<int>(13)); status_or.emplace({1, 2, 3}, absl::make_unique<int>(4)); EXPECT_THAT(status_or, IsOkAndHolds(AllOf(Field(&InPlaceHelper::x, ElementsAre(1, 2, 3)), Field(&InPlaceHelper::y, Pointee(4))))); status_or = absl::InvalidArgumentError("msg"); EXPECT_FALSE(status_or.ok()); EXPECT_EQ(status_or.status().code(), absl::StatusCode::kInvalidArgument); EXPECT_EQ(status_or.status().message(), "msg"); status_or.emplace({1, 2, 3}, absl::make_unique<int>(4)); EXPECT_THAT(status_or, IsOkAndHolds(AllOf(Field(&InPlaceHelper::x, ElementsAre(1, 2, 3)), Field(&InPlaceHelper::y, Pointee(4))))); } TEST(StatusOr, TestCopyCtorStatusOk) { const int kI = 4; const absl::StatusOr<int> original(kI); const absl::StatusOr<int> copy(original); EXPECT_THAT(copy.status(), IsOk()); EXPECT_EQ(*original, *copy); } TEST(StatusOr, TestCopyCtorStatusNotOk) { absl::StatusOr<int> original(absl::CancelledError()); absl::StatusOr<int> copy(original); EXPECT_EQ(copy.status().code(), absl::StatusCode::kCancelled); } TEST(StatusOr, TestCopyCtorNonAssignable) { const int kI = 4; CopyNoAssign value(kI); absl::StatusOr<CopyNoAssign> original(value); absl::StatusOr<CopyNoAssign> copy(original); EXPECT_THAT(copy.status(), IsOk()); EXPECT_EQ(original->foo, copy->foo); } TEST(StatusOr, TestCopyCtorStatusOKConverting) { const int kI = 4; absl::StatusOr<int> original(kI); absl::StatusOr<double> copy(original); EXPECT_THAT(copy.status(), IsOk()); EXPECT_DOUBLE_EQ(*original, *copy); } TEST(StatusOr, TestCopyCtorStatusNotOkConverting) { absl::StatusOr<int> original(absl::CancelledError()); absl::StatusOr<double> copy(original); EXPECT_EQ(copy.status(), original.status()); } TEST(StatusOr, TestAssignmentStatusOk) { { const auto p = std::make_shared<int>(17); absl::StatusOr<std::shared_ptr<int>> source(p); absl::StatusOr<std::shared_ptr<int>> target; target = source; ASSERT_TRUE(target.ok()); EXPECT_THAT(target.status(), IsOk()); EXPECT_EQ(p, *target); ASSERT_TRUE(source.ok()); EXPECT_THAT(source.status(), IsOk()); EXPECT_EQ(p, *source); } { const auto p = std::make_shared<int>(17); absl::StatusOr<std::shared_ptr<int>> source(p); absl::StatusOr<std::shared_ptr<int>> target; target = std::move(source); ASSERT_TRUE(target.ok()); EXPECT_THAT(target.status(), IsOk()); EXPECT_EQ(p, *target); ASSERT_TRUE(source.ok()); EXPECT_THAT(source.status(), IsOk()); EXPECT_EQ(nullptr, *source); } } TEST(StatusOr, TestAssignmentStatusNotOk) { { const absl::Status expected = absl::CancelledError(); absl::StatusOr<int> source(expected); absl::StatusOr<int> target; target = source; EXPECT_FALSE(target.ok()); EXPECT_EQ(expected, target.status()); EXPECT_FALSE(source.ok()); EXPECT_EQ(expected, source.status()); } { const absl::Status expected = absl::CancelledError(); absl::StatusOr<int> source(expected); absl::StatusOr<int> target; target = std::move(source); EXPECT_FALSE(target.ok()); EXPECT_EQ(expected, target.status()); EXPECT_FALSE(source.ok()); EXPECT_EQ(source.status().code(), absl::StatusCode::kInternal); } } TEST(StatusOr, TestAssignmentStatusOKConverting) { { const int kI = 4; absl::StatusOr<int> source(kI); absl::StatusOr<double> target; target = source; ASSERT_TRUE(target.ok()); EXPECT_THAT(target.status(), IsOk()); EXPECT_DOUBLE_EQ(kI, *target); ASSERT_TRUE(source.ok()); EXPECT_THAT(source.status(), IsOk()); EXPECT_DOUBLE_EQ(kI, *source); } { const auto p = new int(17); absl::StatusOr<std::unique_ptr<int>> source(absl::WrapUnique(p)); absl::StatusOr<std::shared_ptr<int>> target; target = std::move(source); ASSERT_TRUE(target.ok()); EXPECT_THAT(target.status(), IsOk()); EXPECT_EQ(p, target->get()); ASSERT_TRUE(source.ok()); EXPECT_THAT(source.status(), IsOk()); EXPECT_EQ(nullptr, source->get()); } } struct A { int x; }; struct ImplicitConstructibleFromA { int x; bool moved; ImplicitConstructibleFromA(const A& a) : x(a.x), moved(false) {} ImplicitConstructibleFromA(A&& a) : x(a.x), moved(true) {} }; TEST(StatusOr, ImplicitConvertingConstructor) { EXPECT_THAT( absl::implicit_cast<absl::StatusOr<ImplicitConstructibleFromA>>( absl::StatusOr<A>(A{11})), IsOkAndHolds(AllOf(Field(&ImplicitConstructibleFromA::x, 11), Field(&ImplicitConstructibleFromA::moved, true)))); absl::StatusOr<A> a(A{12}); EXPECT_THAT( absl::implicit_cast<absl::StatusOr<ImplicitConstructibleFromA>>(a), IsOkAndHolds(AllOf(Field(&ImplicitConstructibleFromA::x, 12), Field(&ImplicitConstructibleFromA::moved, false)))); } struct ExplicitConstructibleFromA { int x; bool moved; explicit ExplicitConstructibleFromA(const A& a) : x(a.x), moved(false) {} explicit ExplicitConstructibleFromA(A&& a) : x(a.x), moved(true) {} }; TEST(StatusOr, ExplicitConvertingConstructor) { EXPECT_FALSE( (std::is_convertible<const absl::StatusOr<A>&, absl::StatusOr<ExplicitConstructibleFromA>>::value)); EXPECT_FALSE( (std::is_convertible<absl::StatusOr<A>&&, absl::StatusOr<ExplicitConstructibleFromA>>::value)); EXPECT_THAT( absl::StatusOr<ExplicitConstructibleFromA>(absl::StatusOr<A>(A{11})), IsOkAndHolds(AllOf(Field(&ExplicitConstructibleFromA::x, 11), Field(&ExplicitConstructibleFromA::moved, true)))); absl::StatusOr<A> a(A{12}); EXPECT_THAT( absl::StatusOr<ExplicitConstructibleFromA>(a), IsOkAndHolds(AllOf(Field(&ExplicitConstructibleFromA::x, 12), Field(&ExplicitConstructibleFromA::moved, false)))); } struct ImplicitConstructibleFromBool { ImplicitConstructibleFromBool(bool y) : x(y) {} bool x = false; }; struct ConvertibleToBool { explicit ConvertibleToBool(bool y) : x(y) {} operator bool() const { return x; } bool x = false; }; TEST(StatusOr, ImplicitBooleanConstructionWithImplicitCasts) { EXPECT_THAT(absl::StatusOr<bool>(absl::StatusOr<ConvertibleToBool>(true)), IsOkAndHolds(true)); EXPECT_THAT(absl::StatusOr<bool>(absl::StatusOr<ConvertibleToBool>(false)), IsOkAndHolds(false)); EXPECT_THAT( absl::implicit_cast<absl::StatusOr<ImplicitConstructibleFromBool>>( absl::StatusOr<bool>(false)), IsOkAndHolds(Field(&ImplicitConstructibleFromBool::x, false))); EXPECT_FALSE((std::is_convertible< absl::StatusOr<ConvertibleToBool>, absl::StatusOr<ImplicitConstructibleFromBool>>::value)); } TEST(StatusOr, BooleanConstructionWithImplicitCasts) { EXPECT_THAT(absl::StatusOr<bool>(absl::StatusOr<ConvertibleToBool>(true)), IsOkAndHolds(true)); EXPECT_THAT(absl::StatusOr<bool>(absl::StatusOr<ConvertibleToBool>(false)), IsOkAndHolds(false)); EXPECT_THAT( absl::StatusOr<ImplicitConstructibleFromBool>{ absl::StatusOr<bool>(false)}, IsOkAndHolds(Field(&ImplicitConstructibleFromBool::x, false))); EXPECT_THAT( absl::StatusOr<ImplicitConstructibleFromBool>{ absl::StatusOr<bool>(absl::InvalidArgumentError(""))}, Not(IsOk())); EXPECT_THAT( absl::StatusOr<ImplicitConstructibleFromBool>{ absl::StatusOr<ConvertibleToBool>(ConvertibleToBool{false})}, IsOkAndHolds(Field(&ImplicitConstructibleFromBool::x, false))); EXPECT_THAT( absl::StatusOr<ImplicitConstructibleFromBool>{ absl::StatusOr<ConvertibleToBool>(absl::InvalidArgumentError(""))}, Not(IsOk())); } TEST(StatusOr, ConstImplicitCast) { EXPECT_THAT(absl::implicit_cast<absl::StatusOr<bool>>( absl::StatusOr<const bool>(true)), IsOkAndHolds(true)); EXPECT_THAT(absl::implicit_cast<absl::StatusOr<bool>>( absl::StatusOr<const bool>(false)), IsOkAndHolds(false)); EXPECT_THAT(absl::implicit_cast<absl::StatusOr<const bool>>( absl::StatusOr<bool>(true)), IsOkAndHolds(true)); EXPECT_THAT(absl::implicit_cast<absl::StatusOr<const bool>>( absl::StatusOr<bool>(false)), IsOkAndHolds(false)); EXPECT_THAT(absl::implicit_cast<absl::StatusOr<const std::string>>( absl::StatusOr<std::string>("foo")), IsOkAndHolds("foo")); EXPECT_THAT(absl::implicit_cast<absl::StatusOr<std::string>>( absl::StatusOr<const std::string>("foo")), IsOkAndHolds("foo")); EXPECT_THAT( absl::implicit_cast<absl::StatusOr<std::shared_ptr<const std::string>>>( absl::StatusOr<std::shared_ptr<std::string>>( std::make_shared<std::string>("foo"))), IsOkAndHolds(Pointee(std::string("foo")))); } TEST(StatusOr, ConstExplicitConstruction) { EXPECT_THAT(absl::StatusOr<bool>(absl::StatusOr<const bool>(true)), IsOkAndHolds(true)); EXPECT_THAT(absl::StatusOr<bool>(absl::StatusOr<const bool>(false)), IsOkAndHolds(false)); EXPECT_THAT(absl::StatusOr<const bool>(absl::StatusOr<bool>(true)), IsOkAndHolds(true)); EXPECT_THAT(absl::StatusOr<const bool>(absl::StatusOr<bool>(false)), IsOkAndHolds(false)); } struct ExplicitConstructibleFromInt { int x; explicit ExplicitConstructibleFromInt(int y) : x(y) {} }; TEST(StatusOr, ExplicitConstruction) { EXPECT_THAT(absl::StatusOr<ExplicitConstructibleFromInt>(10), IsOkAndHolds(Field(&ExplicitConstructibleFromInt::x, 10))); } TEST(StatusOr, ImplicitConstruction) { auto status_or = absl::implicit_cast<absl::StatusOr<absl::variant<int, std::string>>>(10); EXPECT_THAT(status_or, IsOkAndHolds(VariantWith<int>(10))); } TEST(StatusOr, ImplicitConstructionFromInitliazerList) { auto status_or = absl::implicit_cast<absl::StatusOr<std::vector<int>>>({{10, 20, 30}}); EXPECT_THAT(status_or, IsOkAndHolds(ElementsAre(10, 20, 30))); } TEST(StatusOr, UniquePtrImplicitConstruction) { auto status_or = absl::implicit_cast<absl::StatusOr<std::unique_ptr<Base1>>>( absl::make_unique<Derived>()); EXPECT_THAT(status_or, IsOkAndHolds(Ne(nullptr))); } TEST(StatusOr, NestedStatusOrCopyAndMoveConstructorTests) { absl::StatusOr<absl::StatusOr<CopyDetector>> status_or = CopyDetector(10); absl::StatusOr<absl::StatusOr<CopyDetector>> status_error = absl::InvalidArgumentError("foo"); EXPECT_THAT(status_or, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, true, false)))); absl::StatusOr<absl::StatusOr<CopyDetector>> a = status_or; EXPECT_THAT(a, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, false, true)))); absl::StatusOr<absl::StatusOr<CopyDetector>> a_err = status_error; EXPECT_THAT(a_err, Not(IsOk())); const absl::StatusOr<absl::StatusOr<CopyDetector>>& cref = status_or; absl::StatusOr<absl::StatusOr<CopyDetector>> b = cref; EXPECT_THAT(b, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, false, true)))); const absl::StatusOr<absl::StatusOr<CopyDetector>>& cref_err = status_error; absl::StatusOr<absl::StatusOr<CopyDetector>> b_err = cref_err; EXPECT_THAT(b_err, Not(IsOk())); absl::StatusOr<absl::StatusOr<CopyDetector>> c = std::move(status_or); EXPECT_THAT(c, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, true, false)))); absl::StatusOr<absl::StatusOr<CopyDetector>> c_err = std::move(status_error); EXPECT_THAT(c_err, Not(IsOk())); } TEST(StatusOr, NestedStatusOrCopyAndMoveAssignment) { absl::StatusOr<absl::StatusOr<CopyDetector>> status_or = CopyDetector(10); absl::StatusOr<absl::StatusOr<CopyDetector>> status_error = absl::InvalidArgumentError("foo"); absl::StatusOr<absl::StatusOr<CopyDetector>> a; a = status_or; EXPECT_THAT(a, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, false, true)))); a = status_error; EXPECT_THAT(a, Not(IsOk())); const absl::StatusOr<absl::StatusOr<CopyDetector>>& cref = status_or; a = cref; EXPECT_THAT(a, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, false, true)))); const absl::StatusOr<absl::StatusOr<CopyDetector>>& cref_err = status_error; a = cref_err; EXPECT_THAT(a, Not(IsOk())); a = std::move(status_or); EXPECT_THAT(a, IsOkAndHolds(IsOkAndHolds(CopyDetectorHas(10, true, false)))); a = std::move(status_error); EXPECT_THAT(a, Not(IsOk())); } struct Copyable { Copyable() {} Copyable(const Copyable&) {} Copyable& operator=(const Copyable&) { return *this; } }; struct MoveOnly { MoveOnly() {} MoveOnly(MoveOnly&&) {} MoveOnly& operator=(MoveOnly&&) { return *this; } }; struct NonMovable { NonMovable() {} NonMovable(const NonMovable&) = delete; NonMovable(NonMovable&&) = delete; NonMovable& operator=(const NonMovable&) = delete; NonMovable& operator=(NonMovable&&) = delete; }; TEST(StatusOr, CopyAndMoveAbility) { EXPECT_TRUE(std::is_copy_constructible<Copyable>::value); EXPECT_TRUE(std::is_copy_assignable<Copyable>::value); EXPECT_TRUE(std::is_move_constructible<Copyable>::value); EXPECT_TRUE(std::is_move_assignable<Copyable>::value); EXPECT_FALSE(std::is_copy_constructible<MoveOnly>::value); EXPECT_FALSE(std::is_copy_assignable<MoveOnly>::value); EXPECT_TRUE(std::is_move_constructible<MoveOnly>::value); EXPECT_TRUE(std::is_move_assignable<MoveOnly>::value); EXPECT_FALSE(std::is_copy_constructible<NonMovable>::value); EXPECT_FALSE(std::is_copy_assignable<NonMovable>::value); EXPECT_FALSE(std::is_move_constructible<NonMovable>::value); EXPECT_FALSE(std::is_move_assignable<NonMovable>::value); } TEST(StatusOr, StatusOrAnyCopyAndMoveConstructorTests) { absl::StatusOr<absl::any> status_or = CopyDetector(10); absl::StatusOr<absl::any> status_error = absl::InvalidArgumentError("foo"); EXPECT_THAT( status_or, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, true, false)))); absl::StatusOr<absl::any> a = status_or; EXPECT_THAT( a, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, false, true)))); absl::StatusOr<absl::any> a_err = status_error; EXPECT_THAT(a_err, Not(IsOk())); const absl::StatusOr<absl::any>& cref = status_or; absl::StatusOr<absl::any> b = cref; EXPECT_THAT( b, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, false, true)))); const absl::StatusOr<absl::any>& cref_err = status_error; absl::StatusOr<absl::any> b_err = cref_err; EXPECT_THAT(b_err, Not(IsOk())); absl::StatusOr<absl::any> c = std::move(status_or); EXPECT_THAT( c, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, true, false)))); absl::StatusOr<absl::any> c_err = std::move(status_error); EXPECT_THAT(c_err, Not(IsOk())); } TEST(StatusOr, StatusOrAnyCopyAndMoveAssignment) { absl::StatusOr<absl::any> status_or = CopyDetector(10); absl::StatusOr<absl::any> status_error = absl::InvalidArgumentError("foo"); absl::StatusOr<absl::any> a; a = status_or; EXPECT_THAT( a, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, false, true)))); a = status_error; EXPECT_THAT(a, Not(IsOk())); const absl::StatusOr<absl::any>& cref = status_or; a = cref; EXPECT_THAT( a, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, false, true)))); const absl::StatusOr<absl::any>& cref_err = status_error; a = cref_err; EXPECT_THAT(a, Not(IsOk())); a = std::move(status_or); EXPECT_THAT( a, IsOkAndHolds(AnyWith<CopyDetector>(CopyDetectorHas(10, true, false)))); a = std::move(status_error); EXPECT_THAT(a, Not(IsOk())); } TEST(StatusOr, StatusOrCopyAndMoveTestsConstructor) { absl::StatusOr<CopyDetector> status_or(10); ASSERT_THAT(status_or, IsOkAndHolds(CopyDetectorHas(10, false, false))); absl::StatusOr<CopyDetector> a(status_or); EXPECT_THAT(a, IsOkAndHolds(CopyDetectorHas(10, false, true))); const absl::StatusOr<CopyDetector>& cref = status_or; absl::StatusOr<CopyDetector> b(cref); EXPECT_THAT(b, IsOkAndHolds(CopyDetectorHas(10, false, true))); absl::StatusOr<CopyDetector> c(std::move(status_or)); EXPECT_THAT(c, IsOkAndHolds(CopyDetectorHas(10, true, false))); } TEST(StatusOr, StatusOrCopyAndMoveTestsAssignment) { absl::StatusOr<CopyDetector> status_or(10); ASSERT_THAT(status_or, IsOkAndHolds(CopyDetectorHas(10, false, false))); absl::StatusOr<CopyDetector> a; a = status_or; EXPECT_THAT(a, IsOkAndHolds(CopyDetectorHas(10, false, true))); const absl::StatusOr<CopyDetector>& cref = status_or; absl::StatusOr<CopyDetector> b; b = cref; EXPECT_THAT(b, IsOkAndHolds(CopyDetectorHas(10, false, true))); absl::StatusOr<CopyDetector> c; c = std::move(status_or); EXPECT_THAT(c, IsOkAndHolds(CopyDetectorHas(10, true, false))); } TEST(StatusOr, AbslAnyAssignment) { EXPECT_FALSE((std::is_assignable<absl::StatusOr<absl::any>, absl::StatusOr<int>>::value)); absl::StatusOr<absl::any> status_or; status_or = absl::InvalidArgumentError("foo"); EXPECT_THAT(status_or, Not(IsOk())); } TEST(StatusOr, ImplicitAssignment) { absl::StatusOr<absl::variant<int, std::string>> status_or; status_or = 10; EXPECT_THAT(status_or, IsOkAndHolds(VariantWith<int>(10))); } TEST(StatusOr, SelfDirectInitAssignment) { absl::StatusOr<std::vector<int>> status_or = {{10, 20, 30}}; status_or = *status_or; EXPECT_THAT(status_or, IsOkAndHolds(ElementsAre(10, 20, 30))); } TEST(StatusOr, ImplicitCastFromInitializerList) { absl::StatusOr<std::vector<int>> status_or = {{10, 20, 30}}; EXPECT_THAT(status_or, IsOkAndHolds(ElementsAre(10, 20, 30))); } TEST(StatusOr, UniquePtrImplicitAssignment) { absl::StatusOr<std::unique_ptr<Base1>> status_or; status_or = absl::make_unique<Derived>(); EXPECT_THAT(status_or, IsOkAndHolds(Ne(nullptr))); } TEST(StatusOr, Pointer) { struct A {}; struct B : public A {}; struct C : private A {}; EXPECT_TRUE((std::is_constructible<absl::StatusOr<A*>, B*>::value)); EXPECT_TRUE((std::is_convertible<B*, absl::StatusOr<A*>>::value)); EXPECT_FALSE((std::is_constructible<absl::StatusOr<A*>, C*>::value)); EXPECT_FALSE((std::is_convertible<C*, absl::StatusOr<A*>>::value)); } TEST(StatusOr, TestAssignmentStatusNotOkConverting) { { const absl::Status expected = absl::CancelledError(); absl::StatusOr<int> source(expected); absl::StatusOr<double> target; target = source; EXPECT_FALSE(target.ok()); EXPECT_EQ(expected, target.status()); EXPECT_FALSE(source.ok()); EXPECT_EQ(expected, source.status()); } { const absl::Status expected = absl::CancelledError(); absl::StatusOr<int> source(expected); absl::StatusOr<double> target; target = std::move(source); EXPECT_FALSE(target.ok()); EXPECT_EQ(expected, target.status()); EXPECT_FALSE(source.ok()); EXPECT_EQ(source.status().code(), absl::StatusCode::kInternal); } } TEST(StatusOr, SelfAssignment) { { const std::string long_str(128, 'a'); absl::StatusOr<std::string> so = long_str; so = *&so; ASSERT_TRUE(so.ok()); EXPECT_THAT(so.status(), IsOk()); EXPECT_EQ(long_str, *so); } { absl::StatusOr<int> so = absl::NotFoundError("taco"); so = *&so; EXPECT_FALSE(so.ok()); EXPECT_EQ(so.status().code(), absl::StatusCode::kNotFound); EXPECT_EQ(so.status().message(), "taco"); } { absl::StatusOr<int> so = 17; auto& same = so; so = std::move(same); ASSERT_TRUE(so.ok()); EXPECT_THAT(so.status(), IsOk()); EXPECT_EQ(17, *so); } { absl::StatusOr<int> so = absl::NotFoundError("taco"); auto& same = so; so = std::move(same); EXPECT_FALSE(so.ok()); EXPECT_EQ(so.status().code(), absl::StatusCode::kNotFound); EXPECT_EQ(so.status().message(), "taco"); } { const auto raw = new int(17); absl::StatusOr<std::unique_ptr<int>> so = absl::WrapUnique(raw); auto& same = so; so = std::move(same); ASSERT_TRUE(so.ok()); EXPECT_THAT(so.status(), IsOk()); EXPECT_EQ(raw, so->get()); } { absl::StatusOr<std::unique_ptr<int>> so = absl::NotFoundError("taco"); auto& same = so; so = std::move(same); EXPECT_FALSE(so.ok()); EXPECT_EQ(so.status().code(), absl::StatusCode::kNotFound); EXPECT_EQ(so.status().message(), "taco"); } } struct FromConstructibleAssignableLvalue {}; struct FromConstructibleAssignableRvalue {}; struct FromImplicitConstructibleOnly {}; struct FromAssignableOnly {}; struct MockValue { MockValue(const FromConstructibleAssignableLvalue&) : from_rvalue(false), assigned(false) {} MockValue(FromConstructibleAssignableRvalue&&) : from_rvalue(true), assigned(false) {} MockValue(const FromImplicitConstructibleOnly&) : from_rvalue(false), assigned(false) {} MockValue& operator=(const FromConstructibleAssignableLvalue&) { from_rvalue = false; assigned = true; return *this; } MockValue& operator=(FromConstructibleAssignableRvalue&&) { from_rvalue = true; assigned = true; return *this; } MockValue& operator=(const FromAssignableOnly&) { from_rvalue = false; assigned = true; return *this; } bool from_rvalue; bool assigned; }; TEST(StatusOr, PerfectForwardingAssignment) { constexpr int kValue1 = 10, kValue2 = 20; absl::StatusOr<CopyDetector> status_or; CopyDetector lvalue(kValue1); status_or = lvalue; EXPECT_THAT(status_or, IsOkAndHolds(CopyDetectorHas(kValue1, false, true))); status_or = CopyDetector(kValue2); EXPECT_THAT(status_or, IsOkAndHolds(CopyDetectorHas(kValue2, true, false))); EXPECT_TRUE( (std::is_assignable<absl::StatusOr<MockValue>&, const FromConstructibleAssignableLvalue&>::value)); EXPECT_TRUE((std::is_assignable<absl::StatusOr<MockValue>&, FromConstructibleAssignableLvalue&&>::value)); EXPECT_FALSE( (std::is_assignable<absl::StatusOr<MockValue>&, const FromConstructibleAssignableRvalue&>::value)); EXPECT_TRUE((std::is_assignable<absl::StatusOr<MockValue>&, FromConstructibleAssignableRvalue&&>::value)); EXPECT_TRUE( (std::is_assignable<absl::StatusOr<MockValue>&, const FromImplicitConstructibleOnly&>::value)); EXPECT_FALSE((std::is_assignable<absl::StatusOr<MockValue>&, const FromAssignableOnly&>::value)); absl::StatusOr<MockValue> from_lvalue(FromConstructibleAssignableLvalue{}); EXPECT_FALSE(from_lvalue->from_rvalue); EXPECT_FALSE(from_lvalue->assigned); from_lvalue = FromConstructibleAssignableLvalue{}; EXPECT_FALSE(from_lvalue->from_rvalue); EXPECT_TRUE(from_lvalue->assigned); absl::StatusOr<MockValue> from_rvalue(FromConstructibleAssignableRvalue{}); EXPECT_TRUE(from_rvalue->from_rvalue); EXPECT_FALSE(from_rvalue->assigned); from_rvalue = FromConstructibleAssignableRvalue{}; EXPECT_TRUE(from_rvalue->from_rvalue); EXPECT_TRUE(from_rvalue->assigned); absl::StatusOr<MockValue> from_implicit_constructible( FromImplicitConstructibleOnly{}); EXPECT_FALSE(from_implicit_constructible->from_rvalue); EXPECT_FALSE(from_implicit_constructible->assigned); from_implicit_constructible = FromImplicitConstructibleOnly{}; EXPECT_FALSE(from_implicit_constructible->from_rvalue); EXPECT_FALSE(from_implicit_constructible->assigned); } TEST(StatusOr, TestStatus) { absl::StatusOr<int> good(4); EXPECT_TRUE(good.ok()); absl::StatusOr<int> bad(absl::CancelledError()); EXPECT_FALSE(bad.ok()); EXPECT_EQ(bad.status().code(), absl::StatusCode::kCancelled); } TEST(StatusOr, OperatorStarRefQualifiers) { static_assert( std::is_same<const int&, decltype(*std::declval<const absl::StatusOr<int>&>())>(), "Unexpected ref-qualifiers"); static_assert( std::is_same<int&, decltype(*std::declval<absl::StatusOr<int>&>())>(), "Unexpected ref-qualifiers"); static_assert( std::is_same<const int&&, decltype(*std::declval<const absl::StatusOr<int>&&>())>(), "Unexpected ref-qualifiers"); static_assert( std::is_same<int&&, decltype(*std::declval<absl::StatusOr<int>&&>())>(), "Unexpected ref-qualifiers"); } TEST(StatusOr, OperatorStar) { const absl::StatusOr<std::string> const_lvalue("hello"); EXPECT_EQ("hello", *const_lvalue); absl::StatusOr<std::string> lvalue("hello"); EXPECT_EQ("hello", *lvalue); const absl::StatusOr<std::string> const_rvalue("hello"); EXPECT_EQ("hello", *std::move(const_rvalue)); absl::StatusOr<std::string> rvalue("hello"); EXPECT_EQ("hello", *std::move(rvalue)); } TEST(StatusOr, OperatorArrowQualifiers) { static_assert( std::is_same< const int*, decltype(std::declval<const absl::StatusOr<int>&>().operator->())>(), "Unexpected qualifiers"); static_assert( std::is_same< int*, decltype(std::declval<absl::StatusOr<int>&>().operator->())>(), "Unexpected qualifiers"); static_assert( std::is_same< const int*, decltype(std::declval<const absl::StatusOr<int>&&>().operator->())>(), "Unexpected qualifiers"); static_assert( std::is_same< int*, decltype(std::declval<absl::StatusOr<int>&&>().operator->())>(), "Unexpected qualifiers"); } TEST(StatusOr, OperatorArrow) { const absl::StatusOr<std::string> const_lvalue("hello"); EXPECT_EQ(std::string("hello"), const_lvalue->c_str()); absl::StatusOr<std::string> lvalue("hello"); EXPECT_EQ(std::string("hello"), lvalue->c_str()); } TEST(StatusOr, RValueStatus) { absl::StatusOr<int> so(absl::NotFoundError("taco")); const absl::Status s = std::move(so).status(); EXPECT_EQ(s.code(), absl::StatusCode::kNotFound); EXPECT_EQ(s.message(), "taco"); EXPECT_FALSE(so.ok()); EXPECT_FALSE(so.status().ok()); EXPECT_EQ(so.status().code(), absl::StatusCode::kInternal); EXPECT_EQ(so.status().message(), "Status accessed after move."); } TEST(StatusOr, TestValue) { const int kI = 4; absl::StatusOr<int> thing(kI); EXPECT_EQ(kI, *thing); } TEST(StatusOr, TestValueConst) { const int kI = 4; const absl::StatusOr<int> thing(kI); EXPECT_EQ(kI, *thing); } TEST(StatusOr, TestPointerDefaultCtor) { absl::StatusOr<int*> thing; EXPECT_FALSE(thing.ok()); EXPECT_EQ(thing.status().code(), absl::StatusCode::kUnknown); } TEST(StatusOr, TestPointerStatusCtor) { absl::StatusOr<int*> thing(absl::CancelledError()); EXPECT_FALSE(thing.ok()); EXPECT_EQ(thing.status().code(), absl::StatusCode::kCancelled); } TEST(StatusOr, TestPointerValueCtor) { const int kI = 4; { absl::StatusOr<const int*> so(&kI); EXPECT_TRUE(so.ok()); EXPECT_THAT(so.status(), IsOk()); EXPECT_EQ(&kI, *so); } { absl::StatusOr<const int*> so(nullptr); EXPECT_TRUE(so.ok()); EXPECT_THAT(so.status(), IsOk()); EXPECT_EQ(nullptr, *so); } { const int* const p = nullptr; absl::StatusOr<const int*> so(p); EXPECT_TRUE(so.ok()); EXPECT_THAT(so.status(), IsOk()); EXPECT_EQ(nullptr, *so); } } TEST(StatusOr, TestPointerCopyCtorStatusOk) { const int kI = 0; absl::StatusOr<const int*> original(&kI); absl::StatusOr<const int*> copy(original); EXPECT_THAT(copy.status(), IsOk()); EXPECT_EQ(*original, *copy); } TEST(StatusOr, TestPointerCopyCtorStatusNotOk) { absl::StatusOr<int*> original(absl::CancelledError()); absl::StatusOr<int*> copy(original); EXPECT_EQ(copy.status().code(), absl::StatusCode::kCancelled); } TEST(StatusOr, TestPointerCopyCtorStatusOKConverting) { Derived derived; absl::StatusOr<Derived*> original(&derived); absl::StatusOr<Base2*> copy(original); EXPECT_THAT(copy.status(), IsOk()); EXPECT_EQ(static_cast<const Base2*>(*original), *copy); } TEST(StatusOr, TestPointerCopyCtorStatusNotOkConverting) { absl::StatusOr<Derived*> original(absl::CancelledError()); absl::StatusOr<Base2*> copy(original); EXPECT_EQ(copy.status().code(), absl::StatusCode::kCancelled); } TEST(StatusOr, TestPointerAssignmentStatusOk) { const int kI = 0; absl::StatusOr<const int*> source(&kI); absl::StatusOr<const int*> target; target = source; EXPECT_THAT(target.status(), IsOk()); EXPECT_EQ(*source, *target); } TEST(StatusOr, TestPointerAssignmentStatusNotOk) { absl::StatusOr<int*> source(absl::CancelledError()); absl::StatusOr<int*> target; target = source; EXPECT_EQ(target.status().code(), absl::StatusCode::kCancelled); } TEST(StatusOr, TestPointerAssignmentStatusOKConverting) { Derived derived; absl::StatusOr<Derived*> source(&derived); absl::StatusOr<Base2*> target; target = source; EXPECT_THAT(target.status(), IsOk()); EXPECT_EQ(static_cast<const Base2*>(*source), *target); } TEST(StatusOr, TestPointerAssignmentStatusNotOkConverting) { absl::StatusOr<Derived*> source(absl::CancelledError()); absl::StatusOr<Base2*> target; target = source; EXPECT_EQ(target.status(), source.status()); } TEST(StatusOr, TestPointerStatus) { const int kI = 0; absl::StatusOr<const int*> good(&kI); EXPECT_TRUE(good.ok()); absl::StatusOr<const int*> bad(absl::CancelledError()); EXPECT_EQ(bad.status().code(), absl::StatusCode::kCancelled); } TEST(StatusOr, TestPointerValue) { const int kI = 0; absl::StatusOr<const int*> thing(&kI); EXPECT_EQ(&kI, *thing); } TEST(StatusOr, TestPointerValueConst) { const int kI = 0; const absl::StatusOr<const int*> thing(&kI); EXPECT_EQ(&kI, *thing); } TEST(StatusOr, StatusOrVectorOfUniquePointerCanReserveAndResize) { using EvilType = std::vector<std::unique_ptr<int>>; static_assert(std::is_copy_constructible<EvilType>::value, ""); std::vector<::absl::StatusOr<EvilType>> v(5); v.reserve(v.capacity() + 10); v.resize(v.capacity() + 10); } TEST(StatusOr, ConstPayload) { absl::StatusOr<const int> a; absl::StatusOr<const int> b(a); EXPECT_FALSE(std::is_copy_assignable<absl::StatusOr<const int>>::value); absl::StatusOr<const int> c(std::move(a)); EXPECT_FALSE(std::is_move_assignable<absl::StatusOr<const int>>::value); } TEST(StatusOr, MapToStatusOrUniquePtr) { using MapType = std::map<std::string, absl::StatusOr<std::unique_ptr<int>>>; MapType a; MapType b(std::move(a)); a = std::move(b); } TEST(StatusOr, ValueOrOk) { const absl::StatusOr<int> status_or = 0; EXPECT_EQ(status_or.value_or(-1), 0); } TEST(StatusOr, ValueOrDefault) { const absl::StatusOr<int> status_or = absl::CancelledError(); EXPECT_EQ(status_or.value_or(-1), -1); } TEST(StatusOr, MoveOnlyValueOrOk) { EXPECT_THAT(absl::StatusOr<std::unique_ptr<int>>(absl::make_unique<int>(0)) .value_or(absl::make_unique<int>(-1)), Pointee(0)); } TEST(StatusOr, MoveOnlyValueOrDefault) { EXPECT_THAT(absl::StatusOr<std::unique_ptr<int>>(absl::CancelledError()) .value_or(absl::make_unique<int>(-1)), Pointee(-1)); } static absl::StatusOr<int> MakeStatus() { return 100; } TEST(StatusOr, TestIgnoreError) { MakeStatus().IgnoreError(); } TEST(StatusOr, EqualityOperator) { constexpr size_t kNumCases = 4; std::array<absl::StatusOr<int>, kNumCases> group1 = { absl::StatusOr<int>(1), absl::StatusOr<int>(2), absl::StatusOr<int>(absl::InvalidArgumentError("msg")), absl::StatusOr<int>(absl::InternalError("msg"))}; std::array<absl::StatusOr<int>, kNumCases> group2 = { absl::StatusOr<int>(1), absl::StatusOr<int>(2), absl::StatusOr<int>(absl::InvalidArgumentError("msg")), absl::StatusOr<int>(absl::InternalError("msg"))}; for (size_t i = 0; i < kNumCases; ++i) { for (size_t j = 0; j < kNumCases; ++j) { if (i == j) { EXPECT_TRUE(group1[i] == group2[j]); EXPECT_FALSE(group1[i] != group2[j]); } else { EXPECT_FALSE(group1[i] == group2[j]); EXPECT_TRUE(group1[i] != group2[j]); } } } } struct MyType { bool operator==(const MyType&) const { return true; } }; enum class ConvTraits { kNone = 0, kImplicit = 1, kExplicit = 2 }; template <typename T, ConvTraits conv_traits = ConvTraits::kNone> struct StatusOrConversionBase {}; template <typename T> struct StatusOrConversionBase<T, ConvTraits::kImplicit> { operator absl::StatusOr<T>() const& { return absl::InvalidArgumentError("conversion to absl::StatusOr"); } operator absl::StatusOr<T>() && { return absl::InvalidArgumentError("conversion to absl::StatusOr"); } }; template <typename T> struct StatusOrConversionBase<T, ConvTraits::kExplicit> { explicit operator absl::StatusOr<T>() const& { return absl::InvalidArgumentError("conversion to absl::StatusOr"); } explicit operator absl::StatusOr<T>() && { return absl::InvalidArgumentError("conversion to absl::StatusOr"); } }; template <typename T, ConvTraits conv_traits = ConvTraits::kNone> struct ConversionBase {}; template <typename T> struct ConversionBase<T, ConvTraits::kImplicit> { operator T() const& { return t; } operator T() && { return std::move(t); } T t; }; template <typename T> struct ConversionBase<T, ConvTraits::kExplicit> { explicit operator T() const& { return t; } explicit operator T() && { return std::move(t); } T t; }; template <ConvTraits conv_traits = ConvTraits::kNone> struct StatusConversionBase {}; template <> struct StatusConversionBase<ConvTraits::kImplicit> { operator absl::Status() const& { return absl::InternalError("conversion to Status"); } operator absl::Status() && { return absl::InternalError("conversion to Status"); } }; template <> struct StatusConversionBase<ConvTraits::kExplicit> { explicit operator absl::Status() const& { return absl::InternalError("conversion to Status"); } explicit operator absl::Status() && { return absl::InternalError("conversion to Status"); } }; static constexpr int kConvToStatus = 1; static constexpr int kConvToStatusOr = 2; static constexpr int kConvToT = 4; static constexpr int kConvExplicit = 8; constexpr ConvTraits GetConvTraits(int bit, int config) { return (config & bit) == 0 ? ConvTraits::kNone : ((config & kConvExplicit) == 0 ? ConvTraits::kImplicit : ConvTraits::kExplicit); } template <typename T, int config> struct CustomType : StatusOrConversionBase<T, GetConvTraits(kConvToStatusOr, config)>, ConversionBase<T, GetConvTraits(kConvToT, config)>, StatusConversionBase<GetConvTraits(kConvToStatus, config)> {}; struct ConvertibleToAnyStatusOr { template <typename T> operator absl::StatusOr<T>() const { return absl::InvalidArgumentError("Conversion to absl::StatusOr"); } }; TEST(StatusOr, ConstructionFromT) { { ConvertibleToAnyStatusOr v; absl::StatusOr<ConvertibleToAnyStatusOr> statusor(v); EXPECT_TRUE(statusor.ok()); } { ConvertibleToAnyStatusOr v; absl::StatusOr<ConvertibleToAnyStatusOr> statusor = v; EXPECT_TRUE(statusor.ok()); } { CustomType<MyType, kConvToStatus | kConvExplicit> v; absl::StatusOr<CustomType<MyType, kConvToStatus | kConvExplicit>> statusor( v); EXPECT_TRUE(statusor.ok()); } { CustomType<MyType, kConvToStatus | kConvExplicit> v; absl::StatusOr<CustomType<MyType, kConvToStatus | kConvExplicit>> statusor = v; EXPECT_TRUE(statusor.ok()); } } TEST(StatusOr, ConstructionFromTypeConvertibleToT) { { CustomType<MyType, kConvToT | kConvExplicit> v; absl::StatusOr<MyType> statusor(v); EXPECT_TRUE(statusor.ok()); } { CustomType<MyType, kConvToT> v; absl::StatusOr<MyType> statusor = v; EXPECT_TRUE(statusor.ok()); } } TEST(StatusOr, ConstructionFromTypeWithConversionOperatorToStatusOrT) { { CustomType<MyType, kConvToStatusOr | kConvExplicit> v; absl::StatusOr<MyType> statusor(v); EXPECT_EQ(statusor, v.operator absl::StatusOr<MyType>()); } { CustomType<MyType, kConvToT | kConvToStatusOr | kConvExplicit> v; absl::StatusOr<MyType> statusor(v); EXPECT_EQ(statusor, v.operator absl::StatusOr<MyType>()); } { CustomType<MyType, kConvToStatusOr | kConvToStatus | kConvExplicit> v; absl::StatusOr<MyType> statusor(v); EXPECT_EQ(statusor, v.operator absl::StatusOr<MyType>()); } { CustomType<MyType, kConvToT | kConvToStatusOr | kConvToStatus | kConvExplicit> v; absl::StatusOr<MyType> statusor(v); EXPECT_EQ(statusor, v.operator absl::StatusOr<MyType>()); } { CustomType<MyType, kConvToStatusOr> v; absl::StatusOr<MyType> statusor = v; EXPECT_EQ(statusor, v.operator absl::StatusOr<MyType>()); } { CustomType<MyType, kConvToT | kConvToStatusOr> v; absl::StatusOr<MyType> statusor = v; EXPECT_EQ(statusor, v.operator absl::StatusOr<MyType>()); } { CustomType<MyType, kConvToStatusOr | kConvToStatus> v; absl::StatusOr<MyType> statusor = v; EXPECT_EQ(statusor, v.operator absl::StatusOr<MyType>()); } { CustomType<MyType, kConvToT | kConvToStatusOr | kConvToStatus> v; absl::StatusOr<MyType> statusor = v; EXPECT_EQ(statusor, v.operator absl::StatusOr<MyType>()); } } TEST(StatusOr, ConstructionFromTypeConvertibleToStatus) { { CustomType<MyType, kConvToStatus | kConvExplicit> v; absl::StatusOr<MyType> statusor(v); EXPECT_FALSE(statusor.ok()); EXPECT_EQ(statusor.status(), static_cast<absl::Status>(v)); } { CustomType<MyType, kConvToT | kConvToStatus | kConvExplicit> v; absl::StatusOr<MyType> statusor(v); EXPECT_FALSE(statusor.ok()); EXPECT_EQ(statusor.status(), static_cast<absl::Status>(v)); } { CustomType<MyType, kConvToStatus> v; absl::StatusOr<MyType> statusor = v; EXPECT_FALSE(statusor.ok()); EXPECT_EQ(statusor.status(), static_cast<absl::Status>(v)); } { CustomType<MyType, kConvToT | kConvToStatus> v; absl::StatusOr<MyType> statusor = v; EXPECT_FALSE(statusor.ok()); EXPECT_EQ(statusor.status(), static_cast<absl::Status>(v)); } } TEST(StatusOr, AssignmentFromT) { { ConvertibleToAnyStatusOr v; absl::StatusOr<ConvertibleToAnyStatusOr> statusor; statusor = v; EXPECT_TRUE(statusor.ok()); } { CustomType<MyType, kConvToStatus> v; absl::StatusOr<CustomType<MyType, kConvToStatus>> statusor; statusor = v; EXPECT_TRUE(statusor.ok()); } } TEST(StatusOr, AssignmentFromTypeConvertibleToT) { { CustomType<MyType, kConvToT> v; absl::StatusOr<MyType> statusor; statusor = v; EXPECT_TRUE(statusor.ok()); } } TEST(StatusOr, AssignmentFromTypeWithConversionOperatortoStatusOrT) { { CustomType<MyType, kConvToStatusOr> v; absl::StatusOr<MyType> statusor; statusor = v; EXPECT_EQ(statusor, v.operator absl::StatusOr<MyType>()); } { CustomType<MyType, kConvToT | kConvToStatusOr> v; absl::StatusOr<MyType> statusor; statusor = v; EXPECT_EQ(statusor, v.operator absl::StatusOr<MyType>()); } { CustomType<MyType, kConvToStatusOr | kConvToStatus> v; absl::StatusOr<MyType> statusor; statusor = v; EXPECT_EQ(statusor, v.operator absl::StatusOr<MyType>()); } { CustomType<MyType, kConvToT | kConvToStatusOr | kConvToStatus> v; absl::StatusOr<MyType> statusor; statusor = v; EXPECT_EQ(statusor, v.operator absl::StatusOr<MyType>()); } } TEST(StatusOr, AssignmentFromTypeConvertibleToStatus) { { CustomType<MyType, kConvToStatus> v; absl::StatusOr<MyType> statusor; statusor = v; EXPECT_FALSE(statusor.ok()); EXPECT_EQ(statusor.status(), static_cast<absl::Status>(v)); } { CustomType<MyType, kConvToT | kConvToStatus> v; absl::StatusOr<MyType> statusor; statusor = v; EXPECT_FALSE(statusor.ok()); EXPECT_EQ(statusor.status(), static_cast<absl::Status>(v)); } } TEST(StatusOr, StatusAssignmentFromStatusError) { absl::StatusOr<absl::Status> statusor; statusor.AssignStatus(absl::CancelledError()); EXPECT_FALSE(statusor.ok()); EXPECT_EQ(statusor.status(), absl::CancelledError()); } #if GTEST_HAS_DEATH_TEST TEST(StatusOr, StatusAssignmentFromStatusOk) { EXPECT_DEBUG_DEATH( { absl::StatusOr<absl::Status> statusor; statusor.AssignStatus(absl::OkStatus()); EXPECT_FALSE(statusor.ok()); EXPECT_EQ(statusor.status().code(), absl::StatusCode::kInternal); }, "An OK status is not a valid constructor argument to StatusOr<T>"); } #endif TEST(StatusOr, StatusAssignmentFromTypeConvertibleToStatus) { CustomType<MyType, kConvToStatus> v; absl::StatusOr<MyType> statusor; statusor.AssignStatus(v); EXPECT_FALSE(statusor.ok()); EXPECT_EQ(statusor.status(), static_cast<absl::Status>(v)); } struct PrintTestStruct { friend std::ostream& operator<<(std::ostream& os, const PrintTestStruct&) { return os << "ostream"; } template <typename Sink> friend void AbslStringify(Sink& sink, const PrintTestStruct&) { sink.Append("stringify"); } }; TEST(StatusOr, OkPrinting) { absl::StatusOr<PrintTestStruct> print_me = PrintTestStruct{}; std::stringstream stream; stream << print_me; EXPECT_EQ(stream.str(), "ostream"); EXPECT_EQ(absl::StrCat(print_me), "stringify"); } TEST(StatusOr, ErrorPrinting) { absl::StatusOr<PrintTestStruct> print_me = absl::UnknownError("error"); std::stringstream stream; stream << print_me; const auto error_matcher = AllOf(HasSubstr("UNKNOWN"), HasSubstr("error"), AnyOf(AllOf(StartsWith("("), EndsWith(")")), AllOf(StartsWith("["), EndsWith("]")))); EXPECT_THAT(stream.str(), error_matcher); EXPECT_THAT(absl::StrCat(print_me), error_matcher); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/status/statusor.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/status/statusor_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
5485af59-308f-45e1-9106-bff86bd14755
cpp
abseil/abseil-cpp
status_matchers
absl/status/internal/status_matchers.cc
absl/status/status_matchers_test.cc
#include "absl/status/internal/status_matchers.h" #include <ostream> #include <string> #include "gmock/gmock.h" #include "absl/base/config.h" #include "absl/status/status.h" namespace absl_testing { ABSL_NAMESPACE_BEGIN namespace status_internal { void StatusIsMatcherCommonImpl::DescribeTo(std::ostream* os) const { *os << ", has a status code that "; code_matcher_.DescribeTo(os); *os << ", and has an error message that "; message_matcher_.DescribeTo(os); } void StatusIsMatcherCommonImpl::DescribeNegationTo(std::ostream* os) const { *os << ", or has a status code that "; code_matcher_.DescribeNegationTo(os); *os << ", or has an error message that "; message_matcher_.DescribeNegationTo(os); } bool StatusIsMatcherCommonImpl::MatchAndExplain( const ::absl::Status& status, ::testing::MatchResultListener* result_listener) const { ::testing::StringMatchResultListener inner_listener; if (!code_matcher_.MatchAndExplain(status.code(), &inner_listener)) { *result_listener << (inner_listener.str().empty() ? "whose status code is wrong" : "which has a status code " + inner_listener.str()); return false; } if (!message_matcher_.Matches(std::string(status.message()))) { *result_listener << "whose error message is wrong"; return false; } return true; } } ABSL_NAMESPACE_END }
#include "absl/status/status_matchers.h" #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/string_view.h" namespace { using ::absl_testing::IsOk; using ::absl_testing::IsOkAndHolds; using ::absl_testing::StatusIs; using ::testing::Gt; TEST(StatusMatcherTest, StatusIsOk) { EXPECT_THAT(absl::OkStatus(), IsOk()); } TEST(StatusMatcherTest, StatusOrIsOk) { absl::StatusOr<int> ok_int = {0}; EXPECT_THAT(ok_int, IsOk()); } TEST(StatusMatcherTest, StatusIsNotOk) { absl::Status error = absl::UnknownError("Smigla"); EXPECT_NONFATAL_FAILURE(EXPECT_THAT(error, IsOk()), "Smigla"); } TEST(StatusMatcherTest, StatusOrIsNotOk) { absl::StatusOr<int> error = absl::UnknownError("Smigla"); EXPECT_NONFATAL_FAILURE(EXPECT_THAT(error, IsOk()), "Smigla"); } TEST(StatusMatcherTest, IsOkAndHolds) { absl::StatusOr<int> ok_int = {4}; absl::StatusOr<absl::string_view> ok_str = {"text"}; EXPECT_THAT(ok_int, IsOkAndHolds(4)); EXPECT_THAT(ok_int, IsOkAndHolds(Gt(0))); EXPECT_THAT(ok_str, IsOkAndHolds("text")); } TEST(StatusMatcherTest, IsOkAndHoldsFailure) { absl::StatusOr<int> ok_int = {502}; absl::StatusOr<int> error = absl::UnknownError("Smigla"); absl::StatusOr<absl::string_view> ok_str = {"actual"}; EXPECT_NONFATAL_FAILURE(EXPECT_THAT(ok_int, IsOkAndHolds(0)), "502"); EXPECT_NONFATAL_FAILURE(EXPECT_THAT(error, IsOkAndHolds(0)), "Smigla"); EXPECT_NONFATAL_FAILURE(EXPECT_THAT(ok_str, IsOkAndHolds("expected")), "actual"); } TEST(StatusMatcherTest, StatusIs) { absl::Status unknown = absl::UnknownError("unbekannt"); absl::Status invalid = absl::InvalidArgumentError("ungueltig"); EXPECT_THAT(absl::OkStatus(), StatusIs(absl::StatusCode::kOk)); EXPECT_THAT(absl::OkStatus(), StatusIs(0)); EXPECT_THAT(unknown, StatusIs(absl::StatusCode::kUnknown)); EXPECT_THAT(unknown, StatusIs(2)); EXPECT_THAT(unknown, StatusIs(absl::StatusCode::kUnknown, "unbekannt")); EXPECT_THAT(invalid, StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(invalid, StatusIs(3)); EXPECT_THAT(invalid, StatusIs(absl::StatusCode::kInvalidArgument, "ungueltig")); } TEST(StatusMatcherTest, StatusOrIs) { absl::StatusOr<int> ok = {42}; absl::StatusOr<int> unknown = absl::UnknownError("unbekannt"); absl::StatusOr<absl::string_view> invalid = absl::InvalidArgumentError("ungueltig"); EXPECT_THAT(ok, StatusIs(absl::StatusCode::kOk)); EXPECT_THAT(ok, StatusIs(0)); EXPECT_THAT(unknown, StatusIs(absl::StatusCode::kUnknown)); EXPECT_THAT(unknown, StatusIs(2)); EXPECT_THAT(unknown, StatusIs(absl::StatusCode::kUnknown, "unbekannt")); EXPECT_THAT(invalid, StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(invalid, StatusIs(3)); EXPECT_THAT(invalid, StatusIs(absl::StatusCode::kInvalidArgument, "ungueltig")); } TEST(StatusMatcherTest, StatusIsFailure) { absl::Status unknown = absl::UnknownError("unbekannt"); absl::Status invalid = absl::InvalidArgumentError("ungueltig"); EXPECT_NONFATAL_FAILURE( EXPECT_THAT(absl::OkStatus(), StatusIs(absl::StatusCode::kInvalidArgument)), "OK"); EXPECT_NONFATAL_FAILURE( EXPECT_THAT(unknown, StatusIs(absl::StatusCode::kCancelled)), "UNKNOWN"); EXPECT_NONFATAL_FAILURE( EXPECT_THAT(unknown, StatusIs(absl::StatusCode::kUnknown, "inconnu")), "unbekannt"); EXPECT_NONFATAL_FAILURE( EXPECT_THAT(invalid, StatusIs(absl::StatusCode::kOutOfRange)), "INVALID"); EXPECT_NONFATAL_FAILURE( EXPECT_THAT(invalid, StatusIs(absl::StatusCode::kInvalidArgument, "invalide")), "ungueltig"); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/status/internal/status_matchers.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/status/status_matchers_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
dadf7064-62b2-4cb3-8bb2-f22ef4f9c855
cpp
abseil/abseil-cpp
clock
absl/time/clock.cc
absl/time/clock_test.cc
#include "absl/time/clock.h" #include "absl/base/attributes.h" #include "absl/base/optimization.h" #ifdef _WIN32 #include <windows.h> #endif #include <algorithm> #include <atomic> #include <cerrno> #include <cstdint> #include <ctime> #include <limits> #include "absl/base/internal/spinlock.h" #include "absl/base/internal/unscaledcycleclock.h" #include "absl/base/macros.h" #include "absl/base/port.h" #include "absl/base/thread_annotations.h" namespace absl { ABSL_NAMESPACE_BEGIN Time Now() { int64_t n = absl::GetCurrentTimeNanos(); if (n >= 0) { return time_internal::FromUnixDuration( time_internal::MakeDuration(n / 1000000000, n % 1000000000 * 4)); } return time_internal::FromUnixDuration(absl::Nanoseconds(n)); } ABSL_NAMESPACE_END } #ifndef ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS #define ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS 0 #endif #if defined(__APPLE__) || defined(_WIN32) #include "absl/time/internal/get_current_time_chrono.inc" #else #include "absl/time/internal/get_current_time_posix.inc" #endif #ifndef GET_CURRENT_TIME_NANOS_FROM_SYSTEM #define GET_CURRENT_TIME_NANOS_FROM_SYSTEM() \ ::absl::time_internal::GetCurrentTimeNanosFromSystem() #endif #if !ABSL_USE_CYCLECLOCK_FOR_GET_CURRENT_TIME_NANOS namespace absl { ABSL_NAMESPACE_BEGIN int64_t GetCurrentTimeNanos() { return GET_CURRENT_TIME_NANOS_FROM_SYSTEM(); } ABSL_NAMESPACE_END } #else #ifndef GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW #define GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW() \ ::absl::time_internal::UnscaledCycleClockWrapperForGetCurrentTime::Now() #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace time_internal { #if !defined(NDEBUG) && defined(__x86_64__) constexpr int64_t kCycleClockNowMask = ~int64_t{0xff}; #else constexpr int64_t kCycleClockNowMask = ~int64_t{0}; #endif class UnscaledCycleClockWrapperForGetCurrentTime { public: static int64_t Now() { return base_internal::UnscaledCycleClock::Now() & kCycleClockNowMask; } }; } static inline uint64_t SeqAcquire(std::atomic<uint64_t> *seq) { uint64_t x = seq->fetch_add(1, std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_release); return x + 2; } static inline void SeqRelease(std::atomic<uint64_t> *seq, uint64_t x) { seq->store(x, std::memory_order_release); } enum { kScale = 30 }; static const uint64_t kMinNSBetweenSamples = 2000 << 20; static_assert(((kMinNSBetweenSamples << (kScale + 1)) >> (kScale + 1)) == kMinNSBetweenSamples, "cannot represent kMaxBetweenSamplesNSScaled"); struct TimeSampleAtomic { std::atomic<uint64_t> raw_ns{0}; std::atomic<uint64_t> base_ns{0}; std::atomic<uint64_t> base_cycles{0}; std::atomic<uint64_t> nsscaled_per_cycle{0}; std::atomic<uint64_t> min_cycles_per_sample{0}; }; struct TimeSample { uint64_t raw_ns = 0; uint64_t base_ns = 0; uint64_t base_cycles = 0; uint64_t nsscaled_per_cycle = 0; uint64_t min_cycles_per_sample = 0; }; struct ABSL_CACHELINE_ALIGNED TimeState { std::atomic<uint64_t> seq{0}; TimeSampleAtomic last_sample; int64_t stats_initializations{0}; int64_t stats_reinitializations{0}; int64_t stats_calibrations{0}; int64_t stats_slow_paths{0}; int64_t stats_fast_slow_paths{0}; uint64_t last_now_cycles ABSL_GUARDED_BY(lock){0}; std::atomic<uint64_t> approx_syscall_time_in_cycles{10 * 1000}; std::atomic<uint32_t> kernel_time_seen_smaller{0}; absl::base_internal::SpinLock lock{absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY}; }; ABSL_CONST_INIT static TimeState time_state; static int64_t GetCurrentTimeNanosFromKernel(uint64_t last_cycleclock, uint64_t *cycleclock) ABSL_EXCLUSIVE_LOCKS_REQUIRED(time_state.lock) { uint64_t local_approx_syscall_time_in_cycles = time_state.approx_syscall_time_in_cycles.load(std::memory_order_relaxed); int64_t current_time_nanos_from_system; uint64_t before_cycles; uint64_t after_cycles; uint64_t elapsed_cycles; int loops = 0; do { before_cycles = static_cast<uint64_t>(GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW()); current_time_nanos_from_system = GET_CURRENT_TIME_NANOS_FROM_SYSTEM(); after_cycles = static_cast<uint64_t>(GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW()); elapsed_cycles = after_cycles - before_cycles; if (elapsed_cycles >= local_approx_syscall_time_in_cycles && ++loops == 20) { loops = 0; if (local_approx_syscall_time_in_cycles < 1000 * 1000) { local_approx_syscall_time_in_cycles = (local_approx_syscall_time_in_cycles + 1) << 1; } time_state.approx_syscall_time_in_cycles.store( local_approx_syscall_time_in_cycles, std::memory_order_relaxed); } } while (elapsed_cycles >= local_approx_syscall_time_in_cycles || last_cycleclock - after_cycles < (static_cast<uint64_t>(1) << 16)); if ((local_approx_syscall_time_in_cycles >> 1) < elapsed_cycles) { time_state.kernel_time_seen_smaller.store(0, std::memory_order_relaxed); } else if (time_state.kernel_time_seen_smaller.fetch_add( 1, std::memory_order_relaxed) >= 3) { const uint64_t new_approximation = local_approx_syscall_time_in_cycles - (local_approx_syscall_time_in_cycles >> 3); time_state.approx_syscall_time_in_cycles.store(new_approximation, std::memory_order_relaxed); time_state.kernel_time_seen_smaller.store(0, std::memory_order_relaxed); } *cycleclock = after_cycles; return current_time_nanos_from_system; } static int64_t GetCurrentTimeNanosSlowPath() ABSL_ATTRIBUTE_COLD; static void ReadTimeSampleAtomic(const struct TimeSampleAtomic *atomic, struct TimeSample *sample) { sample->base_ns = atomic->base_ns.load(std::memory_order_relaxed); sample->base_cycles = atomic->base_cycles.load(std::memory_order_relaxed); sample->nsscaled_per_cycle = atomic->nsscaled_per_cycle.load(std::memory_order_relaxed); sample->min_cycles_per_sample = atomic->min_cycles_per_sample.load(std::memory_order_relaxed); sample->raw_ns = atomic->raw_ns.load(std::memory_order_relaxed); } int64_t GetCurrentTimeNanos() { uint64_t base_ns; uint64_t base_cycles; uint64_t nsscaled_per_cycle; uint64_t min_cycles_per_sample; uint64_t seq_read0; uint64_t seq_read1; uint64_t now_cycles = static_cast<uint64_t>(GET_CURRENT_TIME_NANOS_CYCLECLOCK_NOW()); seq_read0 = time_state.seq.load(std::memory_order_acquire); base_ns = time_state.last_sample.base_ns.load(std::memory_order_relaxed); base_cycles = time_state.last_sample.base_cycles.load(std::memory_order_relaxed); nsscaled_per_cycle = time_state.last_sample.nsscaled_per_cycle.load(std::memory_order_relaxed); min_cycles_per_sample = time_state.last_sample.min_cycles_per_sample.load( std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_acquire); seq_read1 = time_state.seq.load(std::memory_order_relaxed); uint64_t delta_cycles; if (seq_read0 == seq_read1 && (seq_read0 & 1) == 0 && (delta_cycles = now_cycles - base_cycles) < min_cycles_per_sample) { return static_cast<int64_t>( base_ns + ((delta_cycles * nsscaled_per_cycle) >> kScale)); } return GetCurrentTimeNanosSlowPath(); } static uint64_t SafeDivideAndScale(uint64_t a, uint64_t b) { int safe_shift = kScale; while (((a << safe_shift) >> safe_shift) != a) { safe_shift--; } uint64_t scaled_b = b >> (kScale - safe_shift); uint64_t quotient = 0; if (scaled_b != 0) { quotient = (a << safe_shift) / scaled_b; } return quotient; } static uint64_t UpdateLastSample( uint64_t now_cycles, uint64_t now_ns, uint64_t delta_cycles, const struct TimeSample *sample) ABSL_ATTRIBUTE_COLD; ABSL_ATTRIBUTE_NOINLINE static int64_t GetCurrentTimeNanosSlowPath() ABSL_LOCKS_EXCLUDED(time_state.lock) { time_state.lock.Lock(); uint64_t now_cycles; uint64_t now_ns = static_cast<uint64_t>( GetCurrentTimeNanosFromKernel(time_state.last_now_cycles, &now_cycles)); time_state.last_now_cycles = now_cycles; uint64_t estimated_base_ns; struct TimeSample sample; ReadTimeSampleAtomic(&time_state.last_sample, &sample); uint64_t delta_cycles = now_cycles - sample.base_cycles; if (delta_cycles < sample.min_cycles_per_sample) { estimated_base_ns = sample.base_ns + ((delta_cycles * sample.nsscaled_per_cycle) >> kScale); time_state.stats_fast_slow_paths++; } else { estimated_base_ns = UpdateLastSample(now_cycles, now_ns, delta_cycles, &sample); } time_state.lock.Unlock(); return static_cast<int64_t>(estimated_base_ns); } static uint64_t UpdateLastSample(uint64_t now_cycles, uint64_t now_ns, uint64_t delta_cycles, const struct TimeSample *sample) ABSL_EXCLUSIVE_LOCKS_REQUIRED(time_state.lock) { uint64_t estimated_base_ns = now_ns; uint64_t lock_value = SeqAcquire(&time_state.seq); if (sample->raw_ns == 0 || sample->raw_ns + static_cast<uint64_t>(5) * 1000 * 1000 * 1000 < now_ns || now_ns < sample->raw_ns || now_cycles < sample->base_cycles) { time_state.last_sample.raw_ns.store(now_ns, std::memory_order_relaxed); time_state.last_sample.base_ns.store(estimated_base_ns, std::memory_order_relaxed); time_state.last_sample.base_cycles.store(now_cycles, std::memory_order_relaxed); time_state.last_sample.nsscaled_per_cycle.store(0, std::memory_order_relaxed); time_state.last_sample.min_cycles_per_sample.store( 0, std::memory_order_relaxed); time_state.stats_initializations++; } else if (sample->raw_ns + 500 * 1000 * 1000 < now_ns && sample->base_cycles + 50 < now_cycles) { if (sample->nsscaled_per_cycle != 0) { uint64_t estimated_scaled_ns; int s = -1; do { s++; estimated_scaled_ns = (delta_cycles >> s) * sample->nsscaled_per_cycle; } while (estimated_scaled_ns / sample->nsscaled_per_cycle != (delta_cycles >> s)); estimated_base_ns = sample->base_ns + (estimated_scaled_ns >> (kScale - s)); } uint64_t ns = now_ns - sample->raw_ns; uint64_t measured_nsscaled_per_cycle = SafeDivideAndScale(ns, delta_cycles); uint64_t assumed_next_sample_delta_cycles = SafeDivideAndScale(kMinNSBetweenSamples, measured_nsscaled_per_cycle); int64_t diff_ns = static_cast<int64_t>(now_ns - estimated_base_ns); ns = static_cast<uint64_t>(static_cast<int64_t>(kMinNSBetweenSamples) + diff_ns - (diff_ns / 16)); uint64_t new_nsscaled_per_cycle = SafeDivideAndScale(ns, assumed_next_sample_delta_cycles); if (new_nsscaled_per_cycle != 0 && diff_ns < 100 * 1000 * 1000 && -diff_ns < 100 * 1000 * 1000) { time_state.last_sample.nsscaled_per_cycle.store( new_nsscaled_per_cycle, std::memory_order_relaxed); uint64_t new_min_cycles_per_sample = SafeDivideAndScale(kMinNSBetweenSamples, new_nsscaled_per_cycle); time_state.last_sample.min_cycles_per_sample.store( new_min_cycles_per_sample, std::memory_order_relaxed); time_state.stats_calibrations++; } else { time_state.last_sample.nsscaled_per_cycle.store( 0, std::memory_order_relaxed); time_state.last_sample.min_cycles_per_sample.store( 0, std::memory_order_relaxed); estimated_base_ns = now_ns; time_state.stats_reinitializations++; } time_state.last_sample.raw_ns.store(now_ns, std::memory_order_relaxed); time_state.last_sample.base_ns.store(estimated_base_ns, std::memory_order_relaxed); time_state.last_sample.base_cycles.store(now_cycles, std::memory_order_relaxed); } else { time_state.stats_slow_paths++; } SeqRelease(&time_state.seq, lock_value); return estimated_base_ns; } ABSL_NAMESPACE_END } #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace { constexpr absl::Duration MaxSleep() { #ifdef _WIN32 return absl::Milliseconds( std::numeric_limits<unsigned long>::max()); #else return absl::Seconds(std::numeric_limits<time_t>::max()); #endif } void SleepOnce(absl::Duration to_sleep) { #ifdef _WIN32 Sleep(static_cast<DWORD>(to_sleep / absl::Milliseconds(1))); #else struct timespec sleep_time = absl::ToTimespec(to_sleep); while (nanosleep(&sleep_time, &sleep_time) != 0 && errno == EINTR) { } #endif } } ABSL_NAMESPACE_END } extern "C" { ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalSleepFor)( absl::Duration duration) { while (duration > absl::ZeroDuration()) { absl::Duration to_sleep = std::min(duration, absl::MaxSleep()); absl::SleepOnce(to_sleep); duration -= to_sleep; } } }
#include "absl/time/clock.h" #include "absl/base/config.h" #if defined(ABSL_HAVE_ALARM) #include <signal.h> #include <unistd.h> #ifdef _AIX typedef void (*sig_t)(int); #endif #elif defined(__linux__) || defined(__APPLE__) #error all known Linux and Apple targets have alarm #endif #include "gtest/gtest.h" #include "absl/time/time.h" namespace { TEST(Time, Now) { const absl::Time before = absl::FromUnixNanos(absl::GetCurrentTimeNanos()); const absl::Time now = absl::Now(); const absl::Time after = absl::FromUnixNanos(absl::GetCurrentTimeNanos()); EXPECT_GE(now, before); EXPECT_GE(after, now); } enum class AlarmPolicy { kWithoutAlarm, kWithAlarm }; #if defined(ABSL_HAVE_ALARM) bool alarm_handler_invoked = false; void AlarmHandler(int signo) { ASSERT_EQ(signo, SIGALRM); alarm_handler_invoked = true; } #endif bool SleepForBounded(absl::Duration d, absl::Duration lower_bound, absl::Duration upper_bound, absl::Duration timeout, AlarmPolicy alarm_policy, int* attempts) { const absl::Time deadline = absl::Now() + timeout; while (absl::Now() < deadline) { #if defined(ABSL_HAVE_ALARM) sig_t old_alarm = SIG_DFL; if (alarm_policy == AlarmPolicy::kWithAlarm) { alarm_handler_invoked = false; old_alarm = signal(SIGALRM, AlarmHandler); alarm(absl::ToInt64Seconds(d / 2)); } #else EXPECT_EQ(alarm_policy, AlarmPolicy::kWithoutAlarm); #endif ++*attempts; absl::Time start = absl::Now(); absl::SleepFor(d); absl::Duration actual = absl::Now() - start; #if defined(ABSL_HAVE_ALARM) if (alarm_policy == AlarmPolicy::kWithAlarm) { signal(SIGALRM, old_alarm); if (!alarm_handler_invoked) continue; } #endif if (lower_bound <= actual && actual <= upper_bound) { return true; } } return false; } testing::AssertionResult AssertSleepForBounded(absl::Duration d, absl::Duration early, absl::Duration late, absl::Duration timeout, AlarmPolicy alarm_policy) { const absl::Duration lower_bound = d - early; const absl::Duration upper_bound = d + late; int attempts = 0; if (SleepForBounded(d, lower_bound, upper_bound, timeout, alarm_policy, &attempts)) { return testing::AssertionSuccess(); } return testing::AssertionFailure() << "SleepFor(" << d << ") did not return within [" << lower_bound << ":" << upper_bound << "] in " << attempts << " attempt" << (attempts == 1 ? "" : "s") << " over " << timeout << (alarm_policy == AlarmPolicy::kWithAlarm ? " with" : " without") << " an alarm"; } TEST(SleepFor, Bounded) { const absl::Duration d = absl::Milliseconds(2500); const absl::Duration early = absl::Milliseconds(100); const absl::Duration late = absl::Milliseconds(300); const absl::Duration timeout = 48 * d; EXPECT_TRUE(AssertSleepForBounded(d, early, late, timeout, AlarmPolicy::kWithoutAlarm)); #if defined(ABSL_HAVE_ALARM) EXPECT_TRUE(AssertSleepForBounded(d, early, late, timeout, AlarmPolicy::kWithAlarm)); #endif } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/clock.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/clock_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
3a83369d-4ec1-4f1c-9f66-c263384019f4
cpp
abseil/abseil-cpp
duration
absl/time/duration.cc
absl/time/duration_test.cc
#if defined(_MSC_VER) #include <winsock2.h> #endif #include <algorithm> #include <cassert> #include <chrono> #include <cmath> #include <cstdint> #include <cstdlib> #include <cstring> #include <ctime> #include <functional> #include <limits> #include <string> #include "absl/base/attributes.h" #include "absl/base/casts.h" #include "absl/base/config.h" #include "absl/numeric/int128.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { using time_internal::kTicksPerNanosecond; using time_internal::kTicksPerSecond; constexpr int64_t kint64max = std::numeric_limits<int64_t>::max(); constexpr int64_t kint64min = std::numeric_limits<int64_t>::min(); inline bool IsFinite(double d) { if (std::isnan(d)) return false; return d != std::numeric_limits<double>::infinity() && d != -std::numeric_limits<double>::infinity(); } inline bool IsValidDivisor(double d) { if (std::isnan(d)) return false; return d != 0.0; } inline void NormalizeTicks(int64_t* sec, int64_t* ticks) { if (*ticks < 0) { --*sec; *ticks += kTicksPerSecond; } } inline uint128 MakeU128(int64_t a) { uint128 u128 = 0; if (a < 0) { ++u128; ++a; a = -a; } u128 += static_cast<uint64_t>(a); return u128; } inline uint128 MakeU128Ticks(Duration d) { int64_t rep_hi = time_internal::GetRepHi(d); uint32_t rep_lo = time_internal::GetRepLo(d); if (rep_hi < 0) { ++rep_hi; rep_hi = -rep_hi; rep_lo = kTicksPerSecond - rep_lo; } uint128 u128 = static_cast<uint64_t>(rep_hi); u128 *= static_cast<uint64_t>(kTicksPerSecond); u128 += rep_lo; return u128; } inline Duration MakeDurationFromU128(uint128 u128, bool is_neg) { int64_t rep_hi; uint32_t rep_lo; const uint64_t h64 = Uint128High64(u128); const uint64_t l64 = Uint128Low64(u128); if (h64 == 0) { const uint64_t hi = l64 / kTicksPerSecond; rep_hi = static_cast<int64_t>(hi); rep_lo = static_cast<uint32_t>(l64 - hi * kTicksPerSecond); } else { const uint64_t kMaxRepHi64 = 0x77359400UL; if (h64 >= kMaxRepHi64) { if (is_neg && h64 == kMaxRepHi64 && l64 == 0) { return time_internal::MakeDuration(kint64min); } return is_neg ? -InfiniteDuration() : InfiniteDuration(); } const uint128 kTicksPerSecond128 = static_cast<uint64_t>(kTicksPerSecond); const uint128 hi = u128 / kTicksPerSecond128; rep_hi = static_cast<int64_t>(Uint128Low64(hi)); rep_lo = static_cast<uint32_t>(Uint128Low64(u128 - hi * kTicksPerSecond128)); } if (is_neg) { rep_hi = -rep_hi; if (rep_lo != 0) { --rep_hi; rep_lo = kTicksPerSecond - rep_lo; } } return time_internal::MakeDuration(rep_hi, rep_lo); } inline uint64_t EncodeTwosComp(int64_t v) { return absl::bit_cast<uint64_t>(v); } inline int64_t DecodeTwosComp(uint64_t v) { return absl::bit_cast<int64_t>(v); } inline bool SafeAddRepHi(double a_hi, double b_hi, Duration* d) { double c = a_hi + b_hi; if (c >= static_cast<double>(kint64max)) { *d = InfiniteDuration(); return false; } if (c <= static_cast<double>(kint64min)) { *d = -InfiniteDuration(); return false; } *d = time_internal::MakeDuration(c, time_internal::GetRepLo(*d)); return true; } template <typename Ignored> struct SafeMultiply { uint128 operator()(uint128 a, uint128 b) const { assert(Uint128High64(b) == 0); if (Uint128High64(a) == 0) { return (((Uint128Low64(a) | Uint128Low64(b)) >> 32) == 0) ? static_cast<uint128>(Uint128Low64(a) * Uint128Low64(b)) : a * b; } return b == 0 ? b : (a > Uint128Max() / b) ? Uint128Max() : a * b; } }; template <template <typename> class Operation> inline Duration ScaleFixed(Duration d, int64_t r) { const uint128 a = MakeU128Ticks(d); const uint128 b = MakeU128(r); const uint128 q = Operation<uint128>()(a, b); const bool is_neg = (time_internal::GetRepHi(d) < 0) != (r < 0); return MakeDurationFromU128(q, is_neg); } template <template <typename> class Operation> inline Duration ScaleDouble(Duration d, double r) { Operation<double> op; double hi_doub = op(time_internal::GetRepHi(d), r); double lo_doub = op(time_internal::GetRepLo(d), r); double hi_int = 0; double hi_frac = std::modf(hi_doub, &hi_int); lo_doub /= kTicksPerSecond; lo_doub += hi_frac; double lo_int = 0; double lo_frac = std::modf(lo_doub, &lo_int); int64_t lo64 = std::round(lo_frac * kTicksPerSecond); Duration ans; if (!SafeAddRepHi(hi_int, lo_int, &ans)) return ans; int64_t hi64 = time_internal::GetRepHi(ans); if (!SafeAddRepHi(hi64, lo64 / kTicksPerSecond, &ans)) return ans; hi64 = time_internal::GetRepHi(ans); lo64 %= kTicksPerSecond; NormalizeTicks(&hi64, &lo64); return time_internal::MakeDuration(hi64, lo64); } inline bool IDivFastPath(const Duration num, const Duration den, int64_t* q, Duration* rem) { if (time_internal::IsInfiniteDuration(num) || time_internal::IsInfiniteDuration(den)) return false; int64_t num_hi = time_internal::GetRepHi(num); uint32_t num_lo = time_internal::GetRepLo(num); int64_t den_hi = time_internal::GetRepHi(den); uint32_t den_lo = time_internal::GetRepLo(den); if (den_hi == 0) { if (den_lo == kTicksPerNanosecond) { if (num_hi >= 0 && num_hi < (kint64max - kTicksPerSecond) / 1000000000) { *q = num_hi * 1000000000 + num_lo / kTicksPerNanosecond; *rem = time_internal::MakeDuration(0, num_lo % den_lo); return true; } } else if (den_lo == 100 * kTicksPerNanosecond) { if (num_hi >= 0 && num_hi < (kint64max - kTicksPerSecond) / 10000000) { *q = num_hi * 10000000 + num_lo / (100 * kTicksPerNanosecond); *rem = time_internal::MakeDuration(0, num_lo % den_lo); return true; } } else if (den_lo == 1000 * kTicksPerNanosecond) { if (num_hi >= 0 && num_hi < (kint64max - kTicksPerSecond) / 1000000) { *q = num_hi * 1000000 + num_lo / (1000 * kTicksPerNanosecond); *rem = time_internal::MakeDuration(0, num_lo % den_lo); return true; } } else if (den_lo == 1000000 * kTicksPerNanosecond) { if (num_hi >= 0 && num_hi < (kint64max - kTicksPerSecond) / 1000) { *q = num_hi * 1000 + num_lo / (1000000 * kTicksPerNanosecond); *rem = time_internal::MakeDuration(0, num_lo % den_lo); return true; } } } else if (den_hi > 0 && den_lo == 0) { if (num_hi >= 0) { if (den_hi == 1) { *q = num_hi; *rem = time_internal::MakeDuration(0, num_lo); return true; } *q = num_hi / den_hi; *rem = time_internal::MakeDuration(num_hi % den_hi, num_lo); return true; } if (num_lo != 0) { num_hi += 1; } int64_t quotient = num_hi / den_hi; int64_t rem_sec = num_hi % den_hi; if (rem_sec > 0) { rem_sec -= den_hi; quotient += 1; } if (num_lo != 0) { rem_sec -= 1; } *q = quotient; *rem = time_internal::MakeDuration(rem_sec, num_lo); return true; } return false; } } namespace { int64_t IDivSlowPath(bool satq, const Duration num, const Duration den, Duration* rem) { const bool num_neg = num < ZeroDuration(); const bool den_neg = den < ZeroDuration(); const bool quotient_neg = num_neg != den_neg; if (time_internal::IsInfiniteDuration(num) || den == ZeroDuration()) { *rem = num_neg ? -InfiniteDuration() : InfiniteDuration(); return quotient_neg ? kint64min : kint64max; } if (time_internal::IsInfiniteDuration(den)) { *rem = num; return 0; } const uint128 a = MakeU128Ticks(num); const uint128 b = MakeU128Ticks(den); uint128 quotient128 = a / b; if (satq) { if (quotient128 > uint128(static_cast<uint64_t>(kint64max))) { quotient128 = quotient_neg ? uint128(static_cast<uint64_t>(kint64min)) : uint128(static_cast<uint64_t>(kint64max)); } } const uint128 remainder128 = a - quotient128 * b; *rem = MakeDurationFromU128(remainder128, num_neg); if (!quotient_neg || quotient128 == 0) { return Uint128Low64(quotient128) & kint64max; } return -static_cast<int64_t>(Uint128Low64(quotient128 - 1) & kint64max) - 1; } ABSL_ATTRIBUTE_ALWAYS_INLINE inline int64_t IDivDurationImpl(bool satq, const Duration num, const Duration den, Duration* rem) { int64_t q = 0; if (IDivFastPath(num, den, &q, rem)) { return q; } return IDivSlowPath(satq, num, den, rem); } } int64_t IDivDuration(Duration num, Duration den, Duration* rem) { return IDivDurationImpl(true, num, den, rem); } Duration& Duration::operator+=(Duration rhs) { if (time_internal::IsInfiniteDuration(*this)) return *this; if (time_internal::IsInfiniteDuration(rhs)) return *this = rhs; const int64_t orig_rep_hi = rep_hi_.Get(); rep_hi_ = DecodeTwosComp(EncodeTwosComp(rep_hi_.Get()) + EncodeTwosComp(rhs.rep_hi_.Get())); if (rep_lo_ >= kTicksPerSecond - rhs.rep_lo_) { rep_hi_ = DecodeTwosComp(EncodeTwosComp(rep_hi_.Get()) + 1); rep_lo_ -= kTicksPerSecond; } rep_lo_ += rhs.rep_lo_; if (rhs.rep_hi_.Get() < 0 ? rep_hi_.Get() > orig_rep_hi : rep_hi_.Get() < orig_rep_hi) { return *this = rhs.rep_hi_.Get() < 0 ? -InfiniteDuration() : InfiniteDuration(); } return *this; } Duration& Duration::operator-=(Duration rhs) { if (time_internal::IsInfiniteDuration(*this)) return *this; if (time_internal::IsInfiniteDuration(rhs)) { return *this = rhs.rep_hi_.Get() >= 0 ? -InfiniteDuration() : InfiniteDuration(); } const int64_t orig_rep_hi = rep_hi_.Get(); rep_hi_ = DecodeTwosComp(EncodeTwosComp(rep_hi_.Get()) - EncodeTwosComp(rhs.rep_hi_.Get())); if (rep_lo_ < rhs.rep_lo_) { rep_hi_ = DecodeTwosComp(EncodeTwosComp(rep_hi_.Get()) - 1); rep_lo_ += kTicksPerSecond; } rep_lo_ -= rhs.rep_lo_; if (rhs.rep_hi_.Get() < 0 ? rep_hi_.Get() < orig_rep_hi : rep_hi_.Get() > orig_rep_hi) { return *this = rhs.rep_hi_.Get() >= 0 ? -InfiniteDuration() : InfiniteDuration(); } return *this; } Duration& Duration::operator*=(int64_t r) { if (time_internal::IsInfiniteDuration(*this)) { const bool is_neg = (r < 0) != (rep_hi_.Get() < 0); return *this = is_neg ? -InfiniteDuration() : InfiniteDuration(); } return *this = ScaleFixed<SafeMultiply>(*this, r); } Duration& Duration::operator*=(double r) { if (time_internal::IsInfiniteDuration(*this) || !IsFinite(r)) { const bool is_neg = std::signbit(r) != (rep_hi_.Get() < 0); return *this = is_neg ? -InfiniteDuration() : InfiniteDuration(); } return *this = ScaleDouble<std::multiplies>(*this, r); } Duration& Duration::operator/=(int64_t r) { if (time_internal::IsInfiniteDuration(*this) || r == 0) { const bool is_neg = (r < 0) != (rep_hi_.Get() < 0); return *this = is_neg ? -InfiniteDuration() : InfiniteDuration(); } return *this = ScaleFixed<std::divides>(*this, r); } Duration& Duration::operator/=(double r) { if (time_internal::IsInfiniteDuration(*this) || !IsValidDivisor(r)) { const bool is_neg = std::signbit(r) != (rep_hi_.Get() < 0); return *this = is_neg ? -InfiniteDuration() : InfiniteDuration(); } return *this = ScaleDouble<std::divides>(*this, r); } Duration& Duration::operator%=(Duration rhs) { IDivDurationImpl(false, *this, rhs, this); return *this; } double FDivDuration(Duration num, Duration den) { if (time_internal::IsInfiniteDuration(num) || den == ZeroDuration()) { return (num < ZeroDuration()) == (den < ZeroDuration()) ? std::numeric_limits<double>::infinity() : -std::numeric_limits<double>::infinity(); } if (time_internal::IsInfiniteDuration(den)) return 0.0; double a = static_cast<double>(time_internal::GetRepHi(num)) * kTicksPerSecond + time_internal::GetRepLo(num); double b = static_cast<double>(time_internal::GetRepHi(den)) * kTicksPerSecond + time_internal::GetRepLo(den); return a / b; } Duration Trunc(Duration d, Duration unit) { return d - (d % unit); } Duration Floor(const Duration d, const Duration unit) { const absl::Duration td = Trunc(d, unit); return td <= d ? td : td - AbsDuration(unit); } Duration Ceil(const Duration d, const Duration unit) { const absl::Duration td = Trunc(d, unit); return td >= d ? td : td + AbsDuration(unit); } Duration DurationFromTimespec(timespec ts) { if (static_cast<uint64_t>(ts.tv_nsec) < 1000 * 1000 * 1000) { int64_t ticks = ts.tv_nsec * kTicksPerNanosecond; return time_internal::MakeDuration(ts.tv_sec, ticks); } return Seconds(ts.tv_sec) + Nanoseconds(ts.tv_nsec); } Duration DurationFromTimeval(timeval tv) { if (static_cast<uint64_t>(tv.tv_usec) < 1000 * 1000) { int64_t ticks = tv.tv_usec * 1000 * kTicksPerNanosecond; return time_internal::MakeDuration(tv.tv_sec, ticks); } return Seconds(tv.tv_sec) + Microseconds(tv.tv_usec); } int64_t ToInt64Nanoseconds(Duration d) { if (time_internal::GetRepHi(d) >= 0 && time_internal::GetRepHi(d) >> 33 == 0) { return (time_internal::GetRepHi(d) * 1000 * 1000 * 1000) + (time_internal::GetRepLo(d) / kTicksPerNanosecond); } return d / Nanoseconds(1); } int64_t ToInt64Microseconds(Duration d) { if (time_internal::GetRepHi(d) >= 0 && time_internal::GetRepHi(d) >> 43 == 0) { return (time_internal::GetRepHi(d) * 1000 * 1000) + (time_internal::GetRepLo(d) / (kTicksPerNanosecond * 1000)); } return d / Microseconds(1); } int64_t ToInt64Milliseconds(Duration d) { if (time_internal::GetRepHi(d) >= 0 && time_internal::GetRepHi(d) >> 53 == 0) { return (time_internal::GetRepHi(d) * 1000) + (time_internal::GetRepLo(d) / (kTicksPerNanosecond * 1000 * 1000)); } return d / Milliseconds(1); } int64_t ToInt64Seconds(Duration d) { int64_t hi = time_internal::GetRepHi(d); if (time_internal::IsInfiniteDuration(d)) return hi; if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi; return hi; } int64_t ToInt64Minutes(Duration d) { int64_t hi = time_internal::GetRepHi(d); if (time_internal::IsInfiniteDuration(d)) return hi; if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi; return hi / 60; } int64_t ToInt64Hours(Duration d) { int64_t hi = time_internal::GetRepHi(d); if (time_internal::IsInfiniteDuration(d)) return hi; if (hi < 0 && time_internal::GetRepLo(d) != 0) ++hi; return hi / (60 * 60); } double ToDoubleNanoseconds(Duration d) { return FDivDuration(d, Nanoseconds(1)); } double ToDoubleMicroseconds(Duration d) { return FDivDuration(d, Microseconds(1)); } double ToDoubleMilliseconds(Duration d) { return FDivDuration(d, Milliseconds(1)); } double ToDoubleSeconds(Duration d) { return FDivDuration(d, Seconds(1)); } double ToDoubleMinutes(Duration d) { return FDivDuration(d, Minutes(1)); } double ToDoubleHours(Duration d) { return FDivDuration(d, Hours(1)); } timespec ToTimespec(Duration d) { timespec ts; if (!time_internal::IsInfiniteDuration(d)) { int64_t rep_hi = time_internal::GetRepHi(d); uint32_t rep_lo = time_internal::GetRepLo(d); if (rep_hi < 0) { rep_lo += kTicksPerNanosecond - 1; if (rep_lo >= kTicksPerSecond) { rep_hi += 1; rep_lo -= kTicksPerSecond; } } ts.tv_sec = static_cast<decltype(ts.tv_sec)>(rep_hi); if (ts.tv_sec == rep_hi) { ts.tv_nsec = rep_lo / kTicksPerNanosecond; return ts; } } if (d >= ZeroDuration()) { ts.tv_sec = std::numeric_limits<time_t>::max(); ts.tv_nsec = 1000 * 1000 * 1000 - 1; } else { ts.tv_sec = std::numeric_limits<time_t>::min(); ts.tv_nsec = 0; } return ts; } timeval ToTimeval(Duration d) { timeval tv; timespec ts = ToTimespec(d); if (ts.tv_sec < 0) { ts.tv_nsec += 1000 - 1; if (ts.tv_nsec >= 1000 * 1000 * 1000) { ts.tv_sec += 1; ts.tv_nsec -= 1000 * 1000 * 1000; } } tv.tv_sec = static_cast<decltype(tv.tv_sec)>(ts.tv_sec); if (tv.tv_sec != ts.tv_sec) { if (ts.tv_sec < 0) { tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::min(); tv.tv_usec = 0; } else { tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::max(); tv.tv_usec = 1000 * 1000 - 1; } return tv; } tv.tv_usec = static_cast<int>(ts.tv_nsec / 1000); return tv; } std::chrono::nanoseconds ToChronoNanoseconds(Duration d) { return time_internal::ToChronoDuration<std::chrono::nanoseconds>(d); } std::chrono::microseconds ToChronoMicroseconds(Duration d) { return time_internal::ToChronoDuration<std::chrono::microseconds>(d); } std::chrono::milliseconds ToChronoMilliseconds(Duration d) { return time_internal::ToChronoDuration<std::chrono::milliseconds>(d); } std::chrono::seconds ToChronoSeconds(Duration d) { return time_internal::ToChronoDuration<std::chrono::seconds>(d); } std::chrono::minutes ToChronoMinutes(Duration d) { return time_internal::ToChronoDuration<std::chrono::minutes>(d); } std::chrono::hours ToChronoHours(Duration d) { return time_internal::ToChronoDuration<std::chrono::hours>(d); } namespace { char* Format64(char* ep, int width, int64_t v) { do { --width; *--ep = static_cast<char>('0' + (v % 10)); } while (v /= 10); while (--width >= 0) *--ep = '0'; return ep; } struct DisplayUnit { absl::string_view abbr; int prec; double pow10; }; constexpr DisplayUnit kDisplayNano = {"ns", 2, 1e2}; constexpr DisplayUnit kDisplayMicro = {"us", 5, 1e5}; constexpr DisplayUnit kDisplayMilli = {"ms", 8, 1e8}; constexpr DisplayUnit kDisplaySec = {"s", 11, 1e11}; constexpr DisplayUnit kDisplayMin = {"m", -1, 0.0}; constexpr DisplayUnit kDisplayHour = {"h", -1, 0.0}; void AppendNumberUnit(std::string* out, int64_t n, DisplayUnit unit) { char buf[sizeof("2562047788015216")]; char* const ep = buf + sizeof(buf); char* bp = Format64(ep, 0, n); if (*bp != '0' || bp + 1 != ep) { out->append(bp, static_cast<size_t>(ep - bp)); out->append(unit.abbr.data(), unit.abbr.size()); } } void AppendNumberUnit(std::string* out, double n, DisplayUnit unit) { constexpr int kBufferSize = std::numeric_limits<double>::digits10; const int prec = std::min(kBufferSize, unit.prec); char buf[kBufferSize]; char* ep = buf + sizeof(buf); double d = 0; int64_t frac_part = std::round(std::modf(n, &d) * unit.pow10); int64_t int_part = d; if (int_part != 0 || frac_part != 0) { char* bp = Format64(ep, 0, int_part); out->append(bp, static_cast<size_t>(ep - bp)); if (frac_part != 0) { out->push_back('.'); bp = Format64(ep, prec, frac_part); while (ep[-1] == '0') --ep; out->append(bp, static_cast<size_t>(ep - bp)); } out->append(unit.abbr.data(), unit.abbr.size()); } } } std::string FormatDuration(Duration d) { constexpr Duration kMinDuration = Seconds(kint64min); std::string s; if (d == kMinDuration) { s = "-2562047788015215h30m8s"; return s; } if (d < ZeroDuration()) { s.append("-"); d = -d; } if (d == InfiniteDuration()) { s.append("inf"); } else if (d < Seconds(1)) { if (d < Microseconds(1)) { AppendNumberUnit(&s, FDivDuration(d, Nanoseconds(1)), kDisplayNano); } else if (d < Milliseconds(1)) { AppendNumberUnit(&s, FDivDuration(d, Microseconds(1)), kDisplayMicro); } else { AppendNumberUnit(&s, FDivDuration(d, Milliseconds(1)), kDisplayMilli); } } else { AppendNumberUnit(&s, IDivDuration(d, Hours(1), &d), kDisplayHour); AppendNumberUnit(&s, IDivDuration(d, Minutes(1), &d), kDisplayMin); AppendNumberUnit(&s, FDivDuration(d, Seconds(1)), kDisplaySec); } if (s.empty() || s == "-") { s = "0"; } return s; } namespace { bool ConsumeDurationNumber(const char** dpp, const char* ep, int64_t* int_part, int64_t* frac_part, int64_t* frac_scale) { *int_part = 0; *frac_part = 0; *frac_scale = 1; const char* start = *dpp; for (; *dpp != ep; *dpp += 1) { const int d = **dpp - '0'; if (d < 0 || 10 <= d) break; if (*int_part > kint64max / 10) return false; *int_part *= 10; if (*int_part > kint64max - d) return false; *int_part += d; } const bool int_part_empty = (*dpp == start); if (*dpp == ep || **dpp != '.') return !int_part_empty; for (*dpp += 1; *dpp != ep; *dpp += 1) { const int d = **dpp - '0'; if (d < 0 || 10 <= d) break; if (*frac_scale <= kint64max / 10) { *frac_part *= 10; *frac_part += d; *frac_scale *= 10; } } return !int_part_empty || *frac_scale != 1; } bool ConsumeDurationUnit(const char** start, const char* end, Duration* unit) { size_t size = static_cast<size_t>(end - *start); switch (size) { case 0: return false; default: switch (**start) { case 'n': if (*(*start + 1) == 's') { *start += 2; *unit = Nanoseconds(1); return true; } break; case 'u': if (*(*start + 1) == 's') { *start += 2; *unit = Microseconds(1); return true; } break; case 'm': if (*(*start + 1) == 's') { *start += 2; *unit = Milliseconds(1); return true; } break; default: break; } ABSL_FALLTHROUGH_INTENDED; case 1: switch (**start) { case 's': *unit = Seconds(1); *start += 1; return true; case 'm': *unit = Minutes(1); *start += 1; return true; case 'h': *unit = Hours(1); *start += 1; return true; default: return false; } } } } bool ParseDuration(absl::string_view dur_sv, Duration* d) { int sign = 1; if (absl::ConsumePrefix(&dur_sv, "-")) { sign = -1; } else { absl::ConsumePrefix(&dur_sv, "+"); } if (dur_sv.empty()) return false; if (dur_sv == "0") { *d = ZeroDuration(); return true; } if (dur_sv == "inf") { *d = sign * InfiniteDuration(); return true; } const char* start = dur_sv.data(); const char* end = start + dur_sv.size(); Duration dur; while (start != end) { int64_t int_part; int64_t frac_part; int64_t frac_scale; Duration unit; if (!ConsumeDurationNumber(&start, end, &int_part, &frac_part, &frac_scale) || !ConsumeDurationUnit(&start, end, &unit)) { return false; } if (int_part != 0) dur += sign * int_part * unit; if (frac_part != 0) dur += sign * frac_part * unit / frac_scale; } *d = dur; return true; } bool AbslParseFlag(absl::string_view text, Duration* dst, std::string*) { return ParseDuration(text, dst); } std::string AbslUnparseFlag(Duration d) { return FormatDuration(d); } bool ParseFlag(const std::string& text, Duration* dst, std::string* ) { return ParseDuration(text, dst); } std::string UnparseFlag(Duration d) { return FormatDuration(d); } ABSL_NAMESPACE_END }
#if defined(_MSC_VER) #include <winsock2.h> #endif #include "absl/base/config.h" #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L #include <version> #endif #include <array> #include <cfloat> #include <chrono> #ifdef __cpp_lib_three_way_comparison #include <compare> #endif #include <cmath> #include <cstdint> #include <ctime> #include <iomanip> #include <limits> #include <random> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_format.h" #include "absl/time/time.h" namespace { constexpr int64_t kint64max = std::numeric_limits<int64_t>::max(); constexpr int64_t kint64min = std::numeric_limits<int64_t>::min(); absl::Duration ApproxYears(int64_t n) { return absl::Hours(n) * 365 * 24; } MATCHER_P(TimespecMatcher, ts, "") { if (ts.tv_sec == arg.tv_sec && ts.tv_nsec == arg.tv_nsec) return true; *result_listener << "expected: {" << ts.tv_sec << ", " << ts.tv_nsec << "} "; *result_listener << "actual: {" << arg.tv_sec << ", " << arg.tv_nsec << "}"; return false; } MATCHER_P(TimevalMatcher, tv, "") { if (tv.tv_sec == arg.tv_sec && tv.tv_usec == arg.tv_usec) return true; *result_listener << "expected: {" << tv.tv_sec << ", " << tv.tv_usec << "} "; *result_listener << "actual: {" << arg.tv_sec << ", " << arg.tv_usec << "}"; return false; } TEST(Duration, ConstExpr) { constexpr absl::Duration d0 = absl::ZeroDuration(); static_assert(d0 == absl::ZeroDuration(), "ZeroDuration()"); constexpr absl::Duration d1 = absl::Seconds(1); static_assert(d1 == absl::Seconds(1), "Seconds(1)"); static_assert(d1 != absl::ZeroDuration(), "Seconds(1)"); constexpr absl::Duration d2 = absl::InfiniteDuration(); static_assert(d2 == absl::InfiniteDuration(), "InfiniteDuration()"); static_assert(d2 != absl::ZeroDuration(), "InfiniteDuration()"); } TEST(Duration, ValueSemantics) { constexpr absl::Duration a; constexpr absl::Duration b = a; constexpr absl::Duration c(b); absl::Duration d; d = c; } TEST(Duration, Factories) { constexpr absl::Duration zero = absl::ZeroDuration(); constexpr absl::Duration nano = absl::Nanoseconds(1); constexpr absl::Duration micro = absl::Microseconds(1); constexpr absl::Duration milli = absl::Milliseconds(1); constexpr absl::Duration sec = absl::Seconds(1); constexpr absl::Duration min = absl::Minutes(1); constexpr absl::Duration hour = absl::Hours(1); EXPECT_EQ(zero, absl::Duration()); EXPECT_EQ(zero, absl::Seconds(0)); EXPECT_EQ(nano, absl::Nanoseconds(1)); EXPECT_EQ(micro, absl::Nanoseconds(1000)); EXPECT_EQ(milli, absl::Microseconds(1000)); EXPECT_EQ(sec, absl::Milliseconds(1000)); EXPECT_EQ(min, absl::Seconds(60)); EXPECT_EQ(hour, absl::Minutes(60)); const absl::Duration inf = absl::InfiniteDuration(); EXPECT_GT(inf, absl::Seconds(kint64max)); EXPECT_LT(-inf, absl::Seconds(kint64min)); EXPECT_LT(-inf, absl::Seconds(-kint64max)); EXPECT_EQ(inf, absl::Minutes(kint64max)); EXPECT_EQ(-inf, absl::Minutes(kint64min)); EXPECT_EQ(-inf, absl::Minutes(-kint64max)); EXPECT_GT(inf, absl::Minutes(kint64max / 60)); EXPECT_LT(-inf, absl::Minutes(kint64min / 60)); EXPECT_LT(-inf, absl::Minutes(-kint64max / 60)); EXPECT_EQ(inf, absl::Hours(kint64max)); EXPECT_EQ(-inf, absl::Hours(kint64min)); EXPECT_EQ(-inf, absl::Hours(-kint64max)); EXPECT_GT(inf, absl::Hours(kint64max / 3600)); EXPECT_LT(-inf, absl::Hours(kint64min / 3600)); EXPECT_LT(-inf, absl::Hours(-kint64max / 3600)); } TEST(Duration, ToConversion) { #define TEST_DURATION_CONVERSION(UNIT) \ do { \ const absl::Duration d = absl::UNIT(1.5); \ constexpr absl::Duration z = absl::ZeroDuration(); \ constexpr absl::Duration inf = absl::InfiniteDuration(); \ constexpr double dbl_inf = std::numeric_limits<double>::infinity(); \ EXPECT_EQ(kint64min, absl::ToInt64##UNIT(-inf)); \ EXPECT_EQ(-1, absl::ToInt64##UNIT(-d)); \ EXPECT_EQ(0, absl::ToInt64##UNIT(z)); \ EXPECT_EQ(1, absl::ToInt64##UNIT(d)); \ EXPECT_EQ(kint64max, absl::ToInt64##UNIT(inf)); \ EXPECT_EQ(-dbl_inf, absl::ToDouble##UNIT(-inf)); \ EXPECT_EQ(-1.5, absl::ToDouble##UNIT(-d)); \ EXPECT_EQ(0, absl::ToDouble##UNIT(z)); \ EXPECT_EQ(1.5, absl::ToDouble##UNIT(d)); \ EXPECT_EQ(dbl_inf, absl::ToDouble##UNIT(inf)); \ } while (0) TEST_DURATION_CONVERSION(Nanoseconds); TEST_DURATION_CONVERSION(Microseconds); TEST_DURATION_CONVERSION(Milliseconds); TEST_DURATION_CONVERSION(Seconds); TEST_DURATION_CONVERSION(Minutes); TEST_DURATION_CONVERSION(Hours); #undef TEST_DURATION_CONVERSION } template <int64_t N> void TestToConversion() { constexpr absl::Duration nano = absl::Nanoseconds(N); EXPECT_EQ(N, absl::ToInt64Nanoseconds(nano)); EXPECT_EQ(0, absl::ToInt64Microseconds(nano)); EXPECT_EQ(0, absl::ToInt64Milliseconds(nano)); EXPECT_EQ(0, absl::ToInt64Seconds(nano)); EXPECT_EQ(0, absl::ToInt64Minutes(nano)); EXPECT_EQ(0, absl::ToInt64Hours(nano)); const absl::Duration micro = absl::Microseconds(N); EXPECT_EQ(N * 1000, absl::ToInt64Nanoseconds(micro)); EXPECT_EQ(N, absl::ToInt64Microseconds(micro)); EXPECT_EQ(0, absl::ToInt64Milliseconds(micro)); EXPECT_EQ(0, absl::ToInt64Seconds(micro)); EXPECT_EQ(0, absl::ToInt64Minutes(micro)); EXPECT_EQ(0, absl::ToInt64Hours(micro)); const absl::Duration milli = absl::Milliseconds(N); EXPECT_EQ(N * 1000 * 1000, absl::ToInt64Nanoseconds(milli)); EXPECT_EQ(N * 1000, absl::ToInt64Microseconds(milli)); EXPECT_EQ(N, absl::ToInt64Milliseconds(milli)); EXPECT_EQ(0, absl::ToInt64Seconds(milli)); EXPECT_EQ(0, absl::ToInt64Minutes(milli)); EXPECT_EQ(0, absl::ToInt64Hours(milli)); const absl::Duration sec = absl::Seconds(N); EXPECT_EQ(N * 1000 * 1000 * 1000, absl::ToInt64Nanoseconds(sec)); EXPECT_EQ(N * 1000 * 1000, absl::ToInt64Microseconds(sec)); EXPECT_EQ(N * 1000, absl::ToInt64Milliseconds(sec)); EXPECT_EQ(N, absl::ToInt64Seconds(sec)); EXPECT_EQ(0, absl::ToInt64Minutes(sec)); EXPECT_EQ(0, absl::ToInt64Hours(sec)); const absl::Duration min = absl::Minutes(N); EXPECT_EQ(N * 60 * 1000 * 1000 * 1000, absl::ToInt64Nanoseconds(min)); EXPECT_EQ(N * 60 * 1000 * 1000, absl::ToInt64Microseconds(min)); EXPECT_EQ(N * 60 * 1000, absl::ToInt64Milliseconds(min)); EXPECT_EQ(N * 60, absl::ToInt64Seconds(min)); EXPECT_EQ(N, absl::ToInt64Minutes(min)); EXPECT_EQ(0, absl::ToInt64Hours(min)); const absl::Duration hour = absl::Hours(N); EXPECT_EQ(N * 60 * 60 * 1000 * 1000 * 1000, absl::ToInt64Nanoseconds(hour)); EXPECT_EQ(N * 60 * 60 * 1000 * 1000, absl::ToInt64Microseconds(hour)); EXPECT_EQ(N * 60 * 60 * 1000, absl::ToInt64Milliseconds(hour)); EXPECT_EQ(N * 60 * 60, absl::ToInt64Seconds(hour)); EXPECT_EQ(N * 60, absl::ToInt64Minutes(hour)); EXPECT_EQ(N, absl::ToInt64Hours(hour)); } TEST(Duration, ToConversionDeprecated) { TestToConversion<43>(); TestToConversion<1>(); TestToConversion<0>(); TestToConversion<-1>(); TestToConversion<-43>(); } template <int64_t N> void TestFromChronoBasicEquality() { using std::chrono::nanoseconds; using std::chrono::microseconds; using std::chrono::milliseconds; using std::chrono::seconds; using std::chrono::minutes; using std::chrono::hours; static_assert(absl::Nanoseconds(N) == absl::FromChrono(nanoseconds(N)), ""); static_assert(absl::Microseconds(N) == absl::FromChrono(microseconds(N)), ""); static_assert(absl::Milliseconds(N) == absl::FromChrono(milliseconds(N)), ""); static_assert(absl::Seconds(N) == absl::FromChrono(seconds(N)), ""); static_assert(absl::Minutes(N) == absl::FromChrono(minutes(N)), ""); static_assert(absl::Hours(N) == absl::FromChrono(hours(N)), ""); } TEST(Duration, FromChrono) { TestFromChronoBasicEquality<-123>(); TestFromChronoBasicEquality<-1>(); TestFromChronoBasicEquality<0>(); TestFromChronoBasicEquality<1>(); TestFromChronoBasicEquality<123>(); const auto chrono_minutes_max = std::chrono::minutes::max(); const auto minutes_max = absl::FromChrono(chrono_minutes_max); const int64_t minutes_max_count = chrono_minutes_max.count(); if (minutes_max_count > kint64max / 60) { EXPECT_EQ(absl::InfiniteDuration(), minutes_max); } else { EXPECT_EQ(absl::Minutes(minutes_max_count), minutes_max); } const auto chrono_minutes_min = std::chrono::minutes::min(); const auto minutes_min = absl::FromChrono(chrono_minutes_min); const int64_t minutes_min_count = chrono_minutes_min.count(); if (minutes_min_count < kint64min / 60) { EXPECT_EQ(-absl::InfiniteDuration(), minutes_min); } else { EXPECT_EQ(absl::Minutes(minutes_min_count), minutes_min); } const auto chrono_hours_max = std::chrono::hours::max(); const auto hours_max = absl::FromChrono(chrono_hours_max); const int64_t hours_max_count = chrono_hours_max.count(); if (hours_max_count > kint64max / 3600) { EXPECT_EQ(absl::InfiniteDuration(), hours_max); } else { EXPECT_EQ(absl::Hours(hours_max_count), hours_max); } const auto chrono_hours_min = std::chrono::hours::min(); const auto hours_min = absl::FromChrono(chrono_hours_min); const int64_t hours_min_count = chrono_hours_min.count(); if (hours_min_count < kint64min / 3600) { EXPECT_EQ(-absl::InfiniteDuration(), hours_min); } else { EXPECT_EQ(absl::Hours(hours_min_count), hours_min); } } template <int64_t N> void TestToChrono() { using std::chrono::nanoseconds; using std::chrono::microseconds; using std::chrono::milliseconds; using std::chrono::seconds; using std::chrono::minutes; using std::chrono::hours; EXPECT_EQ(nanoseconds(N), absl::ToChronoNanoseconds(absl::Nanoseconds(N))); EXPECT_EQ(microseconds(N), absl::ToChronoMicroseconds(absl::Microseconds(N))); EXPECT_EQ(milliseconds(N), absl::ToChronoMilliseconds(absl::Milliseconds(N))); EXPECT_EQ(seconds(N), absl::ToChronoSeconds(absl::Seconds(N))); constexpr auto absl_minutes = absl::Minutes(N); auto chrono_minutes = minutes(N); if (absl_minutes == -absl::InfiniteDuration()) { chrono_minutes = minutes::min(); } else if (absl_minutes == absl::InfiniteDuration()) { chrono_minutes = minutes::max(); } EXPECT_EQ(chrono_minutes, absl::ToChronoMinutes(absl_minutes)); constexpr auto absl_hours = absl::Hours(N); auto chrono_hours = hours(N); if (absl_hours == -absl::InfiniteDuration()) { chrono_hours = hours::min(); } else if (absl_hours == absl::InfiniteDuration()) { chrono_hours = hours::max(); } EXPECT_EQ(chrono_hours, absl::ToChronoHours(absl_hours)); } TEST(Duration, ToChrono) { using std::chrono::nanoseconds; using std::chrono::microseconds; using std::chrono::milliseconds; using std::chrono::seconds; using std::chrono::minutes; using std::chrono::hours; TestToChrono<kint64min>(); TestToChrono<-1>(); TestToChrono<0>(); TestToChrono<1>(); TestToChrono<kint64max>(); const auto tick = absl::Nanoseconds(1) / 4; EXPECT_EQ(nanoseconds(0), absl::ToChronoNanoseconds(tick)); EXPECT_EQ(nanoseconds(0), absl::ToChronoNanoseconds(-tick)); EXPECT_EQ(microseconds(0), absl::ToChronoMicroseconds(tick)); EXPECT_EQ(microseconds(0), absl::ToChronoMicroseconds(-tick)); EXPECT_EQ(milliseconds(0), absl::ToChronoMilliseconds(tick)); EXPECT_EQ(milliseconds(0), absl::ToChronoMilliseconds(-tick)); EXPECT_EQ(seconds(0), absl::ToChronoSeconds(tick)); EXPECT_EQ(seconds(0), absl::ToChronoSeconds(-tick)); EXPECT_EQ(minutes(0), absl::ToChronoMinutes(tick)); EXPECT_EQ(minutes(0), absl::ToChronoMinutes(-tick)); EXPECT_EQ(hours(0), absl::ToChronoHours(tick)); EXPECT_EQ(hours(0), absl::ToChronoHours(-tick)); constexpr auto inf = absl::InfiniteDuration(); EXPECT_EQ(nanoseconds::min(), absl::ToChronoNanoseconds(-inf)); EXPECT_EQ(nanoseconds::max(), absl::ToChronoNanoseconds(inf)); EXPECT_EQ(microseconds::min(), absl::ToChronoMicroseconds(-inf)); EXPECT_EQ(microseconds::max(), absl::ToChronoMicroseconds(inf)); EXPECT_EQ(milliseconds::min(), absl::ToChronoMilliseconds(-inf)); EXPECT_EQ(milliseconds::max(), absl::ToChronoMilliseconds(inf)); EXPECT_EQ(seconds::min(), absl::ToChronoSeconds(-inf)); EXPECT_EQ(seconds::max(), absl::ToChronoSeconds(inf)); EXPECT_EQ(minutes::min(), absl::ToChronoMinutes(-inf)); EXPECT_EQ(minutes::max(), absl::ToChronoMinutes(inf)); EXPECT_EQ(hours::min(), absl::ToChronoHours(-inf)); EXPECT_EQ(hours::max(), absl::ToChronoHours(inf)); } TEST(Duration, FactoryOverloads) { enum E { kOne = 1 }; #define TEST_FACTORY_OVERLOADS(NAME) \ EXPECT_EQ(1, NAME(kOne) / NAME(kOne)); \ EXPECT_EQ(1, NAME(static_cast<int8_t>(1)) / NAME(1)); \ EXPECT_EQ(1, NAME(static_cast<int16_t>(1)) / NAME(1)); \ EXPECT_EQ(1, NAME(static_cast<int32_t>(1)) / NAME(1)); \ EXPECT_EQ(1, NAME(static_cast<int64_t>(1)) / NAME(1)); \ EXPECT_EQ(1, NAME(static_cast<uint8_t>(1)) / NAME(1)); \ EXPECT_EQ(1, NAME(static_cast<uint16_t>(1)) / NAME(1)); \ EXPECT_EQ(1, NAME(static_cast<uint32_t>(1)) / NAME(1)); \ EXPECT_EQ(1, NAME(static_cast<uint64_t>(1)) / NAME(1)); \ EXPECT_EQ(NAME(1) / 2, NAME(static_cast<float>(0.5))); \ EXPECT_EQ(NAME(1) / 2, NAME(static_cast<double>(0.5))); \ EXPECT_EQ(1.5, absl::FDivDuration(NAME(static_cast<float>(1.5)), NAME(1))); \ EXPECT_EQ(1.5, absl::FDivDuration(NAME(static_cast<double>(1.5)), NAME(1))); TEST_FACTORY_OVERLOADS(absl::Nanoseconds); TEST_FACTORY_OVERLOADS(absl::Microseconds); TEST_FACTORY_OVERLOADS(absl::Milliseconds); TEST_FACTORY_OVERLOADS(absl::Seconds); TEST_FACTORY_OVERLOADS(absl::Minutes); TEST_FACTORY_OVERLOADS(absl::Hours); #undef TEST_FACTORY_OVERLOADS EXPECT_EQ(absl::Milliseconds(1500), absl::Seconds(1.5)); EXPECT_LT(absl::Nanoseconds(1), absl::Nanoseconds(1.5)); EXPECT_GT(absl::Nanoseconds(2), absl::Nanoseconds(1.5)); const double dbl_inf = std::numeric_limits<double>::infinity(); EXPECT_EQ(absl::InfiniteDuration(), absl::Nanoseconds(dbl_inf)); EXPECT_EQ(absl::InfiniteDuration(), absl::Microseconds(dbl_inf)); EXPECT_EQ(absl::InfiniteDuration(), absl::Milliseconds(dbl_inf)); EXPECT_EQ(absl::InfiniteDuration(), absl::Seconds(dbl_inf)); EXPECT_EQ(absl::InfiniteDuration(), absl::Minutes(dbl_inf)); EXPECT_EQ(absl::InfiniteDuration(), absl::Hours(dbl_inf)); EXPECT_EQ(-absl::InfiniteDuration(), absl::Nanoseconds(-dbl_inf)); EXPECT_EQ(-absl::InfiniteDuration(), absl::Microseconds(-dbl_inf)); EXPECT_EQ(-absl::InfiniteDuration(), absl::Milliseconds(-dbl_inf)); EXPECT_EQ(-absl::InfiniteDuration(), absl::Seconds(-dbl_inf)); EXPECT_EQ(-absl::InfiniteDuration(), absl::Minutes(-dbl_inf)); EXPECT_EQ(-absl::InfiniteDuration(), absl::Hours(-dbl_inf)); } TEST(Duration, InfinityExamples) { constexpr absl::Duration inf = absl::InfiniteDuration(); constexpr absl::Duration d = absl::Seconds(1); EXPECT_TRUE(inf == inf + inf); EXPECT_TRUE(inf == inf + d); EXPECT_TRUE(inf == inf - inf); EXPECT_TRUE(-inf == d - inf); EXPECT_TRUE(inf == d * 1e100); EXPECT_TRUE(0 == d / inf); EXPECT_TRUE(inf == d / 0); EXPECT_TRUE(kint64max == d / absl::ZeroDuration()); } TEST(Duration, InfinityComparison) { const absl::Duration inf = absl::InfiniteDuration(); const absl::Duration any_dur = absl::Seconds(1); EXPECT_EQ(inf, inf); EXPECT_EQ(-inf, -inf); EXPECT_NE(inf, -inf); EXPECT_NE(any_dur, inf); EXPECT_NE(any_dur, -inf); EXPECT_GT(inf, any_dur); EXPECT_LT(-inf, any_dur); EXPECT_LT(-inf, inf); EXPECT_GT(inf, -inf); #ifdef ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON EXPECT_EQ(inf <=> inf, std::strong_ordering::equal); EXPECT_EQ(-inf <=> -inf, std::strong_ordering::equal); EXPECT_EQ(-inf <=> inf, std::strong_ordering::less); EXPECT_EQ(inf <=> -inf, std::strong_ordering::greater); EXPECT_EQ(any_dur <=> inf, std::strong_ordering::less); EXPECT_EQ(any_dur <=> -inf, std::strong_ordering::greater); #endif } TEST(Duration, InfinityAddition) { const absl::Duration sec_max = absl::Seconds(kint64max); const absl::Duration sec_min = absl::Seconds(kint64min); const absl::Duration any_dur = absl::Seconds(1); const absl::Duration inf = absl::InfiniteDuration(); EXPECT_EQ(inf, inf + inf); EXPECT_EQ(inf, inf + -inf); EXPECT_EQ(-inf, -inf + inf); EXPECT_EQ(-inf, -inf + -inf); EXPECT_EQ(inf, inf + any_dur); EXPECT_EQ(inf, any_dur + inf); EXPECT_EQ(-inf, -inf + any_dur); EXPECT_EQ(-inf, any_dur + -inf); absl::Duration almost_inf = sec_max + absl::Nanoseconds(999999999); EXPECT_GT(inf, almost_inf); almost_inf += -absl::Nanoseconds(999999999); EXPECT_GT(inf, almost_inf); EXPECT_EQ(inf, sec_max + absl::Seconds(1)); EXPECT_EQ(inf, sec_max + sec_max); EXPECT_EQ(-inf, sec_min + -absl::Seconds(1)); EXPECT_EQ(-inf, sec_min + -sec_max); const double dbl_inf = std::numeric_limits<double>::infinity(); EXPECT_TRUE(std::isinf(dbl_inf + dbl_inf)); EXPECT_TRUE(std::isnan(dbl_inf + -dbl_inf)); EXPECT_TRUE(std::isnan(-dbl_inf + dbl_inf)); EXPECT_TRUE(std::isinf(-dbl_inf + -dbl_inf)); } TEST(Duration, InfinitySubtraction) { const absl::Duration sec_max = absl::Seconds(kint64max); const absl::Duration sec_min = absl::Seconds(kint64min); const absl::Duration any_dur = absl::Seconds(1); const absl::Duration inf = absl::InfiniteDuration(); EXPECT_EQ(inf, inf - inf); EXPECT_EQ(inf, inf - -inf); EXPECT_EQ(-inf, -inf - inf); EXPECT_EQ(-inf, -inf - -inf); EXPECT_EQ(inf, inf - any_dur); EXPECT_EQ(-inf, any_dur - inf); EXPECT_EQ(-inf, -inf - any_dur); EXPECT_EQ(inf, any_dur - -inf); EXPECT_EQ(inf, sec_max - -absl::Seconds(1)); EXPECT_EQ(inf, sec_max - -sec_max); EXPECT_EQ(-inf, sec_min - absl::Seconds(1)); EXPECT_EQ(-inf, sec_min - sec_max); absl::Duration almost_neg_inf = sec_min; EXPECT_LT(-inf, almost_neg_inf); #ifdef ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON EXPECT_EQ(-inf <=> almost_neg_inf, std::strong_ordering::less); EXPECT_EQ(almost_neg_inf <=> -inf, std::strong_ordering::greater); #endif almost_neg_inf -= -absl::Nanoseconds(1); EXPECT_LT(-inf, almost_neg_inf); #ifdef ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON EXPECT_EQ(-inf <=> almost_neg_inf, std::strong_ordering::less); EXPECT_EQ(almost_neg_inf <=> -inf, std::strong_ordering::greater); #endif const double dbl_inf = std::numeric_limits<double>::infinity(); EXPECT_TRUE(std::isnan(dbl_inf - dbl_inf)); EXPECT_TRUE(std::isinf(dbl_inf - -dbl_inf)); EXPECT_TRUE(std::isinf(-dbl_inf - dbl_inf)); EXPECT_TRUE(std::isnan(-dbl_inf - -dbl_inf)); } TEST(Duration, InfinityMultiplication) { const absl::Duration sec_max = absl::Seconds(kint64max); const absl::Duration sec_min = absl::Seconds(kint64min); const absl::Duration inf = absl::InfiniteDuration(); #define TEST_INF_MUL_WITH_TYPE(T) \ EXPECT_EQ(inf, inf * static_cast<T>(2)); \ EXPECT_EQ(-inf, inf * static_cast<T>(-2)); \ EXPECT_EQ(-inf, -inf * static_cast<T>(2)); \ EXPECT_EQ(inf, -inf * static_cast<T>(-2)); \ EXPECT_EQ(inf, inf * static_cast<T>(0)); \ EXPECT_EQ(-inf, -inf * static_cast<T>(0)); \ EXPECT_EQ(inf, sec_max * static_cast<T>(2)); \ EXPECT_EQ(inf, sec_min * static_cast<T>(-2)); \ EXPECT_EQ(inf, (sec_max / static_cast<T>(2)) * static_cast<T>(3)); \ EXPECT_EQ(-inf, sec_max * static_cast<T>(-2)); \ EXPECT_EQ(-inf, sec_min * static_cast<T>(2)); \ EXPECT_EQ(-inf, (sec_min / static_cast<T>(2)) * static_cast<T>(3)); TEST_INF_MUL_WITH_TYPE(int64_t); TEST_INF_MUL_WITH_TYPE(double); #undef TEST_INF_MUL_WITH_TYPE const double dbl_inf = std::numeric_limits<double>::infinity(); EXPECT_EQ(inf, inf * dbl_inf); EXPECT_EQ(-inf, -inf * dbl_inf); EXPECT_EQ(-inf, inf * -dbl_inf); EXPECT_EQ(inf, -inf * -dbl_inf); const absl::Duration any_dur = absl::Seconds(1); EXPECT_EQ(inf, any_dur * dbl_inf); EXPECT_EQ(-inf, -any_dur * dbl_inf); EXPECT_EQ(-inf, any_dur * -dbl_inf); EXPECT_EQ(inf, -any_dur * -dbl_inf); EXPECT_NE(absl::InfiniteDuration(), absl::Seconds(1) * kint64max); EXPECT_EQ(inf, absl::Seconds(1) * static_cast<double>(kint64max)); EXPECT_NE(-absl::InfiniteDuration(), absl::Seconds(1) * kint64min); EXPECT_EQ(-inf, absl::Seconds(1) * static_cast<double>(kint64min)); EXPECT_NE(inf, sec_max); EXPECT_NE(inf, sec_max / 1); EXPECT_EQ(inf, sec_max / 1.0); EXPECT_NE(inf, sec_max * 1); EXPECT_EQ(inf, sec_max * 1.0); } TEST(Duration, InfinityDivision) { const absl::Duration sec_max = absl::Seconds(kint64max); const absl::Duration sec_min = absl::Seconds(kint64min); const absl::Duration inf = absl::InfiniteDuration(); #define TEST_INF_DIV_WITH_TYPE(T) \ EXPECT_EQ(inf, inf / static_cast<T>(2)); \ EXPECT_EQ(-inf, inf / static_cast<T>(-2)); \ EXPECT_EQ(-inf, -inf / static_cast<T>(2)); \ EXPECT_EQ(inf, -inf / static_cast<T>(-2)); TEST_INF_DIV_WITH_TYPE(int64_t); TEST_INF_DIV_WITH_TYPE(double); #undef TEST_INF_DIV_WITH_TYPE EXPECT_EQ(inf, sec_max / 0.5); EXPECT_EQ(inf, sec_min / -0.5); EXPECT_EQ(inf, ((sec_max / 0.5) + absl::Seconds(1)) / 0.5); EXPECT_EQ(-inf, sec_max / -0.5); EXPECT_EQ(-inf, sec_min / 0.5); EXPECT_EQ(-inf, ((sec_min / 0.5) - absl::Seconds(1)) / 0.5); const double dbl_inf = std::numeric_limits<double>::infinity(); EXPECT_EQ(inf, inf / dbl_inf); EXPECT_EQ(-inf, inf / -dbl_inf); EXPECT_EQ(-inf, -inf / dbl_inf); EXPECT_EQ(inf, -inf / -dbl_inf); const absl::Duration any_dur = absl::Seconds(1); EXPECT_EQ(absl::ZeroDuration(), any_dur / dbl_inf); EXPECT_EQ(absl::ZeroDuration(), any_dur / -dbl_inf); EXPECT_EQ(absl::ZeroDuration(), -any_dur / dbl_inf); EXPECT_EQ(absl::ZeroDuration(), -any_dur / -dbl_inf); } TEST(Duration, InfinityModulus) { const absl::Duration sec_max = absl::Seconds(kint64max); const absl::Duration any_dur = absl::Seconds(1); const absl::Duration inf = absl::InfiniteDuration(); EXPECT_EQ(inf, inf % inf); EXPECT_EQ(inf, inf % -inf); EXPECT_EQ(-inf, -inf % -inf); EXPECT_EQ(-inf, -inf % inf); EXPECT_EQ(any_dur, any_dur % inf); EXPECT_EQ(any_dur, any_dur % -inf); EXPECT_EQ(-any_dur, -any_dur % inf); EXPECT_EQ(-any_dur, -any_dur % -inf); EXPECT_EQ(inf, inf % -any_dur); EXPECT_EQ(inf, inf % any_dur); EXPECT_EQ(-inf, -inf % -any_dur); EXPECT_EQ(-inf, -inf % any_dur); EXPECT_EQ(absl::ZeroDuration(), sec_max % absl::Seconds(1)); EXPECT_EQ(absl::ZeroDuration(), sec_max % absl::Milliseconds(1)); EXPECT_EQ(absl::ZeroDuration(), sec_max % absl::Microseconds(1)); EXPECT_EQ(absl::ZeroDuration(), sec_max % absl::Nanoseconds(1)); EXPECT_EQ(absl::ZeroDuration(), sec_max % absl::Nanoseconds(1) / 4); } TEST(Duration, InfinityIDiv) { const absl::Duration sec_max = absl::Seconds(kint64max); const absl::Duration any_dur = absl::Seconds(1); const absl::Duration inf = absl::InfiniteDuration(); const double dbl_inf = std::numeric_limits<double>::infinity(); absl::Duration rem = absl::ZeroDuration(); EXPECT_EQ(kint64max, absl::IDivDuration(inf, inf, &rem)); EXPECT_EQ(inf, rem); rem = absl::ZeroDuration(); EXPECT_EQ(kint64max, absl::IDivDuration(-inf, -inf, &rem)); EXPECT_EQ(-inf, rem); rem = absl::ZeroDuration(); EXPECT_EQ(kint64max, absl::IDivDuration(inf, any_dur, &rem)); EXPECT_EQ(inf, rem); rem = absl::ZeroDuration(); EXPECT_EQ(0, absl::IDivDuration(any_dur, inf, &rem)); EXPECT_EQ(any_dur, rem); rem = absl::ZeroDuration(); EXPECT_EQ(kint64max, absl::IDivDuration(-inf, -any_dur, &rem)); EXPECT_EQ(-inf, rem); rem = absl::ZeroDuration(); EXPECT_EQ(0, absl::IDivDuration(-any_dur, -inf, &rem)); EXPECT_EQ(-any_dur, rem); rem = absl::ZeroDuration(); EXPECT_EQ(kint64min, absl::IDivDuration(-inf, inf, &rem)); EXPECT_EQ(-inf, rem); rem = absl::ZeroDuration(); EXPECT_EQ(kint64min, absl::IDivDuration(inf, -inf, &rem)); EXPECT_EQ(inf, rem); rem = absl::ZeroDuration(); EXPECT_EQ(kint64min, absl::IDivDuration(-inf, any_dur, &rem)); EXPECT_EQ(-inf, rem); rem = absl::ZeroDuration(); EXPECT_EQ(0, absl::IDivDuration(-any_dur, inf, &rem)); EXPECT_EQ(-any_dur, rem); rem = absl::ZeroDuration(); EXPECT_EQ(kint64min, absl::IDivDuration(inf, -any_dur, &rem)); EXPECT_EQ(inf, rem); rem = absl::ZeroDuration(); EXPECT_EQ(0, absl::IDivDuration(any_dur, -inf, &rem)); EXPECT_EQ(any_dur, rem); rem = any_dur; EXPECT_EQ(kint64max, absl::IDivDuration(sec_max, absl::Nanoseconds(1) / 4, &rem)); EXPECT_EQ(sec_max - absl::Nanoseconds(kint64max) / 4, rem); rem = any_dur; EXPECT_EQ(kint64max, absl::IDivDuration(sec_max, absl::Milliseconds(1), &rem)); EXPECT_EQ(sec_max - absl::Milliseconds(kint64max), rem); rem = any_dur; EXPECT_EQ(kint64max, absl::IDivDuration(-sec_max, -absl::Milliseconds(1), &rem)); EXPECT_EQ(-sec_max + absl::Milliseconds(kint64max), rem); rem = any_dur; EXPECT_EQ(kint64min, absl::IDivDuration(-sec_max, absl::Milliseconds(1), &rem)); EXPECT_EQ(-sec_max - absl::Milliseconds(kint64min), rem); rem = any_dur; EXPECT_EQ(kint64min, absl::IDivDuration(sec_max, -absl::Milliseconds(1), &rem)); EXPECT_EQ(sec_max + absl::Milliseconds(kint64min), rem); EXPECT_TRUE(std::isnan(dbl_inf / dbl_inf)); EXPECT_EQ(kint64max, inf / inf); EXPECT_EQ(kint64max, -inf / -inf); EXPECT_EQ(kint64min, -inf / inf); EXPECT_EQ(kint64min, inf / -inf); EXPECT_TRUE(std::isinf(dbl_inf / 2.0)); EXPECT_EQ(kint64max, inf / any_dur); EXPECT_EQ(kint64max, -inf / -any_dur); EXPECT_EQ(kint64min, -inf / any_dur); EXPECT_EQ(kint64min, inf / -any_dur); EXPECT_EQ(0.0, 2.0 / dbl_inf); EXPECT_EQ(0, any_dur / inf); EXPECT_EQ(0, any_dur / -inf); EXPECT_EQ(0, -any_dur / inf); EXPECT_EQ(0, -any_dur / -inf); EXPECT_EQ(0, absl::ZeroDuration() / inf); EXPECT_EQ(kint64max, sec_max / absl::Milliseconds(1)); EXPECT_EQ(kint64max, -sec_max / -absl::Milliseconds(1)); EXPECT_EQ(kint64min, -sec_max / absl::Milliseconds(1)); EXPECT_EQ(kint64min, sec_max / -absl::Milliseconds(1)); } TEST(Duration, InfinityFDiv) { const absl::Duration any_dur = absl::Seconds(1); const absl::Duration inf = absl::InfiniteDuration(); const double dbl_inf = std::numeric_limits<double>::infinity(); EXPECT_EQ(dbl_inf, absl::FDivDuration(inf, inf)); EXPECT_EQ(dbl_inf, absl::FDivDuration(-inf, -inf)); EXPECT_EQ(dbl_inf, absl::FDivDuration(inf, any_dur)); EXPECT_EQ(0.0, absl::FDivDuration(any_dur, inf)); EXPECT_EQ(dbl_inf, absl::FDivDuration(-inf, -any_dur)); EXPECT_EQ(0.0, absl::FDivDuration(-any_dur, -inf)); EXPECT_EQ(-dbl_inf, absl::FDivDuration(-inf, inf)); EXPECT_EQ(-dbl_inf, absl::FDivDuration(inf, -inf)); EXPECT_EQ(-dbl_inf, absl::FDivDuration(-inf, any_dur)); EXPECT_EQ(0.0, absl::FDivDuration(-any_dur, inf)); EXPECT_EQ(-dbl_inf, absl::FDivDuration(inf, -any_dur)); EXPECT_EQ(0.0, absl::FDivDuration(any_dur, -inf)); } TEST(Duration, DivisionByZero) { const absl::Duration zero = absl::ZeroDuration(); const absl::Duration inf = absl::InfiniteDuration(); const absl::Duration any_dur = absl::Seconds(1); const double dbl_inf = std::numeric_limits<double>::infinity(); const double dbl_denorm = std::numeric_limits<double>::denorm_min(); EXPECT_EQ(inf, zero / 0.0); EXPECT_EQ(-inf, zero / -0.0); EXPECT_EQ(inf, any_dur / 0.0); EXPECT_EQ(-inf, any_dur / -0.0); EXPECT_EQ(-inf, -any_dur / 0.0); EXPECT_EQ(inf, -any_dur / -0.0); EXPECT_EQ(zero, zero / dbl_denorm); EXPECT_EQ(zero, zero / -dbl_denorm); EXPECT_EQ(inf, any_dur / dbl_denorm); EXPECT_EQ(-inf, any_dur / -dbl_denorm); EXPECT_EQ(-inf, -any_dur / dbl_denorm); EXPECT_EQ(inf, -any_dur / -dbl_denorm); absl::Duration rem = zero; EXPECT_EQ(kint64max, absl::IDivDuration(zero, zero, &rem)); EXPECT_EQ(inf, rem); rem = zero; EXPECT_EQ(kint64max, absl::IDivDuration(any_dur, zero, &rem)); EXPECT_EQ(inf, rem); rem = zero; EXPECT_EQ(kint64min, absl::IDivDuration(-any_dur, zero, &rem)); EXPECT_EQ(-inf, rem); EXPECT_EQ(kint64max, zero / zero); EXPECT_EQ(kint64max, any_dur / zero); EXPECT_EQ(kint64min, -any_dur / zero); EXPECT_EQ(dbl_inf, absl::FDivDuration(zero, zero)); EXPECT_EQ(dbl_inf, absl::FDivDuration(any_dur, zero)); EXPECT_EQ(-dbl_inf, absl::FDivDuration(-any_dur, zero)); } TEST(Duration, NaN) { #define TEST_NAN_HANDLING(NAME, NAN) \ do { \ const auto inf = absl::InfiniteDuration(); \ auto x = NAME(NAN); \ EXPECT_TRUE(x == inf || x == -inf); \ auto y = NAME(42); \ y *= NAN; \ EXPECT_TRUE(y == inf || y == -inf); \ auto z = NAME(42); \ z /= NAN; \ EXPECT_TRUE(z == inf || z == -inf); \ } while (0) const double nan = std::numeric_limits<double>::quiet_NaN(); TEST_NAN_HANDLING(absl::Nanoseconds, nan); TEST_NAN_HANDLING(absl::Microseconds, nan); TEST_NAN_HANDLING(absl::Milliseconds, nan); TEST_NAN_HANDLING(absl::Seconds, nan); TEST_NAN_HANDLING(absl::Minutes, nan); TEST_NAN_HANDLING(absl::Hours, nan); TEST_NAN_HANDLING(absl::Nanoseconds, -nan); TEST_NAN_HANDLING(absl::Microseconds, -nan); TEST_NAN_HANDLING(absl::Milliseconds, -nan); TEST_NAN_HANDLING(absl::Seconds, -nan); TEST_NAN_HANDLING(absl::Minutes, -nan); TEST_NAN_HANDLING(absl::Hours, -nan); #undef TEST_NAN_HANDLING } TEST(Duration, Range) { const absl::Duration range = ApproxYears(100 * 1e9); const absl::Duration range_future = range; const absl::Duration range_past = -range; EXPECT_LT(range_future, absl::InfiniteDuration()); EXPECT_GT(range_past, -absl::InfiniteDuration()); const absl::Duration full_range = range_future - range_past; EXPECT_GT(full_range, absl::ZeroDuration()); EXPECT_LT(full_range, absl::InfiniteDuration()); const absl::Duration neg_full_range = range_past - range_future; EXPECT_LT(neg_full_range, absl::ZeroDuration()); EXPECT_GT(neg_full_range, -absl::InfiniteDuration()); EXPECT_LT(neg_full_range, full_range); EXPECT_EQ(neg_full_range, -full_range); #ifdef ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON EXPECT_EQ(range_future <=> absl::InfiniteDuration(), std::strong_ordering::less); EXPECT_EQ(range_past <=> -absl::InfiniteDuration(), std::strong_ordering::greater); EXPECT_EQ(full_range <=> absl::ZeroDuration(), std::strong_ordering::greater); EXPECT_EQ(full_range <=> -absl::InfiniteDuration(), std::strong_ordering::greater); EXPECT_EQ(neg_full_range <=> -absl::InfiniteDuration(), std::strong_ordering::greater); EXPECT_EQ(neg_full_range <=> full_range, std::strong_ordering::less); EXPECT_EQ(neg_full_range <=> -full_range, std::strong_ordering::equal); #endif } TEST(Duration, RelationalOperators) { #define TEST_REL_OPS(UNIT) \ static_assert(UNIT(2) == UNIT(2), ""); \ static_assert(UNIT(1) != UNIT(2), ""); \ static_assert(UNIT(1) < UNIT(2), ""); \ static_assert(UNIT(3) > UNIT(2), ""); \ static_assert(UNIT(1) <= UNIT(2), ""); \ static_assert(UNIT(2) <= UNIT(2), ""); \ static_assert(UNIT(3) >= UNIT(2), ""); \ static_assert(UNIT(2) >= UNIT(2), ""); TEST_REL_OPS(absl::Nanoseconds); TEST_REL_OPS(absl::Microseconds); TEST_REL_OPS(absl::Milliseconds); TEST_REL_OPS(absl::Seconds); TEST_REL_OPS(absl::Minutes); TEST_REL_OPS(absl::Hours); #undef TEST_REL_OPS } #ifdef ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON TEST(Duration, SpaceshipOperators) { #define TEST_REL_OPS(UNIT) \ static_assert(UNIT(2) <=> UNIT(2) == std::strong_ordering::equal, ""); \ static_assert(UNIT(1) <=> UNIT(2) == std::strong_ordering::less, ""); \ static_assert(UNIT(3) <=> UNIT(2) == std::strong_ordering::greater, ""); TEST_REL_OPS(absl::Nanoseconds); TEST_REL_OPS(absl::Microseconds); TEST_REL_OPS(absl::Milliseconds); TEST_REL_OPS(absl::Seconds); TEST_REL_OPS(absl::Minutes); TEST_REL_OPS(absl::Hours); #undef TEST_REL_OPS } #endif TEST(Duration, Addition) { #define TEST_ADD_OPS(UNIT) \ do { \ EXPECT_EQ(UNIT(2), UNIT(1) + UNIT(1)); \ EXPECT_EQ(UNIT(1), UNIT(2) - UNIT(1)); \ EXPECT_EQ(UNIT(0), UNIT(2) - UNIT(2)); \ EXPECT_EQ(UNIT(-1), UNIT(1) - UNIT(2)); \ EXPECT_EQ(UNIT(-2), UNIT(0) - UNIT(2)); \ EXPECT_EQ(UNIT(-2), UNIT(1) - UNIT(3)); \ absl::Duration a = UNIT(1); \ a += UNIT(1); \ EXPECT_EQ(UNIT(2), a); \ a -= UNIT(1); \ EXPECT_EQ(UNIT(1), a); \ } while (0) TEST_ADD_OPS(absl::Nanoseconds); TEST_ADD_OPS(absl::Microseconds); TEST_ADD_OPS(absl::Milliseconds); TEST_ADD_OPS(absl::Seconds); TEST_ADD_OPS(absl::Minutes); TEST_ADD_OPS(absl::Hours); #undef TEST_ADD_OPS EXPECT_EQ(absl::Seconds(2), absl::Seconds(3) - 2 * absl::Milliseconds(500)); EXPECT_EQ(absl::Seconds(2) + absl::Milliseconds(500), absl::Seconds(3) - absl::Milliseconds(500)); EXPECT_EQ(absl::Seconds(1) + absl::Milliseconds(998), absl::Milliseconds(999) + absl::Milliseconds(999)); EXPECT_EQ(absl::Milliseconds(-1), absl::Milliseconds(998) - absl::Milliseconds(999)); EXPECT_GT(absl::Nanoseconds(1), absl::Nanoseconds(1) / 2); EXPECT_EQ(absl::Nanoseconds(1), absl::Nanoseconds(1) / 2 + absl::Nanoseconds(1) / 2); EXPECT_GT(absl::Nanoseconds(1) / 4, absl::Nanoseconds(0)); EXPECT_EQ(absl::Nanoseconds(1) / 8, absl::Nanoseconds(0)); absl::Duration d_7_5 = absl::Seconds(7) + absl::Milliseconds(500); absl::Duration d_3_7 = absl::Seconds(3) + absl::Milliseconds(700); absl::Duration ans_3_8 = absl::Seconds(3) + absl::Milliseconds(800); EXPECT_EQ(ans_3_8, d_7_5 - d_3_7); absl::Duration min_dur = absl::Seconds(kint64min); EXPECT_EQ(absl::Seconds(0), min_dur - min_dur); EXPECT_EQ(absl::Seconds(kint64max), absl::Seconds(-1) - min_dur); } TEST(Duration, Negation) { constexpr absl::Duration negated_zero_duration = -absl::ZeroDuration(); EXPECT_EQ(negated_zero_duration, absl::ZeroDuration()); constexpr absl::Duration negated_infinite_duration = -absl::InfiniteDuration(); EXPECT_NE(negated_infinite_duration, absl::InfiniteDuration()); EXPECT_EQ(-negated_infinite_duration, absl::InfiniteDuration()); EXPECT_TRUE( absl::time_internal::IsInfiniteDuration(negated_infinite_duration)); constexpr absl::Duration max_duration = absl::time_internal::MakeDuration( kint64max, absl::time_internal::kTicksPerSecond - 1); constexpr absl::Duration negated_max_duration = -max_duration; constexpr absl::Duration nearly_min_duration = absl::time_internal::MakeDuration(kint64min, int64_t{1}); constexpr absl::Duration negated_nearly_min_duration = -nearly_min_duration; EXPECT_EQ(negated_max_duration, nearly_min_duration); EXPECT_EQ(negated_nearly_min_duration, max_duration); EXPECT_EQ(-(-max_duration), max_duration); constexpr absl::Duration min_duration = absl::time_internal::MakeDuration(kint64min); constexpr absl::Duration negated_min_duration = -min_duration; EXPECT_EQ(negated_min_duration, absl::InfiniteDuration()); } TEST(Duration, AbsoluteValue) { EXPECT_EQ(absl::ZeroDuration(), AbsDuration(absl::ZeroDuration())); EXPECT_EQ(absl::Seconds(1), AbsDuration(absl::Seconds(1))); EXPECT_EQ(absl::Seconds(1), AbsDuration(absl::Seconds(-1))); EXPECT_EQ(absl::InfiniteDuration(), AbsDuration(absl::InfiniteDuration())); EXPECT_EQ(absl::InfiniteDuration(), AbsDuration(-absl::InfiniteDuration())); absl::Duration max_dur = absl::Seconds(kint64max) + (absl::Seconds(1) - absl::Nanoseconds(1) / 4); EXPECT_EQ(max_dur, AbsDuration(max_dur)); absl::Duration min_dur = absl::Seconds(kint64min); EXPECT_EQ(absl::InfiniteDuration(), AbsDuration(min_dur)); EXPECT_EQ(max_dur, AbsDuration(min_dur + absl::Nanoseconds(1) / 4)); } TEST(Duration, Multiplication) { #define TEST_MUL_OPS(UNIT) \ do { \ EXPECT_EQ(UNIT(5), UNIT(2) * 2.5); \ EXPECT_EQ(UNIT(2), UNIT(5) / 2.5); \ EXPECT_EQ(UNIT(-5), UNIT(-2) * 2.5); \ EXPECT_EQ(UNIT(-5), -UNIT(2) * 2.5); \ EXPECT_EQ(UNIT(-5), UNIT(2) * -2.5); \ EXPECT_EQ(UNIT(-2), UNIT(-5) / 2.5); \ EXPECT_EQ(UNIT(-2), -UNIT(5) / 2.5); \ EXPECT_EQ(UNIT(-2), UNIT(5) / -2.5); \ EXPECT_EQ(UNIT(2), UNIT(11) % UNIT(3)); \ absl::Duration a = UNIT(2); \ a *= 2.5; \ EXPECT_EQ(UNIT(5), a); \ a /= 2.5; \ EXPECT_EQ(UNIT(2), a); \ a %= UNIT(1); \ EXPECT_EQ(UNIT(0), a); \ absl::Duration big = UNIT(1000000000); \ big *= 3; \ big /= 3; \ EXPECT_EQ(UNIT(1000000000), big); \ EXPECT_EQ(-UNIT(2), -UNIT(2)); \ EXPECT_EQ(-UNIT(2), UNIT(2) * -1); \ EXPECT_EQ(-UNIT(2), -1 * UNIT(2)); \ EXPECT_EQ(-UNIT(-2), UNIT(2)); \ EXPECT_EQ(2, UNIT(2) / UNIT(1)); \ absl::Duration rem; \ EXPECT_EQ(2, absl::IDivDuration(UNIT(2), UNIT(1), &rem)); \ EXPECT_EQ(2.0, absl::FDivDuration(UNIT(2), UNIT(1))); \ } while (0) TEST_MUL_OPS(absl::Nanoseconds); TEST_MUL_OPS(absl::Microseconds); TEST_MUL_OPS(absl::Milliseconds); TEST_MUL_OPS(absl::Seconds); TEST_MUL_OPS(absl::Minutes); TEST_MUL_OPS(absl::Hours); #undef TEST_MUL_OPS absl::Duration max_dur = absl::Seconds(kint64max) + (absl::Seconds(1) - absl::Nanoseconds(1) / 4); absl::Duration min_dur = absl::Seconds(kint64min); EXPECT_EQ(max_dur, max_dur * 1); EXPECT_EQ(max_dur, max_dur / 1); EXPECT_EQ(min_dur, min_dur * 1); EXPECT_EQ(min_dur, min_dur / 1); absl::Duration sigfigs = absl::Seconds(2000000000) + absl::Nanoseconds(3); EXPECT_EQ(absl::Seconds(666666666) + absl::Nanoseconds(666666667) + absl::Nanoseconds(1) / 2, sigfigs / 3); sigfigs = absl::Seconds(int64_t{7000000000}); EXPECT_EQ(absl::Seconds(2333333333) + absl::Nanoseconds(333333333) + absl::Nanoseconds(1) / 4, sigfigs / 3); EXPECT_EQ(absl::Seconds(7) + absl::Milliseconds(500), absl::Seconds(3) * 2.5); EXPECT_EQ(absl::Seconds(8) * -1 + absl::Milliseconds(300), (absl::Seconds(2) + absl::Milliseconds(200)) * -3.5); EXPECT_EQ(-absl::Seconds(8) + absl::Milliseconds(300), (absl::Seconds(2) + absl::Milliseconds(200)) * -3.5); EXPECT_EQ(absl::Seconds(1) + absl::Milliseconds(875), (absl::Seconds(7) + absl::Milliseconds(500)) / 4); EXPECT_EQ(absl::Seconds(30), (absl::Seconds(7) + absl::Milliseconds(500)) / 0.25); EXPECT_EQ(absl::Seconds(3), (absl::Seconds(7) + absl::Milliseconds(500)) / 2.5); EXPECT_EQ(absl::Nanoseconds(0), absl::Nanoseconds(7) % absl::Nanoseconds(1)); EXPECT_EQ(absl::Nanoseconds(0), absl::Nanoseconds(0) % absl::Nanoseconds(10)); EXPECT_EQ(absl::Nanoseconds(2), absl::Nanoseconds(7) % absl::Nanoseconds(5)); EXPECT_EQ(absl::Nanoseconds(2), absl::Nanoseconds(2) % absl::Nanoseconds(5)); EXPECT_EQ(absl::Nanoseconds(1), absl::Nanoseconds(10) % absl::Nanoseconds(3)); EXPECT_EQ(absl::Nanoseconds(1), absl::Nanoseconds(10) % absl::Nanoseconds(-3)); EXPECT_EQ(absl::Nanoseconds(-1), absl::Nanoseconds(-10) % absl::Nanoseconds(3)); EXPECT_EQ(absl::Nanoseconds(-1), absl::Nanoseconds(-10) % absl::Nanoseconds(-3)); EXPECT_EQ(absl::Milliseconds(100), absl::Seconds(1) % absl::Milliseconds(300)); EXPECT_EQ( absl::Milliseconds(300), (absl::Seconds(3) + absl::Milliseconds(800)) % absl::Milliseconds(500)); EXPECT_EQ(absl::Nanoseconds(1), absl::Nanoseconds(1) % absl::Seconds(1)); EXPECT_EQ(absl::Nanoseconds(-1), absl::Nanoseconds(-1) % absl::Seconds(1)); EXPECT_EQ(0, absl::Nanoseconds(-1) / absl::Seconds(1)); #define TEST_MOD_IDENTITY(a, b) \ EXPECT_EQ((a), ((a) / (b))*(b) + ((a)%(b))) TEST_MOD_IDENTITY(absl::Seconds(0), absl::Seconds(2)); TEST_MOD_IDENTITY(absl::Seconds(1), absl::Seconds(1)); TEST_MOD_IDENTITY(absl::Seconds(1), absl::Seconds(2)); TEST_MOD_IDENTITY(absl::Seconds(2), absl::Seconds(1)); TEST_MOD_IDENTITY(absl::Seconds(-2), absl::Seconds(1)); TEST_MOD_IDENTITY(absl::Seconds(2), absl::Seconds(-1)); TEST_MOD_IDENTITY(absl::Seconds(-2), absl::Seconds(-1)); TEST_MOD_IDENTITY(absl::Nanoseconds(0), absl::Nanoseconds(2)); TEST_MOD_IDENTITY(absl::Nanoseconds(1), absl::Nanoseconds(1)); TEST_MOD_IDENTITY(absl::Nanoseconds(1), absl::Nanoseconds(2)); TEST_MOD_IDENTITY(absl::Nanoseconds(2), absl::Nanoseconds(1)); TEST_MOD_IDENTITY(absl::Nanoseconds(-2), absl::Nanoseconds(1)); TEST_MOD_IDENTITY(absl::Nanoseconds(2), absl::Nanoseconds(-1)); TEST_MOD_IDENTITY(absl::Nanoseconds(-2), absl::Nanoseconds(-1)); absl::Duration mixed_a = absl::Seconds(1) + absl::Nanoseconds(2); absl::Duration mixed_b = absl::Seconds(1) + absl::Nanoseconds(3); TEST_MOD_IDENTITY(absl::Seconds(0), mixed_a); TEST_MOD_IDENTITY(mixed_a, mixed_a); TEST_MOD_IDENTITY(mixed_a, mixed_b); TEST_MOD_IDENTITY(mixed_b, mixed_a); TEST_MOD_IDENTITY(-mixed_a, mixed_b); TEST_MOD_IDENTITY(mixed_a, -mixed_b); TEST_MOD_IDENTITY(-mixed_a, -mixed_b); #undef TEST_MOD_IDENTITY } TEST(Duration, Truncation) { const absl::Duration d = absl::Nanoseconds(1234567890); const absl::Duration inf = absl::InfiniteDuration(); for (int unit_sign : {1, -1}) { EXPECT_EQ(absl::Nanoseconds(1234567890), Trunc(d, unit_sign * absl::Nanoseconds(1))); EXPECT_EQ(absl::Microseconds(1234567), Trunc(d, unit_sign * absl::Microseconds(1))); EXPECT_EQ(absl::Milliseconds(1234), Trunc(d, unit_sign * absl::Milliseconds(1))); EXPECT_EQ(absl::Seconds(1), Trunc(d, unit_sign * absl::Seconds(1))); EXPECT_EQ(inf, Trunc(inf, unit_sign * absl::Seconds(1))); EXPECT_EQ(absl::Nanoseconds(-1234567890), Trunc(-d, unit_sign * absl::Nanoseconds(1))); EXPECT_EQ(absl::Microseconds(-1234567), Trunc(-d, unit_sign * absl::Microseconds(1))); EXPECT_EQ(absl::Milliseconds(-1234), Trunc(-d, unit_sign * absl::Milliseconds(1))); EXPECT_EQ(absl::Seconds(-1), Trunc(-d, unit_sign * absl::Seconds(1))); EXPECT_EQ(-inf, Trunc(-inf, unit_sign * absl::Seconds(1))); } } TEST(Duration, Flooring) { const absl::Duration d = absl::Nanoseconds(1234567890); const absl::Duration inf = absl::InfiniteDuration(); for (int unit_sign : {1, -1}) { EXPECT_EQ(absl::Nanoseconds(1234567890), absl::Floor(d, unit_sign * absl::Nanoseconds(1))); EXPECT_EQ(absl::Microseconds(1234567), absl::Floor(d, unit_sign * absl::Microseconds(1))); EXPECT_EQ(absl::Milliseconds(1234), absl::Floor(d, unit_sign * absl::Milliseconds(1))); EXPECT_EQ(absl::Seconds(1), absl::Floor(d, unit_sign * absl::Seconds(1))); EXPECT_EQ(inf, absl::Floor(inf, unit_sign * absl::Seconds(1))); EXPECT_EQ(absl::Nanoseconds(-1234567890), absl::Floor(-d, unit_sign * absl::Nanoseconds(1))); EXPECT_EQ(absl::Microseconds(-1234568), absl::Floor(-d, unit_sign * absl::Microseconds(1))); EXPECT_EQ(absl::Milliseconds(-1235), absl::Floor(-d, unit_sign * absl::Milliseconds(1))); EXPECT_EQ(absl::Seconds(-2), absl::Floor(-d, unit_sign * absl::Seconds(1))); EXPECT_EQ(-inf, absl::Floor(-inf, unit_sign * absl::Seconds(1))); } } TEST(Duration, Ceiling) { const absl::Duration d = absl::Nanoseconds(1234567890); const absl::Duration inf = absl::InfiniteDuration(); for (int unit_sign : {1, -1}) { EXPECT_EQ(absl::Nanoseconds(1234567890), absl::Ceil(d, unit_sign * absl::Nanoseconds(1))); EXPECT_EQ(absl::Microseconds(1234568), absl::Ceil(d, unit_sign * absl::Microseconds(1))); EXPECT_EQ(absl::Milliseconds(1235), absl::Ceil(d, unit_sign * absl::Milliseconds(1))); EXPECT_EQ(absl::Seconds(2), absl::Ceil(d, unit_sign * absl::Seconds(1))); EXPECT_EQ(inf, absl::Ceil(inf, unit_sign * absl::Seconds(1))); EXPECT_EQ(absl::Nanoseconds(-1234567890), absl::Ceil(-d, unit_sign * absl::Nanoseconds(1))); EXPECT_EQ(absl::Microseconds(-1234567), absl::Ceil(-d, unit_sign * absl::Microseconds(1))); EXPECT_EQ(absl::Milliseconds(-1234), absl::Ceil(-d, unit_sign * absl::Milliseconds(1))); EXPECT_EQ(absl::Seconds(-1), absl::Ceil(-d, unit_sign * absl::Seconds(1))); EXPECT_EQ(-inf, absl::Ceil(-inf, unit_sign * absl::Seconds(1))); } } TEST(Duration, RoundTripUnits) { const int kRange = 100000; #define ROUND_TRIP_UNIT(U, LOW, HIGH) \ do { \ for (int64_t i = LOW; i < HIGH; ++i) { \ absl::Duration d = absl::U(i); \ if (d == absl::InfiniteDuration()) \ EXPECT_EQ(kint64max, d / absl::U(1)); \ else if (d == -absl::InfiniteDuration()) \ EXPECT_EQ(kint64min, d / absl::U(1)); \ else \ EXPECT_EQ(i, absl::U(i) / absl::U(1)); \ } \ } while (0) ROUND_TRIP_UNIT(Nanoseconds, kint64min, kint64min + kRange); ROUND_TRIP_UNIT(Nanoseconds, -kRange, kRange); ROUND_TRIP_UNIT(Nanoseconds, kint64max - kRange, kint64max); ROUND_TRIP_UNIT(Microseconds, kint64min, kint64min + kRange); ROUND_TRIP_UNIT(Microseconds, -kRange, kRange); ROUND_TRIP_UNIT(Microseconds, kint64max - kRange, kint64max); ROUND_TRIP_UNIT(Milliseconds, kint64min, kint64min + kRange); ROUND_TRIP_UNIT(Milliseconds, -kRange, kRange); ROUND_TRIP_UNIT(Milliseconds, kint64max - kRange, kint64max); ROUND_TRIP_UNIT(Seconds, kint64min, kint64min + kRange); ROUND_TRIP_UNIT(Seconds, -kRange, kRange); ROUND_TRIP_UNIT(Seconds, kint64max - kRange, kint64max); ROUND_TRIP_UNIT(Minutes, kint64min / 60, kint64min / 60 + kRange); ROUND_TRIP_UNIT(Minutes, -kRange, kRange); ROUND_TRIP_UNIT(Minutes, kint64max / 60 - kRange, kint64max / 60); ROUND_TRIP_UNIT(Hours, kint64min / 3600, kint64min / 3600 + kRange); ROUND_TRIP_UNIT(Hours, -kRange, kRange); ROUND_TRIP_UNIT(Hours, kint64max / 3600 - kRange, kint64max / 3600); #undef ROUND_TRIP_UNIT } TEST(Duration, TruncConversions) { const struct { absl::Duration d; timespec ts; } to_ts[] = { {absl::Seconds(1) + absl::Nanoseconds(1), {1, 1}}, {absl::Seconds(1) + absl::Nanoseconds(1) / 2, {1, 0}}, {absl::Seconds(1) + absl::Nanoseconds(0), {1, 0}}, {absl::Seconds(0) + absl::Nanoseconds(0), {0, 0}}, {absl::Seconds(0) - absl::Nanoseconds(1) / 2, {0, 0}}, {absl::Seconds(0) - absl::Nanoseconds(1), {-1, 999999999}}, {absl::Seconds(-1) + absl::Nanoseconds(1), {-1, 1}}, {absl::Seconds(-1) + absl::Nanoseconds(1) / 2, {-1, 1}}, {absl::Seconds(-1) + absl::Nanoseconds(0), {-1, 0}}, {absl::Seconds(-1) - absl::Nanoseconds(1) / 2, {-1, 0}}, }; for (const auto& test : to_ts) { EXPECT_THAT(absl::ToTimespec(test.d), TimespecMatcher(test.ts)); } const struct { timespec ts; absl::Duration d; } from_ts[] = { {{1, 1}, absl::Seconds(1) + absl::Nanoseconds(1)}, {{1, 0}, absl::Seconds(1) + absl::Nanoseconds(0)}, {{0, 0}, absl::Seconds(0) + absl::Nanoseconds(0)}, {{0, -1}, absl::Seconds(0) - absl::Nanoseconds(1)}, {{-1, 999999999}, absl::Seconds(0) - absl::Nanoseconds(1)}, {{-1, 1}, absl::Seconds(-1) + absl::Nanoseconds(1)}, {{-1, 0}, absl::Seconds(-1) + absl::Nanoseconds(0)}, {{-1, -1}, absl::Seconds(-1) - absl::Nanoseconds(1)}, {{-2, 999999999}, absl::Seconds(-1) - absl::Nanoseconds(1)}, }; for (const auto& test : from_ts) { EXPECT_EQ(test.d, absl::DurationFromTimespec(test.ts)); } const struct { absl::Duration d; timeval tv; } to_tv[] = { {absl::Seconds(1) + absl::Microseconds(1), {1, 1}}, {absl::Seconds(1) + absl::Microseconds(1) / 2, {1, 0}}, {absl::Seconds(1) + absl::Microseconds(0), {1, 0}}, {absl::Seconds(0) + absl::Microseconds(0), {0, 0}}, {absl::Seconds(0) - absl::Microseconds(1) / 2, {0, 0}}, {absl::Seconds(0) - absl::Microseconds(1), {-1, 999999}}, {absl::Seconds(-1) + absl::Microseconds(1), {-1, 1}}, {absl::Seconds(-1) + absl::Microseconds(1) / 2, {-1, 1}}, {absl::Seconds(-1) + absl::Microseconds(0), {-1, 0}}, {absl::Seconds(-1) - absl::Microseconds(1) / 2, {-1, 0}}, }; for (const auto& test : to_tv) { EXPECT_THAT(absl::ToTimeval(test.d), TimevalMatcher(test.tv)); } const struct { timeval tv; absl::Duration d; } from_tv[] = { {{1, 1}, absl::Seconds(1) + absl::Microseconds(1)}, {{1, 0}, absl::Seconds(1) + absl::Microseconds(0)}, {{0, 0}, absl::Seconds(0) + absl::Microseconds(0)}, {{0, -1}, absl::Seconds(0) - absl::Microseconds(1)}, {{-1, 999999}, absl::Seconds(0) - absl::Microseconds(1)}, {{-1, 1}, absl::Seconds(-1) + absl::Microseconds(1)}, {{-1, 0}, absl::Seconds(-1) + absl::Microseconds(0)}, {{-1, -1}, absl::Seconds(-1) - absl::Microseconds(1)}, {{-2, 999999}, absl::Seconds(-1) - absl::Microseconds(1)}, }; for (const auto& test : from_tv) { EXPECT_EQ(test.d, absl::DurationFromTimeval(test.tv)); } } TEST(Duration, SmallConversions) { EXPECT_EQ(absl::ZeroDuration(), absl::Seconds(0)); EXPECT_EQ(absl::ZeroDuration(), absl::Seconds(std::nextafter(0.125e-9, 0))); EXPECT_EQ(absl::Nanoseconds(1) / 4, absl::Seconds(0.125e-9)); EXPECT_EQ(absl::Nanoseconds(1) / 4, absl::Seconds(0.250e-9)); EXPECT_EQ(absl::Nanoseconds(1) / 2, absl::Seconds(0.375e-9)); EXPECT_EQ(absl::Nanoseconds(1) / 2, absl::Seconds(0.500e-9)); EXPECT_EQ(absl::Nanoseconds(3) / 4, absl::Seconds(0.625e-9)); EXPECT_EQ(absl::Nanoseconds(3) / 4, absl::Seconds(0.750e-9)); EXPECT_EQ(absl::Nanoseconds(1), absl::Seconds(0.875e-9)); EXPECT_EQ(absl::Nanoseconds(1), absl::Seconds(1.000e-9)); EXPECT_EQ(absl::ZeroDuration(), absl::Seconds(std::nextafter(-0.125e-9, 0))); EXPECT_EQ(-absl::Nanoseconds(1) / 4, absl::Seconds(-0.125e-9)); EXPECT_EQ(-absl::Nanoseconds(1) / 4, absl::Seconds(-0.250e-9)); EXPECT_EQ(-absl::Nanoseconds(1) / 2, absl::Seconds(-0.375e-9)); EXPECT_EQ(-absl::Nanoseconds(1) / 2, absl::Seconds(-0.500e-9)); EXPECT_EQ(-absl::Nanoseconds(3) / 4, absl::Seconds(-0.625e-9)); EXPECT_EQ(-absl::Nanoseconds(3) / 4, absl::Seconds(-0.750e-9)); EXPECT_EQ(-absl::Nanoseconds(1), absl::Seconds(-0.875e-9)); EXPECT_EQ(-absl::Nanoseconds(1), absl::Seconds(-1.000e-9)); timespec ts; ts.tv_sec = 0; ts.tv_nsec = 0; EXPECT_THAT(ToTimespec(absl::Nanoseconds(0)), TimespecMatcher(ts)); EXPECT_THAT(ToTimespec(absl::Nanoseconds(1) / 4), TimespecMatcher(ts)); EXPECT_THAT(ToTimespec(absl::Nanoseconds(2) / 4), TimespecMatcher(ts)); EXPECT_THAT(ToTimespec(absl::Nanoseconds(3) / 4), TimespecMatcher(ts)); ts.tv_nsec = 1; EXPECT_THAT(ToTimespec(absl::Nanoseconds(4) / 4), TimespecMatcher(ts)); EXPECT_THAT(ToTimespec(absl::Nanoseconds(5) / 4), TimespecMatcher(ts)); EXPECT_THAT(ToTimespec(absl::Nanoseconds(6) / 4), TimespecMatcher(ts)); EXPECT_THAT(ToTimespec(absl::Nanoseconds(7) / 4), TimespecMatcher(ts)); ts.tv_nsec = 2; EXPECT_THAT(ToTimespec(absl::Nanoseconds(8) / 4), TimespecMatcher(ts)); timeval tv; tv.tv_sec = 0; tv.tv_usec = 0; EXPECT_THAT(ToTimeval(absl::Nanoseconds(0)), TimevalMatcher(tv)); EXPECT_THAT(ToTimeval(absl::Nanoseconds(999)), TimevalMatcher(tv)); tv.tv_usec = 1; EXPECT_THAT(ToTimeval(absl::Nanoseconds(1000)), TimevalMatcher(tv)); EXPECT_THAT(ToTimeval(absl::Nanoseconds(1999)), TimevalMatcher(tv)); tv.tv_usec = 2; EXPECT_THAT(ToTimeval(absl::Nanoseconds(2000)), TimevalMatcher(tv)); } void VerifyApproxSameAsMul(double time_as_seconds, int* const misses) { auto direct_seconds = absl::Seconds(time_as_seconds); auto mul_by_one_second = time_as_seconds * absl::Seconds(1); if (absl::AbsDuration(direct_seconds - mul_by_one_second) > absl::time_internal::MakeDuration(0, 1u)) { if (*misses > 10) return; ASSERT_LE(++(*misses), 10) << "Too many errors, not reporting more."; EXPECT_EQ(direct_seconds, mul_by_one_second) << "given double time_as_seconds = " << std::setprecision(17) << time_as_seconds; } } TEST(Duration, ToDoubleSecondsCheckEdgeCases) { #if (defined(__i386__) || defined(_M_IX86)) && FLT_EVAL_METHOD != 0 GTEST_SKIP() << "Skipping the test because we detected x87 floating-point semantics"; #endif constexpr uint32_t kTicksPerSecond = absl::time_internal::kTicksPerSecond; constexpr auto duration_tick = absl::time_internal::MakeDuration(0, 1u); int misses = 0; for (int64_t seconds = 0; seconds < 99; ++seconds) { uint32_t tick_vals[] = {0, +999, +999999, +999999999, kTicksPerSecond - 1, 0, 1000, 1000000, 1000000000, kTicksPerSecond, 1, 1001, 1000001, 1000000001, kTicksPerSecond + 1, 2, 1002, 1000002, 1000000002, kTicksPerSecond + 2, 3, 1003, 1000003, 1000000003, kTicksPerSecond + 3, 4, 1004, 1000004, 1000000004, kTicksPerSecond + 4, 5, 6, 7, 8, 9}; for (uint32_t ticks : tick_vals) { absl::Duration s_plus_t = absl::Seconds(seconds) + ticks * duration_tick; for (absl::Duration d : {s_plus_t, -s_plus_t}) { absl::Duration after_d = d + duration_tick; EXPECT_NE(d, after_d); EXPECT_EQ(after_d - d, duration_tick); double low_edge = ToDoubleSeconds(d); EXPECT_EQ(d, absl::Seconds(low_edge)); double high_edge = ToDoubleSeconds(after_d); EXPECT_EQ(after_d, absl::Seconds(high_edge)); for (;;) { double midpoint = low_edge + (high_edge - low_edge) / 2; if (midpoint == low_edge || midpoint == high_edge) break; absl::Duration mid_duration = absl::Seconds(midpoint); if (mid_duration == d) { low_edge = midpoint; } else { EXPECT_EQ(mid_duration, after_d); high_edge = midpoint; } } VerifyApproxSameAsMul(low_edge, &misses); VerifyApproxSameAsMul(high_edge, &misses); } } } } TEST(Duration, ToDoubleSecondsCheckRandom) { std::random_device rd; std::seed_seq seed({rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd()}); std::mt19937_64 gen(seed); std::uniform_real_distribution<double> uniform(std::log(0.125e-9), std::log(9.223377e+18)); int misses = 0; for (int i = 0; i < 1000000; ++i) { double d = std::exp(uniform(gen)); VerifyApproxSameAsMul(d, &misses); VerifyApproxSameAsMul(-d, &misses); } } TEST(Duration, ConversionSaturation) { absl::Duration d; const auto max_timeval_sec = std::numeric_limits<decltype(timeval::tv_sec)>::max(); const auto min_timeval_sec = std::numeric_limits<decltype(timeval::tv_sec)>::min(); timeval tv; tv.tv_sec = max_timeval_sec; tv.tv_usec = 999998; d = absl::DurationFromTimeval(tv); tv = ToTimeval(d); EXPECT_EQ(max_timeval_sec, tv.tv_sec); EXPECT_EQ(999998, tv.tv_usec); d += absl::Microseconds(1); tv = ToTimeval(d); EXPECT_EQ(max_timeval_sec, tv.tv_sec); EXPECT_EQ(999999, tv.tv_usec); d += absl::Microseconds(1); tv = ToTimeval(d); EXPECT_EQ(max_timeval_sec, tv.tv_sec); EXPECT_EQ(999999, tv.tv_usec); tv.tv_sec = min_timeval_sec; tv.tv_usec = 1; d = absl::DurationFromTimeval(tv); tv = ToTimeval(d); EXPECT_EQ(min_timeval_sec, tv.tv_sec); EXPECT_EQ(1, tv.tv_usec); d -= absl::Microseconds(1); tv = ToTimeval(d); EXPECT_EQ(min_timeval_sec, tv.tv_sec); EXPECT_EQ(0, tv.tv_usec); d -= absl::Microseconds(1); tv = ToTimeval(d); EXPECT_EQ(min_timeval_sec, tv.tv_sec); EXPECT_EQ(0, tv.tv_usec); const auto max_timespec_sec = std::numeric_limits<decltype(timespec::tv_sec)>::max(); const auto min_timespec_sec = std::numeric_limits<decltype(timespec::tv_sec)>::min(); timespec ts; ts.tv_sec = max_timespec_sec; ts.tv_nsec = 999999998; d = absl::DurationFromTimespec(ts); ts = absl::ToTimespec(d); EXPECT_EQ(max_timespec_sec, ts.tv_sec); EXPECT_EQ(999999998, ts.tv_nsec); d += absl::Nanoseconds(1); ts = absl::ToTimespec(d); EXPECT_EQ(max_timespec_sec, ts.tv_sec); EXPECT_EQ(999999999, ts.tv_nsec); d += absl::Nanoseconds(1); ts = absl::ToTimespec(d); EXPECT_EQ(max_timespec_sec, ts.tv_sec); EXPECT_EQ(999999999, ts.tv_nsec); ts.tv_sec = min_timespec_sec; ts.tv_nsec = 1; d = absl::DurationFromTimespec(ts); ts = absl::ToTimespec(d); EXPECT_EQ(min_timespec_sec, ts.tv_sec); EXPECT_EQ(1, ts.tv_nsec); d -= absl::Nanoseconds(1); ts = absl::ToTimespec(d); EXPECT_EQ(min_timespec_sec, ts.tv_sec); EXPECT_EQ(0, ts.tv_nsec); d -= absl::Nanoseconds(1); ts = absl::ToTimespec(d); EXPECT_EQ(min_timespec_sec, ts.tv_sec); EXPECT_EQ(0, ts.tv_nsec); } TEST(Duration, FormatDuration) { EXPECT_EQ("72h3m0.5s", absl::FormatDuration(absl::Hours(72) + absl::Minutes(3) + absl::Milliseconds(500))); EXPECT_EQ("2540400h10m10s", absl::FormatDuration(absl::Hours(2540400) + absl::Minutes(10) + absl::Seconds(10))); EXPECT_EQ("0", absl::FormatDuration(absl::ZeroDuration())); EXPECT_EQ("0", absl::FormatDuration(absl::Seconds(0))); EXPECT_EQ("0", absl::FormatDuration(absl::Nanoseconds(0))); EXPECT_EQ("1ns", absl::FormatDuration(absl::Nanoseconds(1))); EXPECT_EQ("1us", absl::FormatDuration(absl::Microseconds(1))); EXPECT_EQ("1ms", absl::FormatDuration(absl::Milliseconds(1))); EXPECT_EQ("1s", absl::FormatDuration(absl::Seconds(1))); EXPECT_EQ("1m", absl::FormatDuration(absl::Minutes(1))); EXPECT_EQ("1h", absl::FormatDuration(absl::Hours(1))); EXPECT_EQ("1h1m", absl::FormatDuration(absl::Hours(1) + absl::Minutes(1))); EXPECT_EQ("1h1s", absl::FormatDuration(absl::Hours(1) + absl::Seconds(1))); EXPECT_EQ("1m1s", absl::FormatDuration(absl::Minutes(1) + absl::Seconds(1))); EXPECT_EQ("1h0.25s", absl::FormatDuration(absl::Hours(1) + absl::Milliseconds(250))); EXPECT_EQ("1m0.25s", absl::FormatDuration(absl::Minutes(1) + absl::Milliseconds(250))); EXPECT_EQ("1h1m0.25s", absl::FormatDuration(absl::Hours(1) + absl::Minutes(1) + absl::Milliseconds(250))); EXPECT_EQ("1h0.0005s", absl::FormatDuration(absl::Hours(1) + absl::Microseconds(500))); EXPECT_EQ("1h0.0000005s", absl::FormatDuration(absl::Hours(1) + absl::Nanoseconds(500))); EXPECT_EQ("1.5ns", absl::FormatDuration(absl::Nanoseconds(1) + absl::Nanoseconds(1) / 2)); EXPECT_EQ("1.25ns", absl::FormatDuration(absl::Nanoseconds(1) + absl::Nanoseconds(1) / 4)); EXPECT_EQ("1ns", absl::FormatDuration(absl::Nanoseconds(1) + absl::Nanoseconds(1) / 9)); EXPECT_EQ("1.2us", absl::FormatDuration(absl::Microseconds(1) + absl::Nanoseconds(200))); EXPECT_EQ("1.2ms", absl::FormatDuration(absl::Milliseconds(1) + absl::Microseconds(200))); EXPECT_EQ("1.0002ms", absl::FormatDuration(absl::Milliseconds(1) + absl::Nanoseconds(200))); EXPECT_EQ("1.00001ms", absl::FormatDuration(absl::Milliseconds(1) + absl::Nanoseconds(10))); EXPECT_EQ("1.000001ms", absl::FormatDuration(absl::Milliseconds(1) + absl::Nanoseconds(1))); EXPECT_EQ("-1ns", absl::FormatDuration(absl::Nanoseconds(-1))); EXPECT_EQ("-1us", absl::FormatDuration(absl::Microseconds(-1))); EXPECT_EQ("-1ms", absl::FormatDuration(absl::Milliseconds(-1))); EXPECT_EQ("-1s", absl::FormatDuration(absl::Seconds(-1))); EXPECT_EQ("-1m", absl::FormatDuration(absl::Minutes(-1))); EXPECT_EQ("-1h", absl::FormatDuration(absl::Hours(-1))); EXPECT_EQ("-1h1m", absl::FormatDuration(-(absl::Hours(1) + absl::Minutes(1)))); EXPECT_EQ("-1h1s", absl::FormatDuration(-(absl::Hours(1) + absl::Seconds(1)))); EXPECT_EQ("-1m1s", absl::FormatDuration(-(absl::Minutes(1) + absl::Seconds(1)))); EXPECT_EQ("-1ns", absl::FormatDuration(absl::Nanoseconds(-1))); EXPECT_EQ("-1.2us", absl::FormatDuration( -(absl::Microseconds(1) + absl::Nanoseconds(200)))); EXPECT_EQ("-1.2ms", absl::FormatDuration( -(absl::Milliseconds(1) + absl::Microseconds(200)))); EXPECT_EQ("-1.0002ms", absl::FormatDuration(-(absl::Milliseconds(1) + absl::Nanoseconds(200)))); EXPECT_EQ("-1.00001ms", absl::FormatDuration(-(absl::Milliseconds(1) + absl::Nanoseconds(10)))); EXPECT_EQ("-1.000001ms", absl::FormatDuration(-(absl::Milliseconds(1) + absl::Nanoseconds(1)))); const absl::Duration qns = absl::Nanoseconds(1) / 4; const absl::Duration max_dur = absl::Seconds(kint64max) + (absl::Seconds(1) - qns); const absl::Duration min_dur = absl::Seconds(kint64min); EXPECT_EQ("0.25ns", absl::FormatDuration(qns)); EXPECT_EQ("-0.25ns", absl::FormatDuration(-qns)); EXPECT_EQ("2562047788015215h30m7.99999999975s", absl::FormatDuration(max_dur)); EXPECT_EQ("-2562047788015215h30m8s", absl::FormatDuration(min_dur)); EXPECT_EQ("55.00000000025s", absl::FormatDuration(absl::Seconds(55) + qns)); EXPECT_EQ("55.00000025ms", absl::FormatDuration(absl::Milliseconds(55) + qns)); EXPECT_EQ("55.00025us", absl::FormatDuration(absl::Microseconds(55) + qns)); EXPECT_EQ("55.25ns", absl::FormatDuration(absl::Nanoseconds(55) + qns)); EXPECT_EQ("inf", absl::FormatDuration(absl::InfiniteDuration())); EXPECT_EQ("-inf", absl::FormatDuration(-absl::InfiniteDuration())); const absl::Duration huge_range = ApproxYears(100000000000); EXPECT_EQ("876000000000000h", absl::FormatDuration(huge_range)); EXPECT_EQ("-876000000000000h", absl::FormatDuration(-huge_range)); EXPECT_EQ("876000000000000h0.999999999s", absl::FormatDuration(huge_range + (absl::Seconds(1) - absl::Nanoseconds(1)))); EXPECT_EQ("876000000000000h0.9999999995s", absl::FormatDuration( huge_range + (absl::Seconds(1) - absl::Nanoseconds(1) / 2))); EXPECT_EQ("876000000000000h0.99999999975s", absl::FormatDuration( huge_range + (absl::Seconds(1) - absl::Nanoseconds(1) / 4))); EXPECT_EQ("-876000000000000h0.999999999s", absl::FormatDuration(-huge_range - (absl::Seconds(1) - absl::Nanoseconds(1)))); EXPECT_EQ("-876000000000000h0.9999999995s", absl::FormatDuration( -huge_range - (absl::Seconds(1) - absl::Nanoseconds(1) / 2))); EXPECT_EQ("-876000000000000h0.99999999975s", absl::FormatDuration( -huge_range - (absl::Seconds(1) - absl::Nanoseconds(1) / 4))); } TEST(Duration, ParseDuration) { absl::Duration d; EXPECT_TRUE(absl::ParseDuration("0", &d)); EXPECT_EQ(absl::ZeroDuration(), d); EXPECT_TRUE(absl::ParseDuration("+0", &d)); EXPECT_EQ(absl::ZeroDuration(), d); EXPECT_TRUE(absl::ParseDuration("-0", &d)); EXPECT_EQ(absl::ZeroDuration(), d); EXPECT_TRUE(absl::ParseDuration("inf", &d)); EXPECT_EQ(absl::InfiniteDuration(), d); EXPECT_TRUE(absl::ParseDuration("+inf", &d)); EXPECT_EQ(absl::InfiniteDuration(), d); EXPECT_TRUE(absl::ParseDuration("-inf", &d)); EXPECT_EQ(-absl::InfiniteDuration(), d); EXPECT_FALSE(absl::ParseDuration("infBlah", &d)); EXPECT_FALSE(absl::ParseDuration("", &d)); EXPECT_FALSE(absl::ParseDuration("0.0", &d)); EXPECT_FALSE(absl::ParseDuration(".0", &d)); EXPECT_FALSE(absl::ParseDuration(".", &d)); EXPECT_FALSE(absl::ParseDuration("01", &d)); EXPECT_FALSE(absl::ParseDuration("1", &d)); EXPECT_FALSE(absl::ParseDuration("-1", &d)); EXPECT_FALSE(absl::ParseDuration("2", &d)); EXPECT_FALSE(absl::ParseDuration("2 s", &d)); EXPECT_FALSE(absl::ParseDuration(".s", &d)); EXPECT_FALSE(absl::ParseDuration("-.s", &d)); EXPECT_FALSE(absl::ParseDuration("s", &d)); EXPECT_FALSE(absl::ParseDuration(" 2s", &d)); EXPECT_FALSE(absl::ParseDuration("2s ", &d)); EXPECT_FALSE(absl::ParseDuration(" 2s ", &d)); EXPECT_FALSE(absl::ParseDuration("2mt", &d)); EXPECT_FALSE(absl::ParseDuration("1e3s", &d)); EXPECT_TRUE(absl::ParseDuration("1ns", &d)); EXPECT_EQ(absl::Nanoseconds(1), d); EXPECT_TRUE(absl::ParseDuration("1us", &d)); EXPECT_EQ(absl::Microseconds(1), d); EXPECT_TRUE(absl::ParseDuration("1ms", &d)); EXPECT_EQ(absl::Milliseconds(1), d); EXPECT_TRUE(absl::ParseDuration("1s", &d)); EXPECT_EQ(absl::Seconds(1), d); EXPECT_TRUE(absl::ParseDuration("2m", &d)); EXPECT_EQ(absl::Minutes(2), d); EXPECT_TRUE(absl::ParseDuration("2h", &d)); EXPECT_EQ(absl::Hours(2), d); EXPECT_TRUE(absl::ParseDuration("9223372036854775807us", &d)); EXPECT_EQ(absl::Microseconds(9223372036854775807), d); EXPECT_TRUE(absl::ParseDuration("-9223372036854775807us", &d)); EXPECT_EQ(absl::Microseconds(-9223372036854775807), d); EXPECT_TRUE(absl::ParseDuration("2h3m4s", &d)); EXPECT_EQ(absl::Hours(2) + absl::Minutes(3) + absl::Seconds(4), d); EXPECT_TRUE(absl::ParseDuration("3m4s5us", &d)); EXPECT_EQ(absl::Minutes(3) + absl::Seconds(4) + absl::Microseconds(5), d); EXPECT_TRUE(absl::ParseDuration("2h3m4s5ms6us7ns", &d)); EXPECT_EQ(absl::Hours(2) + absl::Minutes(3) + absl::Seconds(4) + absl::Milliseconds(5) + absl::Microseconds(6) + absl::Nanoseconds(7), d); EXPECT_TRUE(absl::ParseDuration("2us3m4s5h", &d)); EXPECT_EQ(absl::Hours(5) + absl::Minutes(3) + absl::Seconds(4) + absl::Microseconds(2), d); EXPECT_TRUE(absl::ParseDuration("1.5ns", &d)); EXPECT_EQ(1.5 * absl::Nanoseconds(1), d); EXPECT_TRUE(absl::ParseDuration("1.5us", &d)); EXPECT_EQ(1.5 * absl::Microseconds(1), d); EXPECT_TRUE(absl::ParseDuration("1.5ms", &d)); EXPECT_EQ(1.5 * absl::Milliseconds(1), d); EXPECT_TRUE(absl::ParseDuration("1.5s", &d)); EXPECT_EQ(1.5 * absl::Seconds(1), d); EXPECT_TRUE(absl::ParseDuration("1.5m", &d)); EXPECT_EQ(1.5 * absl::Minutes(1), d); EXPECT_TRUE(absl::ParseDuration("1.5h", &d)); EXPECT_EQ(1.5 * absl::Hours(1), d); EXPECT_TRUE(absl::ParseDuration("0.4294967295s", &d)); EXPECT_EQ(absl::Nanoseconds(429496729) + absl::Nanoseconds(1) / 2, d); EXPECT_TRUE(absl::ParseDuration("0.429496729501234567890123456789s", &d)); EXPECT_EQ(absl::Nanoseconds(429496729) + absl::Nanoseconds(1) / 2, d); EXPECT_TRUE(absl::ParseDuration("-1s", &d)); EXPECT_EQ(absl::Seconds(-1), d); EXPECT_TRUE(absl::ParseDuration("-1m", &d)); EXPECT_EQ(absl::Minutes(-1), d); EXPECT_TRUE(absl::ParseDuration("-1h", &d)); EXPECT_EQ(absl::Hours(-1), d); EXPECT_TRUE(absl::ParseDuration("-1h2s", &d)); EXPECT_EQ(-(absl::Hours(1) + absl::Seconds(2)), d); EXPECT_FALSE(absl::ParseDuration("1h-2s", &d)); EXPECT_FALSE(absl::ParseDuration("-1h-2s", &d)); EXPECT_FALSE(absl::ParseDuration("-1h -2s", &d)); } TEST(Duration, FormatParseRoundTrip) { #define TEST_PARSE_ROUNDTRIP(d) \ do { \ std::string s = absl::FormatDuration(d); \ absl::Duration dur; \ EXPECT_TRUE(absl::ParseDuration(s, &dur)); \ EXPECT_EQ(d, dur); \ } while (0) TEST_PARSE_ROUNDTRIP(absl::Nanoseconds(1)); TEST_PARSE_ROUNDTRIP(absl::Microseconds(1)); TEST_PARSE_ROUNDTRIP(absl::Milliseconds(1)); TEST_PARSE_ROUNDTRIP(absl::Seconds(1)); TEST_PARSE_ROUNDTRIP(absl::Minutes(1)); TEST_PARSE_ROUNDTRIP(absl::Hours(1)); TEST_PARSE_ROUNDTRIP(absl::Hours(1) + absl::Nanoseconds(2)); TEST_PARSE_ROUNDTRIP(absl::Nanoseconds(-1)); TEST_PARSE_ROUNDTRIP(absl::Microseconds(-1)); TEST_PARSE_ROUNDTRIP(absl::Milliseconds(-1)); TEST_PARSE_ROUNDTRIP(absl::Seconds(-1)); TEST_PARSE_ROUNDTRIP(absl::Minutes(-1)); TEST_PARSE_ROUNDTRIP(absl::Hours(-1)); TEST_PARSE_ROUNDTRIP(absl::Hours(-1) + absl::Nanoseconds(2)); TEST_PARSE_ROUNDTRIP(absl::Hours(1) + absl::Nanoseconds(-2)); TEST_PARSE_ROUNDTRIP(absl::Hours(-1) + absl::Nanoseconds(-2)); TEST_PARSE_ROUNDTRIP(absl::Nanoseconds(1) + absl::Nanoseconds(1) / 4); const absl::Duration huge_range = ApproxYears(100000000000); TEST_PARSE_ROUNDTRIP(huge_range); TEST_PARSE_ROUNDTRIP(huge_range + (absl::Seconds(1) - absl::Nanoseconds(1))); #undef TEST_PARSE_ROUNDTRIP } TEST(Duration, AbslStringify) { absl::Duration d = absl::Seconds(1); EXPECT_EQ(absl::StrFormat("%v", d), absl::FormatDuration(d)); } TEST(Duration, NoPadding) { using NoPadding = std::array<uint32_t, 3>; EXPECT_EQ(sizeof(NoPadding), sizeof(absl::Duration)); EXPECT_EQ(alignof(NoPadding), alignof(absl::Duration)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/duration.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/duration_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
dc717713-4129-44c3-8efc-bf49df16771f
cpp
abseil/abseil-cpp
civil_time
absl/time/civil_time.cc
absl/time/internal/cctz/src/civil_time_test.cc
#include "absl/time/civil_time.h" #include <cstdlib> #include <ostream> #include <string> #include "absl/strings/str_cat.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { inline civil_year_t NormalizeYear(civil_year_t year) { return 2400 + year % 400; } std::string FormatYearAnd(string_view fmt, CivilSecond cs) { const CivilSecond ncs(NormalizeYear(cs.year()), cs.month(), cs.day(), cs.hour(), cs.minute(), cs.second()); const TimeZone utc = UTCTimeZone(); return StrCat(cs.year(), FormatTime(fmt, FromCivil(ncs, utc), utc)); } template <typename CivilT> bool ParseYearAnd(string_view fmt, string_view s, CivilT* c) { const std::string ss = std::string(s); const char* const np = ss.c_str(); char* endp; errno = 0; const civil_year_t y = std::strtoll(np, &endp, 10); if (endp == np || errno == ERANGE) return false; const std::string norm = StrCat(NormalizeYear(y), endp); const TimeZone utc = UTCTimeZone(); Time t; if (ParseTime(StrCat("%Y", fmt), norm, utc, &t, nullptr)) { const auto cs = ToCivilSecond(t, utc); *c = CivilT(y, cs.month(), cs.day(), cs.hour(), cs.minute(), cs.second()); return true; } return false; } template <typename CivilT1, typename CivilT2> bool ParseAs(string_view s, CivilT2* c) { CivilT1 t1; if (ParseCivilTime(s, &t1)) { *c = CivilT2(t1); return true; } return false; } template <typename CivilT> bool ParseLenient(string_view s, CivilT* c) { if (ParseCivilTime(s, c)) return true; if (ParseAs<CivilDay>(s, c)) return true; if (ParseAs<CivilSecond>(s, c)) return true; if (ParseAs<CivilHour>(s, c)) return true; if (ParseAs<CivilMonth>(s, c)) return true; if (ParseAs<CivilMinute>(s, c)) return true; if (ParseAs<CivilYear>(s, c)) return true; return false; } } std::string FormatCivilTime(CivilSecond c) { return FormatYearAnd("-%m-%d%ET%H:%M:%S", c); } std::string FormatCivilTime(CivilMinute c) { return FormatYearAnd("-%m-%d%ET%H:%M", c); } std::string FormatCivilTime(CivilHour c) { return FormatYearAnd("-%m-%d%ET%H", c); } std::string FormatCivilTime(CivilDay c) { return FormatYearAnd("-%m-%d", c); } std::string FormatCivilTime(CivilMonth c) { return FormatYearAnd("-%m", c); } std::string FormatCivilTime(CivilYear c) { return FormatYearAnd("", c); } bool ParseCivilTime(string_view s, CivilSecond* c) { return ParseYearAnd("-%m-%d%ET%H:%M:%S", s, c); } bool ParseCivilTime(string_view s, CivilMinute* c) { return ParseYearAnd("-%m-%d%ET%H:%M", s, c); } bool ParseCivilTime(string_view s, CivilHour* c) { return ParseYearAnd("-%m-%d%ET%H", s, c); } bool ParseCivilTime(string_view s, CivilDay* c) { return ParseYearAnd("-%m-%d", s, c); } bool ParseCivilTime(string_view s, CivilMonth* c) { return ParseYearAnd("-%m", s, c); } bool ParseCivilTime(string_view s, CivilYear* c) { return ParseYearAnd("", s, c); } bool ParseLenientCivilTime(string_view s, CivilSecond* c) { return ParseLenient(s, c); } bool ParseLenientCivilTime(string_view s, CivilMinute* c) { return ParseLenient(s, c); } bool ParseLenientCivilTime(string_view s, CivilHour* c) { return ParseLenient(s, c); } bool ParseLenientCivilTime(string_view s, CivilDay* c) { return ParseLenient(s, c); } bool ParseLenientCivilTime(string_view s, CivilMonth* c) { return ParseLenient(s, c); } bool ParseLenientCivilTime(string_view s, CivilYear* c) { return ParseLenient(s, c); } namespace time_internal { std::ostream& operator<<(std::ostream& os, CivilYear y) { return os << FormatCivilTime(y); } std::ostream& operator<<(std::ostream& os, CivilMonth m) { return os << FormatCivilTime(m); } std::ostream& operator<<(std::ostream& os, CivilDay d) { return os << FormatCivilTime(d); } std::ostream& operator<<(std::ostream& os, CivilHour h) { return os << FormatCivilTime(h); } std::ostream& operator<<(std::ostream& os, CivilMinute m) { return os << FormatCivilTime(m); } std::ostream& operator<<(std::ostream& os, CivilSecond s) { return os << FormatCivilTime(s); } bool AbslParseFlag(string_view s, CivilSecond* c, std::string*) { return ParseLenientCivilTime(s, c); } bool AbslParseFlag(string_view s, CivilMinute* c, std::string*) { return ParseLenientCivilTime(s, c); } bool AbslParseFlag(string_view s, CivilHour* c, std::string*) { return ParseLenientCivilTime(s, c); } bool AbslParseFlag(string_view s, CivilDay* c, std::string*) { return ParseLenientCivilTime(s, c); } bool AbslParseFlag(string_view s, CivilMonth* c, std::string*) { return ParseLenientCivilTime(s, c); } bool AbslParseFlag(string_view s, CivilYear* c, std::string*) { return ParseLenientCivilTime(s, c); } std::string AbslUnparseFlag(CivilSecond c) { return FormatCivilTime(c); } std::string AbslUnparseFlag(CivilMinute c) { return FormatCivilTime(c); } std::string AbslUnparseFlag(CivilHour c) { return FormatCivilTime(c); } std::string AbslUnparseFlag(CivilDay c) { return FormatCivilTime(c); } std::string AbslUnparseFlag(CivilMonth c) { return FormatCivilTime(c); } std::string AbslUnparseFlag(CivilYear c) { return FormatCivilTime(c); } } ABSL_NAMESPACE_END }
#include "absl/time/internal/cctz/include/cctz/civil_time.h" #include <iomanip> #include <limits> #include <sstream> #include <string> #include <type_traits> #include "gtest/gtest.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace time_internal { namespace cctz { namespace { template <typename T> std::string Format(const T& t) { std::stringstream ss; ss << t; return ss.str(); } } #if __cpp_constexpr >= 201304 || (defined(_MSC_VER) && _MSC_VER >= 1910) TEST(CivilTime, Normal) { constexpr civil_second css(2016, 1, 28, 17, 14, 12); static_assert(css.second() == 12, "Normal.second"); constexpr civil_minute cmm(2016, 1, 28, 17, 14); static_assert(cmm.minute() == 14, "Normal.minute"); constexpr civil_hour chh(2016, 1, 28, 17); static_assert(chh.hour() == 17, "Normal.hour"); constexpr civil_day cd(2016, 1, 28); static_assert(cd.day() == 28, "Normal.day"); constexpr civil_month cm(2016, 1); static_assert(cm.month() == 1, "Normal.month"); constexpr civil_year cy(2016); static_assert(cy.year() == 2016, "Normal.year"); } TEST(CivilTime, Conversion) { constexpr civil_year cy(2016); static_assert(cy.year() == 2016, "Conversion.year"); constexpr civil_month cm(cy); static_assert(cm.month() == 1, "Conversion.month"); constexpr civil_day cd(cm); static_assert(cd.day() == 1, "Conversion.day"); constexpr civil_hour chh(cd); static_assert(chh.hour() == 0, "Conversion.hour"); constexpr civil_minute cmm(chh); static_assert(cmm.minute() == 0, "Conversion.minute"); constexpr civil_second css(cmm); static_assert(css.second() == 0, "Conversion.second"); } TEST(CivilTime, Normalized) { constexpr civil_second cs(2016, 1, 28, 17, 14, 12); static_assert(cs.year() == 2016, "Normalized.year"); static_assert(cs.month() == 1, "Normalized.month"); static_assert(cs.day() == 28, "Normalized.day"); static_assert(cs.hour() == 17, "Normalized.hour"); static_assert(cs.minute() == 14, "Normalized.minute"); static_assert(cs.second() == 12, "Normalized.second"); } TEST(CivilTime, SecondOverflow) { constexpr civil_second cs(2016, 1, 28, 17, 14, 121); static_assert(cs.year() == 2016, "SecondOverflow.year"); static_assert(cs.month() == 1, "SecondOverflow.month"); static_assert(cs.day() == 28, "SecondOverflow.day"); static_assert(cs.hour() == 17, "SecondOverflow.hour"); static_assert(cs.minute() == 16, "SecondOverflow.minute"); static_assert(cs.second() == 1, "SecondOverflow.second"); } TEST(CivilTime, SecondUnderflow) { constexpr civil_second cs(2016, 1, 28, 17, 14, -121); static_assert(cs.year() == 2016, "SecondUnderflow.year"); static_assert(cs.month() == 1, "SecondUnderflow.month"); static_assert(cs.day() == 28, "SecondUnderflow.day"); static_assert(cs.hour() == 17, "SecondUnderflow.hour"); static_assert(cs.minute() == 11, "SecondUnderflow.minute"); static_assert(cs.second() == 59, "SecondUnderflow.second"); } TEST(CivilTime, MinuteOverflow) { constexpr civil_second cs(2016, 1, 28, 17, 121, 12); static_assert(cs.year() == 2016, "MinuteOverflow.year"); static_assert(cs.month() == 1, "MinuteOverflow.month"); static_assert(cs.day() == 28, "MinuteOverflow.day"); static_assert(cs.hour() == 19, "MinuteOverflow.hour"); static_assert(cs.minute() == 1, "MinuteOverflow.minute"); static_assert(cs.second() == 12, "MinuteOverflow.second"); } TEST(CivilTime, MinuteUnderflow) { constexpr civil_second cs(2016, 1, 28, 17, -121, 12); static_assert(cs.year() == 2016, "MinuteUnderflow.year"); static_assert(cs.month() == 1, "MinuteUnderflow.month"); static_assert(cs.day() == 28, "MinuteUnderflow.day"); static_assert(cs.hour() == 14, "MinuteUnderflow.hour"); static_assert(cs.minute() == 59, "MinuteUnderflow.minute"); static_assert(cs.second() == 12, "MinuteUnderflow.second"); } TEST(CivilTime, HourOverflow) { constexpr civil_second cs(2016, 1, 28, 49, 14, 12); static_assert(cs.year() == 2016, "HourOverflow.year"); static_assert(cs.month() == 1, "HourOverflow.month"); static_assert(cs.day() == 30, "HourOverflow.day"); static_assert(cs.hour() == 1, "HourOverflow.hour"); static_assert(cs.minute() == 14, "HourOverflow.minute"); static_assert(cs.second() == 12, "HourOverflow.second"); } TEST(CivilTime, HourUnderflow) { constexpr civil_second cs(2016, 1, 28, -49, 14, 12); static_assert(cs.year() == 2016, "HourUnderflow.year"); static_assert(cs.month() == 1, "HourUnderflow.month"); static_assert(cs.day() == 25, "HourUnderflow.day"); static_assert(cs.hour() == 23, "HourUnderflow.hour"); static_assert(cs.minute() == 14, "HourUnderflow.minute"); static_assert(cs.second() == 12, "HourUnderflow.second"); } TEST(CivilTime, MonthOverflow) { constexpr civil_second cs(2016, 25, 28, 17, 14, 12); static_assert(cs.year() == 2018, "MonthOverflow.year"); static_assert(cs.month() == 1, "MonthOverflow.month"); static_assert(cs.day() == 28, "MonthOverflow.day"); static_assert(cs.hour() == 17, "MonthOverflow.hour"); static_assert(cs.minute() == 14, "MonthOverflow.minute"); static_assert(cs.second() == 12, "MonthOverflow.second"); } TEST(CivilTime, MonthUnderflow) { constexpr civil_second cs(2016, -25, 28, 17, 14, 12); static_assert(cs.year() == 2013, "MonthUnderflow.year"); static_assert(cs.month() == 11, "MonthUnderflow.month"); static_assert(cs.day() == 28, "MonthUnderflow.day"); static_assert(cs.hour() == 17, "MonthUnderflow.hour"); static_assert(cs.minute() == 14, "MonthUnderflow.minute"); static_assert(cs.second() == 12, "MonthUnderflow.second"); } TEST(CivilTime, C4Overflow) { constexpr civil_second cs(2016, 1, 292195, 17, 14, 12); static_assert(cs.year() == 2816, "C4Overflow.year"); static_assert(cs.month() == 1, "C4Overflow.month"); static_assert(cs.day() == 1, "C4Overflow.day"); static_assert(cs.hour() == 17, "C4Overflow.hour"); static_assert(cs.minute() == 14, "C4Overflow.minute"); static_assert(cs.second() == 12, "C4Overflow.second"); } TEST(CivilTime, C4Underflow) { constexpr civil_second cs(2016, 1, -292195, 17, 14, 12); static_assert(cs.year() == 1215, "C4Underflow.year"); static_assert(cs.month() == 12, "C4Underflow.month"); static_assert(cs.day() == 30, "C4Underflow.day"); static_assert(cs.hour() == 17, "C4Underflow.hour"); static_assert(cs.minute() == 14, "C4Underflow.minute"); static_assert(cs.second() == 12, "C4Underflow.second"); } TEST(CivilTime, MixedNormalization) { constexpr civil_second cs(2016, -42, 122, 99, -147, 4949); static_assert(cs.year() == 2012, "MixedNormalization.year"); static_assert(cs.month() == 10, "MixedNormalization.month"); static_assert(cs.day() == 4, "MixedNormalization.day"); static_assert(cs.hour() == 1, "MixedNormalization.hour"); static_assert(cs.minute() == 55, "MixedNormalization.minute"); static_assert(cs.second() == 29, "MixedNormalization.second"); } TEST(CivilTime, Less) { constexpr civil_second cs1(2016, 1, 28, 17, 14, 12); constexpr civil_second cs2(2016, 1, 28, 17, 14, 13); constexpr bool less = cs1 < cs2; static_assert(less, "Less"); } TEST(CivilTime, Addition) { constexpr civil_second cs1(2016, 1, 28, 17, 14, 12); constexpr civil_second cs2 = cs1 + 50; static_assert(cs2.year() == 2016, "Addition.year"); static_assert(cs2.month() == 1, "Addition.month"); static_assert(cs2.day() == 28, "Addition.day"); static_assert(cs2.hour() == 17, "Addition.hour"); static_assert(cs2.minute() == 15, "Addition.minute"); static_assert(cs2.second() == 2, "Addition.second"); } TEST(CivilTime, Subtraction) { constexpr civil_second cs1(2016, 1, 28, 17, 14, 12); constexpr civil_second cs2 = cs1 - 50; static_assert(cs2.year() == 2016, "Subtraction.year"); static_assert(cs2.month() == 1, "Subtraction.month"); static_assert(cs2.day() == 28, "Subtraction.day"); static_assert(cs2.hour() == 17, "Subtraction.hour"); static_assert(cs2.minute() == 13, "Subtraction.minute"); static_assert(cs2.second() == 22, "Subtraction.second"); } TEST(CivilTime, Difference) { constexpr civil_day cd1(2016, 1, 28); constexpr civil_day cd2(2015, 1, 28); constexpr int diff = cd1 - cd2; static_assert(diff == 365, "Difference"); } TEST(CivilTime, ConstructionWithHugeYear) { constexpr civil_hour h(-9223372036854775807, 1, 1, -1); static_assert(h.year() == -9223372036854775807 - 1, "ConstructionWithHugeYear"); static_assert(h.month() == 12, "ConstructionWithHugeYear"); static_assert(h.day() == 31, "ConstructionWithHugeYear"); static_assert(h.hour() == 23, "ConstructionWithHugeYear"); } TEST(CivilTime, DifferenceWithHugeYear) { { constexpr civil_day d1(9223372036854775807, 1, 1); constexpr civil_day d2(9223372036854775807, 12, 31); static_assert(d2 - d1 == 364, "DifferenceWithHugeYear"); } { constexpr civil_day d1(-9223372036854775807 - 1, 1, 1); constexpr civil_day d2(-9223372036854775807 - 1, 12, 31); static_assert(d2 - d1 == 365, "DifferenceWithHugeYear"); } { constexpr civil_day d1(9223372036854775807, 1, 1); constexpr civil_day d2(9198119301927009252, 6, 6); static_assert(d1 - d2 == 9223372036854775807, "DifferenceWithHugeYear"); static_assert((d2 - 1) - d1 == -9223372036854775807 - 1, "DifferenceWithHugeYear"); } { constexpr civil_day d1(-9223372036854775807 - 1, 1, 1); constexpr civil_day d2(-9198119301927009254, 7, 28); static_assert(d2 - d1 == 9223372036854775807, "DifferenceWithHugeYear"); static_assert(d1 - (d2 + 1) == -9223372036854775807 - 1, "DifferenceWithHugeYear"); } { constexpr civil_day d1(-12626367463883278, 9, 3); constexpr civil_day d2(12626367463883277, 3, 28); static_assert(d2 - d1 == 9223372036854775807, "DifferenceWithHugeYear"); static_assert(d1 - (d2 + 1) == -9223372036854775807 - 1, "DifferenceWithHugeYear"); } } TEST(CivilTime, DifferenceNoIntermediateOverflow) { { constexpr civil_second s1(-292277022657, 1, 27, 8, 29 - 1, 52); constexpr civil_second s2(1970, 1, 1, 0, 0 - 1, 0); static_assert(s1 - s2 == -9223372036854775807 - 1, "DifferenceNoIntermediateOverflow"); } { constexpr civil_second s1(292277026596, 12, 4, 15, 30, 7 - 7); constexpr civil_second s2(1970, 1, 1, 0, 0, 0 - 7); static_assert(s1 - s2 == 9223372036854775807, "DifferenceNoIntermediateOverflow"); } } TEST(CivilTime, WeekDay) { constexpr civil_day cd(2016, 1, 28); constexpr weekday wd = get_weekday(cd); static_assert(wd == weekday::thursday, "Weekday"); } TEST(CivilTime, NextWeekDay) { constexpr civil_day cd(2016, 1, 28); constexpr civil_day next = next_weekday(cd, weekday::thursday); static_assert(next.year() == 2016, "NextWeekDay.year"); static_assert(next.month() == 2, "NextWeekDay.month"); static_assert(next.day() == 4, "NextWeekDay.day"); } TEST(CivilTime, PrevWeekDay) { constexpr civil_day cd(2016, 1, 28); constexpr civil_day prev = prev_weekday(cd, weekday::thursday); static_assert(prev.year() == 2016, "PrevWeekDay.year"); static_assert(prev.month() == 1, "PrevWeekDay.month"); static_assert(prev.day() == 21, "PrevWeekDay.day"); } TEST(CivilTime, YearDay) { constexpr civil_day cd(2016, 1, 28); constexpr int yd = get_yearday(cd); static_assert(yd == 28, "YearDay"); } #endif TEST(CivilTime, DefaultConstruction) { civil_second ss; EXPECT_EQ("1970-01-01T00:00:00", Format(ss)); civil_minute mm; EXPECT_EQ("1970-01-01T00:00", Format(mm)); civil_hour hh; EXPECT_EQ("1970-01-01T00", Format(hh)); civil_day d; EXPECT_EQ("1970-01-01", Format(d)); civil_month m; EXPECT_EQ("1970-01", Format(m)); civil_year y; EXPECT_EQ("1970", Format(y)); } TEST(CivilTime, StructMember) { struct S { civil_day day; }; S s = {}; EXPECT_EQ(civil_day{}, s.day); } TEST(CivilTime, FieldsConstruction) { EXPECT_EQ("2015-01-02T03:04:05", Format(civil_second(2015, 1, 2, 3, 4, 5))); EXPECT_EQ("2015-01-02T03:04:00", Format(civil_second(2015, 1, 2, 3, 4))); EXPECT_EQ("2015-01-02T03:00:00", Format(civil_second(2015, 1, 2, 3))); EXPECT_EQ("2015-01-02T00:00:00", Format(civil_second(2015, 1, 2))); EXPECT_EQ("2015-01-01T00:00:00", Format(civil_second(2015, 1))); EXPECT_EQ("2015-01-01T00:00:00", Format(civil_second(2015))); EXPECT_EQ("2015-01-02T03:04", Format(civil_minute(2015, 1, 2, 3, 4, 5))); EXPECT_EQ("2015-01-02T03:04", Format(civil_minute(2015, 1, 2, 3, 4))); EXPECT_EQ("2015-01-02T03:00", Format(civil_minute(2015, 1, 2, 3))); EXPECT_EQ("2015-01-02T00:00", Format(civil_minute(2015, 1, 2))); EXPECT_EQ("2015-01-01T00:00", Format(civil_minute(2015, 1))); EXPECT_EQ("2015-01-01T00:00", Format(civil_minute(2015))); EXPECT_EQ("2015-01-02T03", Format(civil_hour(2015, 1, 2, 3, 4, 5))); EXPECT_EQ("2015-01-02T03", Format(civil_hour(2015, 1, 2, 3, 4))); EXPECT_EQ("2015-01-02T03", Format(civil_hour(2015, 1, 2, 3))); EXPECT_EQ("2015-01-02T00", Format(civil_hour(2015, 1, 2))); EXPECT_EQ("2015-01-01T00", Format(civil_hour(2015, 1))); EXPECT_EQ("2015-01-01T00", Format(civil_hour(2015))); EXPECT_EQ("2015-01-02", Format(civil_day(2015, 1, 2, 3, 4, 5))); EXPECT_EQ("2015-01-02", Format(civil_day(2015, 1, 2, 3, 4))); EXPECT_EQ("2015-01-02", Format(civil_day(2015, 1, 2, 3))); EXPECT_EQ("2015-01-02", Format(civil_day(2015, 1, 2))); EXPECT_EQ("2015-01-01", Format(civil_day(2015, 1))); EXPECT_EQ("2015-01-01", Format(civil_day(2015))); EXPECT_EQ("2015-01", Format(civil_month(2015, 1, 2, 3, 4, 5))); EXPECT_EQ("2015-01", Format(civil_month(2015, 1, 2, 3, 4))); EXPECT_EQ("2015-01", Format(civil_month(2015, 1, 2, 3))); EXPECT_EQ("2015-01", Format(civil_month(2015, 1, 2))); EXPECT_EQ("2015-01", Format(civil_month(2015, 1))); EXPECT_EQ("2015-01", Format(civil_month(2015))); EXPECT_EQ("2015", Format(civil_year(2015, 1, 2, 3, 4, 5))); EXPECT_EQ("2015", Format(civil_year(2015, 1, 2, 3, 4))); EXPECT_EQ("2015", Format(civil_year(2015, 1, 2, 3))); EXPECT_EQ("2015", Format(civil_year(2015, 1, 2))); EXPECT_EQ("2015", Format(civil_year(2015, 1))); EXPECT_EQ("2015", Format(civil_year(2015))); } TEST(CivilTime, FieldsConstructionLimits) { const int kIntMax = std::numeric_limits<int>::max(); EXPECT_EQ("2038-01-19T03:14:07", Format(civil_second(1970, 1, 1, 0, 0, kIntMax))); EXPECT_EQ("6121-02-11T05:21:07", Format(civil_second(1970, 1, 1, 0, kIntMax, kIntMax))); EXPECT_EQ("251104-11-20T12:21:07", Format(civil_second(1970, 1, 1, kIntMax, kIntMax, kIntMax))); EXPECT_EQ("6130715-05-30T12:21:07", Format(civil_second(1970, 1, kIntMax, kIntMax, kIntMax, kIntMax))); EXPECT_EQ( "185087685-11-26T12:21:07", Format(civil_second(1970, kIntMax, kIntMax, kIntMax, kIntMax, kIntMax))); const int kIntMin = std::numeric_limits<int>::min(); EXPECT_EQ("1901-12-13T20:45:52", Format(civil_second(1970, 1, 1, 0, 0, kIntMin))); EXPECT_EQ("-2182-11-20T18:37:52", Format(civil_second(1970, 1, 1, 0, kIntMin, kIntMin))); EXPECT_EQ("-247165-02-11T10:37:52", Format(civil_second(1970, 1, 1, kIntMin, kIntMin, kIntMin))); EXPECT_EQ("-6126776-08-01T10:37:52", Format(civil_second(1970, 1, kIntMin, kIntMin, kIntMin, kIntMin))); EXPECT_EQ( "-185083747-10-31T10:37:52", Format(civil_second(1970, kIntMin, kIntMin, kIntMin, kIntMin, kIntMin))); } TEST(CivilTime, ImplicitCrossAlignment) { civil_year year(2015); civil_month month = year; civil_day day = month; civil_hour hour = day; civil_minute minute = hour; civil_second second = minute; second = year; EXPECT_EQ(second, year); second = month; EXPECT_EQ(second, month); second = day; EXPECT_EQ(second, day); second = hour; EXPECT_EQ(second, hour); second = minute; EXPECT_EQ(second, minute); minute = year; EXPECT_EQ(minute, year); minute = month; EXPECT_EQ(minute, month); minute = day; EXPECT_EQ(minute, day); minute = hour; EXPECT_EQ(minute, hour); hour = year; EXPECT_EQ(hour, year); hour = month; EXPECT_EQ(hour, month); hour = day; EXPECT_EQ(hour, day); day = year; EXPECT_EQ(day, year); day = month; EXPECT_EQ(day, month); month = year; EXPECT_EQ(month, year); EXPECT_FALSE((std::is_convertible<civil_second, civil_minute>::value)); EXPECT_FALSE((std::is_convertible<civil_second, civil_hour>::value)); EXPECT_FALSE((std::is_convertible<civil_second, civil_day>::value)); EXPECT_FALSE((std::is_convertible<civil_second, civil_month>::value)); EXPECT_FALSE((std::is_convertible<civil_second, civil_year>::value)); EXPECT_FALSE((std::is_convertible<civil_minute, civil_hour>::value)); EXPECT_FALSE((std::is_convertible<civil_minute, civil_day>::value)); EXPECT_FALSE((std::is_convertible<civil_minute, civil_month>::value)); EXPECT_FALSE((std::is_convertible<civil_minute, civil_year>::value)); EXPECT_FALSE((std::is_convertible<civil_hour, civil_day>::value)); EXPECT_FALSE((std::is_convertible<civil_hour, civil_month>::value)); EXPECT_FALSE((std::is_convertible<civil_hour, civil_year>::value)); EXPECT_FALSE((std::is_convertible<civil_day, civil_month>::value)); EXPECT_FALSE((std::is_convertible<civil_day, civil_year>::value)); EXPECT_FALSE((std::is_convertible<civil_month, civil_year>::value)); } TEST(CivilTime, ExplicitCrossAlignment) { civil_second second(2015, 1, 2, 3, 4, 5); EXPECT_EQ("2015-01-02T03:04:05", Format(second)); civil_minute minute(second); EXPECT_EQ("2015-01-02T03:04", Format(minute)); civil_hour hour(minute); EXPECT_EQ("2015-01-02T03", Format(hour)); civil_day day(hour); EXPECT_EQ("2015-01-02", Format(day)); civil_month month(day); EXPECT_EQ("2015-01", Format(month)); civil_year year(month); EXPECT_EQ("2015", Format(year)); month = civil_month(year); EXPECT_EQ("2015-01", Format(month)); day = civil_day(month); EXPECT_EQ("2015-01-01", Format(day)); hour = civil_hour(day); EXPECT_EQ("2015-01-01T00", Format(hour)); minute = civil_minute(hour); EXPECT_EQ("2015-01-01T00:00", Format(minute)); second = civil_second(minute); EXPECT_EQ("2015-01-01T00:00:00", Format(second)); } template <typename T1, typename T2> struct HasDifference { template <typename U1, typename U2> static std::false_type test(...); template <typename U1, typename U2> static std::true_type test(decltype(std::declval<U1>() - std::declval<U2>())); static constexpr bool value = decltype(test<T1, T2>(0))::value; }; TEST(CivilTime, DisallowCrossAlignedDifference) { static_assert(HasDifference<civil_second, civil_second>::value, ""); static_assert(HasDifference<civil_minute, civil_minute>::value, ""); static_assert(HasDifference<civil_hour, civil_hour>::value, ""); static_assert(HasDifference<civil_day, civil_day>::value, ""); static_assert(HasDifference<civil_month, civil_month>::value, ""); static_assert(HasDifference<civil_year, civil_year>::value, ""); static_assert(!HasDifference<civil_second, civil_minute>::value, ""); static_assert(!HasDifference<civil_second, civil_hour>::value, ""); static_assert(!HasDifference<civil_second, civil_day>::value, ""); static_assert(!HasDifference<civil_second, civil_month>::value, ""); static_assert(!HasDifference<civil_second, civil_year>::value, ""); static_assert(!HasDifference<civil_minute, civil_hour>::value, ""); static_assert(!HasDifference<civil_minute, civil_day>::value, ""); static_assert(!HasDifference<civil_minute, civil_month>::value, ""); static_assert(!HasDifference<civil_minute, civil_year>::value, ""); static_assert(!HasDifference<civil_hour, civil_day>::value, ""); static_assert(!HasDifference<civil_hour, civil_month>::value, ""); static_assert(!HasDifference<civil_hour, civil_year>::value, ""); static_assert(!HasDifference<civil_day, civil_month>::value, ""); static_assert(!HasDifference<civil_day, civil_year>::value, ""); static_assert(!HasDifference<civil_month, civil_year>::value, ""); } TEST(CivilTime, ValueSemantics) { const civil_hour a(2015, 1, 2, 3); const civil_hour b = a; const civil_hour c(b); civil_hour d; d = c; EXPECT_EQ("2015-01-02T03", Format(d)); } TEST(CivilTime, Relational) { const civil_year year(2014); const civil_month month(year); EXPECT_EQ(year, month); #define TEST_RELATIONAL(OLDER, YOUNGER) \ do { \ EXPECT_FALSE(OLDER < OLDER); \ EXPECT_FALSE(OLDER > OLDER); \ EXPECT_TRUE(OLDER >= OLDER); \ EXPECT_TRUE(OLDER <= OLDER); \ EXPECT_FALSE(YOUNGER < YOUNGER); \ EXPECT_FALSE(YOUNGER > YOUNGER); \ EXPECT_TRUE(YOUNGER >= YOUNGER); \ EXPECT_TRUE(YOUNGER <= YOUNGER); \ EXPECT_EQ(OLDER, OLDER); \ EXPECT_NE(OLDER, YOUNGER); \ EXPECT_LT(OLDER, YOUNGER); \ EXPECT_LE(OLDER, YOUNGER); \ EXPECT_GT(YOUNGER, OLDER); \ EXPECT_GE(YOUNGER, OLDER); \ } while (0) TEST_RELATIONAL(civil_second(2014, 1, 1, 0, 0, 0), civil_second(2015, 1, 1, 0, 0, 0)); TEST_RELATIONAL(civil_second(2014, 1, 1, 0, 0, 0), civil_second(2014, 2, 1, 0, 0, 0)); TEST_RELATIONAL(civil_second(2014, 1, 1, 0, 0, 0), civil_second(2014, 1, 2, 0, 0, 0)); TEST_RELATIONAL(civil_second(2014, 1, 1, 0, 0, 0), civil_second(2014, 1, 1, 1, 0, 0)); TEST_RELATIONAL(civil_second(2014, 1, 1, 1, 0, 0), civil_second(2014, 1, 1, 1, 1, 0)); TEST_RELATIONAL(civil_second(2014, 1, 1, 1, 1, 0), civil_second(2014, 1, 1, 1, 1, 1)); TEST_RELATIONAL(civil_day(2014, 1, 1), civil_minute(2014, 1, 1, 1, 1)); TEST_RELATIONAL(civil_day(2014, 1, 1), civil_month(2014, 2)); #undef TEST_RELATIONAL } TEST(CivilTime, Arithmetic) { civil_second second(2015, 1, 2, 3, 4, 5); EXPECT_EQ("2015-01-02T03:04:06", Format(second += 1)); EXPECT_EQ("2015-01-02T03:04:07", Format(second + 1)); EXPECT_EQ("2015-01-02T03:04:08", Format(2 + second)); EXPECT_EQ("2015-01-02T03:04:05", Format(second - 1)); EXPECT_EQ("2015-01-02T03:04:05", Format(second -= 1)); EXPECT_EQ("2015-01-02T03:04:05", Format(second++)); EXPECT_EQ("2015-01-02T03:04:07", Format(++second)); EXPECT_EQ("2015-01-02T03:04:07", Format(second--)); EXPECT_EQ("2015-01-02T03:04:05", Format(--second)); civil_minute minute(2015, 1, 2, 3, 4); EXPECT_EQ("2015-01-02T03:05", Format(minute += 1)); EXPECT_EQ("2015-01-02T03:06", Format(minute + 1)); EXPECT_EQ("2015-01-02T03:07", Format(2 + minute)); EXPECT_EQ("2015-01-02T03:04", Format(minute - 1)); EXPECT_EQ("2015-01-02T03:04", Format(minute -= 1)); EXPECT_EQ("2015-01-02T03:04", Format(minute++)); EXPECT_EQ("2015-01-02T03:06", Format(++minute)); EXPECT_EQ("2015-01-02T03:06", Format(minute--)); EXPECT_EQ("2015-01-02T03:04", Format(--minute)); civil_hour hour(2015, 1, 2, 3); EXPECT_EQ("2015-01-02T04", Format(hour += 1)); EXPECT_EQ("2015-01-02T05", Format(hour + 1)); EXPECT_EQ("2015-01-02T06", Format(2 + hour)); EXPECT_EQ("2015-01-02T03", Format(hour - 1)); EXPECT_EQ("2015-01-02T03", Format(hour -= 1)); EXPECT_EQ("2015-01-02T03", Format(hour++)); EXPECT_EQ("2015-01-02T05", Format(++hour)); EXPECT_EQ("2015-01-02T05", Format(hour--)); EXPECT_EQ("2015-01-02T03", Format(--hour)); civil_day day(2015, 1, 2); EXPECT_EQ("2015-01-03", Format(day += 1)); EXPECT_EQ("2015-01-04", Format(day + 1)); EXPECT_EQ("2015-01-05", Format(2 + day)); EXPECT_EQ("2015-01-02", Format(day - 1)); EXPECT_EQ("2015-01-02", Format(day -= 1)); EXPECT_EQ("2015-01-02", Format(day++)); EXPECT_EQ("2015-01-04", Format(++day)); EXPECT_EQ("2015-01-04", Format(day--)); EXPECT_EQ("2015-01-02", Format(--day)); civil_month month(2015, 1); EXPECT_EQ("2015-02", Format(month += 1)); EXPECT_EQ("2015-03", Format(month + 1)); EXPECT_EQ("2015-04", Format(2 + month)); EXPECT_EQ("2015-01", Format(month - 1)); EXPECT_EQ("2015-01", Format(month -= 1)); EXPECT_EQ("2015-01", Format(month++)); EXPECT_EQ("2015-03", Format(++month)); EXPECT_EQ("2015-03", Format(month--)); EXPECT_EQ("2015-01", Format(--month)); civil_year year(2015); EXPECT_EQ("2016", Format(year += 1)); EXPECT_EQ("2017", Format(year + 1)); EXPECT_EQ("2018", Format(2 + year)); EXPECT_EQ("2015", Format(year - 1)); EXPECT_EQ("2015", Format(year -= 1)); EXPECT_EQ("2015", Format(year++)); EXPECT_EQ("2017", Format(++year)); EXPECT_EQ("2017", Format(year--)); EXPECT_EQ("2015", Format(--year)); } TEST(CivilTime, ArithmeticLimits) { const int kIntMax = std::numeric_limits<int>::max(); const int kIntMin = std::numeric_limits<int>::min(); civil_second second(1970, 1, 1, 0, 0, 0); second += kIntMax; EXPECT_EQ("2038-01-19T03:14:07", Format(second)); second -= kIntMax; EXPECT_EQ("1970-01-01T00:00:00", Format(second)); second += kIntMin; EXPECT_EQ("1901-12-13T20:45:52", Format(second)); second -= kIntMin; EXPECT_EQ("1970-01-01T00:00:00", Format(second)); civil_minute minute(1970, 1, 1, 0, 0); minute += kIntMax; EXPECT_EQ("6053-01-23T02:07", Format(minute)); minute -= kIntMax; EXPECT_EQ("1970-01-01T00:00", Format(minute)); minute += kIntMin; EXPECT_EQ("-2114-12-08T21:52", Format(minute)); minute -= kIntMin; EXPECT_EQ("1970-01-01T00:00", Format(minute)); civil_hour hour(1970, 1, 1, 0); hour += kIntMax; EXPECT_EQ("246953-10-09T07", Format(hour)); hour -= kIntMax; EXPECT_EQ("1970-01-01T00", Format(hour)); hour += kIntMin; EXPECT_EQ("-243014-03-24T16", Format(hour)); hour -= kIntMin; EXPECT_EQ("1970-01-01T00", Format(hour)); civil_day day(1970, 1, 1); day += kIntMax; EXPECT_EQ("5881580-07-11", Format(day)); day -= kIntMax; EXPECT_EQ("1970-01-01", Format(day)); day += kIntMin; EXPECT_EQ("-5877641-06-23", Format(day)); day -= kIntMin; EXPECT_EQ("1970-01-01", Format(day)); civil_month month(1970, 1); month += kIntMax; EXPECT_EQ("178958940-08", Format(month)); month -= kIntMax; EXPECT_EQ("1970-01", Format(month)); month += kIntMin; EXPECT_EQ("-178955001-05", Format(month)); month -= kIntMin; EXPECT_EQ("1970-01", Format(month)); civil_year year(0); year += kIntMax; EXPECT_EQ("2147483647", Format(year)); year -= kIntMax; EXPECT_EQ("0", Format(year)); year += kIntMin; EXPECT_EQ("-2147483648", Format(year)); year -= kIntMin; EXPECT_EQ("0", Format(year)); } TEST(CivilTime, ArithmeticDifference) { civil_second second(2015, 1, 2, 3, 4, 5); EXPECT_EQ(0, second - second); EXPECT_EQ(10, (second + 10) - second); EXPECT_EQ(-10, (second - 10) - second); civil_minute minute(2015, 1, 2, 3, 4); EXPECT_EQ(0, minute - minute); EXPECT_EQ(10, (minute + 10) - minute); EXPECT_EQ(-10, (minute - 10) - minute); civil_hour hour(2015, 1, 2, 3); EXPECT_EQ(0, hour - hour); EXPECT_EQ(10, (hour + 10) - hour); EXPECT_EQ(-10, (hour - 10) - hour); civil_day day(2015, 1, 2); EXPECT_EQ(0, day - day); EXPECT_EQ(10, (day + 10) - day); EXPECT_EQ(-10, (day - 10) - day); civil_month month(2015, 1); EXPECT_EQ(0, month - month); EXPECT_EQ(10, (month + 10) - month); EXPECT_EQ(-10, (month - 10) - month); civil_year year(2015); EXPECT_EQ(0, year - year); EXPECT_EQ(10, (year + 10) - year); EXPECT_EQ(-10, (year - 10) - year); } TEST(CivilTime, DifferenceLimits) { const int kIntMax = std::numeric_limits<int>::max(); const int kIntMin = std::numeric_limits<int>::min(); const civil_day max_day(kIntMax, 12, 31); EXPECT_EQ(1, max_day - (max_day - 1)); EXPECT_EQ(-1, (max_day - 1) - max_day); const civil_day min_day(kIntMin, 1, 1); EXPECT_EQ(1, (min_day + 1) - min_day); EXPECT_EQ(-1, min_day - (min_day + 1)); const civil_day d1(1970, 1, 1); const civil_day d2(5881580, 7, 11); EXPECT_EQ(kIntMax, d2 - d1); EXPECT_EQ(kIntMin, d1 - (d2 + 1)); } TEST(CivilTime, Properties) { civil_second ss(2015, 2, 3, 4, 5, 6); EXPECT_EQ(2015, ss.year()); EXPECT_EQ(2, ss.month()); EXPECT_EQ(3, ss.day()); EXPECT_EQ(4, ss.hour()); EXPECT_EQ(5, ss.minute()); EXPECT_EQ(6, ss.second()); EXPECT_EQ(weekday::tuesday, get_weekday(ss)); EXPECT_EQ(34, get_yearday(ss)); civil_minute mm(2015, 2, 3, 4, 5, 6); EXPECT_EQ(2015, mm.year()); EXPECT_EQ(2, mm.month()); EXPECT_EQ(3, mm.day()); EXPECT_EQ(4, mm.hour()); EXPECT_EQ(5, mm.minute()); EXPECT_EQ(0, mm.second()); EXPECT_EQ(weekday::tuesday, get_weekday(mm)); EXPECT_EQ(34, get_yearday(mm)); civil_hour hh(2015, 2, 3, 4, 5, 6); EXPECT_EQ(2015, hh.year()); EXPECT_EQ(2, hh.month()); EXPECT_EQ(3, hh.day()); EXPECT_EQ(4, hh.hour()); EXPECT_EQ(0, hh.minute()); EXPECT_EQ(0, hh.second()); EXPECT_EQ(weekday::tuesday, get_weekday(hh)); EXPECT_EQ(34, get_yearday(hh)); civil_day d(2015, 2, 3, 4, 5, 6); EXPECT_EQ(2015, d.year()); EXPECT_EQ(2, d.month()); EXPECT_EQ(3, d.day()); EXPECT_EQ(0, d.hour()); EXPECT_EQ(0, d.minute()); EXPECT_EQ(0, d.second()); EXPECT_EQ(weekday::tuesday, get_weekday(d)); EXPECT_EQ(34, get_yearday(d)); civil_month m(2015, 2, 3, 4, 5, 6); EXPECT_EQ(2015, m.year()); EXPECT_EQ(2, m.month()); EXPECT_EQ(1, m.day()); EXPECT_EQ(0, m.hour()); EXPECT_EQ(0, m.minute()); EXPECT_EQ(0, m.second()); EXPECT_EQ(weekday::sunday, get_weekday(m)); EXPECT_EQ(32, get_yearday(m)); civil_year y(2015, 2, 3, 4, 5, 6); EXPECT_EQ(2015, y.year()); EXPECT_EQ(1, y.month()); EXPECT_EQ(1, y.day()); EXPECT_EQ(0, y.hour()); EXPECT_EQ(0, y.minute()); EXPECT_EQ(0, y.second()); EXPECT_EQ(weekday::thursday, get_weekday(y)); EXPECT_EQ(1, get_yearday(y)); } TEST(CivilTime, OutputStream) { EXPECT_EQ("2016", Format(civil_year(2016))); EXPECT_EQ("123", Format(civil_year(123))); EXPECT_EQ("0", Format(civil_year(0))); EXPECT_EQ("-1", Format(civil_year(-1))); EXPECT_EQ("2016-02", Format(civil_month(2016, 2))); EXPECT_EQ("2016-02-03", Format(civil_day(2016, 2, 3))); EXPECT_EQ("2016-02-03T04", Format(civil_hour(2016, 2, 3, 4))); EXPECT_EQ("2016-02-03T04:05", Format(civil_minute(2016, 2, 3, 4, 5))); EXPECT_EQ("2016-02-03T04:05:06", Format(civil_second(2016, 2, 3, 4, 5, 6))); EXPECT_EQ("Monday", Format(weekday::monday)); EXPECT_EQ("Tuesday", Format(weekday::tuesday)); EXPECT_EQ("Wednesday", Format(weekday::wednesday)); EXPECT_EQ("Thursday", Format(weekday::thursday)); EXPECT_EQ("Friday", Format(weekday::friday)); EXPECT_EQ("Saturday", Format(weekday::saturday)); EXPECT_EQ("Sunday", Format(weekday::sunday)); } TEST(CivilTime, OutputStreamLeftFillWidth) { civil_second cs(2016, 2, 3, 4, 5, 6); { std::stringstream ss; ss << std::left << std::setfill('.'); ss << std::setw(3) << 'X'; ss << std::setw(21) << civil_year(cs); ss << std::setw(3) << 'X'; EXPECT_EQ("X..2016.................X..", ss.str()); } { std::stringstream ss; ss << std::left << std::setfill('.'); ss << std::setw(3) << 'X'; ss << std::setw(21) << civil_month(cs); ss << std::setw(3) << 'X'; EXPECT_EQ("X..2016-02..............X..", ss.str()); } { std::stringstream ss; ss << std::left << std::setfill('.'); ss << std::setw(3) << 'X'; ss << std::setw(21) << civil_day(cs); ss << std::setw(3) << 'X'; EXPECT_EQ("X..2016-02-03...........X..", ss.str()); } { std::stringstream ss; ss << std::left << std::setfill('.'); ss << std::setw(3) << 'X'; ss << std::setw(21) << civil_hour(cs); ss << std::setw(3) << 'X'; EXPECT_EQ("X..2016-02-03T04........X..", ss.str()); } { std::stringstream ss; ss << std::left << std::setfill('.'); ss << std::setw(3) << 'X'; ss << std::setw(21) << civil_minute(cs); ss << std::setw(3) << 'X'; EXPECT_EQ("X..2016-02-03T04:05.....X..", ss.str()); } { std::stringstream ss; ss << std::left << std::setfill('.'); ss << std::setw(3) << 'X'; ss << std::setw(21) << civil_second(cs); ss << std::setw(3) << 'X'; EXPECT_EQ("X..2016-02-03T04:05:06..X..", ss.str()); } } TEST(CivilTime, NextPrevWeekday) { const civil_day thursday(1970, 1, 1); EXPECT_EQ(weekday::thursday, get_weekday(thursday)); civil_day d = next_weekday(thursday, weekday::thursday); EXPECT_EQ(7, d - thursday) << Format(d); EXPECT_EQ(d - 14, prev_weekday(thursday, weekday::thursday)); d = next_weekday(thursday, weekday::friday); EXPECT_EQ(1, d - thursday) << Format(d); EXPECT_EQ(d - 7, prev_weekday(thursday, weekday::friday)); d = next_weekday(thursday, weekday::saturday); EXPECT_EQ(2, d - thursday) << Format(d); EXPECT_EQ(d - 7, prev_weekday(thursday, weekday::saturday)); d = next_weekday(thursday, weekday::sunday); EXPECT_EQ(3, d - thursday) << Format(d); EXPECT_EQ(d - 7, prev_weekday(thursday, weekday::sunday)); d = next_weekday(thursday, weekday::monday); EXPECT_EQ(4, d - thursday) << Format(d); EXPECT_EQ(d - 7, prev_weekday(thursday, weekday::monday)); d = next_weekday(thursday, weekday::tuesday); EXPECT_EQ(5, d - thursday) << Format(d); EXPECT_EQ(d - 7, prev_weekday(thursday, weekday::tuesday)); d = next_weekday(thursday, weekday::wednesday); EXPECT_EQ(6, d - thursday) << Format(d); EXPECT_EQ(d - 7, prev_weekday(thursday, weekday::wednesday)); } TEST(CivilTime, NormalizeWithHugeYear) { civil_month c(9223372036854775807, 1); EXPECT_EQ("9223372036854775807-01", Format(c)); c = c - 1; EXPECT_EQ("9223372036854775806-12", Format(c)); c = civil_month(-9223372036854775807 - 1, 1); EXPECT_EQ("-9223372036854775808-01", Format(c)); c = c + 12; EXPECT_EQ("-9223372036854775807-01", Format(c)); } TEST(CivilTime, LeapYears) { const struct { int year; int days; struct { int month; int day; } leap_day; } kLeapYearTable[]{ {1900, 365, {3, 1}}, {1999, 365, {3, 1}}, {2000, 366, {2, 29}}, {2001, 365, {3, 1}}, {2002, 365, {3, 1}}, {2003, 365, {3, 1}}, {2004, 366, {2, 29}}, {2005, 365, {3, 1}}, {2006, 365, {3, 1}}, {2007, 365, {3, 1}}, {2008, 366, {2, 29}}, {2009, 365, {3, 1}}, {2100, 365, {3, 1}}, }; for (const auto& e : kLeapYearTable) { const civil_day feb28(e.year, 2, 28); const civil_day next_day = feb28 + 1; EXPECT_EQ(e.leap_day.month, next_day.month()); EXPECT_EQ(e.leap_day.day, next_day.day()); const civil_year year(feb28); const civil_year next_year = year + 1; EXPECT_EQ(e.days, civil_day(next_year) - civil_day(year)); } } TEST(CivilTime, FirstThursdayInMonth) { const civil_day nov1(2014, 11, 1); const civil_day thursday = next_weekday(nov1 - 1, weekday::thursday); EXPECT_EQ("2014-11-06", Format(thursday)); const civil_day thanksgiving = thursday + 7 * 3; EXPECT_EQ("2014-11-27", Format(thanksgiving)); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/civil_time.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/internal/cctz/src/civil_time_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
c0b6a6bc-27ba-43e0-95f9-2ca9a301d851
cpp
abseil/abseil-cpp
format
absl/time/format.cc
absl/time/format_test.cc
#include <string.h> #include <cctype> #include <cstdint> #include <utility> #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/time/internal/cctz/include/cctz/time_zone.h" #include "absl/time/time.h" namespace cctz = absl::time_internal::cctz; namespace absl { ABSL_NAMESPACE_BEGIN ABSL_DLL extern const char RFC3339_full[] = "%Y-%m-%d%ET%H:%M:%E*S%Ez"; ABSL_DLL extern const char RFC3339_sec[] = "%Y-%m-%d%ET%H:%M:%S%Ez"; ABSL_DLL extern const char RFC1123_full[] = "%a, %d %b %E4Y %H:%M:%S %z"; ABSL_DLL extern const char RFC1123_no_wday[] = "%d %b %E4Y %H:%M:%S %z"; namespace { const char kInfiniteFutureStr[] = "infinite-future"; const char kInfinitePastStr[] = "infinite-past"; struct cctz_parts { cctz::time_point<cctz::seconds> sec; cctz::detail::femtoseconds fem; }; inline cctz::time_point<cctz::seconds> unix_epoch() { return std::chrono::time_point_cast<cctz::seconds>( std::chrono::system_clock::from_time_t(0)); } cctz_parts Split(absl::Time t) { const auto d = time_internal::ToUnixDuration(t); const int64_t rep_hi = time_internal::GetRepHi(d); const int64_t rep_lo = time_internal::GetRepLo(d); const auto sec = unix_epoch() + cctz::seconds(rep_hi); const auto fem = cctz::detail::femtoseconds(rep_lo * (1000 * 1000 / 4)); return {sec, fem}; } absl::Time Join(const cctz_parts& parts) { const int64_t rep_hi = (parts.sec - unix_epoch()).count(); const uint32_t rep_lo = static_cast<uint32_t>(parts.fem.count() / (1000 * 1000 / 4)); const auto d = time_internal::MakeDuration(rep_hi, rep_lo); return time_internal::FromUnixDuration(d); } } std::string FormatTime(absl::string_view format, absl::Time t, absl::TimeZone tz) { if (t == absl::InfiniteFuture()) return std::string(kInfiniteFutureStr); if (t == absl::InfinitePast()) return std::string(kInfinitePastStr); const auto parts = Split(t); return cctz::detail::format(std::string(format), parts.sec, parts.fem, cctz::time_zone(tz)); } std::string FormatTime(absl::Time t, absl::TimeZone tz) { return FormatTime(RFC3339_full, t, tz); } std::string FormatTime(absl::Time t) { return absl::FormatTime(RFC3339_full, t, absl::LocalTimeZone()); } bool ParseTime(absl::string_view format, absl::string_view input, absl::Time* time, std::string* err) { return absl::ParseTime(format, input, absl::UTCTimeZone(), time, err); } bool ParseTime(absl::string_view format, absl::string_view input, absl::TimeZone tz, absl::Time* time, std::string* err) { auto strip_leading_space = [](absl::string_view* sv) { while (!sv->empty()) { if (!std::isspace(sv->front())) return; sv->remove_prefix(1); } }; struct Literal { const char* name; size_t size; absl::Time value; }; static Literal literals[] = { {kInfiniteFutureStr, strlen(kInfiniteFutureStr), InfiniteFuture()}, {kInfinitePastStr, strlen(kInfinitePastStr), InfinitePast()}, }; strip_leading_space(&input); for (const auto& lit : literals) { if (absl::StartsWith(input, absl::string_view(lit.name, lit.size))) { absl::string_view tail = input; tail.remove_prefix(lit.size); strip_leading_space(&tail); if (tail.empty()) { *time = lit.value; return true; } } } std::string error; cctz_parts parts; const bool b = cctz::detail::parse(std::string(format), std::string(input), cctz::time_zone(tz), &parts.sec, &parts.fem, &error); if (b) { *time = Join(parts); } else if (err != nullptr) { *err = std::move(error); } return b; } bool AbslParseFlag(absl::string_view text, absl::Time* t, std::string* error) { return absl::ParseTime(RFC3339_full, text, absl::UTCTimeZone(), t, error); } std::string AbslUnparseFlag(absl::Time t) { return absl::FormatTime(RFC3339_full, t, absl::UTCTimeZone()); } bool ParseFlag(const std::string& text, absl::Time* t, std::string* error) { return absl::ParseTime(RFC3339_full, text, absl::UTCTimeZone(), t, error); } std::string UnparseFlag(absl::Time t) { return absl::FormatTime(RFC3339_full, t, absl::UTCTimeZone()); } ABSL_NAMESPACE_END }
#include <cstdint> #include <limits> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/time/internal/test_util.h" #include "absl/time/time.h" using testing::HasSubstr; namespace { void TestFormatSpecifier(absl::Time t, absl::TimeZone tz, const std::string& fmt, const std::string& ans) { EXPECT_EQ(ans, absl::FormatTime(fmt, t, tz)); EXPECT_EQ("xxx " + ans, absl::FormatTime("xxx " + fmt, t, tz)); EXPECT_EQ(ans + " yyy", absl::FormatTime(fmt + " yyy", t, tz)); EXPECT_EQ("xxx " + ans + " yyy", absl::FormatTime("xxx " + fmt + " yyy", t, tz)); } TEST(FormatTime, Basics) { absl::TimeZone tz = absl::UTCTimeZone(); absl::Time t = absl::FromTimeT(0); EXPECT_EQ("", absl::FormatTime("", t, tz)); EXPECT_EQ(" ", absl::FormatTime(" ", t, tz)); EXPECT_EQ(" ", absl::FormatTime(" ", t, tz)); EXPECT_EQ("xxx", absl::FormatTime("xxx", t, tz)); std::string big(128, 'x'); EXPECT_EQ(big, absl::FormatTime(big, t, tz)); std::string bigger(100000, 'x'); EXPECT_EQ(bigger, absl::FormatTime(bigger, t, tz)); t += absl::Hours(13) + absl::Minutes(4) + absl::Seconds(5); t += absl::Milliseconds(6) + absl::Microseconds(7) + absl::Nanoseconds(8); EXPECT_EQ("1970-01-01", absl::FormatTime("%Y-%m-%d", t, tz)); EXPECT_EQ("13:04:05", absl::FormatTime("%H:%M:%S", t, tz)); EXPECT_EQ("13:04:05.006", absl::FormatTime("%H:%M:%E3S", t, tz)); EXPECT_EQ("13:04:05.006007", absl::FormatTime("%H:%M:%E6S", t, tz)); EXPECT_EQ("13:04:05.006007008", absl::FormatTime("%H:%M:%E9S", t, tz)); } TEST(FormatTime, LocaleSpecific) { const absl::TimeZone tz = absl::UTCTimeZone(); absl::Time t = absl::FromTimeT(0); TestFormatSpecifier(t, tz, "%a", "Thu"); TestFormatSpecifier(t, tz, "%A", "Thursday"); TestFormatSpecifier(t, tz, "%b", "Jan"); TestFormatSpecifier(t, tz, "%B", "January"); const std::string s = absl::FormatTime("%c", absl::FromTimeT(0), absl::UTCTimeZone()); EXPECT_THAT(s, HasSubstr("1970")); EXPECT_THAT(s, HasSubstr("00:00:00")); TestFormatSpecifier(t, tz, "%p", "AM"); TestFormatSpecifier(t, tz, "%x", "01/01/70"); TestFormatSpecifier(t, tz, "%X", "00:00:00"); } TEST(FormatTime, ExtendedSeconds) { const absl::TimeZone tz = absl::UTCTimeZone(); absl::Time t = absl::FromTimeT(0) + absl::Seconds(5); EXPECT_EQ("05", absl::FormatTime("%E*S", t, tz)); EXPECT_EQ("05.000000000000000", absl::FormatTime("%E15S", t, tz)); t += absl::Milliseconds(6) + absl::Microseconds(7) + absl::Nanoseconds(8); EXPECT_EQ("05.006007008", absl::FormatTime("%E*S", t, tz)); EXPECT_EQ("05", absl::FormatTime("%E0S", t, tz)); EXPECT_EQ("05.006007008000000", absl::FormatTime("%E15S", t, tz)); t = absl::FromUnixMicros(-1); EXPECT_EQ("1969-12-31 23:59:59.999999", absl::FormatTime("%Y-%m-%d %H:%M:%E*S", t, tz)); t = absl::FromUnixMicros(1395024427333304); EXPECT_EQ("2014-03-17 02:47:07.333304", absl::FormatTime("%Y-%m-%d %H:%M:%E*S", t, tz)); t += absl::Microseconds(1); EXPECT_EQ("2014-03-17 02:47:07.333305", absl::FormatTime("%Y-%m-%d %H:%M:%E*S", t, tz)); } TEST(FormatTime, RFC1123FormatPadsYear) { absl::TimeZone tz = absl::UTCTimeZone(); absl::Time t = absl::FromCivil(absl::CivilSecond(77, 6, 28, 9, 8, 7), tz); EXPECT_EQ("Mon, 28 Jun 0077 09:08:07 +0000", absl::FormatTime(absl::RFC1123_full, t, tz)); EXPECT_EQ("28 Jun 0077 09:08:07 +0000", absl::FormatTime(absl::RFC1123_no_wday, t, tz)); } TEST(FormatTime, InfiniteTime) { absl::TimeZone tz = absl::time_internal::LoadTimeZone("America/Los_Angeles"); EXPECT_EQ("infinite-future", absl::FormatTime("%H:%M blah", absl::InfiniteFuture(), tz)); EXPECT_EQ("infinite-past", absl::FormatTime("%H:%M blah", absl::InfinitePast(), tz)); } TEST(ParseTime, Basics) { absl::Time t = absl::FromTimeT(1234567890); std::string err; EXPECT_TRUE(absl::ParseTime("", "", &t, &err)) << err; EXPECT_EQ(absl::UnixEpoch(), t); EXPECT_TRUE(absl::ParseTime(" ", " ", &t, &err)) << err; EXPECT_TRUE(absl::ParseTime(" ", " ", &t, &err)) << err; EXPECT_TRUE(absl::ParseTime("x", "x", &t, &err)) << err; EXPECT_TRUE(absl::ParseTime("xxx", "xxx", &t, &err)) << err; EXPECT_TRUE(absl::ParseTime("%Y-%m-%d %H:%M:%S %z", "2013-06-28 19:08:09 -0800", &t, &err)) << err; const auto ci = absl::FixedTimeZone(-8 * 60 * 60).At(t); EXPECT_EQ(absl::CivilSecond(2013, 6, 28, 19, 8, 9), ci.cs); EXPECT_EQ(absl::ZeroDuration(), ci.subsecond); } TEST(ParseTime, NullErrorString) { absl::Time t; EXPECT_FALSE(absl::ParseTime("%Q", "invalid format", &t, nullptr)); EXPECT_FALSE(absl::ParseTime("%H", "12 trailing data", &t, nullptr)); EXPECT_FALSE( absl::ParseTime("%H out of range", "42 out of range", &t, nullptr)); } TEST(ParseTime, WithTimeZone) { const absl::TimeZone tz = absl::time_internal::LoadTimeZone("America/Los_Angeles"); absl::Time t; std::string e; EXPECT_TRUE( absl::ParseTime("%Y-%m-%d %H:%M:%S", "2013-06-28 19:08:09", tz, &t, &e)) << e; auto ci = tz.At(t); EXPECT_EQ(absl::CivilSecond(2013, 6, 28, 19, 8, 9), ci.cs); EXPECT_EQ(absl::ZeroDuration(), ci.subsecond); EXPECT_TRUE(absl::ParseTime("%Y-%m-%d %H:%M:%S %z", "2013-06-28 19:08:09 +0800", tz, &t, &e)) << e; ci = absl::FixedTimeZone(8 * 60 * 60).At(t); EXPECT_EQ(absl::CivilSecond(2013, 6, 28, 19, 8, 9), ci.cs); EXPECT_EQ(absl::ZeroDuration(), ci.subsecond); } TEST(ParseTime, ErrorCases) { absl::Time t = absl::FromTimeT(0); std::string err; EXPECT_FALSE(absl::ParseTime("%S", "123", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Illegal trailing data")); err.clear(); EXPECT_FALSE(absl::ParseTime("%Q", "x", &t, &err)) << err; EXPECT_FALSE(err.empty()); EXPECT_FALSE(absl::ParseTime("%m-%d", "2-3 blah", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Illegal trailing data")); EXPECT_FALSE(absl::ParseTime("%m-%d", "2-31", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Out-of-range")); EXPECT_TRUE(absl::ParseTime("%z", "-0203", &t, &err)) << err; EXPECT_FALSE(absl::ParseTime("%z", "- 2 3", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); EXPECT_TRUE(absl::ParseTime("%Ez", "-02:03", &t, &err)) << err; EXPECT_FALSE(absl::ParseTime("%Ez", "- 2: 3", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); EXPECT_FALSE(absl::ParseTime("%Ez", "+-08:00", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); EXPECT_FALSE(absl::ParseTime("%Ez", "-+08:00", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); EXPECT_FALSE(absl::ParseTime("%Y", "-0", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); EXPECT_FALSE(absl::ParseTime("%E4Y", "-0", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); EXPECT_FALSE(absl::ParseTime("%H", "-0", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); EXPECT_FALSE(absl::ParseTime("%M", "-0", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); EXPECT_FALSE(absl::ParseTime("%S", "-0", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); EXPECT_FALSE(absl::ParseTime("%z", "+-000", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); EXPECT_FALSE(absl::ParseTime("%Ez", "+-0:00", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); EXPECT_FALSE(absl::ParseTime("%z", "-00-0", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Illegal trailing data")); EXPECT_FALSE(absl::ParseTime("%Ez", "-00:-0", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Illegal trailing data")); } TEST(ParseTime, ExtendedSeconds) { std::string err; absl::Time t; t = absl::UnixEpoch(); EXPECT_TRUE(absl::ParseTime("%E*S", "0.2147483647", &t, &err)) << err; EXPECT_EQ(absl::UnixEpoch() + absl::Nanoseconds(214748364) + absl::Nanoseconds(1) / 2, t); t = absl::UnixEpoch(); EXPECT_TRUE(absl::ParseTime("%E*S", "0.2147483648", &t, &err)) << err; EXPECT_EQ(absl::UnixEpoch() + absl::Nanoseconds(214748364) + absl::Nanoseconds(3) / 4, t); t = absl::UnixEpoch(); EXPECT_TRUE(absl::ParseTime( "%E*S", "0.214748364801234567890123456789012345678901234567890123456789", &t, &err)) << err; EXPECT_EQ(absl::UnixEpoch() + absl::Nanoseconds(214748364) + absl::Nanoseconds(3) / 4, t); } TEST(ParseTime, ExtendedOffsetErrors) { std::string err; absl::Time t; EXPECT_FALSE(absl::ParseTime("%z", "-123", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Illegal trailing data")); EXPECT_FALSE(absl::ParseTime("%z", "-1", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); EXPECT_FALSE(absl::ParseTime("%Ez", "-12:3", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Illegal trailing data")); EXPECT_FALSE(absl::ParseTime("%Ez", "-123", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Illegal trailing data")); EXPECT_FALSE(absl::ParseTime("%Ez", "-1", &t, &err)) << err; EXPECT_THAT(err, HasSubstr("Failed to parse")); } TEST(ParseTime, InfiniteTime) { absl::Time t; std::string err; EXPECT_TRUE(absl::ParseTime("%H:%M blah", "infinite-future", &t, &err)); EXPECT_EQ(absl::InfiniteFuture(), t); EXPECT_TRUE(absl::ParseTime("%H:%M blah", " infinite-future", &t, &err)); EXPECT_EQ(absl::InfiniteFuture(), t); EXPECT_TRUE(absl::ParseTime("%H:%M blah", "infinite-future ", &t, &err)); EXPECT_EQ(absl::InfiniteFuture(), t); EXPECT_TRUE(absl::ParseTime("%H:%M blah", " infinite-future ", &t, &err)); EXPECT_EQ(absl::InfiniteFuture(), t); EXPECT_TRUE(absl::ParseTime("%H:%M blah", "infinite-past", &t, &err)); EXPECT_EQ(absl::InfinitePast(), t); EXPECT_TRUE(absl::ParseTime("%H:%M blah", " infinite-past", &t, &err)); EXPECT_EQ(absl::InfinitePast(), t); EXPECT_TRUE(absl::ParseTime("%H:%M blah", "infinite-past ", &t, &err)); EXPECT_EQ(absl::InfinitePast(), t); EXPECT_TRUE(absl::ParseTime("%H:%M blah", " infinite-past ", &t, &err)); EXPECT_EQ(absl::InfinitePast(), t); absl::TimeZone tz = absl::UTCTimeZone(); EXPECT_TRUE(absl::ParseTime("infinite-future %H:%M", "infinite-future 03:04", &t, &err)); EXPECT_NE(absl::InfiniteFuture(), t); EXPECT_EQ(3, tz.At(t).cs.hour()); EXPECT_EQ(4, tz.At(t).cs.minute()); EXPECT_TRUE( absl::ParseTime("infinite-past %H:%M", "infinite-past 03:04", &t, &err)); EXPECT_NE(absl::InfinitePast(), t); EXPECT_EQ(3, tz.At(t).cs.hour()); EXPECT_EQ(4, tz.At(t).cs.minute()); EXPECT_FALSE(absl::ParseTime("infinite-future %H:%M", "03:04", &t, &err)); EXPECT_FALSE(absl::ParseTime("infinite-past %H:%M", "03:04", &t, &err)); } TEST(ParseTime, FailsOnUnrepresentableTime) { const absl::TimeZone utc = absl::UTCTimeZone(); absl::Time t; EXPECT_FALSE( absl::ParseTime("%Y-%m-%d", "-292277022657-01-27", utc, &t, nullptr)); EXPECT_TRUE( absl::ParseTime("%Y-%m-%d", "-292277022657-01-28", utc, &t, nullptr)); EXPECT_TRUE( absl::ParseTime("%Y-%m-%d", "292277026596-12-04", utc, &t, nullptr)); EXPECT_FALSE( absl::ParseTime("%Y-%m-%d", "292277026596-12-05", utc, &t, nullptr)); } TEST(FormatParse, RoundTrip) { const absl::TimeZone lax = absl::time_internal::LoadTimeZone("America/Los_Angeles"); const absl::Time in = absl::FromCivil(absl::CivilSecond(1977, 6, 28, 9, 8, 7), lax); const absl::Duration subseconds = absl::Nanoseconds(654321); std::string err; { absl::Time out; const std::string s = absl::FormatTime(absl::RFC3339_full, in + subseconds, lax); EXPECT_TRUE(absl::ParseTime(absl::RFC3339_full, s, &out, &err)) << s << ": " << err; EXPECT_EQ(in + subseconds, out); } { absl::Time out; const std::string s = absl::FormatTime(absl::RFC1123_full, in, lax); EXPECT_TRUE(absl::ParseTime(absl::RFC1123_full, s, &out, &err)) << s << ": " << err; EXPECT_EQ(in, out); } #if !defined(_MSC_VER) && !defined(__EMSCRIPTEN__) { absl::Time out; const std::string s = absl::FormatTime("%c", in, absl::UTCTimeZone()); EXPECT_TRUE(absl::ParseTime("%c", s, &out, &err)) << s << ": " << err; EXPECT_EQ(in, out); } #endif } TEST(FormatParse, RoundTripDistantFuture) { const absl::TimeZone tz = absl::UTCTimeZone(); const absl::Time in = absl::FromUnixSeconds(std::numeric_limits<int64_t>::max()); std::string err; absl::Time out; const std::string s = absl::FormatTime(absl::RFC3339_full, in, tz); EXPECT_TRUE(absl::ParseTime(absl::RFC3339_full, s, &out, &err)) << s << ": " << err; EXPECT_EQ(in, out); } TEST(FormatParse, RoundTripDistantPast) { const absl::TimeZone tz = absl::UTCTimeZone(); const absl::Time in = absl::FromUnixSeconds(std::numeric_limits<int64_t>::min()); std::string err; absl::Time out; const std::string s = absl::FormatTime(absl::RFC3339_full, in, tz); EXPECT_TRUE(absl::ParseTime(absl::RFC3339_full, s, &out, &err)) << s << ": " << err; EXPECT_EQ(in, out); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/format.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/format_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
5d083516-07e8-4022-8d7d-5f0b07fbdc65
cpp
abseil/abseil-cpp
time
absl/time/time.cc
absl/time/time_test.cc
#include "absl/time/time.h" #if defined(_MSC_VER) #include <winsock2.h> #endif #include <cstring> #include <ctime> #include <limits> #include "absl/time/internal/cctz/include/cctz/civil_time.h" #include "absl/time/internal/cctz/include/cctz/time_zone.h" namespace cctz = absl::time_internal::cctz; namespace absl { ABSL_NAMESPACE_BEGIN namespace { inline cctz::time_point<cctz::seconds> unix_epoch() { return std::chrono::time_point_cast<cctz::seconds>( std::chrono::system_clock::from_time_t(0)); } inline int64_t FloorToUnit(absl::Duration d, absl::Duration unit) { absl::Duration rem; int64_t q = absl::IDivDuration(d, unit, &rem); return (q > 0 || rem >= ZeroDuration() || q == std::numeric_limits<int64_t>::min()) ? q : q - 1; } ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING inline absl::Time::Breakdown InfiniteFutureBreakdown() { absl::Time::Breakdown bd; bd.year = std::numeric_limits<int64_t>::max(); bd.month = 12; bd.day = 31; bd.hour = 23; bd.minute = 59; bd.second = 59; bd.subsecond = absl::InfiniteDuration(); bd.weekday = 4; bd.yearday = 365; bd.offset = 0; bd.is_dst = false; bd.zone_abbr = "-00"; return bd; } inline absl::Time::Breakdown InfinitePastBreakdown() { Time::Breakdown bd; bd.year = std::numeric_limits<int64_t>::min(); bd.month = 1; bd.day = 1; bd.hour = 0; bd.minute = 0; bd.second = 0; bd.subsecond = -absl::InfiniteDuration(); bd.weekday = 7; bd.yearday = 1; bd.offset = 0; bd.is_dst = false; bd.zone_abbr = "-00"; return bd; } ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING inline absl::TimeZone::CivilInfo InfiniteFutureCivilInfo() { TimeZone::CivilInfo ci; ci.cs = CivilSecond::max(); ci.subsecond = InfiniteDuration(); ci.offset = 0; ci.is_dst = false; ci.zone_abbr = "-00"; return ci; } inline absl::TimeZone::CivilInfo InfinitePastCivilInfo() { TimeZone::CivilInfo ci; ci.cs = CivilSecond::min(); ci.subsecond = -InfiniteDuration(); ci.offset = 0; ci.is_dst = false; ci.zone_abbr = "-00"; return ci; } ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING inline absl::TimeConversion InfiniteFutureTimeConversion() { absl::TimeConversion tc; tc.pre = tc.trans = tc.post = absl::InfiniteFuture(); tc.kind = absl::TimeConversion::UNIQUE; tc.normalized = true; return tc; } inline TimeConversion InfinitePastTimeConversion() { absl::TimeConversion tc; tc.pre = tc.trans = tc.post = absl::InfinitePast(); tc.kind = absl::TimeConversion::UNIQUE; tc.normalized = true; return tc; } ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING Time MakeTimeWithOverflow(const cctz::time_point<cctz::seconds>& sec, const cctz::civil_second& cs, const cctz::time_zone& tz, bool* normalized = nullptr) { const auto max = cctz::time_point<cctz::seconds>::max(); const auto min = cctz::time_point<cctz::seconds>::min(); if (sec == max) { const auto al = tz.lookup(max); if (cs > al.cs) { if (normalized) *normalized = true; return absl::InfiniteFuture(); } } if (sec == min) { const auto al = tz.lookup(min); if (cs < al.cs) { if (normalized) *normalized = true; return absl::InfinitePast(); } } const auto hi = (sec - unix_epoch()).count(); return time_internal::FromUnixDuration(time_internal::MakeDuration(hi)); } inline int MapWeekday(const cctz::weekday& wd) { switch (wd) { case cctz::weekday::monday: return 1; case cctz::weekday::tuesday: return 2; case cctz::weekday::wednesday: return 3; case cctz::weekday::thursday: return 4; case cctz::weekday::friday: return 5; case cctz::weekday::saturday: return 6; case cctz::weekday::sunday: return 7; } return 1; } bool FindTransition(const cctz::time_zone& tz, bool (cctz::time_zone::*find_transition)( const cctz::time_point<cctz::seconds>& tp, cctz::time_zone::civil_transition* trans) const, Time t, TimeZone::CivilTransition* trans) { const auto tp = unix_epoch() + cctz::seconds(ToUnixSeconds(t)); cctz::time_zone::civil_transition tr; if (!(tz.*find_transition)(tp, &tr)) return false; trans->from = CivilSecond(tr.from); trans->to = CivilSecond(tr.to); return true; } } ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING absl::Time::Breakdown Time::In(absl::TimeZone tz) const { if (*this == absl::InfiniteFuture()) return InfiniteFutureBreakdown(); if (*this == absl::InfinitePast()) return InfinitePastBreakdown(); const auto tp = unix_epoch() + cctz::seconds(time_internal::GetRepHi(rep_)); const auto al = cctz::time_zone(tz).lookup(tp); const auto cs = al.cs; const auto cd = cctz::civil_day(cs); absl::Time::Breakdown bd; bd.year = cs.year(); bd.month = cs.month(); bd.day = cs.day(); bd.hour = cs.hour(); bd.minute = cs.minute(); bd.second = cs.second(); bd.subsecond = time_internal::MakeDuration(0, time_internal::GetRepLo(rep_)); bd.weekday = MapWeekday(cctz::get_weekday(cd)); bd.yearday = cctz::get_yearday(cd); bd.offset = al.offset; bd.is_dst = al.is_dst; bd.zone_abbr = al.abbr; return bd; } ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING absl::Time FromUDate(double udate) { return time_internal::FromUnixDuration(absl::Milliseconds(udate)); } absl::Time FromUniversal(int64_t universal) { return absl::UniversalEpoch() + 100 * absl::Nanoseconds(universal); } int64_t ToUnixNanos(Time t) { if (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >= 0 && time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >> 33 == 0) { return (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) * 1000 * 1000 * 1000) + (time_internal::GetRepLo(time_internal::ToUnixDuration(t)) / 4); } return FloorToUnit(time_internal::ToUnixDuration(t), absl::Nanoseconds(1)); } int64_t ToUnixMicros(Time t) { if (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >= 0 && time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >> 43 == 0) { return (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) * 1000 * 1000) + (time_internal::GetRepLo(time_internal::ToUnixDuration(t)) / 4000); } return FloorToUnit(time_internal::ToUnixDuration(t), absl::Microseconds(1)); } int64_t ToUnixMillis(Time t) { if (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >= 0 && time_internal::GetRepHi(time_internal::ToUnixDuration(t)) >> 53 == 0) { return (time_internal::GetRepHi(time_internal::ToUnixDuration(t)) * 1000) + (time_internal::GetRepLo(time_internal::ToUnixDuration(t)) / (4000 * 1000)); } return FloorToUnit(time_internal::ToUnixDuration(t), absl::Milliseconds(1)); } int64_t ToUnixSeconds(Time t) { return time_internal::GetRepHi(time_internal::ToUnixDuration(t)); } time_t ToTimeT(Time t) { return absl::ToTimespec(t).tv_sec; } double ToUDate(Time t) { return absl::FDivDuration(time_internal::ToUnixDuration(t), absl::Milliseconds(1)); } int64_t ToUniversal(absl::Time t) { return absl::FloorToUnit(t - absl::UniversalEpoch(), absl::Nanoseconds(100)); } absl::Time TimeFromTimespec(timespec ts) { return time_internal::FromUnixDuration(absl::DurationFromTimespec(ts)); } absl::Time TimeFromTimeval(timeval tv) { return time_internal::FromUnixDuration(absl::DurationFromTimeval(tv)); } timespec ToTimespec(Time t) { timespec ts; absl::Duration d = time_internal::ToUnixDuration(t); if (!time_internal::IsInfiniteDuration(d)) { ts.tv_sec = static_cast<decltype(ts.tv_sec)>(time_internal::GetRepHi(d)); if (ts.tv_sec == time_internal::GetRepHi(d)) { ts.tv_nsec = time_internal::GetRepLo(d) / 4; return ts; } } if (d >= absl::ZeroDuration()) { ts.tv_sec = std::numeric_limits<time_t>::max(); ts.tv_nsec = 1000 * 1000 * 1000 - 1; } else { ts.tv_sec = std::numeric_limits<time_t>::min(); ts.tv_nsec = 0; } return ts; } timeval ToTimeval(Time t) { timeval tv; timespec ts = absl::ToTimespec(t); tv.tv_sec = static_cast<decltype(tv.tv_sec)>(ts.tv_sec); if (tv.tv_sec != ts.tv_sec) { if (ts.tv_sec < 0) { tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::min(); tv.tv_usec = 0; } else { tv.tv_sec = std::numeric_limits<decltype(tv.tv_sec)>::max(); tv.tv_usec = 1000 * 1000 - 1; } return tv; } tv.tv_usec = static_cast<int>(ts.tv_nsec / 1000); return tv; } Time FromChrono(const std::chrono::system_clock::time_point& tp) { return time_internal::FromUnixDuration(time_internal::FromChrono( tp - std::chrono::system_clock::from_time_t(0))); } std::chrono::system_clock::time_point ToChronoTime(absl::Time t) { using D = std::chrono::system_clock::duration; auto d = time_internal::ToUnixDuration(t); if (d < ZeroDuration()) d = Floor(d, FromChrono(D{1})); return std::chrono::system_clock::from_time_t(0) + time_internal::ToChronoDuration<D>(d); } absl::TimeZone::CivilInfo TimeZone::At(Time t) const { if (t == absl::InfiniteFuture()) return InfiniteFutureCivilInfo(); if (t == absl::InfinitePast()) return InfinitePastCivilInfo(); const auto ud = time_internal::ToUnixDuration(t); const auto tp = unix_epoch() + cctz::seconds(time_internal::GetRepHi(ud)); const auto al = cz_.lookup(tp); TimeZone::CivilInfo ci; ci.cs = CivilSecond(al.cs); ci.subsecond = time_internal::MakeDuration(0, time_internal::GetRepLo(ud)); ci.offset = al.offset; ci.is_dst = al.is_dst; ci.zone_abbr = al.abbr; return ci; } absl::TimeZone::TimeInfo TimeZone::At(CivilSecond ct) const { const cctz::civil_second cs(ct); const auto cl = cz_.lookup(cs); TimeZone::TimeInfo ti; switch (cl.kind) { case cctz::time_zone::civil_lookup::UNIQUE: ti.kind = TimeZone::TimeInfo::UNIQUE; break; case cctz::time_zone::civil_lookup::SKIPPED: ti.kind = TimeZone::TimeInfo::SKIPPED; break; case cctz::time_zone::civil_lookup::REPEATED: ti.kind = TimeZone::TimeInfo::REPEATED; break; } ti.pre = MakeTimeWithOverflow(cl.pre, cs, cz_); ti.trans = MakeTimeWithOverflow(cl.trans, cs, cz_); ti.post = MakeTimeWithOverflow(cl.post, cs, cz_); return ti; } bool TimeZone::NextTransition(Time t, CivilTransition* trans) const { return FindTransition(cz_, &cctz::time_zone::next_transition, t, trans); } bool TimeZone::PrevTransition(Time t, CivilTransition* trans) const { return FindTransition(cz_, &cctz::time_zone::prev_transition, t, trans); } ABSL_INTERNAL_DISABLE_DEPRECATED_DECLARATION_WARNING absl::TimeConversion ConvertDateTime(int64_t year, int mon, int day, int hour, int min, int sec, TimeZone tz) { if (year > 300000000000) return InfiniteFutureTimeConversion(); if (year < -300000000000) return InfinitePastTimeConversion(); const CivilSecond cs(year, mon, day, hour, min, sec); const auto ti = tz.At(cs); TimeConversion tc; tc.pre = ti.pre; tc.trans = ti.trans; tc.post = ti.post; switch (ti.kind) { case TimeZone::TimeInfo::UNIQUE: tc.kind = TimeConversion::UNIQUE; break; case TimeZone::TimeInfo::SKIPPED: tc.kind = TimeConversion::SKIPPED; break; case TimeZone::TimeInfo::REPEATED: tc.kind = TimeConversion::REPEATED; break; } tc.normalized = false; if (year != cs.year() || mon != cs.month() || day != cs.day() || hour != cs.hour() || min != cs.minute() || sec != cs.second()) { tc.normalized = true; } return tc; } ABSL_INTERNAL_RESTORE_DEPRECATED_DECLARATION_WARNING absl::Time FromTM(const struct tm& tm, absl::TimeZone tz) { civil_year_t tm_year = tm.tm_year; if (tm_year > 300000000000ll) return InfiniteFuture(); if (tm_year < -300000000000ll) return InfinitePast(); int tm_mon = tm.tm_mon; if (tm_mon == std::numeric_limits<int>::max()) { tm_mon -= 12; tm_year += 1; } const auto ti = tz.At(CivilSecond(tm_year + 1900, tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec)); return tm.tm_isdst == 0 ? ti.post : ti.pre; } struct tm ToTM(absl::Time t, absl::TimeZone tz) { struct tm tm = {}; const auto ci = tz.At(t); const auto& cs = ci.cs; tm.tm_sec = cs.second(); tm.tm_min = cs.minute(); tm.tm_hour = cs.hour(); tm.tm_mday = cs.day(); tm.tm_mon = cs.month() - 1; if (cs.year() < std::numeric_limits<int>::min() + 1900) { tm.tm_year = std::numeric_limits<int>::min(); } else if (cs.year() > std::numeric_limits<int>::max()) { tm.tm_year = std::numeric_limits<int>::max() - 1900; } else { tm.tm_year = static_cast<int>(cs.year() - 1900); } switch (GetWeekday(cs)) { case Weekday::sunday: tm.tm_wday = 0; break; case Weekday::monday: tm.tm_wday = 1; break; case Weekday::tuesday: tm.tm_wday = 2; break; case Weekday::wednesday: tm.tm_wday = 3; break; case Weekday::thursday: tm.tm_wday = 4; break; case Weekday::friday: tm.tm_wday = 5; break; case Weekday::saturday: tm.tm_wday = 6; break; } tm.tm_yday = GetYearDay(cs) - 1; tm.tm_isdst = ci.is_dst ? 1 : 0; return tm; } ABSL_NAMESPACE_END }
#include "absl/time/time.h" #include "absl/time/civil_time.h" #if defined(_MSC_VER) #include <winsock2.h> #endif #include "absl/base/config.h" #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L #include <version> #endif #include <chrono> #ifdef __cpp_lib_three_way_comparison #include <compare> #endif #include <cstdint> #include <cstring> #include <ctime> #include <iomanip> #include <ios> #include <limits> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/numeric/int128.h" #include "absl/strings/str_format.h" #include "absl/time/clock.h" #include "absl/time/internal/test_util.h" namespace { #if defined(GTEST_USES_SIMPLE_RE) && GTEST_USES_SIMPLE_RE const char kZoneAbbrRE[] = ".*"; #else const char kZoneAbbrRE[] = "[A-Za-z]{3,4}|[-+][0-9]{2}([0-9]{2})?"; #endif #define EXPECT_CIVIL_INFO(ci, y, m, d, h, min, s, off, isdst) \ do { \ EXPECT_EQ(y, ci.cs.year()); \ EXPECT_EQ(m, ci.cs.month()); \ EXPECT_EQ(d, ci.cs.day()); \ EXPECT_EQ(h, ci.cs.hour()); \ EXPECT_EQ(min, ci.cs.minute()); \ EXPECT_EQ(s, ci.cs.second()); \ EXPECT_EQ(off, ci.offset); \ EXPECT_EQ(isdst, ci.is_dst); \ EXPECT_THAT(ci.zone_abbr, testing::MatchesRegex(kZoneAbbrRE)); \ } while (0) MATCHER_P(TimespecMatcher, ts, "") { if (ts.tv_sec == arg.tv_sec && ts.tv_nsec == arg.tv_nsec) return true; *result_listener << "expected: {" << ts.tv_sec << ", " << ts.tv_nsec << "} "; *result_listener << "actual: {" << arg.tv_sec << ", " << arg.tv_nsec << "}"; return false; } MATCHER_P(TimevalMatcher, tv, "") { if (tv.tv_sec == arg.tv_sec && tv.tv_usec == arg.tv_usec) return true; *result_listener << "expected: {" << tv.tv_sec << ", " << tv.tv_usec << "} "; *result_listener << "actual: {" << arg.tv_sec << ", " << arg.tv_usec << "}"; return false; } TEST(Time, ConstExpr) { constexpr absl::Time t0 = absl::UnixEpoch(); static_assert(t0 == absl::UnixEpoch(), "UnixEpoch"); constexpr absl::Time t1 = absl::InfiniteFuture(); static_assert(t1 != absl::UnixEpoch(), "InfiniteFuture"); constexpr absl::Time t2 = absl::InfinitePast(); static_assert(t2 != absl::UnixEpoch(), "InfinitePast"); constexpr absl::Time t3 = absl::FromUnixNanos(0); static_assert(t3 == absl::UnixEpoch(), "FromUnixNanos"); constexpr absl::Time t4 = absl::FromUnixMicros(0); static_assert(t4 == absl::UnixEpoch(), "FromUnixMicros"); constexpr absl::Time t5 = absl::FromUnixMillis(0); static_assert(t5 == absl::UnixEpoch(), "FromUnixMillis"); constexpr absl::Time t6 = absl::FromUnixSeconds(0); static_assert(t6 == absl::UnixEpoch(), "FromUnixSeconds"); constexpr absl::Time t7 = absl::FromTimeT(0); static_assert(t7 == absl::UnixEpoch(), "FromTimeT"); } TEST(Time, ValueSemantics) { absl::Time a; absl::Time b = a; EXPECT_EQ(a, b); absl::Time c(a); EXPECT_EQ(a, b); EXPECT_EQ(a, c); EXPECT_EQ(b, c); b = c; EXPECT_EQ(a, b); EXPECT_EQ(a, c); EXPECT_EQ(b, c); } TEST(Time, UnixEpoch) { const auto ci = absl::UTCTimeZone().At(absl::UnixEpoch()); EXPECT_EQ(absl::CivilSecond(1970, 1, 1, 0, 0, 0), ci.cs); EXPECT_EQ(absl::ZeroDuration(), ci.subsecond); EXPECT_EQ(absl::Weekday::thursday, absl::GetWeekday(ci.cs)); } TEST(Time, Breakdown) { absl::TimeZone tz = absl::time_internal::LoadTimeZone("America/New_York"); absl::Time t = absl::UnixEpoch(); auto ci = tz.At(t); EXPECT_CIVIL_INFO(ci, 1969, 12, 31, 19, 0, 0, -18000, false); EXPECT_EQ(absl::ZeroDuration(), ci.subsecond); EXPECT_EQ(absl::Weekday::wednesday, absl::GetWeekday(ci.cs)); t -= absl::Nanoseconds(1); ci = tz.At(t); EXPECT_CIVIL_INFO(ci, 1969, 12, 31, 18, 59, 59, -18000, false); EXPECT_EQ(absl::Nanoseconds(999999999), ci.subsecond); EXPECT_EQ(absl::Weekday::wednesday, absl::GetWeekday(ci.cs)); t += absl::Hours(24) * 2735; t += absl::Hours(18) + absl::Minutes(30) + absl::Seconds(15) + absl::Nanoseconds(9); ci = tz.At(t); EXPECT_CIVIL_INFO(ci, 1977, 6, 28, 14, 30, 15, -14400, true); EXPECT_EQ(8, ci.subsecond / absl::Nanoseconds(1)); EXPECT_EQ(absl::Weekday::tuesday, absl::GetWeekday(ci.cs)); } TEST(Time, AdditiveOperators) { const absl::Duration d = absl::Nanoseconds(1); const absl::Time t0; const absl::Time t1 = t0 + d; EXPECT_EQ(d, t1 - t0); EXPECT_EQ(-d, t0 - t1); EXPECT_EQ(t0, t1 - d); absl::Time t(t0); EXPECT_EQ(t0, t); t += d; EXPECT_EQ(t0 + d, t); EXPECT_EQ(d, t - t0); t -= d; EXPECT_EQ(t0, t); t = absl::UnixEpoch(); t += absl::Milliseconds(500); EXPECT_EQ(absl::UnixEpoch() + absl::Milliseconds(500), t); t += absl::Milliseconds(600); EXPECT_EQ(absl::UnixEpoch() + absl::Milliseconds(1100), t); t -= absl::Milliseconds(600); EXPECT_EQ(absl::UnixEpoch() + absl::Milliseconds(500), t); t -= absl::Milliseconds(500); EXPECT_EQ(absl::UnixEpoch(), t); } TEST(Time, RelationalOperators) { constexpr absl::Time t1 = absl::FromUnixNanos(0); constexpr absl::Time t2 = absl::FromUnixNanos(1); constexpr absl::Time t3 = absl::FromUnixNanos(2); static_assert(absl::UnixEpoch() == t1, ""); static_assert(t1 == t1, ""); static_assert(t2 == t2, ""); static_assert(t3 == t3, ""); static_assert(t1 < t2, ""); static_assert(t2 < t3, ""); static_assert(t1 < t3, ""); static_assert(t1 <= t1, ""); static_assert(t1 <= t2, ""); static_assert(t2 <= t2, ""); static_assert(t2 <= t3, ""); static_assert(t3 <= t3, ""); static_assert(t1 <= t3, ""); static_assert(t2 > t1, ""); static_assert(t3 > t2, ""); static_assert(t3 > t1, ""); static_assert(t2 >= t2, ""); static_assert(t2 >= t1, ""); static_assert(t3 >= t3, ""); static_assert(t3 >= t2, ""); static_assert(t1 >= t1, ""); static_assert(t3 >= t1, ""); #ifdef ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON static_assert((t1 <=> t1) == std::strong_ordering::equal, ""); static_assert((t2 <=> t2) == std::strong_ordering::equal, ""); static_assert((t3 <=> t3) == std::strong_ordering::equal, ""); static_assert((t1 <=> t2) == std::strong_ordering::less, ""); static_assert((t2 <=> t3) == std::strong_ordering::less, ""); static_assert((t1 <=> t3) == std::strong_ordering::less, ""); static_assert((t2 <=> t1) == std::strong_ordering::greater, ""); static_assert((t3 <=> t2) == std::strong_ordering::greater, ""); static_assert((t3 <=> t1) == std::strong_ordering::greater, ""); #endif } TEST(Time, Infinity) { constexpr absl::Time ifuture = absl::InfiniteFuture(); constexpr absl::Time ipast = absl::InfinitePast(); static_assert(ifuture == ifuture, ""); static_assert(ipast == ipast, ""); static_assert(ipast < ifuture, ""); static_assert(ifuture > ipast, ""); #ifdef ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON static_assert((ifuture <=> ifuture) == std::strong_ordering::equal, ""); static_assert((ipast <=> ipast) == std::strong_ordering::equal, ""); static_assert((ipast <=> ifuture) == std::strong_ordering::less, ""); static_assert((ifuture <=> ipast) == std::strong_ordering::greater, ""); #endif EXPECT_EQ(ifuture, ifuture + absl::Seconds(1)); EXPECT_EQ(ifuture, ifuture - absl::Seconds(1)); EXPECT_EQ(ipast, ipast + absl::Seconds(1)); EXPECT_EQ(ipast, ipast - absl::Seconds(1)); EXPECT_EQ(absl::InfiniteDuration(), ifuture - ifuture); EXPECT_EQ(absl::InfiniteDuration(), ifuture - ipast); EXPECT_EQ(-absl::InfiniteDuration(), ipast - ifuture); EXPECT_EQ(-absl::InfiniteDuration(), ipast - ipast); constexpr absl::Time t = absl::UnixEpoch(); static_assert(t < ifuture, ""); static_assert(t > ipast, ""); #ifdef ABSL_INTERNAL_TIME_HAS_THREE_WAY_COMPARISON static_assert((t <=> ifuture) == std::strong_ordering::less, ""); static_assert((t <=> ipast) == std::strong_ordering::greater, ""); static_assert((ipast <=> t) == std::strong_ordering::less, ""); static_assert((ifuture <=> t) == std::strong_ordering::greater, ""); #endif EXPECT_EQ(ifuture, t + absl::InfiniteDuration()); EXPECT_EQ(ipast, t - absl::InfiniteDuration()); } TEST(Time, FloorConversion) { #define TEST_FLOOR_CONVERSION(TO, FROM) \ EXPECT_EQ(1, TO(FROM(1001))); \ EXPECT_EQ(1, TO(FROM(1000))); \ EXPECT_EQ(0, TO(FROM(999))); \ EXPECT_EQ(0, TO(FROM(1))); \ EXPECT_EQ(0, TO(FROM(0))); \ EXPECT_EQ(-1, TO(FROM(-1))); \ EXPECT_EQ(-1, TO(FROM(-999))); \ EXPECT_EQ(-1, TO(FROM(-1000))); \ EXPECT_EQ(-2, TO(FROM(-1001))); TEST_FLOOR_CONVERSION(absl::ToUnixMicros, absl::FromUnixNanos); TEST_FLOOR_CONVERSION(absl::ToUnixMillis, absl::FromUnixMicros); TEST_FLOOR_CONVERSION(absl::ToUnixSeconds, absl::FromUnixMillis); TEST_FLOOR_CONVERSION(absl::ToTimeT, absl::FromUnixMillis); #undef TEST_FLOOR_CONVERSION EXPECT_EQ(1, absl::ToUnixNanos(absl::UnixEpoch() + absl::Nanoseconds(3) / 2)); EXPECT_EQ(1, absl::ToUnixNanos(absl::UnixEpoch() + absl::Nanoseconds(1))); EXPECT_EQ(0, absl::ToUnixNanos(absl::UnixEpoch() + absl::Nanoseconds(1) / 2)); EXPECT_EQ(0, absl::ToUnixNanos(absl::UnixEpoch() + absl::ZeroDuration())); EXPECT_EQ(-1, absl::ToUnixNanos(absl::UnixEpoch() - absl::Nanoseconds(1) / 2)); EXPECT_EQ(-1, absl::ToUnixNanos(absl::UnixEpoch() - absl::Nanoseconds(1))); EXPECT_EQ(-2, absl::ToUnixNanos(absl::UnixEpoch() - absl::Nanoseconds(3) / 2)); EXPECT_EQ(1, absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(101))); EXPECT_EQ(1, absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(100))); EXPECT_EQ(0, absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(99))); EXPECT_EQ(0, absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(1))); EXPECT_EQ(0, absl::ToUniversal(absl::UniversalEpoch() + absl::ZeroDuration())); EXPECT_EQ(-1, absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(-1))); EXPECT_EQ(-1, absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(-99))); EXPECT_EQ( -1, absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(-100))); EXPECT_EQ( -2, absl::ToUniversal(absl::UniversalEpoch() + absl::Nanoseconds(-101))); const struct { absl::Time t; timespec ts; } to_ts[] = { {absl::FromUnixSeconds(1) + absl::Nanoseconds(1), {1, 1}}, {absl::FromUnixSeconds(1) + absl::Nanoseconds(1) / 2, {1, 0}}, {absl::FromUnixSeconds(1) + absl::ZeroDuration(), {1, 0}}, {absl::FromUnixSeconds(0) + absl::ZeroDuration(), {0, 0}}, {absl::FromUnixSeconds(0) - absl::Nanoseconds(1) / 2, {-1, 999999999}}, {absl::FromUnixSeconds(0) - absl::Nanoseconds(1), {-1, 999999999}}, {absl::FromUnixSeconds(-1) + absl::Nanoseconds(1), {-1, 1}}, {absl::FromUnixSeconds(-1) + absl::Nanoseconds(1) / 2, {-1, 0}}, {absl::FromUnixSeconds(-1) + absl::ZeroDuration(), {-1, 0}}, {absl::FromUnixSeconds(-1) - absl::Nanoseconds(1) / 2, {-2, 999999999}}, }; for (const auto& test : to_ts) { EXPECT_THAT(absl::ToTimespec(test.t), TimespecMatcher(test.ts)); } const struct { timespec ts; absl::Time t; } from_ts[] = { {{1, 1}, absl::FromUnixSeconds(1) + absl::Nanoseconds(1)}, {{1, 0}, absl::FromUnixSeconds(1) + absl::ZeroDuration()}, {{0, 0}, absl::FromUnixSeconds(0) + absl::ZeroDuration()}, {{0, -1}, absl::FromUnixSeconds(0) - absl::Nanoseconds(1)}, {{-1, 999999999}, absl::FromUnixSeconds(0) - absl::Nanoseconds(1)}, {{-1, 1}, absl::FromUnixSeconds(-1) + absl::Nanoseconds(1)}, {{-1, 0}, absl::FromUnixSeconds(-1) + absl::ZeroDuration()}, {{-1, -1}, absl::FromUnixSeconds(-1) - absl::Nanoseconds(1)}, {{-2, 999999999}, absl::FromUnixSeconds(-1) - absl::Nanoseconds(1)}, }; for (const auto& test : from_ts) { EXPECT_EQ(test.t, absl::TimeFromTimespec(test.ts)); } const struct { absl::Time t; timeval tv; } to_tv[] = { {absl::FromUnixSeconds(1) + absl::Microseconds(1), {1, 1}}, {absl::FromUnixSeconds(1) + absl::Microseconds(1) / 2, {1, 0}}, {absl::FromUnixSeconds(1) + absl::ZeroDuration(), {1, 0}}, {absl::FromUnixSeconds(0) + absl::ZeroDuration(), {0, 0}}, {absl::FromUnixSeconds(0) - absl::Microseconds(1) / 2, {-1, 999999}}, {absl::FromUnixSeconds(0) - absl::Microseconds(1), {-1, 999999}}, {absl::FromUnixSeconds(-1) + absl::Microseconds(1), {-1, 1}}, {absl::FromUnixSeconds(-1) + absl::Microseconds(1) / 2, {-1, 0}}, {absl::FromUnixSeconds(-1) + absl::ZeroDuration(), {-1, 0}}, {absl::FromUnixSeconds(-1) - absl::Microseconds(1) / 2, {-2, 999999}}, }; for (const auto& test : to_tv) { EXPECT_THAT(absl::ToTimeval(test.t), TimevalMatcher(test.tv)); } const struct { timeval tv; absl::Time t; } from_tv[] = { {{1, 1}, absl::FromUnixSeconds(1) + absl::Microseconds(1)}, {{1, 0}, absl::FromUnixSeconds(1) + absl::ZeroDuration()}, {{0, 0}, absl::FromUnixSeconds(0) + absl::ZeroDuration()}, {{0, -1}, absl::FromUnixSeconds(0) - absl::Microseconds(1)}, {{-1, 999999}, absl::FromUnixSeconds(0) - absl::Microseconds(1)}, {{-1, 1}, absl::FromUnixSeconds(-1) + absl::Microseconds(1)}, {{-1, 0}, absl::FromUnixSeconds(-1) + absl::ZeroDuration()}, {{-1, -1}, absl::FromUnixSeconds(-1) - absl::Microseconds(1)}, {{-2, 999999}, absl::FromUnixSeconds(-1) - absl::Microseconds(1)}, }; for (const auto& test : from_tv) { EXPECT_EQ(test.t, absl::TimeFromTimeval(test.tv)); } const int64_t min_plus_1 = std::numeric_limits<int64_t>::min() + 1; EXPECT_EQ(min_plus_1, absl::ToUnixSeconds(absl::FromUnixSeconds(min_plus_1))); EXPECT_EQ(std::numeric_limits<int64_t>::min(), absl::ToUnixSeconds(absl::FromUnixSeconds(min_plus_1) - absl::Nanoseconds(1) / 2)); EXPECT_EQ(std::numeric_limits<int64_t>::max(), absl::ToUnixSeconds( absl::FromUnixSeconds(std::numeric_limits<int64_t>::max()) + absl::Nanoseconds(1) / 2)); EXPECT_EQ(std::numeric_limits<int64_t>::max(), absl::ToUnixSeconds( absl::FromUnixSeconds(std::numeric_limits<int64_t>::max()))); EXPECT_EQ(std::numeric_limits<int64_t>::max() - 1, absl::ToUnixSeconds( absl::FromUnixSeconds(std::numeric_limits<int64_t>::max()) - absl::Nanoseconds(1) / 2)); } TEST(Time, RoundtripConversion) { #define TEST_CONVERSION_ROUND_TRIP(SOURCE, FROM, TO, MATCHER) \ EXPECT_THAT(TO(FROM(SOURCE)), MATCHER(SOURCE)) int64_t now_ns = absl::GetCurrentTimeNanos(); TEST_CONVERSION_ROUND_TRIP(-1, absl::FromUnixNanos, absl::ToUnixNanos, testing::Eq); TEST_CONVERSION_ROUND_TRIP(0, absl::FromUnixNanos, absl::ToUnixNanos, testing::Eq); TEST_CONVERSION_ROUND_TRIP(1, absl::FromUnixNanos, absl::ToUnixNanos, testing::Eq); TEST_CONVERSION_ROUND_TRIP(now_ns, absl::FromUnixNanos, absl::ToUnixNanos, testing::Eq) << now_ns; int64_t now_us = absl::GetCurrentTimeNanos() / 1000; TEST_CONVERSION_ROUND_TRIP(-1, absl::FromUnixMicros, absl::ToUnixMicros, testing::Eq); TEST_CONVERSION_ROUND_TRIP(0, absl::FromUnixMicros, absl::ToUnixMicros, testing::Eq); TEST_CONVERSION_ROUND_TRIP(1, absl::FromUnixMicros, absl::ToUnixMicros, testing::Eq); TEST_CONVERSION_ROUND_TRIP(now_us, absl::FromUnixMicros, absl::ToUnixMicros, testing::Eq) << now_us; int64_t now_ms = absl::GetCurrentTimeNanos() / 1000000; TEST_CONVERSION_ROUND_TRIP(-1, absl::FromUnixMillis, absl::ToUnixMillis, testing::Eq); TEST_CONVERSION_ROUND_TRIP(0, absl::FromUnixMillis, absl::ToUnixMillis, testing::Eq); TEST_CONVERSION_ROUND_TRIP(1, absl::FromUnixMillis, absl::ToUnixMillis, testing::Eq); TEST_CONVERSION_ROUND_TRIP(now_ms, absl::FromUnixMillis, absl::ToUnixMillis, testing::Eq) << now_ms; int64_t now_s = std::time(nullptr); TEST_CONVERSION_ROUND_TRIP(-1, absl::FromUnixSeconds, absl::ToUnixSeconds, testing::Eq); TEST_CONVERSION_ROUND_TRIP(0, absl::FromUnixSeconds, absl::ToUnixSeconds, testing::Eq); TEST_CONVERSION_ROUND_TRIP(1, absl::FromUnixSeconds, absl::ToUnixSeconds, testing::Eq); TEST_CONVERSION_ROUND_TRIP(now_s, absl::FromUnixSeconds, absl::ToUnixSeconds, testing::Eq) << now_s; time_t now_time_t = std::time(nullptr); TEST_CONVERSION_ROUND_TRIP(-1, absl::FromTimeT, absl::ToTimeT, testing::Eq); TEST_CONVERSION_ROUND_TRIP(0, absl::FromTimeT, absl::ToTimeT, testing::Eq); TEST_CONVERSION_ROUND_TRIP(1, absl::FromTimeT, absl::ToTimeT, testing::Eq); TEST_CONVERSION_ROUND_TRIP(now_time_t, absl::FromTimeT, absl::ToTimeT, testing::Eq) << now_time_t; timeval tv; tv.tv_sec = -1; tv.tv_usec = 0; TEST_CONVERSION_ROUND_TRIP(tv, absl::TimeFromTimeval, absl::ToTimeval, TimevalMatcher); tv.tv_sec = -1; tv.tv_usec = 999999; TEST_CONVERSION_ROUND_TRIP(tv, absl::TimeFromTimeval, absl::ToTimeval, TimevalMatcher); tv.tv_sec = 0; tv.tv_usec = 0; TEST_CONVERSION_ROUND_TRIP(tv, absl::TimeFromTimeval, absl::ToTimeval, TimevalMatcher); tv.tv_sec = 0; tv.tv_usec = 1; TEST_CONVERSION_ROUND_TRIP(tv, absl::TimeFromTimeval, absl::ToTimeval, TimevalMatcher); tv.tv_sec = 1; tv.tv_usec = 0; TEST_CONVERSION_ROUND_TRIP(tv, absl::TimeFromTimeval, absl::ToTimeval, TimevalMatcher); timespec ts; ts.tv_sec = -1; ts.tv_nsec = 0; TEST_CONVERSION_ROUND_TRIP(ts, absl::TimeFromTimespec, absl::ToTimespec, TimespecMatcher); ts.tv_sec = -1; ts.tv_nsec = 999999999; TEST_CONVERSION_ROUND_TRIP(ts, absl::TimeFromTimespec, absl::ToTimespec, TimespecMatcher); ts.tv_sec = 0; ts.tv_nsec = 0; TEST_CONVERSION_ROUND_TRIP(ts, absl::TimeFromTimespec, absl::ToTimespec, TimespecMatcher); ts.tv_sec = 0; ts.tv_nsec = 1; TEST_CONVERSION_ROUND_TRIP(ts, absl::TimeFromTimespec, absl::ToTimespec, TimespecMatcher); ts.tv_sec = 1; ts.tv_nsec = 0; TEST_CONVERSION_ROUND_TRIP(ts, absl::TimeFromTimespec, absl::ToTimespec, TimespecMatcher); double now_ud = absl::GetCurrentTimeNanos() / 1000000; TEST_CONVERSION_ROUND_TRIP(-1.5, absl::FromUDate, absl::ToUDate, testing::DoubleEq); TEST_CONVERSION_ROUND_TRIP(-1, absl::FromUDate, absl::ToUDate, testing::DoubleEq); TEST_CONVERSION_ROUND_TRIP(-0.5, absl::FromUDate, absl::ToUDate, testing::DoubleEq); TEST_CONVERSION_ROUND_TRIP(0, absl::FromUDate, absl::ToUDate, testing::DoubleEq); TEST_CONVERSION_ROUND_TRIP(0.5, absl::FromUDate, absl::ToUDate, testing::DoubleEq); TEST_CONVERSION_ROUND_TRIP(1, absl::FromUDate, absl::ToUDate, testing::DoubleEq); TEST_CONVERSION_ROUND_TRIP(1.5, absl::FromUDate, absl::ToUDate, testing::DoubleEq); TEST_CONVERSION_ROUND_TRIP(now_ud, absl::FromUDate, absl::ToUDate, testing::DoubleEq) << std::fixed << std::setprecision(17) << now_ud; int64_t now_uni = ((719162LL * (24 * 60 * 60)) * (1000 * 1000 * 10)) + (absl::GetCurrentTimeNanos() / 100); TEST_CONVERSION_ROUND_TRIP(-1, absl::FromUniversal, absl::ToUniversal, testing::Eq); TEST_CONVERSION_ROUND_TRIP(0, absl::FromUniversal, absl::ToUniversal, testing::Eq); TEST_CONVERSION_ROUND_TRIP(1, absl::FromUniversal, absl::ToUniversal, testing::Eq); TEST_CONVERSION_ROUND_TRIP(now_uni, absl::FromUniversal, absl::ToUniversal, testing::Eq) << now_uni; #undef TEST_CONVERSION_ROUND_TRIP } template <typename Duration> std::chrono::system_clock::time_point MakeChronoUnixTime(const Duration& d) { return std::chrono::system_clock::from_time_t(0) + d; } TEST(Time, FromChrono) { EXPECT_EQ(absl::FromTimeT(-1), absl::FromChrono(std::chrono::system_clock::from_time_t(-1))); EXPECT_EQ(absl::FromTimeT(0), absl::FromChrono(std::chrono::system_clock::from_time_t(0))); EXPECT_EQ(absl::FromTimeT(1), absl::FromChrono(std::chrono::system_clock::from_time_t(1))); EXPECT_EQ( absl::FromUnixMillis(-1), absl::FromChrono(MakeChronoUnixTime(std::chrono::milliseconds(-1)))); EXPECT_EQ(absl::FromUnixMillis(0), absl::FromChrono(MakeChronoUnixTime(std::chrono::milliseconds(0)))); EXPECT_EQ(absl::FromUnixMillis(1), absl::FromChrono(MakeChronoUnixTime(std::chrono::milliseconds(1)))); const auto century_sec = 60 * 60 * 24 * 365 * int64_t{100}; const auto century = std::chrono::seconds(century_sec); const auto chrono_future = MakeChronoUnixTime(century); const auto chrono_past = MakeChronoUnixTime(-century); EXPECT_EQ(absl::FromUnixSeconds(century_sec), absl::FromChrono(chrono_future)); EXPECT_EQ(absl::FromUnixSeconds(-century_sec), absl::FromChrono(chrono_past)); EXPECT_EQ(chrono_future, absl::ToChronoTime(absl::FromUnixSeconds(century_sec))); EXPECT_EQ(chrono_past, absl::ToChronoTime(absl::FromUnixSeconds(-century_sec))); } TEST(Time, ToChronoTime) { EXPECT_EQ(std::chrono::system_clock::from_time_t(-1), absl::ToChronoTime(absl::FromTimeT(-1))); EXPECT_EQ(std::chrono::system_clock::from_time_t(0), absl::ToChronoTime(absl::FromTimeT(0))); EXPECT_EQ(std::chrono::system_clock::from_time_t(1), absl::ToChronoTime(absl::FromTimeT(1))); EXPECT_EQ(MakeChronoUnixTime(std::chrono::milliseconds(-1)), absl::ToChronoTime(absl::FromUnixMillis(-1))); EXPECT_EQ(MakeChronoUnixTime(std::chrono::milliseconds(0)), absl::ToChronoTime(absl::FromUnixMillis(0))); EXPECT_EQ(MakeChronoUnixTime(std::chrono::milliseconds(1)), absl::ToChronoTime(absl::FromUnixMillis(1))); const auto tick = absl::Nanoseconds(1) / 4; EXPECT_EQ(std::chrono::system_clock::from_time_t(0) - std::chrono::system_clock::duration(1), absl::ToChronoTime(absl::UnixEpoch() - tick)); } TEST(Time, Chrono128) { using Timestamp = std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<absl::int128, std::atto>>; for (const auto tp : {std::chrono::system_clock::time_point::min(), std::chrono::system_clock::time_point::max()}) { EXPECT_EQ(tp, absl::ToChronoTime(absl::FromChrono(tp))); EXPECT_EQ(tp, std::chrono::time_point_cast< std::chrono::system_clock::time_point::duration>( std::chrono::time_point_cast<Timestamp::duration>(tp))); } Timestamp::duration::rep v = std::numeric_limits<int64_t>::min(); v *= Timestamp::duration::period::den; auto ts = Timestamp(Timestamp::duration(v)); ts += std::chrono::duration<int64_t, std::atto>(0); EXPECT_EQ(std::numeric_limits<int64_t>::min(), ts.time_since_epoch().count() / Timestamp::duration::period::den); EXPECT_EQ(0, ts.time_since_epoch().count() % Timestamp::duration::period::den); v = std::numeric_limits<int64_t>::max(); v *= Timestamp::duration::period::den; ts = Timestamp(Timestamp::duration(v)); ts += std::chrono::duration<int64_t, std::atto>(999999999750000000); EXPECT_EQ(std::numeric_limits<int64_t>::max(), ts.time_since_epoch().count() / Timestamp::duration::period::den); EXPECT_EQ(999999999750000000, ts.time_since_epoch().count() % Timestamp::duration::period::den); } TEST(Time, TimeZoneAt) { const absl::TimeZone nyc = absl::time_internal::LoadTimeZone("America/New_York"); const std::string fmt = "%a, %e %b %Y %H:%M:%S %z (%Z)"; absl::CivilSecond nov01(2013, 11, 1, 8, 30, 0); const auto nov01_ci = nyc.At(nov01); EXPECT_EQ(absl::TimeZone::TimeInfo::UNIQUE, nov01_ci.kind); EXPECT_EQ("Fri, 1 Nov 2013 08:30:00 -0400 (EDT)", absl::FormatTime(fmt, nov01_ci.pre, nyc)); EXPECT_EQ(nov01_ci.pre, nov01_ci.trans); EXPECT_EQ(nov01_ci.pre, nov01_ci.post); EXPECT_EQ(nov01_ci.pre, absl::FromCivil(nov01, nyc)); absl::CivilSecond mar13(2011, 3, 13, 2, 15, 0); const auto mar_ci = nyc.At(mar13); EXPECT_EQ(absl::TimeZone::TimeInfo::SKIPPED, mar_ci.kind); EXPECT_EQ("Sun, 13 Mar 2011 03:15:00 -0400 (EDT)", absl::FormatTime(fmt, mar_ci.pre, nyc)); EXPECT_EQ("Sun, 13 Mar 2011 03:00:00 -0400 (EDT)", absl::FormatTime(fmt, mar_ci.trans, nyc)); EXPECT_EQ("Sun, 13 Mar 2011 01:15:00 -0500 (EST)", absl::FormatTime(fmt, mar_ci.post, nyc)); EXPECT_EQ(mar_ci.trans, absl::FromCivil(mar13, nyc)); absl::CivilSecond nov06(2011, 11, 6, 1, 15, 0); const auto nov06_ci = nyc.At(nov06); EXPECT_EQ(absl::TimeZone::TimeInfo::REPEATED, nov06_ci.kind); EXPECT_EQ("Sun, 6 Nov 2011 01:15:00 -0400 (EDT)", absl::FormatTime(fmt, nov06_ci.pre, nyc)); EXPECT_EQ("Sun, 6 Nov 2011 01:00:00 -0500 (EST)", absl::FormatTime(fmt, nov06_ci.trans, nyc)); EXPECT_EQ("Sun, 6 Nov 2011 01:15:00 -0500 (EST)", absl::FormatTime(fmt, nov06_ci.post, nyc)); EXPECT_EQ(nov06_ci.pre, absl::FromCivil(nov06, nyc)); absl::CivilSecond minus1(1969, 12, 31, 18, 59, 59); const auto minus1_cl = nyc.At(minus1); EXPECT_EQ(absl::TimeZone::TimeInfo::UNIQUE, minus1_cl.kind); EXPECT_EQ(-1, absl::ToTimeT(minus1_cl.pre)); EXPECT_EQ("Wed, 31 Dec 1969 18:59:59 -0500 (EST)", absl::FormatTime(fmt, minus1_cl.pre, nyc)); EXPECT_EQ("Wed, 31 Dec 1969 23:59:59 +0000 (UTC)", absl::FormatTime(fmt, minus1_cl.pre, absl::UTCTimeZone())); } TEST(Time, FromCivilUTC) { const absl::TimeZone utc = absl::UTCTimeZone(); const std::string fmt = "%a, %e %b %Y %H:%M:%S %z (%Z)"; const int kMax = std::numeric_limits<int>::max(); const int kMin = std::numeric_limits<int>::min(); absl::Time t; t = absl::FromCivil( absl::CivilSecond(292091940881, kMax, kMax, kMax, kMax, kMax), utc); EXPECT_EQ("Fri, 25 Nov 292277026596 12:21:07 +0000 (UTC)", absl::FormatTime(fmt, t, utc)); t = absl::FromCivil( absl::CivilSecond(292091940882, kMax, kMax, kMax, kMax, kMax), utc); EXPECT_EQ("infinite-future", absl::FormatTime(fmt, t, utc)); t = absl::FromCivil( absl::CivilSecond(-292091936940, kMin, kMin, kMin, kMin, kMin), utc); EXPECT_EQ("Fri, 1 Nov -292277022657 10:37:52 +0000 (UTC)", absl::FormatTime(fmt, t, utc)); t = absl::FromCivil( absl::CivilSecond(-292091936941, kMin, kMin, kMin, kMin, kMin), utc); EXPECT_EQ("infinite-past", absl::FormatTime(fmt, t, utc)); t = absl::FromCivil(absl::CivilSecond(1900, 2, 28, 23, 59, 59), utc); EXPECT_EQ("Wed, 28 Feb 1900 23:59:59 +0000 (UTC)", absl::FormatTime(fmt, t, utc)); t = absl::FromCivil(absl::CivilSecond(1900, 3, 1, 0, 0, 0), utc); EXPECT_EQ("Thu, 1 Mar 1900 00:00:00 +0000 (UTC)", absl::FormatTime(fmt, t, utc)); t = absl::FromCivil(absl::CivilSecond(2000, 2, 29, 23, 59, 59), utc); EXPECT_EQ("Tue, 29 Feb 2000 23:59:59 +0000 (UTC)", absl::FormatTime(fmt, t, utc)); t = absl::FromCivil(absl::CivilSecond(2000, 3, 1, 0, 0, 0), utc); EXPECT_EQ("Wed, 1 Mar 2000 00:00:00 +0000 (UTC)", absl::FormatTime(fmt, t, utc)); } TEST(Time, ToTM) { const absl::TimeZone utc = absl::UTCTimeZone(); const absl::Time start = absl::FromCivil(absl::CivilSecond(2014, 1, 2, 3, 4, 5), utc); const absl::Time end = absl::FromCivil(absl::CivilSecond(2014, 1, 5, 3, 4, 5), utc); for (absl::Time t = start; t < end; t += absl::Seconds(30)) { const struct tm tm_bt = absl::ToTM(t, utc); const time_t tt = absl::ToTimeT(t); struct tm tm_lc; #ifdef _WIN32 gmtime_s(&tm_lc, &tt); #else gmtime_r(&tt, &tm_lc); #endif EXPECT_EQ(tm_lc.tm_year, tm_bt.tm_year); EXPECT_EQ(tm_lc.tm_mon, tm_bt.tm_mon); EXPECT_EQ(tm_lc.tm_mday, tm_bt.tm_mday); EXPECT_EQ(tm_lc.tm_hour, tm_bt.tm_hour); EXPECT_EQ(tm_lc.tm_min, tm_bt.tm_min); EXPECT_EQ(tm_lc.tm_sec, tm_bt.tm_sec); EXPECT_EQ(tm_lc.tm_wday, tm_bt.tm_wday); EXPECT_EQ(tm_lc.tm_yday, tm_bt.tm_yday); EXPECT_EQ(tm_lc.tm_isdst, tm_bt.tm_isdst); ASSERT_FALSE(HasFailure()); } const absl::TimeZone nyc = absl::time_internal::LoadTimeZone("America/New_York"); absl::Time t = absl::FromCivil(absl::CivilSecond(2014, 3, 1, 0, 0, 0), nyc); struct tm tm = absl::ToTM(t, nyc); EXPECT_FALSE(tm.tm_isdst); t = absl::FromCivil(absl::CivilSecond(2014, 4, 1, 0, 0, 0), nyc); tm = absl::ToTM(t, nyc); EXPECT_TRUE(tm.tm_isdst); tm = absl::ToTM(absl::InfiniteFuture(), nyc); EXPECT_EQ(std::numeric_limits<int>::max() - 1900, tm.tm_year); EXPECT_EQ(11, tm.tm_mon); EXPECT_EQ(31, tm.tm_mday); EXPECT_EQ(23, tm.tm_hour); EXPECT_EQ(59, tm.tm_min); EXPECT_EQ(59, tm.tm_sec); EXPECT_EQ(4, tm.tm_wday); EXPECT_EQ(364, tm.tm_yday); EXPECT_FALSE(tm.tm_isdst); tm = absl::ToTM(absl::InfinitePast(), nyc); EXPECT_EQ(std::numeric_limits<int>::min(), tm.tm_year); EXPECT_EQ(0, tm.tm_mon); EXPECT_EQ(1, tm.tm_mday); EXPECT_EQ(0, tm.tm_hour); EXPECT_EQ(0, tm.tm_min); EXPECT_EQ(0, tm.tm_sec); EXPECT_EQ(0, tm.tm_wday); EXPECT_EQ(0, tm.tm_yday); EXPECT_FALSE(tm.tm_isdst); } TEST(Time, FromTM) { const absl::TimeZone nyc = absl::time_internal::LoadTimeZone("America/New_York"); struct tm tm; std::memset(&tm, 0, sizeof(tm)); tm.tm_year = 2014 - 1900; tm.tm_mon = 6 - 1; tm.tm_mday = 28; tm.tm_hour = 1; tm.tm_min = 2; tm.tm_sec = 3; tm.tm_isdst = -1; absl::Time t = absl::FromTM(tm, nyc); EXPECT_EQ("2014-06-28T01:02:03-04:00", absl::FormatTime(t, nyc)); tm.tm_isdst = 0; t = absl::FromTM(tm, nyc); EXPECT_EQ("2014-06-28T01:02:03-04:00", absl::FormatTime(t, nyc)); tm.tm_isdst = 1; t = absl::FromTM(tm, nyc); EXPECT_EQ("2014-06-28T01:02:03-04:00", absl::FormatTime(t, nyc)); tm.tm_year = 2014 - 1900; tm.tm_mon = 11 - 1; tm.tm_mday = 2; tm.tm_hour = 1; tm.tm_min = 30; tm.tm_sec = 42; tm.tm_isdst = -1; t = absl::FromTM(tm, nyc); EXPECT_EQ("2014-11-02T01:30:42-04:00", absl::FormatTime(t, nyc)); tm.tm_isdst = 0; t = absl::FromTM(tm, nyc); EXPECT_EQ("2014-11-02T01:30:42-05:00", absl::FormatTime(t, nyc)); tm.tm_isdst = 1; t = absl::FromTM(tm, nyc); EXPECT_EQ("2014-11-02T01:30:42-04:00", absl::FormatTime(t, nyc)); tm.tm_year = 2014 - 1900; tm.tm_mon = 3 - 1; tm.tm_mday = 9; tm.tm_hour = 2; tm.tm_min = 30; tm.tm_sec = 42; tm.tm_isdst = -1; t = absl::FromTM(tm, nyc); EXPECT_EQ("2014-03-09T03:30:42-04:00", absl::FormatTime(t, nyc)); tm.tm_isdst = 0; t = absl::FromTM(tm, nyc); EXPECT_EQ("2014-03-09T01:30:42-05:00", absl::FormatTime(t, nyc)); tm.tm_isdst = 1; t = absl::FromTM(tm, nyc); EXPECT_EQ("2014-03-09T03:30:42-04:00", absl::FormatTime(t, nyc)); tm.tm_year = 2147483647 - 1900 + 1; tm.tm_mon = 6 - 1; tm.tm_mday = 28; tm.tm_hour = 1; tm.tm_min = 2; tm.tm_sec = 3; tm.tm_isdst = -1; t = absl::FromTM(tm, absl::UTCTimeZone()); EXPECT_EQ("2147483648-06-28T01:02:03+00:00", absl::FormatTime(t, absl::UTCTimeZone())); tm.tm_year = 2019 - 1900; tm.tm_mon = 2147483647; tm.tm_mday = 28; tm.tm_hour = 1; tm.tm_min = 2; tm.tm_sec = 3; tm.tm_isdst = -1; t = absl::FromTM(tm, absl::UTCTimeZone()); EXPECT_EQ("178958989-08-28T01:02:03+00:00", absl::FormatTime(t, absl::UTCTimeZone())); } TEST(Time, TMRoundTrip) { const absl::TimeZone nyc = absl::time_internal::LoadTimeZone("America/New_York"); absl::Time start = absl::FromCivil(absl::CivilHour(2014, 3, 9, 0), nyc); absl::Time end = absl::FromCivil(absl::CivilHour(2014, 3, 9, 4), nyc); for (absl::Time t = start; t < end; t += absl::Minutes(1)) { struct tm tm = absl::ToTM(t, nyc); absl::Time rt = absl::FromTM(tm, nyc); EXPECT_EQ(rt, t); } start = absl::FromCivil(absl::CivilHour(2014, 11, 2, 0), nyc); end = absl::FromCivil(absl::CivilHour(2014, 11, 2, 4), nyc); for (absl::Time t = start; t < end; t += absl::Minutes(1)) { struct tm tm = absl::ToTM(t, nyc); absl::Time rt = absl::FromTM(tm, nyc); EXPECT_EQ(rt, t); } start = absl::FromCivil(absl::CivilHour(2014, 6, 27, 22), nyc); end = absl::FromCivil(absl::CivilHour(2014, 6, 28, 4), nyc); for (absl::Time t = start; t < end; t += absl::Minutes(1)) { struct tm tm = absl::ToTM(t, nyc); absl::Time rt = absl::FromTM(tm, nyc); EXPECT_EQ(rt, t); } } TEST(Time, Range) { const absl::Duration range = absl::Hours(24) * 365.2425 * 100000000000; absl::Time bases[2] = {absl::UnixEpoch(), absl::Now()}; for (const auto base : bases) { absl::Time bottom = base - range; EXPECT_GT(bottom, bottom - absl::Nanoseconds(1)); EXPECT_LT(bottom, bottom + absl::Nanoseconds(1)); absl::Time top = base + range; EXPECT_GT(top, top - absl::Nanoseconds(1)); EXPECT_LT(top, top + absl::Nanoseconds(1)); absl::Duration full_range = 2 * range; EXPECT_EQ(full_range, top - bottom); EXPECT_EQ(-full_range, bottom - top); } } TEST(Time, Limits) { const absl::Time zero; const absl::Time max = zero + absl::Seconds(std::numeric_limits<int64_t>::max()) + absl::Nanoseconds(999999999) + absl::Nanoseconds(3) / 4; const absl::Time min = zero + absl::Seconds(std::numeric_limits<int64_t>::min()); EXPECT_LT(max, absl::InfiniteFuture()); EXPECT_GT(min, absl::InfinitePast()); EXPECT_LT(zero, max); EXPECT_GT(zero, min); EXPECT_GE(absl::UnixEpoch(), min); EXPECT_LT(absl::UnixEpoch(), max); EXPECT_LT(absl::ZeroDuration(), max - zero); EXPECT_LT(absl::ZeroDuration(), zero - absl::Nanoseconds(1) / 4 - min); EXPECT_GT(max, max - absl::Nanoseconds(1) / 4); EXPECT_LT(min, min + absl::Nanoseconds(1) / 4); } TEST(Time, ConversionSaturation) { const absl::TimeZone utc = absl::UTCTimeZone(); absl::Time t; const auto max_time_t = std::numeric_limits<time_t>::max(); const auto min_time_t = std::numeric_limits<time_t>::min(); time_t tt = max_time_t - 1; t = absl::FromTimeT(tt); tt = absl::ToTimeT(t); EXPECT_EQ(max_time_t - 1, tt); t += absl::Seconds(1); tt = absl::ToTimeT(t); EXPECT_EQ(max_time_t, tt); t += absl::Seconds(1); tt = absl::ToTimeT(t); EXPECT_EQ(max_time_t, tt); tt = min_time_t + 1; t = absl::FromTimeT(tt); tt = absl::ToTimeT(t); EXPECT_EQ(min_time_t + 1, tt); t -= absl::Seconds(1); tt = absl::ToTimeT(t); EXPECT_EQ(min_time_t, tt); t -= absl::Seconds(1); tt = absl::ToTimeT(t); EXPECT_EQ(min_time_t, tt); const auto max_timeval_sec = std::numeric_limits<decltype(timeval::tv_sec)>::max(); const auto min_timeval_sec = std::numeric_limits<decltype(timeval::tv_sec)>::min(); timeval tv; tv.tv_sec = max_timeval_sec; tv.tv_usec = 999998; t = absl::TimeFromTimeval(tv); tv = absl::ToTimeval(t); EXPECT_EQ(max_timeval_sec, tv.tv_sec); EXPECT_EQ(999998, tv.tv_usec); t += absl::Microseconds(1); tv = absl::ToTimeval(t); EXPECT_EQ(max_timeval_sec, tv.tv_sec); EXPECT_EQ(999999, tv.tv_usec); t += absl::Microseconds(1); tv = absl::ToTimeval(t); EXPECT_EQ(max_timeval_sec, tv.tv_sec); EXPECT_EQ(999999, tv.tv_usec); tv.tv_sec = min_timeval_sec; tv.tv_usec = 1; t = absl::TimeFromTimeval(tv); tv = absl::ToTimeval(t); EXPECT_EQ(min_timeval_sec, tv.tv_sec); EXPECT_EQ(1, tv.tv_usec); t -= absl::Microseconds(1); tv = absl::ToTimeval(t); EXPECT_EQ(min_timeval_sec, tv.tv_sec); EXPECT_EQ(0, tv.tv_usec); t -= absl::Microseconds(1); tv = absl::ToTimeval(t); EXPECT_EQ(min_timeval_sec, tv.tv_sec); EXPECT_EQ(0, tv.tv_usec); const auto max_timespec_sec = std::numeric_limits<decltype(timespec::tv_sec)>::max(); const auto min_timespec_sec = std::numeric_limits<decltype(timespec::tv_sec)>::min(); timespec ts; ts.tv_sec = max_timespec_sec; ts.tv_nsec = 999999998; t = absl::TimeFromTimespec(ts); ts = absl::ToTimespec(t); EXPECT_EQ(max_timespec_sec, ts.tv_sec); EXPECT_EQ(999999998, ts.tv_nsec); t += absl::Nanoseconds(1); ts = absl::ToTimespec(t); EXPECT_EQ(max_timespec_sec, ts.tv_sec); EXPECT_EQ(999999999, ts.tv_nsec); t += absl::Nanoseconds(1); ts = absl::ToTimespec(t); EXPECT_EQ(max_timespec_sec, ts.tv_sec); EXPECT_EQ(999999999, ts.tv_nsec); ts.tv_sec = min_timespec_sec; ts.tv_nsec = 1; t = absl::TimeFromTimespec(ts); ts = absl::ToTimespec(t); EXPECT_EQ(min_timespec_sec, ts.tv_sec); EXPECT_EQ(1, ts.tv_nsec); t -= absl::Nanoseconds(1); ts = absl::ToTimespec(t); EXPECT_EQ(min_timespec_sec, ts.tv_sec); EXPECT_EQ(0, ts.tv_nsec); t -= absl::Nanoseconds(1); ts = absl::ToTimespec(t); EXPECT_EQ(min_timespec_sec, ts.tv_sec); EXPECT_EQ(0, ts.tv_nsec); auto ci = utc.At(absl::InfiniteFuture()); EXPECT_CIVIL_INFO(ci, std::numeric_limits<int64_t>::max(), 12, 31, 23, 59, 59, 0, false); EXPECT_EQ(absl::InfiniteDuration(), ci.subsecond); EXPECT_EQ(absl::Weekday::thursday, absl::GetWeekday(ci.cs)); EXPECT_EQ(365, absl::GetYearDay(ci.cs)); EXPECT_STREQ("-00", ci.zone_abbr); ci = utc.At(absl::InfinitePast()); EXPECT_CIVIL_INFO(ci, std::numeric_limits<int64_t>::min(), 1, 1, 0, 0, 0, 0, false); EXPECT_EQ(-absl::InfiniteDuration(), ci.subsecond); EXPECT_EQ(absl::Weekday::sunday, absl::GetWeekday(ci.cs)); EXPECT_EQ(1, absl::GetYearDay(ci.cs)); EXPECT_STREQ("-00", ci.zone_abbr); t = absl::FromCivil(absl::CivilSecond(292277026596, 12, 4, 15, 30, 6), utc); EXPECT_EQ("292277026596-12-04T15:30:06+00:00", absl::FormatTime(absl::RFC3339_full, t, utc)); t = absl::FromCivil(absl::CivilSecond(292277026596, 12, 4, 15, 30, 7), utc); EXPECT_EQ("292277026596-12-04T15:30:07+00:00", absl::FormatTime(absl::RFC3339_full, t, utc)); EXPECT_EQ( absl::UnixEpoch() + absl::Seconds(std::numeric_limits<int64_t>::max()), t); const absl::TimeZone plus14 = absl::FixedTimeZone(14 * 60 * 60); t = absl::FromCivil(absl::CivilSecond(292277026596, 12, 5, 5, 30, 7), plus14); EXPECT_EQ("292277026596-12-05T05:30:07+14:00", absl::FormatTime(absl::RFC3339_full, t, plus14)); EXPECT_EQ( absl::UnixEpoch() + absl::Seconds(std::numeric_limits<int64_t>::max()), t); t = absl::FromCivil(absl::CivilSecond(292277026596, 12, 4, 15, 30, 8), utc); EXPECT_EQ("infinite-future", absl::FormatTime(absl::RFC3339_full, t, utc)); t = absl::FromCivil(absl::CivilSecond(-292277022657, 1, 27, 8, 29, 53), utc); EXPECT_EQ("-292277022657-01-27T08:29:53+00:00", absl::FormatTime(absl::RFC3339_full, t, utc)); t = absl::FromCivil(absl::CivilSecond(-292277022657, 1, 27, 8, 29, 52), utc); EXPECT_EQ("-292277022657-01-27T08:29:52+00:00", absl::FormatTime(absl::RFC3339_full, t, utc)); EXPECT_EQ( absl::UnixEpoch() + absl::Seconds(std::numeric_limits<int64_t>::min()), t); const absl::TimeZone minus12 = absl::FixedTimeZone(-12 * 60 * 60); t = absl::FromCivil(absl::CivilSecond(-292277022657, 1, 26, 20, 29, 52), minus12); EXPECT_EQ("-292277022657-01-26T20:29:52-12:00", absl::FormatTime(absl::RFC3339_full, t, minus12)); EXPECT_EQ( absl::UnixEpoch() + absl::Seconds(std::numeric_limits<int64_t>::min()), t); t = absl::FromCivil(absl::CivilSecond(-292277022657, 1, 27, 8, 29, 51), utc); EXPECT_EQ("infinite-past", absl::FormatTime(absl::RFC3339_full, t, utc)); } TEST(Time, ExtendedConversionSaturation) { const absl::TimeZone syd = absl::time_internal::LoadTimeZone("Australia/Sydney"); const absl::TimeZone nyc = absl::time_internal::LoadTimeZone("America/New_York"); const absl::Time max = absl::FromUnixSeconds(std::numeric_limits<int64_t>::max()); absl::TimeZone::CivilInfo ci; absl::Time t; ci = syd.At(max); EXPECT_CIVIL_INFO(ci, 292277026596, 12, 5, 2, 30, 7, 39600, true); t = absl::FromCivil(absl::CivilSecond(292277026596, 12, 5, 2, 30, 7), syd); EXPECT_EQ(max, t); ci = nyc.At(max); EXPECT_CIVIL_INFO(ci, 292277026596, 12, 4, 10, 30, 7, -18000, false); t = absl::FromCivil(absl::CivilSecond(292277026596, 12, 4, 10, 30, 7), nyc); EXPECT_EQ(max, t); t = absl::FromCivil(absl::CivilSecond(292277026596, 12, 5, 2, 30, 8), syd); EXPECT_EQ(absl::InfiniteFuture(), t); t = absl::FromCivil(absl::CivilSecond(292277026596, 12, 4, 10, 30, 8), nyc); EXPECT_EQ(absl::InfiniteFuture(), t); t = absl::FromCivil(absl::CivilSecond(292277026596, 12, 5, 2, 30, 9), syd); EXPECT_EQ(absl::InfiniteFuture(), t); t = absl::FromCivil(absl::CivilSecond(292277026596, 12, 4, 10, 30, 9), nyc); EXPECT_EQ(absl::InfiniteFuture(), t); t = absl::FromCivil(absl::CivilSecond::max(), syd); EXPECT_EQ(absl::InfiniteFuture(), t); t = absl::FromCivil(absl::CivilSecond::max(), nyc); EXPECT_EQ(absl::InfiniteFuture(), t); } TEST(Time, FromCivilAlignment) { const absl::TimeZone utc = absl::UTCTimeZone(); const absl::CivilSecond cs(2015, 2, 3, 4, 5, 6); absl::Time t = absl::FromCivil(cs, utc); EXPECT_EQ("2015-02-03T04:05:06+00:00", absl::FormatTime(t, utc)); t = absl::FromCivil(absl::CivilMinute(cs), utc); EXPECT_EQ("2015-02-03T04:05:00+00:00", absl::FormatTime(t, utc)); t = absl::FromCivil(absl::CivilHour(cs), utc); EXPECT_EQ("2015-02-03T04:00:00+00:00", absl::FormatTime(t, utc)); t = absl::FromCivil(absl::CivilDay(cs), utc); EXPECT_EQ("2015-02-03T00:00:00+00:00", absl::FormatTime(t, utc)); t = absl::FromCivil(absl::CivilMonth(cs), utc); EXPECT_EQ("2015-02-01T00:00:00+00:00", absl::FormatTime(t, utc)); t = absl::FromCivil(absl::CivilYear(cs), utc); EXPECT_EQ("2015-01-01T00:00:00+00:00", absl::FormatTime(t, utc)); } TEST(Time, LegacyDateTime) { const absl::TimeZone utc = absl::UTCTimeZone(); const std::string ymdhms = "%Y-%m-%d %H:%M:%S"; const int kMax = std::numeric_limits<int>::max(); const int kMin = std::numeric_limits<int>::min(); absl::Time t; t = absl::FromDateTime(std::numeric_limits<absl::civil_year_t>::max(), kMax, kMax, kMax, kMax, kMax, utc); EXPECT_EQ("infinite-future", absl::FormatTime(ymdhms, t, utc)); t = absl::FromDateTime(std::numeric_limits<absl::civil_year_t>::min(), kMin, kMin, kMin, kMin, kMin, utc); EXPECT_EQ("infinite-past", absl::FormatTime(ymdhms, t, utc)); EXPECT_TRUE(absl::ConvertDateTime(2013, 10, 32, 8, 30, 0, utc).normalized); t = absl::FromDateTime(2015, 1, 1, 0, 0, 60, utc); EXPECT_EQ("2015-01-01 00:01:00", absl::FormatTime(ymdhms, t, utc)); t = absl::FromDateTime(2015, 1, 1, 0, 60, 0, utc); EXPECT_EQ("2015-01-01 01:00:00", absl::FormatTime(ymdhms, t, utc)); t = absl::FromDateTime(2015, 1, 1, 24, 0, 0, utc); EXPECT_EQ("2015-01-02 00:00:00", absl::FormatTime(ymdhms, t, utc)); t = absl::FromDateTime(2015, 1, 32, 0, 0, 0, utc); EXPECT_EQ("2015-02-01 00:00:00", absl::FormatTime(ymdhms, t, utc)); t = absl::FromDateTime(2015, 13, 1, 0, 0, 0, utc); EXPECT_EQ("2016-01-01 00:00:00", absl::FormatTime(ymdhms, t, utc)); t = absl::FromDateTime(2015, 13, 32, 60, 60, 60, utc); EXPECT_EQ("2016-02-03 13:01:00", absl::FormatTime(ymdhms, t, utc)); t = absl::FromDateTime(2015, 1, 1, 0, 0, -1, utc); EXPECT_EQ("2014-12-31 23:59:59", absl::FormatTime(ymdhms, t, utc)); t = absl::FromDateTime(2015, 1, 1, 0, -1, 0, utc); EXPECT_EQ("2014-12-31 23:59:00", absl::FormatTime(ymdhms, t, utc)); t = absl::FromDateTime(2015, 1, 1, -1, 0, 0, utc); EXPECT_EQ("2014-12-31 23:00:00", absl::FormatTime(ymdhms, t, utc)); t = absl::FromDateTime(2015, 1, -1, 0, 0, 0, utc); EXPECT_EQ("2014-12-30 00:00:00", absl::FormatTime(ymdhms, t, utc)); t = absl::FromDateTime(2015, -1, 1, 0, 0, 0, utc); EXPECT_EQ("2014-11-01 00:00:00", absl::FormatTime(ymdhms, t, utc)); t = absl::FromDateTime(2015, -1, -1, -1, -1, -1, utc); EXPECT_EQ("2014-10-29 22:58:59", absl::FormatTime(ymdhms, t, utc)); } TEST(Time, NextTransitionUTC) { const auto tz = absl::UTCTimeZone(); absl::TimeZone::CivilTransition trans; auto t = absl::InfinitePast(); EXPECT_FALSE(tz.NextTransition(t, &trans)); t = absl::InfiniteFuture(); EXPECT_FALSE(tz.NextTransition(t, &trans)); } TEST(Time, PrevTransitionUTC) { const auto tz = absl::UTCTimeZone(); absl::TimeZone::CivilTransition trans; auto t = absl::InfiniteFuture(); EXPECT_FALSE(tz.PrevTransition(t, &trans)); t = absl::InfinitePast(); EXPECT_FALSE(tz.PrevTransition(t, &trans)); } TEST(Time, NextTransitionNYC) { const auto tz = absl::time_internal::LoadTimeZone("America/New_York"); absl::TimeZone::CivilTransition trans; auto t = absl::FromCivil(absl::CivilSecond(2018, 6, 30, 0, 0, 0), tz); EXPECT_TRUE(tz.NextTransition(t, &trans)); EXPECT_EQ(absl::CivilSecond(2018, 11, 4, 2, 0, 0), trans.from); EXPECT_EQ(absl::CivilSecond(2018, 11, 4, 1, 0, 0), trans.to); t = absl::InfiniteFuture(); EXPECT_FALSE(tz.NextTransition(t, &trans)); t = absl::InfinitePast(); EXPECT_TRUE(tz.NextTransition(t, &trans)); if (trans.from == absl::CivilSecond(1918, 03, 31, 2, 0, 0)) { EXPECT_EQ(absl::CivilSecond(1918, 3, 31, 3, 0, 0), trans.to); } else { EXPECT_EQ(absl::CivilSecond(1883, 11, 18, 12, 3, 58), trans.from); EXPECT_EQ(absl::CivilSecond(1883, 11, 18, 12, 0, 0), trans.to); } } TEST(Time, PrevTransitionNYC) { const auto tz = absl::time_internal::LoadTimeZone("America/New_York"); absl::TimeZone::CivilTransition trans; auto t = absl::FromCivil(absl::CivilSecond(2018, 6, 30, 0, 0, 0), tz); EXPECT_TRUE(tz.PrevTransition(t, &trans)); EXPECT_EQ(absl::CivilSecond(2018, 3, 11, 2, 0, 0), trans.from); EXPECT_EQ(absl::CivilSecond(2018, 3, 11, 3, 0, 0), trans.to); t = absl::InfinitePast(); EXPECT_FALSE(tz.PrevTransition(t, &trans)); t = absl::InfiniteFuture(); EXPECT_TRUE(tz.PrevTransition(t, &trans)); } TEST(Time, AbslStringify) { absl::Time t = absl::Now(); EXPECT_EQ(absl::StrFormat("%v", t), absl::FormatTime(t)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/time.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/time_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
fb16cc9f-89be-40f0-9cba-b695c81a1028
cpp
abseil/abseil-cpp
time_zone_format
absl/time/internal/cctz/src/time_zone_format.cc
absl/time/internal/cctz/src/time_zone_format_test.cc
#if !defined(HAS_STRPTIME) #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__VXWORKS__) #define HAS_STRPTIME 1 #endif #endif #if defined(HAS_STRPTIME) && HAS_STRPTIME #if !defined(_XOPEN_SOURCE) && !defined(__FreeBSD__) && !defined(__OpenBSD__) #define _XOPEN_SOURCE 500 #endif #endif #include "absl/base/config.h" #include "absl/time/internal/cctz/include/cctz/time_zone.h" #include <time.h> #include <cctype> #include <chrono> #include <cstddef> #include <cstdint> #include <cstring> #include <ctime> #include <limits> #include <string> #include <vector> #if !HAS_STRPTIME #include <iomanip> #include <sstream> #endif #include "absl/time/internal/cctz/include/cctz/civil_time.h" #include "time_zone_if.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace time_internal { namespace cctz { namespace detail { namespace { #if !HAS_STRPTIME char* strptime(const char* s, const char* fmt, std::tm* tm) { std::istringstream input(s); input >> std::get_time(tm, fmt); if (input.fail()) return nullptr; return const_cast<char*>(s) + (input.eof() ? strlen(s) : static_cast<std::size_t>(input.tellg())); } #endif int ToTmWday(weekday wd) { switch (wd) { case weekday::sunday: return 0; case weekday::monday: return 1; case weekday::tuesday: return 2; case weekday::wednesday: return 3; case weekday::thursday: return 4; case weekday::friday: return 5; case weekday::saturday: return 6; } return 0; } weekday FromTmWday(int tm_wday) { switch (tm_wday) { case 0: return weekday::sunday; case 1: return weekday::monday; case 2: return weekday::tuesday; case 3: return weekday::wednesday; case 4: return weekday::thursday; case 5: return weekday::friday; case 6: return weekday::saturday; } return weekday::sunday; } std::tm ToTM(const time_zone::absolute_lookup& al) { std::tm tm{}; tm.tm_sec = al.cs.second(); tm.tm_min = al.cs.minute(); tm.tm_hour = al.cs.hour(); tm.tm_mday = al.cs.day(); tm.tm_mon = al.cs.month() - 1; if (al.cs.year() < std::numeric_limits<int>::min() + 1900) { tm.tm_year = std::numeric_limits<int>::min(); } else if (al.cs.year() - 1900 > std::numeric_limits<int>::max()) { tm.tm_year = std::numeric_limits<int>::max(); } else { tm.tm_year = static_cast<int>(al.cs.year() - 1900); } tm.tm_wday = ToTmWday(get_weekday(al.cs)); tm.tm_yday = get_yearday(al.cs) - 1; tm.tm_isdst = al.is_dst ? 1 : 0; return tm; } int ToWeek(const civil_day& cd, weekday week_start) { const civil_day d(cd.year() % 400, cd.month(), cd.day()); return static_cast<int>((d - prev_weekday(civil_year(d), week_start)) / 7); } const char kDigits[] = "0123456789"; char* Format64(char* ep, int width, std::int_fast64_t v) { bool neg = false; if (v < 0) { --width; neg = true; if (v == std::numeric_limits<std::int_fast64_t>::min()) { std::int_fast64_t last_digit = -(v % 10); v /= 10; if (last_digit < 0) { ++v; last_digit += 10; } --width; *--ep = kDigits[last_digit]; } v = -v; } do { --width; *--ep = kDigits[v % 10]; } while (v /= 10); while (--width >= 0) *--ep = '0'; if (neg) *--ep = '-'; return ep; } char* Format02d(char* ep, int v) { *--ep = kDigits[v % 10]; *--ep = kDigits[(v / 10) % 10]; return ep; } char* FormatOffset(char* ep, int offset, const char* mode) { char sign = '+'; if (offset < 0) { offset = -offset; sign = '-'; } const int seconds = offset % 60; const int minutes = (offset /= 60) % 60; const int hours = offset /= 60; const char sep = mode[0]; const bool ext = (sep != '\0' && mode[1] == '*'); const bool ccc = (ext && mode[2] == ':'); if (ext && (!ccc || seconds != 0)) { ep = Format02d(ep, seconds); *--ep = sep; } else { if (hours == 0 && minutes == 0) sign = '+'; } if (!ccc || minutes != 0 || seconds != 0) { ep = Format02d(ep, minutes); if (sep != '\0') *--ep = sep; } ep = Format02d(ep, hours); *--ep = sign; return ep; } void FormatTM(std::string* out, const std::string& fmt, const std::tm& tm) { for (std::size_t i = 2; i != 32; i *= 2) { std::size_t buf_size = fmt.size() * i; std::vector<char> buf(buf_size); if (std::size_t len = strftime(&buf[0], buf_size, fmt.c_str(), &tm)) { out->append(&buf[0], len); return; } } } template <typename T> const char* ParseInt(const char* dp, int width, T min, T max, T* vp) { if (dp != nullptr) { const T kmin = std::numeric_limits<T>::min(); bool erange = false; bool neg = false; T value = 0; if (*dp == '-') { neg = true; if (width <= 0 || --width != 0) { ++dp; } else { dp = nullptr; } } if (const char* const bp = dp) { while (const char* cp = strchr(kDigits, *dp)) { int d = static_cast<int>(cp - kDigits); if (d >= 10) break; if (value < kmin / 10) { erange = true; break; } value *= 10; if (value < kmin + d) { erange = true; break; } value -= d; dp += 1; if (width > 0 && --width == 0) break; } if (dp != bp && !erange && (neg || value != kmin)) { if (!neg || value != 0) { if (!neg) value = -value; if (min <= value && value <= max) { *vp = value; } else { dp = nullptr; } } else { dp = nullptr; } } else { dp = nullptr; } } } return dp; } const int kDigits10_64 = 18; const std::int_fast64_t kExp10[kDigits10_64 + 1] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, 100000000000, 1000000000000, 10000000000000, 100000000000000, 1000000000000000, 10000000000000000, 100000000000000000, 1000000000000000000, }; } std::string format(const std::string& format, const time_point<seconds>& tp, const detail::femtoseconds& fs, const time_zone& tz) { std::string result; result.reserve(format.size()); const time_zone::absolute_lookup al = tz.lookup(tp); const std::tm tm = ToTM(al); char buf[3 + kDigits10_64]; char* const ep = buf + sizeof(buf); char* bp; const char* pending = format.c_str(); const char* cur = pending; const char* end = pending + format.length(); while (cur != end) { const char* start = cur; while (cur != end && *cur != '%') ++cur; if (cur != start && pending == start) { result.append(pending, static_cast<std::size_t>(cur - pending)); pending = start = cur; } const char* percent = cur; while (cur != end && *cur == '%') ++cur; if (cur != start && pending == start) { std::size_t escaped = static_cast<std::size_t>(cur - pending) / 2; result.append(pending, escaped); pending += escaped * 2; if (pending != cur && cur == end) { result.push_back(*pending++); } } if (cur == end || (cur - percent) % 2 == 0) continue; if (strchr("YmdeUuWwHMSzZs%", *cur)) { if (cur - 1 != pending) { FormatTM(&result, std::string(pending, cur - 1), tm); } switch (*cur) { case 'Y': bp = Format64(ep, 0, al.cs.year()); result.append(bp, static_cast<std::size_t>(ep - bp)); break; case 'm': bp = Format02d(ep, al.cs.month()); result.append(bp, static_cast<std::size_t>(ep - bp)); break; case 'd': case 'e': bp = Format02d(ep, al.cs.day()); if (*cur == 'e' && *bp == '0') *bp = ' '; result.append(bp, static_cast<std::size_t>(ep - bp)); break; case 'U': bp = Format02d(ep, ToWeek(civil_day(al.cs), weekday::sunday)); result.append(bp, static_cast<std::size_t>(ep - bp)); break; case 'u': bp = Format64(ep, 0, tm.tm_wday ? tm.tm_wday : 7); result.append(bp, static_cast<std::size_t>(ep - bp)); break; case 'W': bp = Format02d(ep, ToWeek(civil_day(al.cs), weekday::monday)); result.append(bp, static_cast<std::size_t>(ep - bp)); break; case 'w': bp = Format64(ep, 0, tm.tm_wday); result.append(bp, static_cast<std::size_t>(ep - bp)); break; case 'H': bp = Format02d(ep, al.cs.hour()); result.append(bp, static_cast<std::size_t>(ep - bp)); break; case 'M': bp = Format02d(ep, al.cs.minute()); result.append(bp, static_cast<std::size_t>(ep - bp)); break; case 'S': bp = Format02d(ep, al.cs.second()); result.append(bp, static_cast<std::size_t>(ep - bp)); break; case 'z': bp = FormatOffset(ep, al.offset, ""); result.append(bp, static_cast<std::size_t>(ep - bp)); break; case 'Z': result.append(al.abbr); break; case 's': bp = Format64(ep, 0, ToUnixSeconds(tp)); result.append(bp, static_cast<std::size_t>(ep - bp)); break; case '%': result.push_back('%'); break; } pending = ++cur; continue; } if (*cur == ':' && cur + 1 != end) { if (*(cur + 1) == 'z') { if (cur - 1 != pending) { FormatTM(&result, std::string(pending, cur - 1), tm); } bp = FormatOffset(ep, al.offset, ":"); result.append(bp, static_cast<std::size_t>(ep - bp)); pending = cur += 2; continue; } if (*(cur + 1) == ':' && cur + 2 != end) { if (*(cur + 2) == 'z') { if (cur - 1 != pending) { FormatTM(&result, std::string(pending, cur - 1), tm); } bp = FormatOffset(ep, al.offset, ":*"); result.append(bp, static_cast<std::size_t>(ep - bp)); pending = cur += 3; continue; } if (*(cur + 2) == ':' && cur + 3 != end) { if (*(cur + 3) == 'z') { if (cur - 1 != pending) { FormatTM(&result, std::string(pending, cur - 1), tm); } bp = FormatOffset(ep, al.offset, ":*:"); result.append(bp, static_cast<std::size_t>(ep - bp)); pending = cur += 4; continue; } } } } if (*cur != 'E' || ++cur == end) continue; if (*cur == 'T') { if (cur - 2 != pending) { FormatTM(&result, std::string(pending, cur - 2), tm); } result.append("T"); pending = ++cur; } else if (*cur == 'z') { if (cur - 2 != pending) { FormatTM(&result, std::string(pending, cur - 2), tm); } bp = FormatOffset(ep, al.offset, ":"); result.append(bp, static_cast<std::size_t>(ep - bp)); pending = ++cur; } else if (*cur == '*' && cur + 1 != end && *(cur + 1) == 'z') { if (cur - 2 != pending) { FormatTM(&result, std::string(pending, cur - 2), tm); } bp = FormatOffset(ep, al.offset, ":*"); result.append(bp, static_cast<std::size_t>(ep - bp)); pending = cur += 2; } else if (*cur == '*' && cur + 1 != end && (*(cur + 1) == 'S' || *(cur + 1) == 'f')) { if (cur - 2 != pending) { FormatTM(&result, std::string(pending, cur - 2), tm); } char* cp = ep; bp = Format64(cp, 15, fs.count()); while (cp != bp && cp[-1] == '0') --cp; switch (*(cur + 1)) { case 'S': if (cp != bp) *--bp = '.'; bp = Format02d(bp, al.cs.second()); break; case 'f': if (cp == bp) *--bp = '0'; break; } result.append(bp, static_cast<std::size_t>(cp - bp)); pending = cur += 2; } else if (*cur == '4' && cur + 1 != end && *(cur + 1) == 'Y') { if (cur - 2 != pending) { FormatTM(&result, std::string(pending, cur - 2), tm); } bp = Format64(ep, 4, al.cs.year()); result.append(bp, static_cast<std::size_t>(ep - bp)); pending = cur += 2; } else if (std::isdigit(*cur)) { int n = 0; if (const char* np = ParseInt(cur, 0, 0, 1024, &n)) { if (*np == 'S' || *np == 'f') { if (cur - 2 != pending) { FormatTM(&result, std::string(pending, cur - 2), tm); } bp = ep; if (n > 0) { if (n > kDigits10_64) n = kDigits10_64; bp = Format64(bp, n, (n > 15) ? fs.count() * kExp10[n - 15] : fs.count() / kExp10[15 - n]); if (*np == 'S') *--bp = '.'; } if (*np == 'S') bp = Format02d(bp, al.cs.second()); result.append(bp, static_cast<std::size_t>(ep - bp)); pending = cur = ++np; } } } } if (end != pending) { FormatTM(&result, std::string(pending, end), tm); } return result; } namespace { const char* ParseOffset(const char* dp, const char* mode, int* offset) { if (dp != nullptr) { const char first = *dp++; if (first == '+' || first == '-') { char sep = mode[0]; int hours = 0; int minutes = 0; int seconds = 0; const char* ap = ParseInt(dp, 2, 0, 23, &hours); if (ap != nullptr && ap - dp == 2) { dp = ap; if (sep != '\0' && *ap == sep) ++ap; const char* bp = ParseInt(ap, 2, 0, 59, &minutes); if (bp != nullptr && bp - ap == 2) { dp = bp; if (sep != '\0' && *bp == sep) ++bp; const char* cp = ParseInt(bp, 2, 0, 59, &seconds); if (cp != nullptr && cp - bp == 2) dp = cp; } *offset = ((hours * 60 + minutes) * 60) + seconds; if (first == '-') *offset = -*offset; } else { dp = nullptr; } } else if (first == 'Z' || first == 'z') { *offset = 0; } else { dp = nullptr; } } return dp; } const char* ParseZone(const char* dp, std::string* zone) { zone->clear(); if (dp != nullptr) { while (*dp != '\0' && !std::isspace(*dp)) zone->push_back(*dp++); if (zone->empty()) dp = nullptr; } return dp; } const char* ParseSubSeconds(const char* dp, detail::femtoseconds* subseconds) { if (dp != nullptr) { std::int_fast64_t v = 0; std::int_fast64_t exp = 0; const char* const bp = dp; while (const char* cp = strchr(kDigits, *dp)) { int d = static_cast<int>(cp - kDigits); if (d >= 10) break; if (exp < 15) { exp += 1; v *= 10; v += d; } ++dp; } if (dp != bp) { v *= kExp10[15 - exp]; *subseconds = detail::femtoseconds(v); } else { dp = nullptr; } } return dp; } const char* ParseTM(const char* dp, const char* fmt, std::tm* tm) { if (dp != nullptr) { dp = strptime(dp, fmt, tm); } return dp; } bool FromWeek(int week_num, weekday week_start, year_t* year, std::tm* tm) { const civil_year y(*year % 400); civil_day cd = prev_weekday(y, week_start); cd = next_weekday(cd - 1, FromTmWday(tm->tm_wday)) + (week_num * 7); if (const year_t shift = cd.year() - y.year()) { if (shift > 0) { if (*year > std::numeric_limits<year_t>::max() - shift) return false; } else { if (*year < std::numeric_limits<year_t>::min() - shift) return false; } *year += shift; } tm->tm_mon = cd.month() - 1; tm->tm_mday = cd.day(); return true; } } bool parse(const std::string& format, const std::string& input, const time_zone& tz, time_point<seconds>* sec, detail::femtoseconds* fs, std::string* err) { const char* data = input.c_str(); while (std::isspace(*data)) ++data; const year_t kyearmax = std::numeric_limits<year_t>::max(); const year_t kyearmin = std::numeric_limits<year_t>::min(); bool saw_year = false; year_t year = 1970; std::tm tm{}; tm.tm_year = 1970 - 1900; tm.tm_mon = 1 - 1; tm.tm_mday = 1; tm.tm_hour = 0; tm.tm_min = 0; tm.tm_sec = 0; tm.tm_wday = 4; tm.tm_yday = 0; tm.tm_isdst = 0; auto subseconds = detail::femtoseconds::zero(); bool saw_offset = false; int offset = 0; std::string zone = "UTC"; const char* fmt = format.c_str(); bool twelve_hour = false; bool afternoon = false; int week_num = -1; weekday week_start = weekday::sunday; bool saw_percent_s = false; std::int_fast64_t percent_s = 0; while (data != nullptr && *fmt != '\0') { if (std::isspace(*fmt)) { while (std::isspace(*data)) ++data; while (std::isspace(*++fmt)) continue; continue; } if (*fmt != '%') { if (*data == *fmt) { ++data; ++fmt; } else { data = nullptr; } continue; } const char* percent = fmt; if (*++fmt == '\0') { data = nullptr; continue; } switch (*fmt++) { case 'Y': data = ParseInt(data, 0, kyearmin, kyearmax, &year); if (data != nullptr) saw_year = true; continue; case 'm': data = ParseInt(data, 2, 1, 12, &tm.tm_mon); if (data != nullptr) tm.tm_mon -= 1; week_num = -1; continue; case 'd': case 'e': data = ParseInt(data, 2, 1, 31, &tm.tm_mday); week_num = -1; continue; case 'U': data = ParseInt(data, 0, 0, 53, &week_num); week_start = weekday::sunday; continue; case 'W': data = ParseInt(data, 0, 0, 53, &week_num); week_start = weekday::monday; continue; case 'u': data = ParseInt(data, 0, 1, 7, &tm.tm_wday); if (data != nullptr) tm.tm_wday %= 7; continue; case 'w': data = ParseInt(data, 0, 0, 6, &tm.tm_wday); continue; case 'H': data = ParseInt(data, 2, 0, 23, &tm.tm_hour); twelve_hour = false; continue; case 'M': data = ParseInt(data, 2, 0, 59, &tm.tm_min); continue; case 'S': data = ParseInt(data, 2, 0, 60, &tm.tm_sec); continue; case 'I': case 'l': case 'r': twelve_hour = true; break; case 'R': case 'T': case 'c': case 'X': twelve_hour = false; break; case 'z': data = ParseOffset(data, "", &offset); if (data != nullptr) saw_offset = true; continue; case 'Z': data = ParseZone(data, &zone); continue; case 's': data = ParseInt(data, 0, std::numeric_limits<std::int_fast64_t>::min(), std::numeric_limits<std::int_fast64_t>::max(), &percent_s); if (data != nullptr) saw_percent_s = true; continue; case ':': if (fmt[0] == 'z' || (fmt[0] == ':' && (fmt[1] == 'z' || (fmt[1] == ':' && fmt[2] == 'z')))) { data = ParseOffset(data, ":", &offset); if (data != nullptr) saw_offset = true; fmt += (fmt[0] == 'z') ? 1 : (fmt[1] == 'z') ? 2 : 3; continue; } break; case '%': data = (*data == '%' ? data + 1 : nullptr); continue; case 'E': if (fmt[0] == 'T') { if (*data == 'T' || *data == 't') { ++data; ++fmt; } else { data = nullptr; } continue; } if (fmt[0] == 'z' || (fmt[0] == '*' && fmt[1] == 'z')) { data = ParseOffset(data, ":", &offset); if (data != nullptr) saw_offset = true; fmt += (fmt[0] == 'z') ? 1 : 2; continue; } if (fmt[0] == '*' && fmt[1] == 'S') { data = ParseInt(data, 2, 0, 60, &tm.tm_sec); if (data != nullptr && *data == '.') { data = ParseSubSeconds(data + 1, &subseconds); } fmt += 2; continue; } if (fmt[0] == '*' && fmt[1] == 'f') { if (data != nullptr && std::isdigit(*data)) { data = ParseSubSeconds(data, &subseconds); } fmt += 2; continue; } if (fmt[0] == '4' && fmt[1] == 'Y') { const char* bp = data; data = ParseInt(data, 4, year_t{-999}, year_t{9999}, &year); if (data != nullptr) { if (data - bp == 4) { saw_year = true; } else { data = nullptr; } } fmt += 2; continue; } if (std::isdigit(*fmt)) { int n = 0; if (const char* np = ParseInt(fmt, 0, 0, 1024, &n)) { if (*np == 'S') { data = ParseInt(data, 2, 0, 60, &tm.tm_sec); if (data != nullptr && *data == '.') { data = ParseSubSeconds(data + 1, &subseconds); } fmt = ++np; continue; } if (*np == 'f') { if (data != nullptr && std::isdigit(*data)) { data = ParseSubSeconds(data, &subseconds); } fmt = ++np; continue; } } } if (*fmt == 'c') twelve_hour = false; if (*fmt == 'X') twelve_hour = false; if (*fmt != '\0') ++fmt; break; case 'O': if (*fmt == 'H') twelve_hour = false; if (*fmt == 'I') twelve_hour = true; if (*fmt != '\0') ++fmt; break; } const char* orig_data = data; std::string spec(percent, static_cast<std::size_t>(fmt - percent)); data = ParseTM(data, spec.c_str(), &tm); if (spec == "%p" && data != nullptr) { std::string test_input = "1"; test_input.append(orig_data, static_cast<std::size_t>(data - orig_data)); const char* test_data = test_input.c_str(); std::tm tmp{}; ParseTM(test_data, "%I%p", &tmp); afternoon = (tmp.tm_hour == 13); } } if (twelve_hour && afternoon && tm.tm_hour < 12) { tm.tm_hour += 12; } if (data == nullptr) { if (err != nullptr) *err = "Failed to parse input"; return false; } while (std::isspace(*data)) ++data; if (*data != '\0') { if (err != nullptr) *err = "Illegal trailing data in input string"; return false; } if (saw_percent_s) { *sec = FromUnixSeconds(percent_s); *fs = detail::femtoseconds::zero(); return true; } time_zone ptz = saw_offset ? utc_time_zone() : tz; if (tm.tm_sec == 60) { tm.tm_sec -= 1; offset -= 1; subseconds = detail::femtoseconds::zero(); } if (!saw_year) { year = year_t{tm.tm_year}; if (year > kyearmax - 1900) { if (err != nullptr) *err = "Out-of-range year"; return false; } year += 1900; } if (week_num != -1) { if (!FromWeek(week_num, week_start, &year, &tm)) { if (err != nullptr) *err = "Out-of-range field"; return false; } } const int month = tm.tm_mon + 1; civil_second cs(year, month, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); if (cs.month() != month || cs.day() != tm.tm_mday) { if (err != nullptr) *err = "Out-of-range field"; return false; } if ((offset < 0 && cs > civil_second::max() + offset) || (offset > 0 && cs < civil_second::min() + offset)) { if (err != nullptr) *err = "Out-of-range field"; return false; } cs -= offset; const auto tp = ptz.lookup(cs).pre; if (tp == time_point<seconds>::max()) { const auto al = ptz.lookup(time_point<seconds>::max()); if (cs > al.cs) { if (err != nullptr) *err = "Out-of-range field"; return false; } } if (tp == time_point<seconds>::min()) { const auto al = ptz.lookup(time_point<seconds>::min()); if (cs < al.cs) { if (err != nullptr) *err = "Out-of-range field"; return false; } } *sec = tp; *fs = subseconds; return true; } } } } ABSL_NAMESPACE_END }
#include <chrono> #include <cstdint> #include <iomanip> #include <sstream> #include <string> #include "absl/base/config.h" #include "absl/time/internal/cctz/include/cctz/time_zone.h" #if defined(__linux__) #include <features.h> #endif #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/time/internal/cctz/include/cctz/civil_time.h" namespace chrono = std::chrono; namespace absl { ABSL_NAMESPACE_BEGIN namespace time_internal { namespace cctz { namespace { #define ExpectTime(tp, tz, y, m, d, hh, mm, ss, off, isdst, zone) \ do { \ time_zone::absolute_lookup al = tz.lookup(tp); \ EXPECT_EQ(y, al.cs.year()); \ EXPECT_EQ(m, al.cs.month()); \ EXPECT_EQ(d, al.cs.day()); \ EXPECT_EQ(hh, al.cs.hour()); \ EXPECT_EQ(mm, al.cs.minute()); \ EXPECT_EQ(ss, al.cs.second()); \ EXPECT_EQ(off, al.offset); \ EXPECT_TRUE(isdst == al.is_dst); \ EXPECT_STREQ(zone, al.abbr); \ } while (0) const char RFC3339_full[] = "%Y-%m-%d%ET%H:%M:%E*S%Ez"; const char RFC3339_sec[] = "%Y-%m-%d%ET%H:%M:%S%Ez"; const char RFC1123_full[] = "%a, %d %b %Y %H:%M:%S %z"; const char RFC1123_no_wday[] = "%d %b %Y %H:%M:%S %z"; template <typename D> void TestFormatSpecifier(time_point<D> tp, time_zone tz, const std::string& fmt, const std::string& ans) { EXPECT_EQ(ans, absl::time_internal::cctz::format(fmt, tp, tz)) << fmt; EXPECT_EQ("xxx " + ans, absl::time_internal::cctz::format("xxx " + fmt, tp, tz)); EXPECT_EQ(ans + " yyy", absl::time_internal::cctz::format(fmt + " yyy", tp, tz)); EXPECT_EQ("xxx " + ans + " yyy", absl::time_internal::cctz::format("xxx " + fmt + " yyy", tp, tz)); } } TEST(Format, TimePointResolution) { const char kFmt[] = "%H:%M:%E*S"; const time_zone utc = utc_time_zone(); const time_point<chrono::nanoseconds> t0 = chrono::system_clock::from_time_t(1420167845) + chrono::milliseconds(123) + chrono::microseconds(456) + chrono::nanoseconds(789); EXPECT_EQ("03:04:05.123456789", absl::time_internal::cctz::format( kFmt, chrono::time_point_cast<chrono::nanoseconds>(t0), utc)); EXPECT_EQ("03:04:05.123456", absl::time_internal::cctz::format( kFmt, chrono::time_point_cast<chrono::microseconds>(t0), utc)); EXPECT_EQ("03:04:05.123", absl::time_internal::cctz::format( kFmt, chrono::time_point_cast<chrono::milliseconds>(t0), utc)); EXPECT_EQ("03:04:05", absl::time_internal::cctz::format( kFmt, chrono::time_point_cast<chrono::seconds>(t0), utc)); EXPECT_EQ( "03:04:05", absl::time_internal::cctz::format( kFmt, chrono::time_point_cast<absl::time_internal::cctz::seconds>(t0), utc)); EXPECT_EQ("03:04:00", absl::time_internal::cctz::format( kFmt, chrono::time_point_cast<chrono::minutes>(t0), utc)); EXPECT_EQ("03:00:00", absl::time_internal::cctz::format( kFmt, chrono::time_point_cast<chrono::hours>(t0), utc)); } TEST(Format, TimePointExtendedResolution) { const char kFmt[] = "%H:%M:%E*S"; const time_zone utc = utc_time_zone(); const time_point<absl::time_internal::cctz::seconds> tp = chrono::time_point_cast<absl::time_internal::cctz::seconds>( chrono::system_clock::from_time_t(0)) + chrono::hours(12) + chrono::minutes(34) + chrono::seconds(56); EXPECT_EQ( "12:34:56.123456789012345", detail::format(kFmt, tp, detail::femtoseconds(123456789012345), utc)); EXPECT_EQ( "12:34:56.012345678901234", detail::format(kFmt, tp, detail::femtoseconds(12345678901234), utc)); EXPECT_EQ("12:34:56.001234567890123", detail::format(kFmt, tp, detail::femtoseconds(1234567890123), utc)); EXPECT_EQ("12:34:56.000123456789012", detail::format(kFmt, tp, detail::femtoseconds(123456789012), utc)); EXPECT_EQ("12:34:56.000000000000123", detail::format(kFmt, tp, detail::femtoseconds(123), utc)); EXPECT_EQ("12:34:56.000000000000012", detail::format(kFmt, tp, detail::femtoseconds(12), utc)); EXPECT_EQ("12:34:56.000000000000001", detail::format(kFmt, tp, detail::femtoseconds(1), utc)); } TEST(Format, Basics) { time_zone tz = utc_time_zone(); time_point<chrono::nanoseconds> tp = chrono::system_clock::from_time_t(0); EXPECT_EQ("", absl::time_internal::cctz::format("", tp, tz)); EXPECT_EQ(" ", absl::time_internal::cctz::format(" ", tp, tz)); EXPECT_EQ(" ", absl::time_internal::cctz::format(" ", tp, tz)); EXPECT_EQ("xxx", absl::time_internal::cctz::format("xxx", tp, tz)); std::string big(128, 'x'); EXPECT_EQ(big, absl::time_internal::cctz::format(big, tp, tz)); std::string bigger(100000, 'x'); EXPECT_EQ(bigger, absl::time_internal::cctz::format(bigger, tp, tz)); tp += chrono::hours(13) + chrono::minutes(4) + chrono::seconds(5); tp += chrono::milliseconds(6) + chrono::microseconds(7) + chrono::nanoseconds(8); EXPECT_EQ("1970-01-01", absl::time_internal::cctz::format("%Y-%m-%d", tp, tz)); EXPECT_EQ("13:04:05", absl::time_internal::cctz::format("%H:%M:%S", tp, tz)); EXPECT_EQ("13:04:05.006", absl::time_internal::cctz::format("%H:%M:%E3S", tp, tz)); EXPECT_EQ("13:04:05.006007", absl::time_internal::cctz::format("%H:%M:%E6S", tp, tz)); EXPECT_EQ("13:04:05.006007008", absl::time_internal::cctz::format("%H:%M:%E9S", tp, tz)); } TEST(Format, PosixConversions) { const time_zone tz = utc_time_zone(); auto tp = chrono::system_clock::from_time_t(0); TestFormatSpecifier(tp, tz, "%d", "01"); TestFormatSpecifier(tp, tz, "%e", " 1"); TestFormatSpecifier(tp, tz, "%H", "00"); TestFormatSpecifier(tp, tz, "%I", "12"); TestFormatSpecifier(tp, tz, "%j", "001"); TestFormatSpecifier(tp, tz, "%m", "01"); TestFormatSpecifier(tp, tz, "%M", "00"); TestFormatSpecifier(tp, tz, "%S", "00"); TestFormatSpecifier(tp, tz, "%U", "00"); #if !defined(__EMSCRIPTEN__) TestFormatSpecifier(tp, tz, "%w", "4"); #endif TestFormatSpecifier(tp, tz, "%W", "00"); TestFormatSpecifier(tp, tz, "%y", "70"); TestFormatSpecifier(tp, tz, "%Y", "1970"); TestFormatSpecifier(tp, tz, "%z", "+0000"); TestFormatSpecifier(tp, tz, "%Z", "UTC"); TestFormatSpecifier(tp, tz, "%%", "%"); #if defined(__linux__) TestFormatSpecifier(tp, tz, "%C", "19"); TestFormatSpecifier(tp, tz, "%D", "01/01/70"); TestFormatSpecifier(tp, tz, "%F", "1970-01-01"); TestFormatSpecifier(tp, tz, "%g", "70"); TestFormatSpecifier(tp, tz, "%G", "1970"); #if defined(__GLIBC__) TestFormatSpecifier(tp, tz, "%k", " 0"); TestFormatSpecifier(tp, tz, "%l", "12"); #endif TestFormatSpecifier(tp, tz, "%n", "\n"); TestFormatSpecifier(tp, tz, "%R", "00:00"); TestFormatSpecifier(tp, tz, "%t", "\t"); TestFormatSpecifier(tp, tz, "%T", "00:00:00"); TestFormatSpecifier(tp, tz, "%u", "4"); TestFormatSpecifier(tp, tz, "%V", "01"); TestFormatSpecifier(tp, tz, "%s", "0"); #endif } TEST(Format, LocaleSpecific) { const time_zone tz = utc_time_zone(); auto tp = chrono::system_clock::from_time_t(0); TestFormatSpecifier(tp, tz, "%a", "Thu"); TestFormatSpecifier(tp, tz, "%A", "Thursday"); TestFormatSpecifier(tp, tz, "%b", "Jan"); TestFormatSpecifier(tp, tz, "%B", "January"); const std::string s = absl::time_internal::cctz::format("%c", tp, utc_time_zone()); EXPECT_THAT(s, testing::HasSubstr("1970")); EXPECT_THAT(s, testing::HasSubstr("00:00:00")); TestFormatSpecifier(tp, tz, "%p", "AM"); TestFormatSpecifier(tp, tz, "%x", "01/01/70"); TestFormatSpecifier(tp, tz, "%X", "00:00:00"); #if defined(__linux__) TestFormatSpecifier(tp, tz, "%h", "Jan"); #if defined(__GLIBC__) TestFormatSpecifier(tp, tz, "%P", "am"); #endif TestFormatSpecifier(tp, tz, "%r", "12:00:00 AM"); TestFormatSpecifier(tp, tz, "%Ec", "Thu Jan 1 00:00:00 1970"); TestFormatSpecifier(tp, tz, "%EC", "19"); TestFormatSpecifier(tp, tz, "%Ex", "01/01/70"); TestFormatSpecifier(tp, tz, "%EX", "00:00:00"); TestFormatSpecifier(tp, tz, "%Ey", "70"); TestFormatSpecifier(tp, tz, "%EY", "1970"); TestFormatSpecifier(tp, tz, "%Od", "01"); TestFormatSpecifier(tp, tz, "%Oe", " 1"); TestFormatSpecifier(tp, tz, "%OH", "00"); TestFormatSpecifier(tp, tz, "%OI", "12"); TestFormatSpecifier(tp, tz, "%Om", "01"); TestFormatSpecifier(tp, tz, "%OM", "00"); TestFormatSpecifier(tp, tz, "%OS", "00"); TestFormatSpecifier(tp, tz, "%Ou", "4"); TestFormatSpecifier(tp, tz, "%OU", "00"); TestFormatSpecifier(tp, tz, "%OV", "01"); TestFormatSpecifier(tp, tz, "%Ow", "4"); TestFormatSpecifier(tp, tz, "%OW", "00"); TestFormatSpecifier(tp, tz, "%Oy", "70"); #endif } TEST(Format, Escaping) { const time_zone tz = utc_time_zone(); auto tp = chrono::system_clock::from_time_t(0); TestFormatSpecifier(tp, tz, "%%", "%"); TestFormatSpecifier(tp, tz, "%%a", "%a"); TestFormatSpecifier(tp, tz, "%%b", "%b"); TestFormatSpecifier(tp, tz, "%%Ea", "%Ea"); TestFormatSpecifier(tp, tz, "%%Es", "%Es"); TestFormatSpecifier(tp, tz, "%%E3S", "%E3S"); TestFormatSpecifier(tp, tz, "%%OS", "%OS"); TestFormatSpecifier(tp, tz, "%%O3S", "%O3S"); TestFormatSpecifier(tp, tz, "%%%Y", "%1970"); TestFormatSpecifier(tp, tz, "%%%E3S", "%00.000"); TestFormatSpecifier(tp, tz, "%%%%E3S", "%%E3S"); } TEST(Format, ExtendedSeconds) { const time_zone tz = utc_time_zone(); time_point<chrono::nanoseconds> tp = chrono::system_clock::from_time_t(0); tp += chrono::seconds(5); EXPECT_EQ("05", absl::time_internal::cctz::format("%E*S", tp, tz)); EXPECT_EQ("05", absl::time_internal::cctz::format("%E0S", tp, tz)); EXPECT_EQ("05.0", absl::time_internal::cctz::format("%E1S", tp, tz)); EXPECT_EQ("05.00", absl::time_internal::cctz::format("%E2S", tp, tz)); EXPECT_EQ("05.000", absl::time_internal::cctz::format("%E3S", tp, tz)); EXPECT_EQ("05.0000", absl::time_internal::cctz::format("%E4S", tp, tz)); EXPECT_EQ("05.00000", absl::time_internal::cctz::format("%E5S", tp, tz)); EXPECT_EQ("05.000000", absl::time_internal::cctz::format("%E6S", tp, tz)); EXPECT_EQ("05.0000000", absl::time_internal::cctz::format("%E7S", tp, tz)); EXPECT_EQ("05.00000000", absl::time_internal::cctz::format("%E8S", tp, tz)); EXPECT_EQ("05.000000000", absl::time_internal::cctz::format("%E9S", tp, tz)); EXPECT_EQ("05.0000000000", absl::time_internal::cctz::format("%E10S", tp, tz)); EXPECT_EQ("05.00000000000", absl::time_internal::cctz::format("%E11S", tp, tz)); EXPECT_EQ("05.000000000000", absl::time_internal::cctz::format("%E12S", tp, tz)); EXPECT_EQ("05.0000000000000", absl::time_internal::cctz::format("%E13S", tp, tz)); EXPECT_EQ("05.00000000000000", absl::time_internal::cctz::format("%E14S", tp, tz)); EXPECT_EQ("05.000000000000000", absl::time_internal::cctz::format("%E15S", tp, tz)); tp += chrono::milliseconds(6) + chrono::microseconds(7) + chrono::nanoseconds(8); EXPECT_EQ("05.006007008", absl::time_internal::cctz::format("%E*S", tp, tz)); EXPECT_EQ("05", absl::time_internal::cctz::format("%E0S", tp, tz)); EXPECT_EQ("05.0", absl::time_internal::cctz::format("%E1S", tp, tz)); EXPECT_EQ("05.00", absl::time_internal::cctz::format("%E2S", tp, tz)); EXPECT_EQ("05.006", absl::time_internal::cctz::format("%E3S", tp, tz)); EXPECT_EQ("05.0060", absl::time_internal::cctz::format("%E4S", tp, tz)); EXPECT_EQ("05.00600", absl::time_internal::cctz::format("%E5S", tp, tz)); EXPECT_EQ("05.006007", absl::time_internal::cctz::format("%E6S", tp, tz)); EXPECT_EQ("05.0060070", absl::time_internal::cctz::format("%E7S", tp, tz)); EXPECT_EQ("05.00600700", absl::time_internal::cctz::format("%E8S", tp, tz)); EXPECT_EQ("05.006007008", absl::time_internal::cctz::format("%E9S", tp, tz)); EXPECT_EQ("05.0060070080", absl::time_internal::cctz::format("%E10S", tp, tz)); EXPECT_EQ("05.00600700800", absl::time_internal::cctz::format("%E11S", tp, tz)); EXPECT_EQ("05.006007008000", absl::time_internal::cctz::format("%E12S", tp, tz)); EXPECT_EQ("05.0060070080000", absl::time_internal::cctz::format("%E13S", tp, tz)); EXPECT_EQ("05.00600700800000", absl::time_internal::cctz::format("%E14S", tp, tz)); EXPECT_EQ("05.006007008000000", absl::time_internal::cctz::format("%E15S", tp, tz)); tp = chrono::system_clock::from_time_t(0) + chrono::microseconds(-1); EXPECT_EQ("1969-12-31 23:59:59.999999", absl::time_internal::cctz::format("%Y-%m-%d %H:%M:%E*S", tp, tz)); tp = chrono::system_clock::from_time_t(0) + chrono::microseconds(1395024427333304); EXPECT_EQ("2014-03-17 02:47:07.333304", absl::time_internal::cctz::format("%Y-%m-%d %H:%M:%E*S", tp, tz)); tp += chrono::microseconds(1); EXPECT_EQ("2014-03-17 02:47:07.333305", absl::time_internal::cctz::format("%Y-%m-%d %H:%M:%E*S", tp, tz)); } TEST(Format, ExtendedSubeconds) { const time_zone tz = utc_time_zone(); time_point<chrono::nanoseconds> tp = chrono::system_clock::from_time_t(0); tp += chrono::seconds(5); EXPECT_EQ("0", absl::time_internal::cctz::format("%E*f", tp, tz)); EXPECT_EQ("", absl::time_internal::cctz::format("%E0f", tp, tz)); EXPECT_EQ("0", absl::time_internal::cctz::format("%E1f", tp, tz)); EXPECT_EQ("00", absl::time_internal::cctz::format("%E2f", tp, tz)); EXPECT_EQ("000", absl::time_internal::cctz::format("%E3f", tp, tz)); EXPECT_EQ("0000", absl::time_internal::cctz::format("%E4f", tp, tz)); EXPECT_EQ("00000", absl::time_internal::cctz::format("%E5f", tp, tz)); EXPECT_EQ("000000", absl::time_internal::cctz::format("%E6f", tp, tz)); EXPECT_EQ("0000000", absl::time_internal::cctz::format("%E7f", tp, tz)); EXPECT_EQ("00000000", absl::time_internal::cctz::format("%E8f", tp, tz)); EXPECT_EQ("000000000", absl::time_internal::cctz::format("%E9f", tp, tz)); EXPECT_EQ("0000000000", absl::time_internal::cctz::format("%E10f", tp, tz)); EXPECT_EQ("00000000000", absl::time_internal::cctz::format("%E11f", tp, tz)); EXPECT_EQ("000000000000", absl::time_internal::cctz::format("%E12f", tp, tz)); EXPECT_EQ("0000000000000", absl::time_internal::cctz::format("%E13f", tp, tz)); EXPECT_EQ("00000000000000", absl::time_internal::cctz::format("%E14f", tp, tz)); EXPECT_EQ("000000000000000", absl::time_internal::cctz::format("%E15f", tp, tz)); tp += chrono::milliseconds(6) + chrono::microseconds(7) + chrono::nanoseconds(8); EXPECT_EQ("006007008", absl::time_internal::cctz::format("%E*f", tp, tz)); EXPECT_EQ("", absl::time_internal::cctz::format("%E0f", tp, tz)); EXPECT_EQ("0", absl::time_internal::cctz::format("%E1f", tp, tz)); EXPECT_EQ("00", absl::time_internal::cctz::format("%E2f", tp, tz)); EXPECT_EQ("006", absl::time_internal::cctz::format("%E3f", tp, tz)); EXPECT_EQ("0060", absl::time_internal::cctz::format("%E4f", tp, tz)); EXPECT_EQ("00600", absl::time_internal::cctz::format("%E5f", tp, tz)); EXPECT_EQ("006007", absl::time_internal::cctz::format("%E6f", tp, tz)); EXPECT_EQ("0060070", absl::time_internal::cctz::format("%E7f", tp, tz)); EXPECT_EQ("00600700", absl::time_internal::cctz::format("%E8f", tp, tz)); EXPECT_EQ("006007008", absl::time_internal::cctz::format("%E9f", tp, tz)); EXPECT_EQ("0060070080", absl::time_internal::cctz::format("%E10f", tp, tz)); EXPECT_EQ("00600700800", absl::time_internal::cctz::format("%E11f", tp, tz)); EXPECT_EQ("006007008000", absl::time_internal::cctz::format("%E12f", tp, tz)); EXPECT_EQ("0060070080000", absl::time_internal::cctz::format("%E13f", tp, tz)); EXPECT_EQ("00600700800000", absl::time_internal::cctz::format("%E14f", tp, tz)); EXPECT_EQ("006007008000000", absl::time_internal::cctz::format("%E15f", tp, tz)); tp = chrono::system_clock::from_time_t(0) + chrono::microseconds(-1); EXPECT_EQ( "1969-12-31 23:59:59.999999", absl::time_internal::cctz::format("%Y-%m-%d %H:%M:%S.%E*f", tp, tz)); tp = chrono::system_clock::from_time_t(0) + chrono::microseconds(1395024427333304); EXPECT_EQ( "2014-03-17 02:47:07.333304", absl::time_internal::cctz::format("%Y-%m-%d %H:%M:%S.%E*f", tp, tz)); tp += chrono::microseconds(1); EXPECT_EQ( "2014-03-17 02:47:07.333305", absl::time_internal::cctz::format("%Y-%m-%d %H:%M:%S.%E*f", tp, tz)); } TEST(Format, CompareExtendSecondsVsSubseconds) { const time_zone tz = utc_time_zone(); auto fmt_A = [](const std::string& prec) { return "%E" + prec + "S"; }; auto fmt_B = [](const std::string& prec) { return "%S.%E" + prec + "f"; }; time_point<chrono::nanoseconds> tp = chrono::system_clock::from_time_t(0); tp += chrono::seconds(5); EXPECT_EQ("05", absl::time_internal::cctz::format(fmt_A("*"), tp, tz)); EXPECT_EQ("05.0", absl::time_internal::cctz::format(fmt_B("*"), tp, tz)); EXPECT_EQ("05", absl::time_internal::cctz::format(fmt_A("0"), tp, tz)); EXPECT_EQ("05.", absl::time_internal::cctz::format(fmt_B("0"), tp, tz)); for (int prec = 1; prec <= 15; ++prec) { const std::string a = absl::time_internal::cctz::format(fmt_A(std::to_string(prec)), tp, tz); const std::string b = absl::time_internal::cctz::format(fmt_B(std::to_string(prec)), tp, tz); EXPECT_EQ(a, b) << "prec=" << prec; } tp += chrono::milliseconds(6) + chrono::microseconds(7) + chrono::nanoseconds(8); EXPECT_EQ("05.006007008", absl::time_internal::cctz::format(fmt_A("*"), tp, tz)); EXPECT_EQ("05.006007008", absl::time_internal::cctz::format(fmt_B("*"), tp, tz)); EXPECT_EQ("05", absl::time_internal::cctz::format(fmt_A("0"), tp, tz)); EXPECT_EQ("05.", absl::time_internal::cctz::format(fmt_B("0"), tp, tz)); for (int prec = 1; prec <= 15; ++prec) { const std::string a = absl::time_internal::cctz::format(fmt_A(std::to_string(prec)), tp, tz); const std::string b = absl::time_internal::cctz::format(fmt_B(std::to_string(prec)), tp, tz); EXPECT_EQ(a, b) << "prec=" << prec; } } TEST(Format, ExtendedOffset) { const auto tp = chrono::system_clock::from_time_t(0); auto tz = fixed_time_zone(absl::time_internal::cctz::seconds::zero()); TestFormatSpecifier(tp, tz, "%z", "+0000"); TestFormatSpecifier(tp, tz, "%:z", "+00:00"); TestFormatSpecifier(tp, tz, "%Ez", "+00:00"); tz = fixed_time_zone(chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%z", "+0000"); TestFormatSpecifier(tp, tz, "%:z", "+00:00"); TestFormatSpecifier(tp, tz, "%Ez", "+00:00"); tz = fixed_time_zone(-chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%z", "+0000"); TestFormatSpecifier(tp, tz, "%:z", "+00:00"); TestFormatSpecifier(tp, tz, "%Ez", "+00:00"); tz = fixed_time_zone(chrono::minutes(34)); TestFormatSpecifier(tp, tz, "%z", "+0034"); TestFormatSpecifier(tp, tz, "%:z", "+00:34"); TestFormatSpecifier(tp, tz, "%Ez", "+00:34"); tz = fixed_time_zone(-chrono::minutes(34)); TestFormatSpecifier(tp, tz, "%z", "-0034"); TestFormatSpecifier(tp, tz, "%:z", "-00:34"); TestFormatSpecifier(tp, tz, "%Ez", "-00:34"); tz = fixed_time_zone(chrono::minutes(34) + chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%z", "+0034"); TestFormatSpecifier(tp, tz, "%:z", "+00:34"); TestFormatSpecifier(tp, tz, "%Ez", "+00:34"); tz = fixed_time_zone(-chrono::minutes(34) - chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%z", "-0034"); TestFormatSpecifier(tp, tz, "%:z", "-00:34"); TestFormatSpecifier(tp, tz, "%Ez", "-00:34"); tz = fixed_time_zone(chrono::hours(12)); TestFormatSpecifier(tp, tz, "%z", "+1200"); TestFormatSpecifier(tp, tz, "%:z", "+12:00"); TestFormatSpecifier(tp, tz, "%Ez", "+12:00"); tz = fixed_time_zone(-chrono::hours(12)); TestFormatSpecifier(tp, tz, "%z", "-1200"); TestFormatSpecifier(tp, tz, "%:z", "-12:00"); TestFormatSpecifier(tp, tz, "%Ez", "-12:00"); tz = fixed_time_zone(chrono::hours(12) + chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%z", "+1200"); TestFormatSpecifier(tp, tz, "%:z", "+12:00"); TestFormatSpecifier(tp, tz, "%Ez", "+12:00"); tz = fixed_time_zone(-chrono::hours(12) - chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%z", "-1200"); TestFormatSpecifier(tp, tz, "%:z", "-12:00"); TestFormatSpecifier(tp, tz, "%Ez", "-12:00"); tz = fixed_time_zone(chrono::hours(12) + chrono::minutes(34)); TestFormatSpecifier(tp, tz, "%z", "+1234"); TestFormatSpecifier(tp, tz, "%:z", "+12:34"); TestFormatSpecifier(tp, tz, "%Ez", "+12:34"); tz = fixed_time_zone(-chrono::hours(12) - chrono::minutes(34)); TestFormatSpecifier(tp, tz, "%z", "-1234"); TestFormatSpecifier(tp, tz, "%:z", "-12:34"); TestFormatSpecifier(tp, tz, "%Ez", "-12:34"); tz = fixed_time_zone(chrono::hours(12) + chrono::minutes(34) + chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%z", "+1234"); TestFormatSpecifier(tp, tz, "%:z", "+12:34"); TestFormatSpecifier(tp, tz, "%Ez", "+12:34"); tz = fixed_time_zone(-chrono::hours(12) - chrono::minutes(34) - chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%z", "-1234"); TestFormatSpecifier(tp, tz, "%:z", "-12:34"); TestFormatSpecifier(tp, tz, "%Ez", "-12:34"); } TEST(Format, ExtendedSecondOffset) { const auto tp = chrono::system_clock::from_time_t(0); auto tz = fixed_time_zone(absl::time_internal::cctz::seconds::zero()); TestFormatSpecifier(tp, tz, "%E*z", "+00:00:00"); TestFormatSpecifier(tp, tz, "%::z", "+00:00:00"); TestFormatSpecifier(tp, tz, "%:::z", "+00"); tz = fixed_time_zone(chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%E*z", "+00:00:56"); TestFormatSpecifier(tp, tz, "%::z", "+00:00:56"); TestFormatSpecifier(tp, tz, "%:::z", "+00:00:56"); tz = fixed_time_zone(-chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%E*z", "-00:00:56"); TestFormatSpecifier(tp, tz, "%::z", "-00:00:56"); TestFormatSpecifier(tp, tz, "%:::z", "-00:00:56"); tz = fixed_time_zone(chrono::minutes(34)); TestFormatSpecifier(tp, tz, "%E*z", "+00:34:00"); TestFormatSpecifier(tp, tz, "%::z", "+00:34:00"); TestFormatSpecifier(tp, tz, "%:::z", "+00:34"); tz = fixed_time_zone(-chrono::minutes(34)); TestFormatSpecifier(tp, tz, "%E*z", "-00:34:00"); TestFormatSpecifier(tp, tz, "%::z", "-00:34:00"); TestFormatSpecifier(tp, tz, "%:::z", "-00:34"); tz = fixed_time_zone(chrono::minutes(34) + chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%E*z", "+00:34:56"); TestFormatSpecifier(tp, tz, "%::z", "+00:34:56"); TestFormatSpecifier(tp, tz, "%:::z", "+00:34:56"); tz = fixed_time_zone(-chrono::minutes(34) - chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%E*z", "-00:34:56"); TestFormatSpecifier(tp, tz, "%::z", "-00:34:56"); TestFormatSpecifier(tp, tz, "%:::z", "-00:34:56"); tz = fixed_time_zone(chrono::hours(12)); TestFormatSpecifier(tp, tz, "%E*z", "+12:00:00"); TestFormatSpecifier(tp, tz, "%::z", "+12:00:00"); TestFormatSpecifier(tp, tz, "%:::z", "+12"); tz = fixed_time_zone(-chrono::hours(12)); TestFormatSpecifier(tp, tz, "%E*z", "-12:00:00"); TestFormatSpecifier(tp, tz, "%::z", "-12:00:00"); TestFormatSpecifier(tp, tz, "%:::z", "-12"); tz = fixed_time_zone(chrono::hours(12) + chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%E*z", "+12:00:56"); TestFormatSpecifier(tp, tz, "%::z", "+12:00:56"); TestFormatSpecifier(tp, tz, "%:::z", "+12:00:56"); tz = fixed_time_zone(-chrono::hours(12) - chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%E*z", "-12:00:56"); TestFormatSpecifier(tp, tz, "%::z", "-12:00:56"); TestFormatSpecifier(tp, tz, "%:::z", "-12:00:56"); tz = fixed_time_zone(chrono::hours(12) + chrono::minutes(34)); TestFormatSpecifier(tp, tz, "%E*z", "+12:34:00"); TestFormatSpecifier(tp, tz, "%::z", "+12:34:00"); TestFormatSpecifier(tp, tz, "%:::z", "+12:34"); tz = fixed_time_zone(-chrono::hours(12) - chrono::minutes(34)); TestFormatSpecifier(tp, tz, "%E*z", "-12:34:00"); TestFormatSpecifier(tp, tz, "%::z", "-12:34:00"); TestFormatSpecifier(tp, tz, "%:::z", "-12:34"); tz = fixed_time_zone(chrono::hours(12) + chrono::minutes(34) + chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%E*z", "+12:34:56"); TestFormatSpecifier(tp, tz, "%::z", "+12:34:56"); TestFormatSpecifier(tp, tz, "%:::z", "+12:34:56"); tz = fixed_time_zone(-chrono::hours(12) - chrono::minutes(34) - chrono::seconds(56)); TestFormatSpecifier(tp, tz, "%E*z", "-12:34:56"); TestFormatSpecifier(tp, tz, "%::z", "-12:34:56"); TestFormatSpecifier(tp, tz, "%:::z", "-12:34:56"); } TEST(Format, ExtendedYears) { const time_zone utc = utc_time_zone(); const char e4y_fmt[] = "%E4Y%m%d"; auto tp = convert(civil_second(-999, 11, 27, 0, 0, 0), utc); EXPECT_EQ("-9991127", absl::time_internal::cctz::format(e4y_fmt, tp, utc)); tp = convert(civil_second(-99, 11, 27, 0, 0, 0), utc); EXPECT_EQ("-0991127", absl::time_internal::cctz::format(e4y_fmt, tp, utc)); tp = convert(civil_second(-9, 11, 27, 0, 0, 0), utc); EXPECT_EQ("-0091127", absl::time_internal::cctz::format(e4y_fmt, tp, utc)); tp = convert(civil_second(-1, 11, 27, 0, 0, 0), utc); EXPECT_EQ("-0011127", absl::time_internal::cctz::format(e4y_fmt, tp, utc)); tp = convert(civil_second(0, 11, 27, 0, 0, 0), utc); EXPECT_EQ("00001127", absl::time_internal::cctz::format(e4y_fmt, tp, utc)); tp = convert(civil_second(1, 11, 27, 0, 0, 0), utc); EXPECT_EQ("00011127", absl::time_internal::cctz::format(e4y_fmt, tp, utc)); tp = convert(civil_second(9, 11, 27, 0, 0, 0), utc); EXPECT_EQ("00091127", absl::time_internal::cctz::format(e4y_fmt, tp, utc)); tp = convert(civil_second(99, 11, 27, 0, 0, 0), utc); EXPECT_EQ("00991127", absl::time_internal::cctz::format(e4y_fmt, tp, utc)); tp = convert(civil_second(999, 11, 27, 0, 0, 0), utc); EXPECT_EQ("09991127", absl::time_internal::cctz::format(e4y_fmt, tp, utc)); tp = convert(civil_second(9999, 11, 27, 0, 0, 0), utc); EXPECT_EQ("99991127", absl::time_internal::cctz::format(e4y_fmt, tp, utc)); tp = convert(civil_second(-1000, 11, 27, 0, 0, 0), utc); EXPECT_EQ("-10001127", absl::time_internal::cctz::format(e4y_fmt, tp, utc)); tp = convert(civil_second(10000, 11, 27, 0, 0, 0), utc); EXPECT_EQ("100001127", absl::time_internal::cctz::format(e4y_fmt, tp, utc)); } TEST(Format, RFC3339Format) { time_zone tz; EXPECT_TRUE(load_time_zone("America/Los_Angeles", &tz)); time_point<chrono::nanoseconds> tp = convert(civil_second(1977, 6, 28, 9, 8, 7), tz); EXPECT_EQ("1977-06-28T09:08:07-07:00", absl::time_internal::cctz::format(RFC3339_full, tp, tz)); EXPECT_EQ("1977-06-28T09:08:07-07:00", absl::time_internal::cctz::format(RFC3339_sec, tp, tz)); tp += chrono::milliseconds(100); EXPECT_EQ("1977-06-28T09:08:07.1-07:00", absl::time_internal::cctz::format(RFC3339_full, tp, tz)); EXPECT_EQ("1977-06-28T09:08:07-07:00", absl::time_internal::cctz::format(RFC3339_sec, tp, tz)); tp += chrono::milliseconds(20); EXPECT_EQ("1977-06-28T09:08:07.12-07:00", absl::time_internal::cctz::format(RFC3339_full, tp, tz)); EXPECT_EQ("1977-06-28T09:08:07-07:00", absl::time_internal::cctz::format(RFC3339_sec, tp, tz)); tp += chrono::milliseconds(3); EXPECT_EQ("1977-06-28T09:08:07.123-07:00", absl::time_internal::cctz::format(RFC3339_full, tp, tz)); EXPECT_EQ("1977-06-28T09:08:07-07:00", absl::time_internal::cctz::format(RFC3339_sec, tp, tz)); tp += chrono::microseconds(400); EXPECT_EQ("1977-06-28T09:08:07.1234-07:00", absl::time_internal::cctz::format(RFC3339_full, tp, tz)); EXPECT_EQ("1977-06-28T09:08:07-07:00", absl::time_internal::cctz::format(RFC3339_sec, tp, tz)); tp += chrono::microseconds(50); EXPECT_EQ("1977-06-28T09:08:07.12345-07:00", absl::time_internal::cctz::format(RFC3339_full, tp, tz)); EXPECT_EQ("1977-06-28T09:08:07-07:00", absl::time_internal::cctz::format(RFC3339_sec, tp, tz)); tp += chrono::microseconds(6); EXPECT_EQ("1977-06-28T09:08:07.123456-07:00", absl::time_internal::cctz::format(RFC3339_full, tp, tz)); EXPECT_EQ("1977-06-28T09:08:07-07:00", absl::time_internal::cctz::format(RFC3339_sec, tp, tz)); tp += chrono::nanoseconds(700); EXPECT_EQ("1977-06-28T09:08:07.1234567-07:00", absl::time_internal::cctz::format(RFC3339_full, tp, tz)); EXPECT_EQ("1977-06-28T09:08:07-07:00", absl::time_internal::cctz::format(RFC3339_sec, tp, tz)); tp += chrono::nanoseconds(80); EXPECT_EQ("1977-06-28T09:08:07.12345678-07:00", absl::time_internal::cctz::format(RFC3339_full, tp, tz)); EXPECT_EQ("1977-06-28T09:08:07-07:00", absl::time_internal::cctz::format(RFC3339_sec, tp, tz)); tp += chrono::nanoseconds(9); EXPECT_EQ("1977-06-28T09:08:07.123456789-07:00", absl::time_internal::cctz::format(RFC3339_full, tp, tz)); EXPECT_EQ("1977-06-28T09:08:07-07:00", absl::time_internal::cctz::format(RFC3339_sec, tp, tz)); } TEST(Format, RFC1123Format) { time_zone tz; EXPECT_TRUE(load_time_zone("America/Los_Angeles", &tz)); auto tp = convert(civil_second(1977, 6, 28, 9, 8, 7), tz); EXPECT_EQ("Tue, 28 Jun 1977 09:08:07 -0700", absl::time_internal::cctz::format(RFC1123_full, tp, tz)); EXPECT_EQ("28 Jun 1977 09:08:07 -0700", absl::time_internal::cctz::format(RFC1123_no_wday, tp, tz)); } TEST(Format, Week) { const time_zone utc = utc_time_zone(); auto tp = convert(civil_second(2017, 1, 1, 0, 0, 0), utc); EXPECT_EQ("2017-01-7", absl::time_internal::cctz::format("%Y-%U-%u", tp, utc)); EXPECT_EQ("2017-00-0", absl::time_internal::cctz::format("%Y-%W-%w", tp, utc)); tp = convert(civil_second(2017, 12, 31, 0, 0, 0), utc); EXPECT_EQ("2017-53-7", absl::time_internal::cctz::format("%Y-%U-%u", tp, utc)); EXPECT_EQ("2017-52-0", absl::time_internal::cctz::format("%Y-%W-%w", tp, utc)); tp = convert(civil_second(2018, 1, 1, 0, 0, 0), utc); EXPECT_EQ("2018-00-1", absl::time_internal::cctz::format("%Y-%U-%u", tp, utc)); EXPECT_EQ("2018-01-1", absl::time_internal::cctz::format("%Y-%W-%w", tp, utc)); tp = convert(civil_second(2018, 12, 31, 0, 0, 0), utc); EXPECT_EQ("2018-52-1", absl::time_internal::cctz::format("%Y-%U-%u", tp, utc)); EXPECT_EQ("2018-53-1", absl::time_internal::cctz::format("%Y-%W-%w", tp, utc)); tp = convert(civil_second(2019, 1, 1, 0, 0, 0), utc); EXPECT_EQ("2019-00-2", absl::time_internal::cctz::format("%Y-%U-%u", tp, utc)); EXPECT_EQ("2019-00-2", absl::time_internal::cctz::format("%Y-%W-%w", tp, utc)); tp = convert(civil_second(2019, 12, 31, 0, 0, 0), utc); EXPECT_EQ("2019-52-2", absl::time_internal::cctz::format("%Y-%U-%u", tp, utc)); EXPECT_EQ("2019-52-2", absl::time_internal::cctz::format("%Y-%W-%w", tp, utc)); } TEST(Parse, TimePointResolution) { const char kFmt[] = "%H:%M:%E*S"; const time_zone utc = utc_time_zone(); time_point<chrono::nanoseconds> tp_ns; EXPECT_TRUE(parse(kFmt, "03:04:05.123456789", utc, &tp_ns)); EXPECT_EQ("03:04:05.123456789", absl::time_internal::cctz::format(kFmt, tp_ns, utc)); EXPECT_TRUE(parse(kFmt, "03:04:05.123456", utc, &tp_ns)); EXPECT_EQ("03:04:05.123456", absl::time_internal::cctz::format(kFmt, tp_ns, utc)); time_point<chrono::microseconds> tp_us; EXPECT_TRUE(parse(kFmt, "03:04:05.123456789", utc, &tp_us)); EXPECT_EQ("03:04:05.123456", absl::time_internal::cctz::format(kFmt, tp_us, utc)); EXPECT_TRUE(parse(kFmt, "03:04:05.123456", utc, &tp_us)); EXPECT_EQ("03:04:05.123456", absl::time_internal::cctz::format(kFmt, tp_us, utc)); EXPECT_TRUE(parse(kFmt, "03:04:05.123", utc, &tp_us)); EXPECT_EQ("03:04:05.123", absl::time_internal::cctz::format(kFmt, tp_us, utc)); time_point<chrono::milliseconds> tp_ms; EXPECT_TRUE(parse(kFmt, "03:04:05.123456", utc, &tp_ms)); EXPECT_EQ("03:04:05.123", absl::time_internal::cctz::format(kFmt, tp_ms, utc)); EXPECT_TRUE(parse(kFmt, "03:04:05.123", utc, &tp_ms)); EXPECT_EQ("03:04:05.123", absl::time_internal::cctz::format(kFmt, tp_ms, utc)); EXPECT_TRUE(parse(kFmt, "03:04:05", utc, &tp_ms)); EXPECT_EQ("03:04:05", absl::time_internal::cctz::format(kFmt, tp_ms, utc)); time_point<chrono::seconds> tp_s; EXPECT_TRUE(parse(kFmt, "03:04:05.123", utc, &tp_s)); EXPECT_EQ("03:04:05", absl::time_internal::cctz::format(kFmt, tp_s, utc)); EXPECT_TRUE(parse(kFmt, "03:04:05", utc, &tp_s)); EXPECT_EQ("03:04:05", absl::time_internal::cctz::format(kFmt, tp_s, utc)); time_point<chrono::minutes> tp_m; EXPECT_TRUE(parse(kFmt, "03:04:05", utc, &tp_m)); EXPECT_EQ("03:04:00", absl::time_internal::cctz::format(kFmt, tp_m, utc)); time_point<chrono::hours> tp_h; EXPECT_TRUE(parse(kFmt, "03:04:05", utc, &tp_h)); EXPECT_EQ("03:00:00", absl::time_internal::cctz::format(kFmt, tp_h, utc)); } TEST(Parse, TimePointExtendedResolution) { const char kFmt[] = "%H:%M:%E*S"; const time_zone utc = utc_time_zone(); time_point<absl::time_internal::cctz::seconds> tp; detail::femtoseconds fs; EXPECT_TRUE(detail::parse(kFmt, "12:34:56.123456789012345", utc, &tp, &fs)); EXPECT_EQ("12:34:56.123456789012345", detail::format(kFmt, tp, fs, utc)); EXPECT_TRUE(detail::parse(kFmt, "12:34:56.012345678901234", utc, &tp, &fs)); EXPECT_EQ("12:34:56.012345678901234", detail::format(kFmt, tp, fs, utc)); EXPECT_TRUE(detail::parse(kFmt, "12:34:56.001234567890123", utc, &tp, &fs)); EXPECT_EQ("12:34:56.001234567890123", detail::format(kFmt, tp, fs, utc)); EXPECT_TRUE(detail::parse(kFmt, "12:34:56.000000000000123", utc, &tp, &fs)); EXPECT_EQ("12:34:56.000000000000123", detail::format(kFmt, tp, fs, utc)); EXPECT_TRUE(detail::parse(kFmt, "12:34:56.000000000000012", utc, &tp, &fs)); EXPECT_EQ("12:34:56.000000000000012", detail::format(kFmt, tp, fs, utc)); EXPECT_TRUE(detail::parse(kFmt, "12:34:56.000000000000001", utc, &tp, &fs)); EXPECT_EQ("12:34:56.000000000000001", detail::format(kFmt, tp, fs, utc)); } TEST(Parse, Basics) { time_zone tz = utc_time_zone(); time_point<chrono::nanoseconds> tp = chrono::system_clock::from_time_t(1234567890); EXPECT_TRUE(parse("", "", tz, &tp)); EXPECT_EQ(chrono::system_clock::from_time_t(0), tp); EXPECT_TRUE(parse(" ", " ", tz, &tp)); EXPECT_TRUE(parse(" ", " ", tz, &tp)); EXPECT_TRUE(parse("x", "x", tz, &tp)); EXPECT_TRUE(parse("xxx", "xxx", tz, &tp)); EXPECT_TRUE( parse("%Y-%m-%d %H:%M:%S %z", "2013-06-28 19:08:09 -0800", tz, &tp)); ExpectTime(tp, tz, 2013, 6, 29, 3, 8, 9, 0, false, "UTC"); } TEST(Parse, WithTimeZone) { time_zone tz; EXPECT_TRUE(load_time_zone("America/Los_Angeles", &tz)); time_point<chrono::nanoseconds> tp; EXPECT_TRUE(parse("%Y-%m-%d %H:%M:%S", "2013-06-28 19:08:09", tz, &tp)); ExpectTime(tp, tz, 2013, 6, 28, 19, 8, 9, -7 * 60 * 60, true, "PDT"); EXPECT_TRUE(parse("%Y-%m-%d %H:%M:%S %z", "2013-06-28 19:08:09 +0800", utc_time_zone(), &tp)); ExpectTime(tp, tz, 2013, 6, 28, 19 - 8 - 7, 8, 9, -7 * 60 * 60, true, "PDT"); EXPECT_TRUE(parse("%Y-%m-%d %H:%M:%S", "2011-03-13 02:15:00", tz, &tp)); ExpectTime(tp, tz, 2011, 3, 13, 3, 15, 0, -7 * 60 * 60, true, "PDT"); EXPECT_TRUE(parse("%Y-%m-%d %H:%M:%S", "2011-11-06 01:15:00", tz, &tp)); ExpectTime(tp, tz, 2011, 11, 6, 1, 15, 0, -7 * 60 * 60, true, "PDT"); } TEST(Parse, LeapSecond) { time_zone tz; EXPECT_TRUE(load_time_zone("America/Los_Angeles", &tz)); time_point<chrono::nanoseconds> tp; EXPECT_TRUE(parse(RFC3339_full, "2013-06-28T07:08:59-08:00", tz, &tp)); ExpectTime(tp, tz, 2013, 6, 28, 8, 8, 59, -7 * 60 * 60, true, "PDT"); EXPECT_TRUE(parse(RFC3339_full, "2013-06-28T07:08:59.5-08:00", tz, &tp)); ExpectTime(tp, tz, 2013, 6, 28, 8, 8, 59, -7 * 60 * 60, true, "PDT"); EXPECT_TRUE(parse(RFC3339_full, "2013-06-28T07:08:60-08:00", tz, &tp)); ExpectTime(tp, tz, 2013, 6, 28, 8, 9, 0, -7 * 60 * 60, true, "PDT"); EXPECT_TRUE(parse(RFC3339_full, "2013-06-28T07:08:60.5-08:00", tz, &tp)); ExpectTime(tp, tz, 2013, 6, 28, 8, 9, 0, -7 * 60 * 60, true, "PDT"); EXPECT_FALSE(parse(RFC3339_full, "2013-06-28T07:08:61-08:00", tz, &tp)); } TEST(Parse, ErrorCases) { const time_zone tz = utc_time_zone(); auto tp = chrono::system_clock::from_time_t(0); EXPECT_FALSE(parse("%S", "123", tz, &tp)); EXPECT_FALSE(parse("%Q", "x", tz, &tp)); EXPECT_FALSE(parse("%m-%d", "2-3 blah", tz, &tp)); EXPECT_TRUE(parse("%m-%d", "2-3 ", tz, &tp)); EXPECT_EQ(2, convert(tp, utc_time_zone()).month()); EXPECT_EQ(3, convert(tp, utc_time_zone()).day()); EXPECT_FALSE(parse("%m-%d", "2-31", tz, &tp)); EXPECT_TRUE(parse("%z", "-0203", tz, &tp)); EXPECT_FALSE(parse("%z", "- 2 3", tz, &tp)); EXPECT_TRUE(parse("%Ez", "-02:03", tz, &tp)); EXPECT_FALSE(parse("%Ez", "- 2: 3", tz, &tp)); EXPECT_FALSE(parse("%Ez", "+-08:00", tz, &tp)); EXPECT_FALSE(parse("%Ez", "-+08:00", tz, &tp)); EXPECT_FALSE(parse("%Y", "-0", tz, &tp)); EXPECT_FALSE(parse("%E4Y", "-0", tz, &tp)); EXPECT_FALSE(parse("%H", "-0", tz, &tp)); EXPECT_FALSE(parse("%M", "-0", tz, &tp)); EXPECT_FALSE(parse("%S", "-0", tz, &tp)); EXPECT_FALSE(parse("%z", "+-000", tz, &tp)); EXPECT_FALSE(parse("%Ez", "+-0:00", tz, &tp)); EXPECT_FALSE(parse("%z", "-00-0", tz, &tp)); EXPECT_FALSE(parse("%Ez", "-00:-0", tz, &tp)); } TEST(Parse, PosixConversions) { time_zone tz = utc_time_zone(); auto tp = chrono::system_clock::from_time_t(0); const auto reset = convert(civil_second(1977, 6, 28, 9, 8, 7), tz); tp = reset; EXPECT_TRUE(parse("%d", "15", tz, &tp)); EXPECT_EQ(15, convert(tp, tz).day()); tp = reset; EXPECT_TRUE(parse("%e", "15", tz, &tp)); EXPECT_EQ(15, convert(tp, tz).day()); tp = reset; EXPECT_TRUE(parse("%H", "17", tz, &tp)); EXPECT_EQ(17, convert(tp, tz).hour()); tp = reset; EXPECT_TRUE(parse("%I", "5", tz, &tp)); EXPECT_EQ(5, convert(tp, tz).hour()); EXPECT_TRUE(parse("%j", "32", tz, &tp)); tp = reset; EXPECT_TRUE(parse("%m", "11", tz, &tp)); EXPECT_EQ(11, convert(tp, tz).month()); tp = reset; EXPECT_TRUE(parse("%M", "33", tz, &tp)); EXPECT_EQ(33, convert(tp, tz).minute()); tp = reset; EXPECT_TRUE(parse("%S", "55", tz, &tp)); EXPECT_EQ(55, convert(tp, tz).second()); EXPECT_TRUE(parse("%U", "15", tz, &tp)); EXPECT_TRUE(parse("%w", "2", tz, &tp)); EXPECT_TRUE(parse("%W", "22", tz, &tp)); tp = reset; EXPECT_TRUE(parse("%y", "04", tz, &tp)); EXPECT_EQ(2004, convert(tp, tz).year()); tp = reset; EXPECT_TRUE(parse("%Y", "2004", tz, &tp)); EXPECT_EQ(2004, convert(tp, tz).year()); EXPECT_TRUE(parse("%%", "%", tz, &tp)); #if defined(__linux__) #if 0 tp = reset; EXPECT_TRUE(parse("%C %y", "20 04", tz, &tp)); EXPECT_EQ(2004, convert(tp, tz).year()); #endif tp = reset; EXPECT_TRUE(parse("%D", "02/03/04", tz, &tp)); EXPECT_EQ(2, convert(tp, tz).month()); EXPECT_EQ(3, convert(tp, tz).day()); EXPECT_EQ(2004, convert(tp, tz).year()); EXPECT_TRUE(parse("%n", "\n", tz, &tp)); tp = reset; EXPECT_TRUE(parse("%R", "03:44", tz, &tp)); EXPECT_EQ(3, convert(tp, tz).hour()); EXPECT_EQ(44, convert(tp, tz).minute()); EXPECT_TRUE(parse("%t", "\t\v\f\n\r ", tz, &tp)); tp = reset; EXPECT_TRUE(parse("%T", "03:44:55", tz, &tp)); EXPECT_EQ(3, convert(tp, tz).hour()); EXPECT_EQ(44, convert(tp, tz).minute()); EXPECT_EQ(55, convert(tp, tz).second()); tp = reset; EXPECT_TRUE(parse("%s", "1234567890", tz, &tp)); EXPECT_EQ(chrono::system_clock::from_time_t(1234567890), tp); time_zone lax; EXPECT_TRUE(load_time_zone("America/Los_Angeles", &lax)); tp = reset; EXPECT_TRUE(parse("%s", "1234567890", lax, &tp)); EXPECT_EQ(chrono::system_clock::from_time_t(1234567890), tp); tp = reset; EXPECT_TRUE(parse("%s", "1414917000", lax, &tp)); EXPECT_EQ(chrono::system_clock::from_time_t(1414917000), tp); tp = reset; EXPECT_TRUE(parse("%s", "1414920600", lax, &tp)); EXPECT_EQ(chrono::system_clock::from_time_t(1414920600), tp); #endif } TEST(Parse, LocaleSpecific) { time_zone tz = utc_time_zone(); auto tp = chrono::system_clock::from_time_t(0); const auto reset = convert(civil_second(1977, 6, 28, 9, 8, 7), tz); EXPECT_TRUE(parse("%a", "Mon", tz, &tp)); EXPECT_TRUE(parse("%A", "Monday", tz, &tp)); tp = reset; EXPECT_TRUE(parse("%b", "Feb", tz, &tp)); EXPECT_EQ(2, convert(tp, tz).month()); tp = reset; EXPECT_TRUE(parse("%B", "February", tz, &tp)); EXPECT_EQ(2, convert(tp, tz).month()); EXPECT_TRUE(parse("%p", "AM", tz, &tp)); tp = reset; EXPECT_TRUE(parse("%I %p", "5 PM", tz, &tp)); EXPECT_EQ(17, convert(tp, tz).hour()); tp = reset; EXPECT_TRUE(parse("%x", "02/03/04", tz, &tp)); if (convert(tp, tz).month() == 2) { EXPECT_EQ(3, convert(tp, tz).day()); } else { EXPECT_EQ(2, convert(tp, tz).day()); EXPECT_EQ(3, convert(tp, tz).month()); } EXPECT_EQ(2004, convert(tp, tz).year()); tp = reset; EXPECT_TRUE(parse("%X", "15:44:55", tz, &tp)); EXPECT_EQ(15, convert(tp, tz).hour()); EXPECT_EQ(44, convert(tp, tz).minute()); EXPECT_EQ(55, convert(tp, tz).second()); #if defined(__linux__) tp = reset; EXPECT_TRUE(parse("%h", "Feb", tz, &tp)); EXPECT_EQ(2, convert(tp, tz).month()); #if defined(__GLIBC__) tp = reset; EXPECT_TRUE(parse("%l %p", "5 PM", tz, &tp)); EXPECT_EQ(17, convert(tp, tz).hour()); #endif tp = reset; EXPECT_TRUE(parse("%r", "03:44:55 PM", tz, &tp)); EXPECT_EQ(15, convert(tp, tz).hour()); EXPECT_EQ(44, convert(tp, tz).minute()); EXPECT_EQ(55, convert(tp, tz).second()); #if defined(__GLIBC__) tp = reset; EXPECT_TRUE(parse("%Ec", "Tue Nov 19 05:06:07 2013", tz, &tp)); EXPECT_EQ(convert(civil_second(2013, 11, 19, 5, 6, 7), tz), tp); tp = reset; EXPECT_TRUE(parse("%Ex", "02/03/04", tz, &tp)); EXPECT_EQ(2, convert(tp, tz).month()); EXPECT_EQ(3, convert(tp, tz).day()); EXPECT_EQ(2004, convert(tp, tz).year()); tp = reset; EXPECT_TRUE(parse("%EX", "15:44:55", tz, &tp)); EXPECT_EQ(15, convert(tp, tz).hour()); EXPECT_EQ(44, convert(tp, tz).minute()); EXPECT_EQ(55, convert(tp, tz).second()); tp = reset; EXPECT_TRUE(parse("%EY", "2004", tz, &tp)); EXPECT_EQ(2004, convert(tp, tz).year()); tp = reset; EXPECT_TRUE(parse("%Od", "15", tz, &tp)); EXPECT_EQ(15, convert(tp, tz).day()); tp = reset; EXPECT_TRUE(parse("%Oe", "15", tz, &tp)); EXPECT_EQ(15, convert(tp, tz).day()); tp = reset; EXPECT_TRUE(parse("%OH", "17", tz, &tp)); EXPECT_EQ(17, convert(tp, tz).hour()); tp = reset; EXPECT_TRUE(parse("%OI", "5", tz, &tp)); EXPECT_EQ(5, convert(tp, tz).hour()); tp = reset; EXPECT_TRUE(parse("%Om", "11", tz, &tp)); EXPECT_EQ(11, convert(tp, tz).month()); tp = reset; EXPECT_TRUE(parse("%OM", "33", tz, &tp)); EXPECT_EQ(33, convert(tp, tz).minute()); tp = reset; EXPECT_TRUE(parse("%OS", "55", tz, &tp)); EXPECT_EQ(55, convert(tp, tz).second()); EXPECT_TRUE(parse("%OU", "15", tz, &tp)); EXPECT_TRUE(parse("%Ow", "2", tz, &tp)); EXPECT_TRUE(parse("%OW", "22", tz, &tp)); tp = reset; EXPECT_TRUE(parse("%Oy", "04", tz, &tp)); EXPECT_EQ(2004, convert(tp, tz).year()); #endif #endif } TEST(Parse, ExtendedSeconds) { const time_zone tz = utc_time_zone(); const time_point<chrono::nanoseconds> unix_epoch = chrono::system_clock::from_time_t(0); auto precisions = {"*", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"}; for (const std::string prec : precisions) { const std::string fmt = "%E" + prec + "S"; SCOPED_TRACE(fmt); time_point<chrono::nanoseconds> tp = unix_epoch; EXPECT_TRUE(parse(fmt, "5", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::seconds(5), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "05", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::seconds(5), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "05.0", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::seconds(5), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "05.00", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::seconds(5), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "05.6", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::seconds(5) + chrono::milliseconds(600), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "05.60", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::seconds(5) + chrono::milliseconds(600), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "05.600", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::seconds(5) + chrono::milliseconds(600), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "05.67", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::seconds(5) + chrono::milliseconds(670), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "05.670", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::seconds(5) + chrono::milliseconds(670), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "05.678", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::seconds(5) + chrono::milliseconds(678), tp); } time_point<chrono::nanoseconds> tp = unix_epoch; EXPECT_TRUE(parse("%E*S", "0.2147483647", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::nanoseconds(214748364), tp); tp = unix_epoch; EXPECT_TRUE(parse("%E*S", "0.2147483648", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::nanoseconds(214748364), tp); tp = unix_epoch; EXPECT_TRUE(parse( "%E*S", "0.214748364801234567890123456789012345678901234567890123456789", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::nanoseconds(214748364), tp); } TEST(Parse, ExtendedSecondsScan) { const time_zone tz = utc_time_zone(); time_point<chrono::nanoseconds> tp; for (int ms = 0; ms < 1000; ms += 111) { for (int us = 0; us < 1000; us += 27) { const int micros = ms * 1000 + us; for (int ns = 0; ns < 1000; ns += 9) { const auto expected = chrono::system_clock::from_time_t(0) + chrono::nanoseconds(micros * 1000 + ns); std::ostringstream oss; oss << "0." << std::setfill('0') << std::setw(3); oss << ms << std::setw(3) << us << std::setw(3) << ns; const std::string input = oss.str(); EXPECT_TRUE(parse("%E*S", input, tz, &tp)); EXPECT_EQ(expected, tp) << input; } } } } TEST(Parse, ExtendedSubeconds) { const time_zone tz = utc_time_zone(); const time_point<chrono::nanoseconds> unix_epoch = chrono::system_clock::from_time_t(0); auto precisions = {"*", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"}; for (const std::string prec : precisions) { const std::string fmt = "%E" + prec + "f"; SCOPED_TRACE(fmt); time_point<chrono::nanoseconds> tp = unix_epoch - chrono::seconds(1); EXPECT_TRUE(parse(fmt, "", tz, &tp)); EXPECT_EQ(unix_epoch, tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "6", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::milliseconds(600), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "60", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::milliseconds(600), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "600", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::milliseconds(600), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "67", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::milliseconds(670), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "670", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::milliseconds(670), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "678", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::milliseconds(678), tp); tp = unix_epoch; EXPECT_TRUE(parse(fmt, "6789", tz, &tp)); EXPECT_EQ( unix_epoch + chrono::milliseconds(678) + chrono::microseconds(900), tp); } time_point<chrono::nanoseconds> tp = unix_epoch; EXPECT_TRUE(parse("%E*f", "2147483647", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::nanoseconds(214748364), tp); tp = unix_epoch; EXPECT_TRUE(parse("%E*f", "2147483648", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::nanoseconds(214748364), tp); tp = unix_epoch; EXPECT_TRUE(parse( "%E*f", "214748364801234567890123456789012345678901234567890123456789", tz, &tp)); EXPECT_EQ(unix_epoch + chrono::nanoseconds(214748364), tp); } TEST(Parse, ExtendedSubecondsScan) { time_point<chrono::nanoseconds> tp; const time_zone tz = utc_time_zone(); for (int ms = 0; ms < 1000; ms += 111) { for (int us = 0; us < 1000; us += 27) { const int micros = ms * 1000 + us; for (int ns = 0; ns < 1000; ns += 9) { std::ostringstream oss; oss << std::setfill('0') << std::setw(3) << ms; oss << std::setw(3) << us << std::setw(3) << ns; const std::string nanos = oss.str(); const auto expected = chrono::system_clock::from_time_t(0) + chrono::nanoseconds(micros * 1000 + ns); for (int ps = 0; ps < 1000; ps += 250) { std::ostringstream ps_oss; oss << std::setfill('0') << std::setw(3) << ps; const std::string input = nanos + ps_oss.str() + "999"; EXPECT_TRUE(parse("%E*f", input, tz, &tp)); EXPECT_EQ(expected + chrono::nanoseconds(ps) / 1000, tp) << input; } } } } } TEST(Parse, ExtendedOffset) { const time_zone utc = utc_time_zone(); time_point<absl::time_internal::cctz::seconds> tp; EXPECT_TRUE(parse("%Ez", "+00:00", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 0, 0, 0), utc), tp); EXPECT_TRUE(parse("%Ez", "-12:34", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 12, 34, 0), utc), tp); EXPECT_TRUE(parse("%Ez", "+12:34", utc, &tp)); EXPECT_EQ(convert(civil_second(1969, 12, 31, 11, 26, 0), utc), tp); EXPECT_FALSE(parse("%Ez", "-12:3", utc, &tp)); for (auto fmt : {"%Ez", "%z"}) { EXPECT_TRUE(parse(fmt, "+0000", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(fmt, "-1234", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 12, 34, 0), utc), tp); EXPECT_TRUE(parse(fmt, "+1234", utc, &tp)); EXPECT_EQ(convert(civil_second(1969, 12, 31, 11, 26, 0), utc), tp); EXPECT_FALSE(parse(fmt, "-123", utc, &tp)); EXPECT_TRUE(parse(fmt, "+00", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(fmt, "-12", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 12, 0, 0), utc), tp); EXPECT_TRUE(parse(fmt, "+12", utc, &tp)); EXPECT_EQ(convert(civil_second(1969, 12, 31, 12, 0, 0), utc), tp); EXPECT_FALSE(parse(fmt, "-1", utc, &tp)); } } TEST(Parse, ExtendedSecondOffset) { const time_zone utc = utc_time_zone(); time_point<absl::time_internal::cctz::seconds> tp; for (auto fmt : {"%Ez", "%E*z", "%:z", "%::z", "%:::z"}) { EXPECT_TRUE(parse(fmt, "+00:00:00", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(fmt, "-12:34:56", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 12, 34, 56), utc), tp); EXPECT_TRUE(parse(fmt, "+12:34:56", utc, &tp)); EXPECT_EQ(convert(civil_second(1969, 12, 31, 11, 25, 4), utc), tp); EXPECT_FALSE(parse(fmt, "-12:34:5", utc, &tp)); EXPECT_TRUE(parse(fmt, "+000000", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(fmt, "-123456", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 12, 34, 56), utc), tp); EXPECT_TRUE(parse(fmt, "+123456", utc, &tp)); EXPECT_EQ(convert(civil_second(1969, 12, 31, 11, 25, 4), utc), tp); EXPECT_FALSE(parse(fmt, "-12345", utc, &tp)); EXPECT_TRUE(parse(fmt, "+00:00", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(fmt, "-12:34", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 12, 34, 0), utc), tp); EXPECT_TRUE(parse(fmt, "+12:34", utc, &tp)); EXPECT_EQ(convert(civil_second(1969, 12, 31, 11, 26, 0), utc), tp); EXPECT_FALSE(parse(fmt, "-12:3", utc, &tp)); EXPECT_TRUE(parse(fmt, "+0000", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(fmt, "-1234", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 12, 34, 0), utc), tp); EXPECT_TRUE(parse(fmt, "+1234", utc, &tp)); EXPECT_EQ(convert(civil_second(1969, 12, 31, 11, 26, 0), utc), tp); EXPECT_FALSE(parse(fmt, "-123", utc, &tp)); EXPECT_TRUE(parse(fmt, "+00", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(fmt, "-12", utc, &tp)); EXPECT_EQ(convert(civil_second(1970, 1, 1, 12, 0, 0), utc), tp); EXPECT_TRUE(parse(fmt, "+12", utc, &tp)); EXPECT_EQ(convert(civil_second(1969, 12, 31, 12, 0, 0), utc), tp); EXPECT_FALSE(parse(fmt, "-1", utc, &tp)); } } TEST(Parse, ExtendedYears) { const time_zone utc = utc_time_zone(); const char e4y_fmt[] = "%E4Y%m%d"; time_point<absl::time_internal::cctz::seconds> tp; EXPECT_TRUE(parse(e4y_fmt, "-9991127", utc, &tp)); EXPECT_EQ(convert(civil_second(-999, 11, 27, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(e4y_fmt, "-0991127", utc, &tp)); EXPECT_EQ(convert(civil_second(-99, 11, 27, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(e4y_fmt, "-0091127", utc, &tp)); EXPECT_EQ(convert(civil_second(-9, 11, 27, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(e4y_fmt, "-0011127", utc, &tp)); EXPECT_EQ(convert(civil_second(-1, 11, 27, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(e4y_fmt, "00001127", utc, &tp)); EXPECT_EQ(convert(civil_second(0, 11, 27, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(e4y_fmt, "00011127", utc, &tp)); EXPECT_EQ(convert(civil_second(1, 11, 27, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(e4y_fmt, "00091127", utc, &tp)); EXPECT_EQ(convert(civil_second(9, 11, 27, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(e4y_fmt, "00991127", utc, &tp)); EXPECT_EQ(convert(civil_second(99, 11, 27, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(e4y_fmt, "09991127", utc, &tp)); EXPECT_EQ(convert(civil_second(999, 11, 27, 0, 0, 0), utc), tp); EXPECT_TRUE(parse(e4y_fmt, "99991127", utc, &tp)); EXPECT_EQ(convert(civil_second(9999, 11, 27, 0, 0, 0), utc), tp); EXPECT_FALSE(parse(e4y_fmt, "-10001127", utc, &tp)); EXPECT_FALSE(parse(e4y_fmt, "100001127", utc, &tp)); } TEST(Parse, RFC3339Format) { const time_zone tz = utc_time_zone(); time_point<chrono::nanoseconds> tp; EXPECT_TRUE(parse(RFC3339_sec, "2014-02-12T20:21:00+00:00", tz, &tp)); ExpectTime(tp, tz, 2014, 2, 12, 20, 21, 0, 0, false, "UTC"); time_point<chrono::nanoseconds> tp2; EXPECT_TRUE(parse(RFC3339_sec, "2014-02-12t20:21:00+00:00", tz, &tp2)); EXPECT_EQ(tp, tp2); time_point<chrono::nanoseconds> tp3; EXPECT_TRUE(parse(RFC3339_sec, "2014-02-12T20:21:00Z", tz, &tp3)); EXPECT_EQ(tp, tp3); time_point<chrono::nanoseconds> tp4; EXPECT_TRUE(parse(RFC3339_sec, "2014-02-12T20:21:00z", tz, &tp4)); EXPECT_EQ(tp, tp4); } TEST(Parse, Week) { const time_zone utc = utc_time_zone(); time_point<absl::time_internal::cctz::seconds> tp; auto exp = convert(civil_second(2017, 1, 1, 0, 0, 0), utc); EXPECT_TRUE(parse("%Y-%U-%u", "2017-01-7", utc, &tp)); EXPECT_EQ(exp, tp); EXPECT_TRUE(parse("%Y-%W-%w", "2017-00-0", utc, &tp)); EXPECT_EQ(exp, tp); exp = convert(civil_second(2017, 12, 31, 0, 0, 0), utc); EXPECT_TRUE(parse("%Y-%U-%u", "2017-53-7", utc, &tp)); EXPECT_EQ(exp, tp); EXPECT_TRUE(parse("%Y-%W-%w", "2017-52-0", utc, &tp)); EXPECT_EQ(exp, tp); exp = convert(civil_second(2018, 1, 1, 0, 0, 0), utc); EXPECT_TRUE(parse("%Y-%U-%u", "2018-00-1", utc, &tp)); EXPECT_EQ(exp, tp); EXPECT_TRUE(parse("%Y-%W-%w", "2018-01-1", utc, &tp)); EXPECT_EQ(exp, tp); exp = convert(civil_second(2018, 12, 31, 0, 0, 0), utc); EXPECT_TRUE(parse("%Y-%U-%u", "2018-52-1", utc, &tp)); EXPECT_EQ(exp, tp); EXPECT_TRUE(parse("%Y-%W-%w", "2018-53-1", utc, &tp)); EXPECT_EQ(exp, tp); exp = convert(civil_second(2019, 1, 1, 0, 0, 0), utc); EXPECT_TRUE(parse("%Y-%U-%u", "2019-00-2", utc, &tp)); EXPECT_EQ(exp, tp); EXPECT_TRUE(parse("%Y-%W-%w", "2019-00-2", utc, &tp)); EXPECT_EQ(exp, tp); exp = convert(civil_second(2019, 12, 31, 0, 0, 0), utc); EXPECT_TRUE(parse("%Y-%U-%u", "2019-52-2", utc, &tp)); EXPECT_EQ(exp, tp); EXPECT_TRUE(parse("%Y-%W-%w", "2019-52-2", utc, &tp)); EXPECT_EQ(exp, tp); } TEST(Parse, WeekYearShift) { const time_zone utc = utc_time_zone(); time_point<absl::time_internal::cctz::seconds> tp; auto exp = convert(civil_second(2019, 12, 31, 0, 0, 0), utc); EXPECT_TRUE(parse("%Y-%U-%u", "2020-00-2", utc, &tp)); EXPECT_EQ(exp, tp); EXPECT_TRUE(parse("%Y-%W-%w", "2020-00-2", utc, &tp)); EXPECT_EQ(exp, tp); exp = convert(civil_second(2021, 1, 1, 0, 0, 0), utc); EXPECT_TRUE(parse("%Y-%U-%u", "2020-52-5", utc, &tp)); EXPECT_EQ(exp, tp); EXPECT_TRUE(parse("%Y-%W-%w", "2020-52-5", utc, &tp)); EXPECT_EQ(exp, tp); EXPECT_FALSE(parse("%Y-%U-%u", "-9223372036854775808-0-7", utc, &tp)); EXPECT_FALSE(parse("%Y-%U-%u", "9223372036854775807-53-7", utc, &tp)); } TEST(Parse, MaxRange) { const time_zone utc = utc_time_zone(); time_point<absl::time_internal::cctz::seconds> tp; EXPECT_TRUE( parse(RFC3339_sec, "292277026596-12-04T15:30:07+00:00", utc, &tp)); EXPECT_EQ(tp, time_point<absl::time_internal::cctz::seconds>::max()); EXPECT_FALSE( parse(RFC3339_sec, "292277026596-12-04T15:30:08+00:00", utc, &tp)); EXPECT_TRUE( parse(RFC3339_sec, "292277026596-12-04T14:30:07-01:00", utc, &tp)); EXPECT_EQ(tp, time_point<absl::time_internal::cctz::seconds>::max()); EXPECT_FALSE( parse(RFC3339_sec, "292277026596-12-04T14:30:08-01:00", utc, &tp)); EXPECT_TRUE( parse(RFC3339_sec, "-292277022657-01-27T08:29:52+00:00", utc, &tp)); EXPECT_EQ(tp, time_point<absl::time_internal::cctz::seconds>::min()); EXPECT_FALSE( parse(RFC3339_sec, "-292277022657-01-27T08:29:51+00:00", utc, &tp)); EXPECT_TRUE( parse(RFC3339_sec, "-292277022657-01-27T09:29:52+01:00", utc, &tp)); EXPECT_EQ(tp, time_point<absl::time_internal::cctz::seconds>::min()); EXPECT_FALSE( parse(RFC3339_sec, "-292277022657-01-27T08:29:51+01:00", utc, &tp)); EXPECT_FALSE( parse(RFC3339_sec, "9223372036854775807-12-31T23:59:59-00:01", utc, &tp)); EXPECT_FALSE(parse(RFC3339_sec, "-9223372036854775808-01-01T00:00:00+00:01", utc, &tp)); } TEST(Parse, TimePointOverflow) { const time_zone utc = utc_time_zone(); using D = chrono::duration<std::int64_t, std::nano>; time_point<D> tp; EXPECT_TRUE( parse(RFC3339_full, "2262-04-11T23:47:16.8547758079+00:00", utc, &tp)); EXPECT_EQ(tp, time_point<D>::max()); EXPECT_EQ("2262-04-11T23:47:16.854775807+00:00", absl::time_internal::cctz::format(RFC3339_full, tp, utc)); #if 0 EXPECT_FALSE( parse(RFC3339_full, "2262-04-11T23:47:16.8547758080+00:00", utc, &tp)); EXPECT_TRUE( parse(RFC3339_full, "1677-09-21T00:12:43.1452241920+00:00", utc, &tp)); EXPECT_EQ(tp, time_point<D>::min()); EXPECT_EQ("1677-09-21T00:12:43.145224192+00:00", absl::time_internal::cctz::format(RFC3339_full, tp, utc)); EXPECT_FALSE( parse(RFC3339_full, "1677-09-21T00:12:43.1452241919+00:00", utc, &tp)); #endif using DS = chrono::duration<std::int8_t, chrono::seconds::period>; time_point<DS> stp; EXPECT_TRUE(parse(RFC3339_full, "1970-01-01T00:02:07.9+00:00", utc, &stp)); EXPECT_EQ(stp, time_point<DS>::max()); EXPECT_EQ("1970-01-01T00:02:07+00:00", absl::time_internal::cctz::format(RFC3339_full, stp, utc)); EXPECT_FALSE(parse(RFC3339_full, "1970-01-01T00:02:08+00:00", utc, &stp)); EXPECT_TRUE(parse(RFC3339_full, "1969-12-31T23:57:52+00:00", utc, &stp)); EXPECT_EQ(stp, time_point<DS>::min()); EXPECT_EQ("1969-12-31T23:57:52+00:00", absl::time_internal::cctz::format(RFC3339_full, stp, utc)); EXPECT_FALSE(parse(RFC3339_full, "1969-12-31T23:57:51.9+00:00", utc, &stp)); using DM = chrono::duration<std::int8_t, chrono::minutes::period>; time_point<DM> mtp; EXPECT_TRUE(parse(RFC3339_full, "1970-01-01T02:07:59+00:00", utc, &mtp)); EXPECT_EQ(mtp, time_point<DM>::max()); EXPECT_EQ("1970-01-01T02:07:00+00:00", absl::time_internal::cctz::format(RFC3339_full, mtp, utc)); EXPECT_FALSE(parse(RFC3339_full, "1970-01-01T02:08:00+00:00", utc, &mtp)); EXPECT_TRUE(parse(RFC3339_full, "1969-12-31T21:52:00+00:00", utc, &mtp)); EXPECT_EQ(mtp, time_point<DM>::min()); EXPECT_EQ("1969-12-31T21:52:00+00:00", absl::time_internal::cctz::format(RFC3339_full, mtp, utc)); EXPECT_FALSE(parse(RFC3339_full, "1969-12-31T21:51:59+00:00", utc, &mtp)); } TEST(Parse, TimePointOverflowFloor) { const time_zone utc = utc_time_zone(); using D = chrono::duration<std::int64_t, std::micro>; time_point<D> tp; EXPECT_TRUE( parse(RFC3339_full, "294247-01-10T04:00:54.7758079+00:00", utc, &tp)); EXPECT_EQ(tp, time_point<D>::max()); EXPECT_EQ("294247-01-10T04:00:54.775807+00:00", absl::time_internal::cctz::format(RFC3339_full, tp, utc)); #if 0 EXPECT_FALSE( parse(RFC3339_full, "294247-01-10T04:00:54.7758080+00:00", utc, &tp)); EXPECT_TRUE( parse(RFC3339_full, "-290308-12-21T19:59:05.2241920+00:00", utc, &tp)); EXPECT_EQ(tp, time_point<D>::min()); EXPECT_EQ("-290308-12-21T19:59:05.224192+00:00", absl::time_internal::cctz::format(RFC3339_full, tp, utc)); EXPECT_FALSE( parse(RFC3339_full, "-290308-12-21T19:59:05.2241919+00:00", utc, &tp)); #endif } TEST(FormatParse, RoundTrip) { time_zone lax; EXPECT_TRUE(load_time_zone("America/Los_Angeles", &lax)); const auto in = convert(civil_second(1977, 6, 28, 9, 8, 7), lax); const auto subseconds = chrono::nanoseconds(654321); { time_point<chrono::nanoseconds> out; const std::string s = absl::time_internal::cctz::format(RFC3339_full, in + subseconds, lax); EXPECT_TRUE(parse(RFC3339_full, s, lax, &out)) << s; EXPECT_EQ(in + subseconds, out); } { time_point<chrono::nanoseconds> out; const std::string s = absl::time_internal::cctz::format(RFC1123_full, in, lax); EXPECT_TRUE(parse(RFC1123_full, s, lax, &out)) << s; EXPECT_EQ(in, out); } #if defined(_WIN32) || defined(_WIN64) #elif defined(__EMSCRIPTEN__) #else { time_point<chrono::nanoseconds> out; time_zone utc = utc_time_zone(); const std::string s = absl::time_internal::cctz::format("%c", in, utc); EXPECT_TRUE(parse("%c", s, utc, &out)) << s; EXPECT_EQ(in, out); } #endif } TEST(FormatParse, RoundTripDistantFuture) { const time_zone utc = utc_time_zone(); const time_point<absl::time_internal::cctz::seconds> in = time_point<absl::time_internal::cctz::seconds>::max(); const std::string s = absl::time_internal::cctz::format(RFC3339_full, in, utc); time_point<absl::time_internal::cctz::seconds> out; EXPECT_TRUE(parse(RFC3339_full, s, utc, &out)) << s; EXPECT_EQ(in, out); } TEST(FormatParse, RoundTripDistantPast) { const time_zone utc = utc_time_zone(); const time_point<absl::time_internal::cctz::seconds> in = time_point<absl::time_internal::cctz::seconds>::min(); const std::string s = absl::time_internal::cctz::format(RFC3339_full, in, utc); time_point<absl::time_internal::cctz::seconds> out; EXPECT_TRUE(parse(RFC3339_full, s, utc, &out)) << s; EXPECT_EQ(in, out); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/internal/cctz/src/time_zone_format.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/internal/cctz/src/time_zone_format_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
f3262866-5969-4226-8165-e5f8fb7d8624
cpp
abseil/abseil-cpp
time_zone_lookup
absl/time/internal/cctz/src/time_zone_lookup.cc
absl/time/internal/cctz/src/time_zone_lookup_test.cc
#include "absl/base/config.h" #include "absl/time/internal/cctz/include/cctz/time_zone.h" #if defined(__ANDROID__) #include <sys/system_properties.h> #endif #if defined(__APPLE__) #include <CoreFoundation/CFTimeZone.h> #include <vector> #endif #if defined(__Fuchsia__) #include <fuchsia/intl/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/fdio/directory.h> #include <zircon/types.h> #endif #if defined(_WIN32) #include <sdkddkver.h> #if ((defined(_WIN32_WINNT_WIN10) && !defined(__MINGW32__)) || \ (defined(NTDDI_WIN10_NI) && NTDDI_VERSION >= NTDDI_WIN10_NI)) && \ (_WIN32_WINNT >= _WIN32_WINNT_WINXP) #define USE_WIN32_LOCAL_TIME_ZONE #include <roapi.h> #include <tchar.h> #include <wchar.h> #include <windows.globalization.h> #include <windows.h> #include <winstring.h> #endif #endif #include <cstdlib> #include <cstring> #include <string> #include "time_zone_fixed.h" #include "time_zone_impl.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace time_internal { namespace cctz { namespace { #if defined(USE_WIN32_LOCAL_TIME_ZONE) std::string win32_local_time_zone(const HMODULE combase) { std::string result; const auto ro_activate_instance = reinterpret_cast<decltype(&RoActivateInstance)>( GetProcAddress(combase, "RoActivateInstance")); if (!ro_activate_instance) { return result; } const auto windows_create_string_reference = reinterpret_cast<decltype(&WindowsCreateStringReference)>( GetProcAddress(combase, "WindowsCreateStringReference")); if (!windows_create_string_reference) { return result; } const auto windows_delete_string = reinterpret_cast<decltype(&WindowsDeleteString)>( GetProcAddress(combase, "WindowsDeleteString")); if (!windows_delete_string) { return result; } const auto windows_get_string_raw_buffer = reinterpret_cast<decltype(&WindowsGetStringRawBuffer)>( GetProcAddress(combase, "WindowsGetStringRawBuffer")); if (!windows_get_string_raw_buffer) { return result; } HSTRING calendar_class_id; HSTRING_HEADER calendar_class_id_header; HRESULT hr = windows_create_string_reference( RuntimeClass_Windows_Globalization_Calendar, sizeof(RuntimeClass_Windows_Globalization_Calendar) / sizeof(wchar_t) - 1, &calendar_class_id_header, &calendar_class_id); if (FAILED(hr)) { return result; } IInspectable* calendar; hr = ro_activate_instance(calendar_class_id, &calendar); if (FAILED(hr)) { return result; } ABI::Windows::Globalization::ITimeZoneOnCalendar* time_zone; hr = calendar->QueryInterface(IID_PPV_ARGS(&time_zone)); if (FAILED(hr)) { calendar->Release(); return result; } HSTRING tz_hstr; hr = time_zone->GetTimeZone(&tz_hstr); if (SUCCEEDED(hr)) { UINT32 wlen; const PCWSTR tz_wstr = windows_get_string_raw_buffer(tz_hstr, &wlen); if (tz_wstr) { const int size = WideCharToMultiByte(CP_UTF8, 0, tz_wstr, static_cast<int>(wlen), nullptr, 0, nullptr, nullptr); result.resize(static_cast<size_t>(size)); WideCharToMultiByte(CP_UTF8, 0, tz_wstr, static_cast<int>(wlen), &result[0], size, nullptr, nullptr); } windows_delete_string(tz_hstr); } time_zone->Release(); calendar->Release(); return result; } #endif } std::string time_zone::name() const { return effective_impl().Name(); } time_zone::absolute_lookup time_zone::lookup( const time_point<seconds>& tp) const { return effective_impl().BreakTime(tp); } time_zone::civil_lookup time_zone::lookup(const civil_second& cs) const { return effective_impl().MakeTime(cs); } bool time_zone::next_transition(const time_point<seconds>& tp, civil_transition* trans) const { return effective_impl().NextTransition(tp, trans); } bool time_zone::prev_transition(const time_point<seconds>& tp, civil_transition* trans) const { return effective_impl().PrevTransition(tp, trans); } std::string time_zone::version() const { return effective_impl().Version(); } std::string time_zone::description() const { return effective_impl().Description(); } const time_zone::Impl& time_zone::effective_impl() const { if (impl_ == nullptr) { return *time_zone::Impl::UTC().impl_; } return *impl_; } bool load_time_zone(const std::string& name, time_zone* tz) { return time_zone::Impl::LoadTimeZone(name, tz); } time_zone utc_time_zone() { return time_zone::Impl::UTC(); } time_zone fixed_time_zone(const seconds& offset) { time_zone tz; load_time_zone(FixedOffsetToName(offset), &tz); return tz; } time_zone local_time_zone() { const char* zone = ":localtime"; #if defined(__ANDROID__) char sysprop[PROP_VALUE_MAX]; if (__system_property_get("persist.sys.timezone", sysprop) > 0) { zone = sysprop; } #endif #if defined(__APPLE__) std::vector<char> buffer; CFTimeZoneRef tz_default = CFTimeZoneCopyDefault(); if (CFStringRef tz_name = CFTimeZoneGetName(tz_default)) { CFStringEncoding encoding = kCFStringEncodingUTF8; CFIndex length = CFStringGetLength(tz_name); CFIndex max_size = CFStringGetMaximumSizeForEncoding(length, encoding) + 1; buffer.resize(static_cast<size_t>(max_size)); if (CFStringGetCString(tz_name, &buffer[0], max_size, encoding)) { zone = &buffer[0]; } } CFRelease(tz_default); #endif #if defined(__Fuchsia__) std::string primary_tz; [&]() { const zx::duration kTimeout = zx::msec(500); async::Loop loop(&kAsyncLoopConfigNeverAttachToThread); fuchsia::intl::PropertyProviderHandle handle; zx_status_t status = fdio_service_connect_by_name( fuchsia::intl::PropertyProvider::Name_, handle.NewRequest().TakeChannel().release()); if (status != ZX_OK) { return; } fuchsia::intl::PropertyProviderPtr intl_provider; status = intl_provider.Bind(std::move(handle), loop.dispatcher()); if (status != ZX_OK) { return; } intl_provider->GetProfile( [&loop, &primary_tz](fuchsia::intl::Profile profile) { if (!profile.time_zones().empty()) { primary_tz = profile.time_zones()[0].id; } loop.Quit(); }); loop.Run(zx::deadline_after(kTimeout)); }(); if (!primary_tz.empty()) { zone = primary_tz.c_str(); } #endif #if defined(USE_WIN32_LOCAL_TIME_ZONE) std::string winrt_tz; const HMODULE combase = LoadLibraryEx(_T("combase.dll"), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); if (combase) { const auto ro_initialize = reinterpret_cast<decltype(&::RoInitialize)>( GetProcAddress(combase, "RoInitialize")); const auto ro_uninitialize = reinterpret_cast<decltype(&::RoUninitialize)>( GetProcAddress(combase, "RoUninitialize")); if (ro_initialize && ro_uninitialize) { const HRESULT hr = ro_initialize(RO_INIT_MULTITHREADED); if (SUCCEEDED(hr) || hr == RPC_E_CHANGED_MODE) { winrt_tz = win32_local_time_zone(combase); if (SUCCEEDED(hr)) { ro_uninitialize(); } } } FreeLibrary(combase); } if (!winrt_tz.empty()) { zone = winrt_tz.c_str(); } #endif char* tz_env = nullptr; #if defined(_MSC_VER) _dupenv_s(&tz_env, nullptr, "TZ"); #else tz_env = std::getenv("TZ"); #endif if (tz_env) zone = tz_env; if (*zone == ':') ++zone; char* localtime_env = nullptr; if (strcmp(zone, "localtime") == 0) { #if defined(_MSC_VER) _dupenv_s(&localtime_env, nullptr, "LOCALTIME"); #else zone = "/etc/localtime"; localtime_env = std::getenv("LOCALTIME"); #endif if (localtime_env) zone = localtime_env; } const std::string name = zone; #if defined(_MSC_VER) free(localtime_env); free(tz_env); #endif time_zone tz; load_time_zone(name, &tz); return tz; } } } ABSL_NAMESPACE_END }
#include <chrono> #include <cstddef> #include <cstdlib> #include <future> #include <limits> #include <string> #include <thread> #include <vector> #include "absl/base/config.h" #include "absl/time/internal/cctz/include/cctz/time_zone.h" #if defined(__linux__) #include <features.h> #endif #include "gtest/gtest.h" #include "absl/time/internal/cctz/include/cctz/civil_time.h" namespace chrono = std::chrono; namespace absl { ABSL_NAMESPACE_BEGIN namespace time_internal { namespace cctz { namespace { const char* const kTimeZoneNames[] = {"Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmara", "Africa/Bamako", "Africa/Bangui", "Africa/Banjul", "Africa/Bissau", "Africa/Blantyre", "Africa/Brazzaville", "Africa/Bujumbura", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/Conakry", "Africa/Dakar", "Africa/Dar_es_Salaam", "Africa/Djibouti", "Africa/Douala", "Africa/El_Aaiun", "Africa/Freetown", "Africa/Gaborone", "Africa/Harare", "Africa/Johannesburg", "Africa/Juba", "Africa/Kampala", "Africa/Khartoum", "Africa/Kigali", "Africa/Kinshasa", "Africa/Lagos", "Africa/Libreville", "Africa/Lome", "Africa/Luanda", "Africa/Lubumbashi", "Africa/Lusaka", "Africa/Malabo", "Africa/Maputo", "Africa/Maseru", "Africa/Mbabane", "Africa/Mogadishu", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Niamey", "Africa/Nouakchott", "Africa/Ouagadougou", "Africa/Porto-Novo", "Africa/Sao_Tome", "Africa/Timbuktu", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Anguilla", "America/Antigua", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Argentina/Catamarca", "America/Argentina/Cordoba", "America/Argentina/Jujuy", "America/Argentina/La_Rioja", "America/Argentina/Mendoza", "America/Argentina/Rio_Gallegos", "America/Argentina/Salta", "America/Argentina/San_Juan", "America/Argentina/San_Luis", "America/Argentina/Tucuman", "America/Argentina/Ushuaia", "America/Aruba", "America/Asuncion", "America/Atikokan", "America/Atka", "America/Bahia", "America/Bahia_Banderas", "America/Barbados", "America/Belem", "America/Belize", "America/Blanc-Sablon", "America/Boa_Vista", "America/Bogota", "America/Boise", "America/Cambridge_Bay", "America/Campo_Grande", "America/Cancun", "America/Caracas", "America/Cayenne", "America/Cayman", "America/Chicago", "America/Chihuahua", "America/Ciudad_Juarez", "America/Coral_Harbour", "America/Costa_Rica", "America/Creston", "America/Cuiaba", "America/Curacao", "America/Danmarkshavn", "America/Dawson", "America/Dawson_Creek", "America/Denver", "America/Detroit", "America/Dominica", "America/Edmonton", "America/Eirunepe", "America/El_Salvador", "America/Ensenada", "America/Fort_Nelson", "America/Fortaleza", "America/Glace_Bay", "America/Godthab", "America/Goose_Bay", "America/Grand_Turk", "America/Grenada", "America/Guadeloupe", "America/Guatemala", "America/Guayaquil", "America/Guyana", "America/Halifax", "America/Havana", "America/Hermosillo", "America/Indiana/Indianapolis", "America/Indiana/Knox", "America/Indiana/Marengo", "America/Indiana/Petersburg", "America/Indiana/Tell_City", "America/Indiana/Vevay", "America/Indiana/Vincennes", "America/Indiana/Winamac", "America/Inuvik", "America/Iqaluit", "America/Jamaica", "America/Juneau", "America/Kentucky/Louisville", "America/Kentucky/Monticello", "America/Kralendijk", "America/La_Paz", "America/Lima", "America/Los_Angeles", "America/Lower_Princes", "America/Maceio", "America/Managua", "America/Manaus", "America/Marigot", "America/Martinique", "America/Matamoros", "America/Mazatlan", "America/Menominee", "America/Merida", "America/Metlakatla", "America/Mexico_City", "America/Miquelon", "America/Moncton", "America/Monterrey", "America/Montevideo", "America/Montreal", "America/Montserrat", "America/Nassau", "America/New_York", "America/Nipigon", "America/Nome", "America/Noronha", "America/North_Dakota/Beulah", "America/North_Dakota/Center", "America/North_Dakota/New_Salem", "America/Nuuk", "America/Ojinaga", "America/Panama", "America/Pangnirtung", "America/Paramaribo", "America/Phoenix", "America/Port-au-Prince", "America/Port_of_Spain", "America/Porto_Acre", "America/Porto_Velho", "America/Puerto_Rico", "America/Punta_Arenas", "America/Rainy_River", "America/Rankin_Inlet", "America/Recife", "America/Regina", "America/Resolute", "America/Rio_Branco", "America/Santa_Isabel", "America/Santarem", "America/Santiago", "America/Santo_Domingo", "America/Sao_Paulo", "America/Scoresbysund", "America/Shiprock", "America/Sitka", "America/St_Barthelemy", "America/St_Johns", "America/St_Kitts", "America/St_Lucia", "America/St_Thomas", "America/St_Vincent", "America/Swift_Current", "America/Tegucigalpa", "America/Thule", "America/Thunder_Bay", "America/Tijuana", "America/Toronto", "America/Tortola", "America/Vancouver", "America/Virgin", "America/Whitehorse", "America/Winnipeg", "America/Yakutat", "America/Yellowknife", "Antarctica/Casey", "Antarctica/Davis", "Antarctica/DumontDUrville", "Antarctica/Macquarie", "Antarctica/Mawson", "Antarctica/McMurdo", "Antarctica/Palmer", "Antarctica/Rothera", "Antarctica/Syowa", "Antarctica/Troll", "Antarctica/Vostok", "Arctic/Longyearbyen", "Asia/Aden", "Asia/Almaty", "Asia/Amman", "Asia/Anadyr", "Asia/Aqtau", "Asia/Aqtobe", "Asia/Ashgabat", "Asia/Atyrau", "Asia/Baghdad", "Asia/Bahrain", "Asia/Baku", "Asia/Bangkok", "Asia/Barnaul", "Asia/Beirut", "Asia/Bishkek", "Asia/Brunei", "Asia/Chita", "Asia/Choibalsan", "Asia/Chongqing", "Asia/Colombo", "Asia/Damascus", "Asia/Dhaka", "Asia/Dili", "Asia/Dubai", "Asia/Dushanbe", "Asia/Famagusta", "Asia/Gaza", "Asia/Harbin", "Asia/Hebron", "Asia/Ho_Chi_Minh", "Asia/Hong_Kong", "Asia/Hovd", "Asia/Irkutsk", "Asia/Istanbul", "Asia/Jakarta", "Asia/Jayapura", "Asia/Jerusalem", "Asia/Kabul", "Asia/Kamchatka", "Asia/Karachi", "Asia/Kashgar", "Asia/Kathmandu", "Asia/Khandyga", "Asia/Kolkata", "Asia/Krasnoyarsk", "Asia/Kuala_Lumpur", "Asia/Kuching", "Asia/Kuwait", "Asia/Macau", "Asia/Magadan", "Asia/Makassar", "Asia/Manila", "Asia/Muscat", "Asia/Nicosia", "Asia/Novokuznetsk", "Asia/Novosibirsk", "Asia/Omsk", "Asia/Oral", "Asia/Phnom_Penh", "Asia/Pontianak", "Asia/Pyongyang", "Asia/Qatar", "Asia/Qostanay", "Asia/Qyzylorda", "Asia/Riyadh", "Asia/Sakhalin", "Asia/Samarkand", "Asia/Seoul", "Asia/Shanghai", "Asia/Singapore", "Asia/Srednekolymsk", "Asia/Taipei", "Asia/Tashkent", "Asia/Tbilisi", "Asia/Tehran", "Asia/Tel_Aviv", "Asia/Thimphu", "Asia/Tokyo", "Asia/Tomsk", "Asia/Ulaanbaatar", "Asia/Urumqi", "Asia/Ust-Nera", "Asia/Vientiane", "Asia/Vladivostok", "Asia/Yakutsk", "Asia/Yangon", "Asia/Yekaterinburg", "Asia/Yerevan", "Atlantic/Azores", "Atlantic/Bermuda", "Atlantic/Canary", "Atlantic/Cape_Verde", "Atlantic/Faroe", "Atlantic/Jan_Mayen", "Atlantic/Madeira", "Atlantic/Reykjavik", "Atlantic/South_Georgia", "Atlantic/St_Helena", "Atlantic/Stanley", "Australia/Adelaide", "Australia/Brisbane", "Australia/Broken_Hill", "Australia/Canberra", "Australia/Currie", "Australia/Darwin", "Australia/Eucla", "Australia/Hobart", "Australia/Lindeman", "Australia/Lord_Howe", "Australia/Melbourne", "Australia/Perth", "Australia/Sydney", "Australia/Yancowinna", "Etc/GMT", "Etc/GMT+0", "Etc/GMT+1", "Etc/GMT+10", "Etc/GMT+11", "Etc/GMT+12", "Etc/GMT+2", "Etc/GMT+3", "Etc/GMT+4", "Etc/GMT+5", "Etc/GMT+6", "Etc/GMT+7", "Etc/GMT+8", "Etc/GMT+9", "Etc/GMT-0", "Etc/GMT-1", "Etc/GMT-10", "Etc/GMT-11", "Etc/GMT-12", "Etc/GMT-13", "Etc/GMT-14", "Etc/GMT-2", "Etc/GMT-3", "Etc/GMT-4", "Etc/GMT-5", "Etc/GMT-6", "Etc/GMT-7", "Etc/GMT-8", "Etc/GMT-9", "Etc/GMT0", "Etc/Greenwich", "Etc/UCT", "Etc/UTC", "Etc/Universal", "Etc/Zulu", "Europe/Amsterdam", "Europe/Andorra", "Europe/Astrakhan", "Europe/Athens", "Europe/Belfast", "Europe/Belgrade", "Europe/Berlin", "Europe/Bratislava", "Europe/Brussels", "Europe/Bucharest", "Europe/Budapest", "Europe/Busingen", "Europe/Chisinau", "Europe/Copenhagen", "Europe/Dublin", "Europe/Gibraltar", "Europe/Guernsey", "Europe/Helsinki", "Europe/Isle_of_Man", "Europe/Istanbul", "Europe/Jersey", "Europe/Kaliningrad", "Europe/Kirov", "Europe/Kyiv", "Europe/Lisbon", "Europe/Ljubljana", "Europe/London", "Europe/Luxembourg", "Europe/Madrid", "Europe/Malta", "Europe/Mariehamn", "Europe/Minsk", "Europe/Monaco", "Europe/Moscow", "Europe/Nicosia", "Europe/Oslo", "Europe/Paris", "Europe/Podgorica", "Europe/Prague", "Europe/Riga", "Europe/Rome", "Europe/Samara", "Europe/San_Marino", "Europe/Sarajevo", "Europe/Saratov", "Europe/Simferopol", "Europe/Skopje", "Europe/Sofia", "Europe/Stockholm", "Europe/Tallinn", "Europe/Tirane", "Europe/Tiraspol", "Europe/Ulyanovsk", "Europe/Vaduz", "Europe/Vatican", "Europe/Vienna", "Europe/Vilnius", "Europe/Volgograd", "Europe/Warsaw", "Europe/Zagreb", "Europe/Zurich", "Factory", "Indian/Antananarivo", "Indian/Chagos", "Indian/Christmas", "Indian/Cocos", "Indian/Comoro", "Indian/Kerguelen", "Indian/Mahe", "Indian/Maldives", "Indian/Mauritius", "Indian/Mayotte", "Indian/Reunion", "Pacific/Apia", "Pacific/Auckland", "Pacific/Bougainville", "Pacific/Chatham", "Pacific/Chuuk", "Pacific/Easter", "Pacific/Efate", "Pacific/Fakaofo", "Pacific/Fiji", "Pacific/Funafuti", "Pacific/Galapagos", "Pacific/Gambier", "Pacific/Guadalcanal", "Pacific/Guam", "Pacific/Honolulu", "Pacific/Johnston", "Pacific/Kanton", "Pacific/Kiritimati", "Pacific/Kosrae", "Pacific/Kwajalein", "Pacific/Majuro", "Pacific/Marquesas", "Pacific/Midway", "Pacific/Nauru", "Pacific/Niue", "Pacific/Norfolk", "Pacific/Noumea", "Pacific/Pago_Pago", "Pacific/Palau", "Pacific/Pitcairn", "Pacific/Pohnpei", "Pacific/Port_Moresby", "Pacific/Rarotonga", "Pacific/Saipan", "Pacific/Samoa", "Pacific/Tahiti", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Wake", "Pacific/Wallis", "Pacific/Yap", "UTC", nullptr}; time_zone LoadZone(const std::string& name) { time_zone tz; load_time_zone(name, &tz); return tz; } #define ExpectTime(tp, tz, y, m, d, hh, mm, ss, off, isdst, zone) \ do { \ time_zone::absolute_lookup al = tz.lookup(tp); \ EXPECT_EQ(y, al.cs.year()); \ EXPECT_EQ(m, al.cs.month()); \ EXPECT_EQ(d, al.cs.day()); \ EXPECT_EQ(hh, al.cs.hour()); \ EXPECT_EQ(mm, al.cs.minute()); \ EXPECT_EQ(ss, al.cs.second()); \ EXPECT_EQ(off, al.offset); \ EXPECT_TRUE(isdst == al.is_dst); \ \ } while (0) int VersionCmp(time_zone tz, const std::string& target) { std::string version = tz.version(); if (version.empty() && !target.empty()) return 1; return version.compare(target); } } #if !defined(__EMSCRIPTEN__) TEST(TimeZones, LoadZonesConcurrently) { std::promise<void> ready_promise; std::shared_future<void> ready_future(ready_promise.get_future()); auto load_zones = [ready_future](std::promise<void>* started, std::set<std::string>* failures) { started->set_value(); ready_future.wait(); for (const char* const* np = kTimeZoneNames; *np != nullptr; ++np) { std::string zone = *np; time_zone tz; if (load_time_zone(zone, &tz)) { EXPECT_EQ(zone, tz.name()); } else { failures->insert(zone); } } }; const std::size_t n_threads = 128; std::vector<std::thread> threads; std::vector<std::set<std::string>> thread_failures(n_threads); for (std::size_t i = 0; i != n_threads; ++i) { std::promise<void> started; threads.emplace_back(load_zones, &started, &thread_failures[i]); started.get_future().wait(); } ready_promise.set_value(); for (auto& thread : threads) { thread.join(); } #if defined(__ANDROID__) const std::size_t max_failures = 20; #else const std::size_t max_failures = 3; #endif std::set<std::string> failures; for (const auto& thread_failure : thread_failures) { failures.insert(thread_failure.begin(), thread_failure.end()); } EXPECT_LE(failures.size(), max_failures) << testing::PrintToString(failures); } #endif TEST(TimeZone, UTC) { const time_zone utc = utc_time_zone(); time_zone loaded_utc; EXPECT_TRUE(load_time_zone("UTC", &loaded_utc)); EXPECT_EQ(loaded_utc, utc); time_zone loaded_utc0; EXPECT_TRUE(load_time_zone("UTC0", &loaded_utc0)); EXPECT_EQ(loaded_utc0, utc); time_zone loaded_bad; EXPECT_FALSE(load_time_zone("Invalid/TimeZone", &loaded_bad)); EXPECT_EQ(loaded_bad, utc); } TEST(TimeZone, NamedTimeZones) { const time_zone utc = utc_time_zone(); EXPECT_EQ("UTC", utc.name()); const time_zone nyc = LoadZone("America/New_York"); EXPECT_EQ("America/New_York", nyc.name()); const time_zone syd = LoadZone("Australia/Sydney"); EXPECT_EQ("Australia/Sydney", syd.name()); const time_zone fixed0 = fixed_time_zone(absl::time_internal::cctz::seconds::zero()); EXPECT_EQ("UTC", fixed0.name()); const time_zone fixed_pos = fixed_time_zone( chrono::hours(3) + chrono::minutes(25) + chrono::seconds(45)); EXPECT_EQ("Fixed/UTC+03:25:45", fixed_pos.name()); const time_zone fixed_neg = fixed_time_zone( -(chrono::hours(12) + chrono::minutes(34) + chrono::seconds(56))); EXPECT_EQ("Fixed/UTC-12:34:56", fixed_neg.name()); } TEST(TimeZone, Failures) { time_zone tz; EXPECT_FALSE(load_time_zone(":America/Los_Angeles", &tz)); tz = LoadZone("America/Los_Angeles"); EXPECT_FALSE(load_time_zone("Invalid/TimeZone", &tz)); EXPECT_EQ(chrono::system_clock::from_time_t(0), convert(civil_second(1970, 1, 1, 0, 0, 0), tz)); tz = LoadZone("America/Los_Angeles"); EXPECT_FALSE(load_time_zone("Invalid/TimeZone", &tz)); EXPECT_EQ(chrono::system_clock::from_time_t(0), convert(civil_second(1970, 1, 1, 0, 0, 0), tz)); tz = LoadZone("America/Los_Angeles"); EXPECT_FALSE(load_time_zone("", &tz)); EXPECT_EQ(chrono::system_clock::from_time_t(0), convert(civil_second(1970, 1, 1, 0, 0, 0), tz)); } TEST(TimeZone, Equality) { const time_zone a; const time_zone b; EXPECT_EQ(a, b); EXPECT_EQ(a.name(), b.name()); const time_zone implicit_utc; const time_zone explicit_utc = utc_time_zone(); EXPECT_EQ(implicit_utc, explicit_utc); EXPECT_EQ(implicit_utc.name(), explicit_utc.name()); const time_zone fixed_zero = fixed_time_zone(absl::time_internal::cctz::seconds::zero()); EXPECT_EQ(fixed_zero, LoadZone(fixed_zero.name())); EXPECT_EQ(fixed_zero, explicit_utc); const time_zone fixed_utc = LoadZone("Fixed/UTC+00:00:00"); EXPECT_EQ(fixed_utc, LoadZone(fixed_utc.name())); EXPECT_EQ(fixed_utc, explicit_utc); const time_zone fixed_pos = fixed_time_zone( chrono::hours(3) + chrono::minutes(25) + chrono::seconds(45)); EXPECT_EQ(fixed_pos, LoadZone(fixed_pos.name())); EXPECT_NE(fixed_pos, explicit_utc); const time_zone fixed_neg = fixed_time_zone( -(chrono::hours(12) + chrono::minutes(34) + chrono::seconds(56))); EXPECT_EQ(fixed_neg, LoadZone(fixed_neg.name())); EXPECT_NE(fixed_neg, explicit_utc); const time_zone fixed_lim = fixed_time_zone(chrono::hours(24)); EXPECT_EQ(fixed_lim, LoadZone(fixed_lim.name())); EXPECT_NE(fixed_lim, explicit_utc); const time_zone fixed_ovfl = fixed_time_zone(chrono::hours(24) + chrono::seconds(1)); EXPECT_EQ(fixed_ovfl, LoadZone(fixed_ovfl.name())); EXPECT_EQ(fixed_ovfl, explicit_utc); EXPECT_EQ(fixed_time_zone(chrono::seconds(1)), fixed_time_zone(chrono::seconds(1))); const time_zone local = local_time_zone(); EXPECT_EQ(local, LoadZone(local.name())); time_zone la = LoadZone("America/Los_Angeles"); time_zone nyc = LoadZone("America/New_York"); EXPECT_NE(la, nyc); } TEST(StdChronoTimePoint, TimeTAlignment) { auto diff = chrono::system_clock::time_point() - chrono::system_clock::from_time_t(0); EXPECT_EQ(chrono::system_clock::time_point::duration::zero(), diff % chrono::seconds(1)); } TEST(BreakTime, TimePointResolution) { const time_zone utc = utc_time_zone(); const auto t0 = chrono::system_clock::from_time_t(0); ExpectTime(chrono::time_point_cast<chrono::nanoseconds>(t0), utc, 1970, 1, 1, 0, 0, 0, 0, false, "UTC"); ExpectTime(chrono::time_point_cast<chrono::microseconds>(t0), utc, 1970, 1, 1, 0, 0, 0, 0, false, "UTC"); ExpectTime(chrono::time_point_cast<chrono::milliseconds>(t0), utc, 1970, 1, 1, 0, 0, 0, 0, false, "UTC"); ExpectTime(chrono::time_point_cast<chrono::seconds>(t0), utc, 1970, 1, 1, 0, 0, 0, 0, false, "UTC"); ExpectTime(chrono::time_point_cast<absl::time_internal::cctz::seconds>(t0), utc, 1970, 1, 1, 0, 0, 0, 0, false, "UTC"); ExpectTime(chrono::time_point_cast<chrono::minutes>(t0), utc, 1970, 1, 1, 0, 0, 0, 0, false, "UTC"); ExpectTime(chrono::time_point_cast<chrono::hours>(t0), utc, 1970, 1, 1, 0, 0, 0, 0, false, "UTC"); } TEST(BreakTime, LocalTimeInUTC) { const time_zone tz = utc_time_zone(); const auto tp = chrono::system_clock::from_time_t(0); ExpectTime(tp, tz, 1970, 1, 1, 0, 0, 0, 0, false, "UTC"); EXPECT_EQ(weekday::thursday, get_weekday(convert(tp, tz))); } TEST(BreakTime, LocalTimeInUTCUnaligned) { const time_zone tz = utc_time_zone(); const auto tp = chrono::system_clock::from_time_t(0) - chrono::milliseconds(500); ExpectTime(tp, tz, 1969, 12, 31, 23, 59, 59, 0, false, "UTC"); EXPECT_EQ(weekday::wednesday, get_weekday(convert(tp, tz))); } TEST(BreakTime, LocalTimePosix) { const time_zone tz = utc_time_zone(); const auto tp = chrono::system_clock::from_time_t(536457599); ExpectTime(tp, tz, 1986, 12, 31, 23, 59, 59, 0, false, "UTC"); EXPECT_EQ(weekday::wednesday, get_weekday(convert(tp, tz))); } TEST(TimeZoneImpl, LocalTimeInFixed) { const absl::time_internal::cctz::seconds offset = -(chrono::hours(8) + chrono::minutes(33) + chrono::seconds(47)); const time_zone tz = fixed_time_zone(offset); const auto tp = chrono::system_clock::from_time_t(0); ExpectTime(tp, tz, 1969, 12, 31, 15, 26, 13, offset.count(), false, "-083347"); EXPECT_EQ(weekday::wednesday, get_weekday(convert(tp, tz))); } TEST(BreakTime, LocalTimeInNewYork) { const time_zone tz = LoadZone("America/New_York"); const auto tp = chrono::system_clock::from_time_t(45); ExpectTime(tp, tz, 1969, 12, 31, 19, 0, 45, -5 * 60 * 60, false, "EST"); EXPECT_EQ(weekday::wednesday, get_weekday(convert(tp, tz))); } TEST(BreakTime, LocalTimeInMTV) { const time_zone tz = LoadZone("America/Los_Angeles"); const auto tp = chrono::system_clock::from_time_t(1380855729); ExpectTime(tp, tz, 2013, 10, 3, 20, 2, 9, -7 * 60 * 60, true, "PDT"); EXPECT_EQ(weekday::thursday, get_weekday(convert(tp, tz))); } TEST(BreakTime, LocalTimeInSydney) { const time_zone tz = LoadZone("Australia/Sydney"); const auto tp = chrono::system_clock::from_time_t(90); ExpectTime(tp, tz, 1970, 1, 1, 10, 1, 30, 10 * 60 * 60, false, "AEST"); EXPECT_EQ(weekday::thursday, get_weekday(convert(tp, tz))); } TEST(MakeTime, TimePointResolution) { const time_zone utc = utc_time_zone(); const time_point<chrono::nanoseconds> tp_ns = convert(civil_second(2015, 1, 2, 3, 4, 5), utc); EXPECT_EQ("04:05", absl::time_internal::cctz::format("%M:%E*S", tp_ns, utc)); const time_point<chrono::microseconds> tp_us = convert(civil_second(2015, 1, 2, 3, 4, 5), utc); EXPECT_EQ("04:05", absl::time_internal::cctz::format("%M:%E*S", tp_us, utc)); const time_point<chrono::milliseconds> tp_ms = convert(civil_second(2015, 1, 2, 3, 4, 5), utc); EXPECT_EQ("04:05", absl::time_internal::cctz::format("%M:%E*S", tp_ms, utc)); const time_point<chrono::seconds> tp_s = convert(civil_second(2015, 1, 2, 3, 4, 5), utc); EXPECT_EQ("04:05", absl::time_internal::cctz::format("%M:%E*S", tp_s, utc)); const time_point<absl::time_internal::cctz::seconds> tp_s64 = convert(civil_second(2015, 1, 2, 3, 4, 5), utc); EXPECT_EQ("04:05", absl::time_internal::cctz::format("%M:%E*S", tp_s64, utc)); const time_point<chrono::minutes> tp_m = chrono::time_point_cast<chrono::minutes>( convert(civil_second(2015, 1, 2, 3, 4, 5), utc)); EXPECT_EQ("04:00", absl::time_internal::cctz::format("%M:%E*S", tp_m, utc)); const time_point<chrono::hours> tp_h = chrono::time_point_cast<chrono::hours>( convert(civil_second(2015, 1, 2, 3, 4, 5), utc)); EXPECT_EQ("00:00", absl::time_internal::cctz::format("%M:%E*S", tp_h, utc)); } TEST(MakeTime, Normalization) { const time_zone tz = LoadZone("America/New_York"); const auto tp = convert(civil_second(2009, 2, 13, 18, 31, 30), tz); EXPECT_EQ(chrono::system_clock::from_time_t(1234567890), tp); EXPECT_EQ(tp, convert(civil_second(2008, 14, 13, 18, 31, 30), tz)); EXPECT_EQ(tp, convert(civil_second(2009, 1, 44, 18, 31, 30), tz)); EXPECT_EQ(tp, convert(civil_second(2009, 2, 12, 42, 31, 30), tz)); EXPECT_EQ(tp, convert(civil_second(2009, 2, 13, 17, 91, 30), tz)); EXPECT_EQ(tp, convert(civil_second(2009, 2, 13, 18, 30, 90), tz)); } TEST(MakeTime, SysSecondsLimits) { const char RFC3339[] = "%Y-%m-%d%ET%H:%M:%S%Ez"; const time_zone utc = utc_time_zone(); const time_zone east = fixed_time_zone(chrono::hours(14)); const time_zone west = fixed_time_zone(-chrono::hours(14)); time_point<absl::time_internal::cctz::seconds> tp; tp = convert(civil_second(292277026596, 12, 4, 15, 30, 6), utc); EXPECT_EQ("292277026596-12-04T15:30:06+00:00", absl::time_internal::cctz::format(RFC3339, tp, utc)); tp = convert(civil_second(292277026596, 12, 4, 15, 30, 7), utc); EXPECT_EQ("292277026596-12-04T15:30:07+00:00", absl::time_internal::cctz::format(RFC3339, tp, utc)); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::max(), tp); tp = convert(civil_second(292277026596, 12, 4, 15, 30, 8), utc); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::max(), tp); tp = convert(civil_second::max(), utc); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::max(), tp); tp = convert(civil_second(292277026596, 12, 5, 5, 30, 7), east); EXPECT_EQ("292277026596-12-05T05:30:07+14:00", absl::time_internal::cctz::format(RFC3339, tp, east)); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::max(), tp); tp = convert(civil_second(292277026596, 12, 5, 5, 30, 8), east); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::max(), tp); tp = convert(civil_second::max(), east); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::max(), tp); tp = convert(civil_second(292277026596, 12, 4, 1, 30, 7), west); EXPECT_EQ("292277026596-12-04T01:30:07-14:00", absl::time_internal::cctz::format(RFC3339, tp, west)); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::max(), tp); tp = convert(civil_second(292277026596, 12, 4, 7, 30, 8), west); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::max(), tp); tp = convert(civil_second::max(), west); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::max(), tp); tp = convert(civil_second(-292277022657, 1, 27, 8, 29, 53), utc); EXPECT_EQ("-292277022657-01-27T08:29:53+00:00", absl::time_internal::cctz::format(RFC3339, tp, utc)); tp = convert(civil_second(-292277022657, 1, 27, 8, 29, 52), utc); EXPECT_EQ("-292277022657-01-27T08:29:52+00:00", absl::time_internal::cctz::format(RFC3339, tp, utc)); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::min(), tp); tp = convert(civil_second(-292277022657, 1, 27, 8, 29, 51), utc); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::min(), tp); tp = convert(civil_second::min(), utc); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::min(), tp); tp = convert(civil_second(-292277022657, 1, 27, 22, 29, 52), east); EXPECT_EQ("-292277022657-01-27T22:29:52+14:00", absl::time_internal::cctz::format(RFC3339, tp, east)); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::min(), tp); tp = convert(civil_second(-292277022657, 1, 27, 22, 29, 51), east); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::min(), tp); tp = convert(civil_second::min(), east); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::min(), tp); tp = convert(civil_second(-292277022657, 1, 26, 18, 29, 52), west); EXPECT_EQ("-292277022657-01-26T18:29:52-14:00", absl::time_internal::cctz::format(RFC3339, tp, west)); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::min(), tp); tp = convert(civil_second(-292277022657, 1, 26, 18, 29, 51), west); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::min(), tp); tp = convert(civil_second::min(), west); EXPECT_EQ(time_point<absl::time_internal::cctz::seconds>::min(), tp); if (sizeof(std::time_t) >= 8) { #if defined(_WIN32) || defined(_WIN64) #else const time_zone cut = LoadZone("libc:UTC"); const year_t max_tm_year = year_t{std::numeric_limits<int>::max()} + 1900; tp = convert(civil_second(max_tm_year, 12, 31, 23, 59, 59), cut); #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__EMSCRIPTEN__) #else EXPECT_EQ("2147485547-12-31T23:59:59+00:00", absl::time_internal::cctz::format(RFC3339, tp, cut)); #endif const year_t min_tm_year = year_t{std::numeric_limits<int>::min()} + 1900; tp = convert(civil_second(min_tm_year, 1, 1, 0, 0, 0), cut); #if defined(__Fuchsia__) || defined(__EMSCRIPTEN__) #else EXPECT_EQ("-2147481748-01-01T00:00:00+00:00", absl::time_internal::cctz::format(RFC3339, tp, cut)); #endif #endif } } TEST(MakeTime, LocalTimeLibC) { #if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) const char* const ep = getenv("TZ"); std::string tz_name = (ep != nullptr) ? ep : ""; for (const char* const* np = kTimeZoneNames; *np != nullptr; ++np) { ASSERT_EQ(0, setenv("TZ", *np, 1)); const auto zi = local_time_zone(); const auto lc = LoadZone("libc:localtime"); time_zone::civil_transition transition; for (auto tp = zi.lookup(civil_second()).trans; zi.next_transition(tp, &transition); tp = zi.lookup(transition.to).trans) { const auto fcl = zi.lookup(transition.from); const auto tcl = zi.lookup(transition.to); civil_second cs, us; if (fcl.kind == time_zone::civil_lookup::UNIQUE) { if (tcl.kind == time_zone::civil_lookup::UNIQUE) { ASSERT_EQ(transition.from, transition.to); const auto trans = fcl.trans; const auto tal = zi.lookup(trans); const auto tprev = trans - absl::time_internal::cctz::seconds(1); const auto pal = zi.lookup(tprev); if (pal.is_dst == tal.is_dst) { ASSERT_STRNE(pal.abbr, tal.abbr); } continue; } ASSERT_EQ(time_zone::civil_lookup::REPEATED, tcl.kind); cs = transition.to; us = transition.from; } else { ASSERT_EQ(time_zone::civil_lookup::UNIQUE, tcl.kind); ASSERT_EQ(time_zone::civil_lookup::SKIPPED, fcl.kind); cs = transition.from; us = transition.to; } if (us.year() > 2037) break; const auto cl_zi = zi.lookup(cs); if (zi.lookup(cl_zi.pre).is_dst == zi.lookup(cl_zi.post).is_dst) { continue; } if (cs == civil_second(2037, 10, 4, 2, 0, 0)) { const std::string tzname = *np; if (tzname == "Africa/Casablanca" || tzname == "Africa/El_Aaiun") { continue; } } const auto cl_lc = lc.lookup(cs); SCOPED_TRACE(testing::Message() << "For " << cs << " in " << *np); EXPECT_EQ(cl_zi.kind, cl_lc.kind); EXPECT_EQ(cl_zi.pre, cl_lc.pre); EXPECT_EQ(cl_zi.trans, cl_lc.trans); EXPECT_EQ(cl_zi.post, cl_lc.post); const auto ucl_zi = zi.lookup(us); const auto ucl_lc = lc.lookup(us); SCOPED_TRACE(testing::Message() << "For " << us << " in " << *np); EXPECT_EQ(ucl_zi.kind, ucl_lc.kind); EXPECT_EQ(ucl_zi.pre, ucl_lc.pre); EXPECT_EQ(ucl_zi.trans, ucl_lc.trans); EXPECT_EQ(ucl_zi.post, ucl_lc.post); } } if (ep == nullptr) { ASSERT_EQ(0, unsetenv("TZ")); } else { ASSERT_EQ(0, setenv("TZ", tz_name.c_str(), 1)); } #endif } TEST(NextTransition, UTC) { const auto tz = utc_time_zone(); time_zone::civil_transition trans; auto tp = time_point<absl::time_internal::cctz::seconds>::min(); EXPECT_FALSE(tz.next_transition(tp, &trans)); tp = time_point<absl::time_internal::cctz::seconds>::max(); EXPECT_FALSE(tz.next_transition(tp, &trans)); } TEST(PrevTransition, UTC) { const auto tz = utc_time_zone(); time_zone::civil_transition trans; auto tp = time_point<absl::time_internal::cctz::seconds>::max(); EXPECT_FALSE(tz.prev_transition(tp, &trans)); tp = time_point<absl::time_internal::cctz::seconds>::min(); EXPECT_FALSE(tz.prev_transition(tp, &trans)); } TEST(NextTransition, AmericaNewYork) { const auto tz = LoadZone("America/New_York"); time_zone::civil_transition trans; auto tp = convert(civil_second(2018, 6, 30, 0, 0, 0), tz); EXPECT_TRUE(tz.next_transition(tp, &trans)); EXPECT_EQ(civil_second(2018, 11, 4, 2, 0, 0), trans.from); EXPECT_EQ(civil_second(2018, 11, 4, 1, 0, 0), trans.to); tp = time_point<absl::time_internal::cctz::seconds>::max(); EXPECT_FALSE(tz.next_transition(tp, &trans)); tp = time_point<absl::time_internal::cctz::seconds>::min(); EXPECT_TRUE(tz.next_transition(tp, &trans)); if (trans.from == civil_second(1918, 3, 31, 2, 0, 0)) { EXPECT_EQ(civil_second(1918, 3, 31, 3, 0, 0), trans.to); } else { EXPECT_EQ(civil_second(1883, 11, 18, 12, 3, 58), trans.from); EXPECT_EQ(civil_second(1883, 11, 18, 12, 0, 0), trans.to); } } TEST(PrevTransition, AmericaNewYork) { const auto tz = LoadZone("America/New_York"); time_zone::civil_transition trans; auto tp = convert(civil_second(2018, 6, 30, 0, 0, 0), tz); EXPECT_TRUE(tz.prev_transition(tp, &trans)); EXPECT_EQ(civil_second(2018, 3, 11, 2, 0, 0), trans.from); EXPECT_EQ(civil_second(2018, 3, 11, 3, 0, 0), trans.to); tp = time_point<absl::time_internal::cctz::seconds>::min(); EXPECT_FALSE(tz.prev_transition(tp, &trans)); tp = time_point<absl::time_internal::cctz::seconds>::max(); EXPECT_TRUE(tz.prev_transition(tp, &trans)); } TEST(NextTransition, Scan) { for (const char* const* np = kTimeZoneNames; *np != nullptr; ++np) { SCOPED_TRACE(testing::Message() << "In " << *np); time_zone tz; if (!load_time_zone(*np, &tz)) { continue; } auto tp = time_point<absl::time_internal::cctz::seconds>::min(); time_zone::civil_transition trans; while (tz.next_transition(tp, &trans)) { time_zone::civil_lookup from_cl = tz.lookup(trans.from); EXPECT_NE(from_cl.kind, time_zone::civil_lookup::REPEATED); time_zone::civil_lookup to_cl = tz.lookup(trans.to); EXPECT_NE(to_cl.kind, time_zone::civil_lookup::SKIPPED); auto trans_tp = to_cl.trans; time_zone::absolute_lookup trans_al = tz.lookup(trans_tp); EXPECT_EQ(trans_al.cs, trans.to); auto pre_trans_tp = trans_tp - absl::time_internal::cctz::seconds(1); time_zone::absolute_lookup pre_trans_al = tz.lookup(pre_trans_tp); EXPECT_EQ(pre_trans_al.cs + 1, trans.from); auto offset_delta = trans_al.offset - pre_trans_al.offset; EXPECT_EQ(offset_delta, trans.to - trans.from); if (offset_delta == 0) { EXPECT_EQ(to_cl.kind, time_zone::civil_lookup::UNIQUE); if (trans_al.is_dst == pre_trans_al.is_dst) { EXPECT_STRNE(trans_al.abbr, pre_trans_al.abbr); } } tp = trans_tp; } } } TEST(TimeZoneEdgeCase, AmericaNewYork) { const time_zone tz = LoadZone("America/New_York"); auto tp = convert(civil_second(2013, 3, 10, 1, 59, 59), tz); ExpectTime(tp, tz, 2013, 3, 10, 1, 59, 59, -5 * 3600, false, "EST"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2013, 3, 10, 3, 0, 0, -4 * 3600, true, "EDT"); tp = convert(civil_second(2013, 11, 3, 1, 59, 59), tz); ExpectTime(tp, tz, 2013, 11, 3, 1, 59, 59, -4 * 3600, true, "EDT"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2013, 11, 3, 1, 0, 0, -5 * 3600, false, "EST"); } TEST(TimeZoneEdgeCase, AmericaLosAngeles) { const time_zone tz = LoadZone("America/Los_Angeles"); auto tp = convert(civil_second(2013, 3, 10, 1, 59, 59), tz); ExpectTime(tp, tz, 2013, 3, 10, 1, 59, 59, -8 * 3600, false, "PST"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2013, 3, 10, 3, 0, 0, -7 * 3600, true, "PDT"); tp = convert(civil_second(2013, 11, 3, 1, 59, 59), tz); ExpectTime(tp, tz, 2013, 11, 3, 1, 59, 59, -7 * 3600, true, "PDT"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2013, 11, 3, 1, 0, 0, -8 * 3600, false, "PST"); } TEST(TimeZoneEdgeCase, ArizonaNoTransition) { const time_zone tz = LoadZone("America/Phoenix"); auto tp = convert(civil_second(2013, 3, 10, 1, 59, 59), tz); ExpectTime(tp, tz, 2013, 3, 10, 1, 59, 59, -7 * 3600, false, "MST"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2013, 3, 10, 2, 0, 0, -7 * 3600, false, "MST"); tp = convert(civil_second(2013, 11, 3, 1, 59, 59), tz); ExpectTime(tp, tz, 2013, 11, 3, 1, 59, 59, -7 * 3600, false, "MST"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2013, 11, 3, 2, 0, 0, -7 * 3600, false, "MST"); } TEST(TimeZoneEdgeCase, AsiaKathmandu) { const time_zone tz = LoadZone("Asia/Kathmandu"); auto tp = convert(civil_second(1985, 12, 31, 23, 59, 59), tz); ExpectTime(tp, tz, 1985, 12, 31, 23, 59, 59, 5.5 * 3600, false, "+0530"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 1986, 1, 1, 0, 15, 0, 5.75 * 3600, false, "+0545"); } TEST(TimeZoneEdgeCase, PacificChatham) { const time_zone tz = LoadZone("Pacific/Chatham"); auto tp = convert(civil_second(2013, 4, 7, 3, 44, 59), tz); ExpectTime(tp, tz, 2013, 4, 7, 3, 44, 59, 13.75 * 3600, true, "+1345"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2013, 4, 7, 2, 45, 0, 12.75 * 3600, false, "+1245"); tp = convert(civil_second(2013, 9, 29, 2, 44, 59), tz); ExpectTime(tp, tz, 2013, 9, 29, 2, 44, 59, 12.75 * 3600, false, "+1245"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2013, 9, 29, 3, 45, 0, 13.75 * 3600, true, "+1345"); } TEST(TimeZoneEdgeCase, AustraliaLordHowe) { const time_zone tz = LoadZone("Australia/Lord_Howe"); auto tp = convert(civil_second(2013, 4, 7, 1, 59, 59), tz); ExpectTime(tp, tz, 2013, 4, 7, 1, 59, 59, 11 * 3600, true, "+11"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2013, 4, 7, 1, 30, 0, 10.5 * 3600, false, "+1030"); tp = convert(civil_second(2013, 10, 6, 1, 59, 59), tz); ExpectTime(tp, tz, 2013, 10, 6, 1, 59, 59, 10.5 * 3600, false, "+1030"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2013, 10, 6, 2, 30, 0, 11 * 3600, true, "+11"); } TEST(TimeZoneEdgeCase, PacificApia) { const time_zone tz = LoadZone("Pacific/Apia"); auto tp = convert(civil_second(2011, 12, 29, 23, 59, 59), tz); ExpectTime(tp, tz, 2011, 12, 29, 23, 59, 59, -10 * 3600, true, "-10"); EXPECT_EQ(363, get_yearday(convert(tp, tz))); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2011, 12, 31, 0, 0, 0, 14 * 3600, true, "+14"); EXPECT_EQ(365, get_yearday(convert(tp, tz))); } TEST(TimeZoneEdgeCase, AfricaCairo) { const time_zone tz = LoadZone("Africa/Cairo"); if (VersionCmp(tz, "2014c") >= 0) { auto tp = convert(civil_second(2014, 5, 15, 23, 59, 59), tz); ExpectTime(tp, tz, 2014, 5, 15, 23, 59, 59, 2 * 3600, false, "EET"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2014, 5, 16, 1, 0, 0, 3 * 3600, true, "EEST"); } } TEST(TimeZoneEdgeCase, AfricaMonrovia) { const time_zone tz = LoadZone("Africa/Monrovia"); if (VersionCmp(tz, "2017b") >= 0) { auto tp = convert(civil_second(1972, 1, 6, 23, 59, 59), tz); ExpectTime(tp, tz, 1972, 1, 6, 23, 59, 59, -44.5 * 60, false, "MMT"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 1972, 1, 7, 0, 44, 30, 0 * 60, false, "GMT"); } } TEST(TimeZoneEdgeCase, AmericaJamaica) { const time_zone tz = LoadZone("America/Jamaica"); if (!tz.version().empty() && VersionCmp(tz, "2018d") >= 0) { auto tp = convert(civil_second(1889, 12, 31, 0, 0, 0), tz); ExpectTime(tp, tz, 1889, 12, 31, 0, 0, 0, -18430, false, tz.lookup(tp).abbr); tp = convert(civil_second(1889, 12, 31, 23, 59, 59), tz); ExpectTime(tp, tz, 1889, 12, 31, 23, 59, 59, -18430, false, tz.lookup(tp).abbr); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 1890, 1, 1, 0, 0, 0, -18430, false, "KMT"); } auto tp = convert(civil_second(1983, 10, 30, 1, 59, 59), tz); ExpectTime(tp, tz, 1983, 10, 30, 1, 59, 59, -4 * 3600, true, "EDT"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 1983, 10, 30, 1, 0, 0, -5 * 3600, false, "EST"); tp = convert(civil_second(1983, 12, 31, 23, 59, 59), tz); ExpectTime(tp, tz, 1983, 12, 31, 23, 59, 59, -5 * 3600, false, "EST"); } TEST(TimeZoneEdgeCase, EuropeLisbon) { const time_zone tz = LoadZone("Europe/Lisbon"); auto tp = convert(civil_second(1981, 3, 28, 23, 59, 59), tz); ExpectTime(tp, tz, 1981, 3, 28, 23, 59, 59, 0, false, "WET"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 1981, 3, 29, 1, 0, 0, 1 * 3600, true, "WEST"); time_zone::civil_lookup cl1 = tz.lookup(civil_second(1981, 3, 29, 0, 15, 0)); EXPECT_EQ(time_zone::civil_lookup::SKIPPED, cl1.kind); ExpectTime(cl1.pre, tz, 1981, 3, 29, 1, 15, 0, 1 * 3600, true, "WEST"); ExpectTime(cl1.trans, tz, 1981, 3, 29, 1, 0, 0, 1 * 3600, true, "WEST"); ExpectTime(cl1.post, tz, 1981, 3, 28, 23, 15, 0, 0 * 3600, false, "WET"); } TEST(TimeZoneEdgeCase, FixedOffsets) { const time_zone gmtm5 = LoadZone("Etc/GMT+5"); auto tp = convert(civil_second(1970, 1, 1, 0, 0, 0), gmtm5); ExpectTime(tp, gmtm5, 1970, 1, 1, 0, 0, 0, -5 * 3600, false, "-05"); EXPECT_EQ(chrono::system_clock::from_time_t(5 * 3600), tp); const time_zone gmtp5 = LoadZone("Etc/GMT-5"); tp = convert(civil_second(1970, 1, 1, 0, 0, 0), gmtp5); ExpectTime(tp, gmtp5, 1970, 1, 1, 0, 0, 0, 5 * 3600, false, "+05"); EXPECT_EQ(chrono::system_clock::from_time_t(-5 * 3600), tp); } TEST(TimeZoneEdgeCase, NegativeYear) { const time_zone tz = utc_time_zone(); auto tp = convert(civil_second(0, 1, 1, 0, 0, 0), tz); ExpectTime(tp, tz, 0, 1, 1, 0, 0, 0, 0 * 3600, false, "UTC"); EXPECT_EQ(weekday::saturday, get_weekday(convert(tp, tz))); tp -= absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, -1, 12, 31, 23, 59, 59, 0 * 3600, false, "UTC"); EXPECT_EQ(weekday::friday, get_weekday(convert(tp, tz))); } TEST(TimeZoneEdgeCase, UTC32bitLimit) { const time_zone tz = utc_time_zone(); auto tp = convert(civil_second(2038, 1, 19, 3, 14, 7), tz); ExpectTime(tp, tz, 2038, 1, 19, 3, 14, 7, 0 * 3600, false, "UTC"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 2038, 1, 19, 3, 14, 8, 0 * 3600, false, "UTC"); } TEST(TimeZoneEdgeCase, UTC5DigitYear) { const time_zone tz = utc_time_zone(); auto tp = convert(civil_second(9999, 12, 31, 23, 59, 59), tz); ExpectTime(tp, tz, 9999, 12, 31, 23, 59, 59, 0 * 3600, false, "UTC"); tp += absl::time_internal::cctz::seconds(1); ExpectTime(tp, tz, 10000, 1, 1, 0, 0, 0, 0 * 3600, false, "UTC"); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/internal/cctz/src/time_zone_lookup.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/internal/cctz/src/time_zone_lookup_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
562dcff9-1333-4bc5-9bfc-efdd2234c023
cpp
abseil/abseil-cpp
raw_hash_set
absl/container/internal/raw_hash_set.cc
absl/container/internal/raw_hash_set_test.cc
#include "absl/container/internal/raw_hash_set.h" #include <atomic> #include <cassert> #include <cstddef> #include <cstdint> #include <cstring> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/dynamic_annotations.h" #include "absl/base/internal/endian.h" #include "absl/base/optimization.h" #include "absl/container/internal/container_memory.h" #include "absl/container/internal/hashtablez_sampler.h" #include "absl/hash/hash.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { constexpr ctrl_t ZeroCtrlT() { return static_cast<ctrl_t>(0); } alignas(16) ABSL_CONST_INIT ABSL_DLL const ctrl_t kEmptyGroup[32] = { ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ZeroCtrlT(), ctrl_t::kSentinel, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty}; ABSL_CONST_INIT ABSL_DLL const ctrl_t kSooControl[17] = { ZeroCtrlT(), ctrl_t::kSentinel, ZeroCtrlT(), ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty, ctrl_t::kEmpty}; static_assert(NumControlBytes(SooCapacity()) <= 17, "kSooControl capacity too small"); #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL constexpr size_t Group::kWidth; #endif namespace { inline size_t RandomSeed() { #ifdef ABSL_HAVE_THREAD_LOCAL static thread_local size_t counter = 0; ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(&counter, sizeof(size_t)); size_t value = ++counter; #else static std::atomic<size_t> counter(0); size_t value = counter.fetch_add(1, std::memory_order_relaxed); #endif return value ^ static_cast<size_t>(reinterpret_cast<uintptr_t>(&counter)); } bool ShouldRehashForBugDetection(const ctrl_t* ctrl, size_t capacity) { return probe(ctrl, capacity, absl::HashOf(RandomSeed())).offset() < RehashProbabilityConstant(); } } GenerationType* EmptyGeneration() { if (SwisstableGenerationsEnabled()) { constexpr size_t kNumEmptyGenerations = 1024; static constexpr GenerationType kEmptyGenerations[kNumEmptyGenerations]{}; return const_cast<GenerationType*>( &kEmptyGenerations[RandomSeed() % kNumEmptyGenerations]); } return nullptr; } bool CommonFieldsGenerationInfoEnabled:: should_rehash_for_bug_detection_on_insert(const ctrl_t* ctrl, size_t capacity) const { if (reserved_growth_ == kReservedGrowthJustRanOut) return true; if (reserved_growth_ > 0) return false; return ShouldRehashForBugDetection(ctrl, capacity); } bool CommonFieldsGenerationInfoEnabled::should_rehash_for_bug_detection_on_move( const ctrl_t* ctrl, size_t capacity) const { return ShouldRehashForBugDetection(ctrl, capacity); } bool ShouldInsertBackwardsForDebug(size_t capacity, size_t hash, const ctrl_t* ctrl) { return !is_small(capacity) && (H1(hash, ctrl) ^ RandomSeed()) % 13 > 6; } size_t PrepareInsertAfterSoo(size_t hash, size_t slot_size, CommonFields& common) { assert(common.capacity() == NextCapacity(SooCapacity())); assert(HashSetResizeHelper::SooSlotIndex() == 1); PrepareInsertCommon(common); const size_t offset = H1(hash, common.control()) & 2; common.growth_info().OverwriteEmptyAsFull(); SetCtrlInSingleGroupTable(common, offset, H2(hash), slot_size); common.infoz().RecordInsert(hash, 0); return offset; } void ConvertDeletedToEmptyAndFullToDeleted(ctrl_t* ctrl, size_t capacity) { assert(ctrl[capacity] == ctrl_t::kSentinel); assert(IsValidCapacity(capacity)); for (ctrl_t* pos = ctrl; pos < ctrl + capacity; pos += Group::kWidth) { Group{pos}.ConvertSpecialToEmptyAndFullToDeleted(pos); } std::memcpy(ctrl + capacity + 1, ctrl, NumClonedBytes()); ctrl[capacity] = ctrl_t::kSentinel; } template FindInfo find_first_non_full(const CommonFields&, size_t); FindInfo find_first_non_full_outofline(const CommonFields& common, size_t hash) { return find_first_non_full(common, hash); } namespace { static inline void* NextSlot(void* slot, size_t slot_size) { return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(slot) + slot_size); } static inline void* PrevSlot(void* slot, size_t slot_size) { return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(slot) - slot_size); } size_t FindEmptySlot(size_t start, size_t end, const ctrl_t* ctrl) { for (size_t i = start; i < end; ++i) { if (IsEmpty(ctrl[i])) { return i; } } assert(false && "no empty slot"); return ~size_t{}; } void DropDeletesWithoutResize(CommonFields& common, const PolicyFunctions& policy) { void* set = &common; void* slot_array = common.slot_array(); const size_t capacity = common.capacity(); assert(IsValidCapacity(capacity)); assert(!is_small(capacity)); ctrl_t* ctrl = common.control(); ConvertDeletedToEmptyAndFullToDeleted(ctrl, capacity); const void* hash_fn = policy.hash_fn(common); auto hasher = policy.hash_slot; auto transfer = policy.transfer; const size_t slot_size = policy.slot_size; size_t total_probe_length = 0; void* slot_ptr = SlotAddress(slot_array, 0, slot_size); constexpr size_t kUnknownId = ~size_t{}; size_t tmp_space_id = kUnknownId; for (size_t i = 0; i != capacity; ++i, slot_ptr = NextSlot(slot_ptr, slot_size)) { assert(slot_ptr == SlotAddress(slot_array, i, slot_size)); if (IsEmpty(ctrl[i])) { tmp_space_id = i; continue; } if (!IsDeleted(ctrl[i])) continue; const size_t hash = (*hasher)(hash_fn, slot_ptr); const FindInfo target = find_first_non_full(common, hash); const size_t new_i = target.offset; total_probe_length += target.probe_length; const size_t probe_offset = probe(common, hash).offset(); const auto probe_index = [probe_offset, capacity](size_t pos) { return ((pos - probe_offset) & capacity) / Group::kWidth; }; if (ABSL_PREDICT_TRUE(probe_index(new_i) == probe_index(i))) { SetCtrl(common, i, H2(hash), slot_size); continue; } void* new_slot_ptr = SlotAddress(slot_array, new_i, slot_size); if (IsEmpty(ctrl[new_i])) { SetCtrl(common, new_i, H2(hash), slot_size); (*transfer)(set, new_slot_ptr, slot_ptr); SetCtrl(common, i, ctrl_t::kEmpty, slot_size); tmp_space_id = i; } else { assert(IsDeleted(ctrl[new_i])); SetCtrl(common, new_i, H2(hash), slot_size); if (tmp_space_id == kUnknownId) { tmp_space_id = FindEmptySlot(i + 1, capacity, ctrl); } void* tmp_space = SlotAddress(slot_array, tmp_space_id, slot_size); SanitizerUnpoisonMemoryRegion(tmp_space, slot_size); (*transfer)(set, tmp_space, new_slot_ptr); (*transfer)(set, new_slot_ptr, slot_ptr); (*transfer)(set, slot_ptr, tmp_space); SanitizerPoisonMemoryRegion(tmp_space, slot_size); --i; slot_ptr = PrevSlot(slot_ptr, slot_size); } } ResetGrowthLeft(common); common.infoz().RecordRehash(total_probe_length); } static bool WasNeverFull(CommonFields& c, size_t index) { if (is_single_group(c.capacity())) { return true; } const size_t index_before = (index - Group::kWidth) & c.capacity(); const auto empty_after = Group(c.control() + index).MaskEmpty(); const auto empty_before = Group(c.control() + index_before).MaskEmpty(); return empty_before && empty_after && static_cast<size_t>(empty_after.TrailingZeros()) + empty_before.LeadingZeros() < Group::kWidth; } } void EraseMetaOnly(CommonFields& c, size_t index, size_t slot_size) { assert(IsFull(c.control()[index]) && "erasing a dangling iterator"); c.decrement_size(); c.infoz().RecordErase(); if (WasNeverFull(c, index)) { SetCtrl(c, index, ctrl_t::kEmpty, slot_size); c.growth_info().OverwriteFullAsEmpty(); return; } c.growth_info().OverwriteFullAsDeleted(); SetCtrl(c, index, ctrl_t::kDeleted, slot_size); } void ClearBackingArray(CommonFields& c, const PolicyFunctions& policy, bool reuse, bool soo_enabled) { c.set_size(0); if (reuse) { assert(!soo_enabled || c.capacity() > SooCapacity()); ResetCtrl(c, policy.slot_size); ResetGrowthLeft(c); c.infoz().RecordStorageChanged(0, c.capacity()); } else { c.infoz().RecordClearedReservation(); c.infoz().RecordStorageChanged(0, soo_enabled ? SooCapacity() : 0); (*policy.dealloc)(c, policy); c = soo_enabled ? CommonFields{soo_tag_t{}} : CommonFields{non_soo_tag_t{}}; } } void HashSetResizeHelper::GrowIntoSingleGroupShuffleControlBytes( ctrl_t* __restrict new_ctrl, size_t new_capacity) const { assert(is_single_group(new_capacity)); constexpr size_t kHalfWidth = Group::kWidth / 2; constexpr size_t kQuarterWidth = Group::kWidth / 4; assert(old_capacity_ < kHalfWidth); static_assert(sizeof(uint64_t) >= kHalfWidth, "Group size is too large. The ctrl bytes for half a group must " "fit into a uint64_t for this implementation."); static_assert(sizeof(uint64_t) <= Group::kWidth, "Group size is too small. The ctrl bytes for a group must " "cover a uint64_t for this implementation."); const size_t half_old_capacity = old_capacity_ / 2; uint64_t copied_bytes = 0; copied_bytes = absl::little_endian::Load64(old_ctrl() + half_old_capacity + 1); constexpr uint64_t kEmptyXorSentinel = static_cast<uint8_t>(ctrl_t::kEmpty) ^ static_cast<uint8_t>(ctrl_t::kSentinel); const uint64_t mask_convert_old_sentinel_to_empty = kEmptyXorSentinel << (half_old_capacity * 8); copied_bytes ^= mask_convert_old_sentinel_to_empty; absl::little_endian::Store64(new_ctrl, copied_bytes); std::memset(new_ctrl + old_capacity_ + 1, static_cast<int8_t>(ctrl_t::kEmpty), Group::kWidth); std::memset(new_ctrl + NumControlBytes(new_capacity) - kHalfWidth, static_cast<int8_t>(ctrl_t::kEmpty), kHalfWidth); absl::little_endian::Store64(new_ctrl + new_capacity + 1, copied_bytes); std::memset(new_ctrl + new_capacity + old_capacity_ + 2, static_cast<int8_t>(ctrl_t::kEmpty), kQuarterWidth); new_ctrl[new_capacity] = ctrl_t::kSentinel; } void HashSetResizeHelper::InitControlBytesAfterSoo(ctrl_t* new_ctrl, ctrl_t h2, size_t new_capacity) { assert(is_single_group(new_capacity)); std::memset(new_ctrl, static_cast<int8_t>(ctrl_t::kEmpty), NumControlBytes(new_capacity)); assert(HashSetResizeHelper::SooSlotIndex() == 1); assert(had_soo_slot_ || h2 == ctrl_t::kEmpty); new_ctrl[1] = new_ctrl[new_capacity + 2] = h2; new_ctrl[new_capacity] = ctrl_t::kSentinel; } void HashSetResizeHelper::GrowIntoSingleGroupShuffleTransferableSlots( void* new_slots, size_t slot_size) const { assert(old_capacity_ > 0); const size_t half_old_capacity = old_capacity_ / 2; SanitizerUnpoisonMemoryRegion(old_slots(), slot_size * old_capacity_); std::memcpy(new_slots, SlotAddress(old_slots(), half_old_capacity + 1, slot_size), slot_size * half_old_capacity); std::memcpy(SlotAddress(new_slots, half_old_capacity + 1, slot_size), old_slots(), slot_size * (half_old_capacity + 1)); } void HashSetResizeHelper::GrowSizeIntoSingleGroupTransferable( CommonFields& c, size_t slot_size) { assert(old_capacity_ < Group::kWidth / 2); assert(is_single_group(c.capacity())); assert(IsGrowingIntoSingleGroupApplicable(old_capacity_, c.capacity())); GrowIntoSingleGroupShuffleControlBytes(c.control(), c.capacity()); GrowIntoSingleGroupShuffleTransferableSlots(c.slot_array(), slot_size); PoisonSingleGroupEmptySlots(c, slot_size); } void HashSetResizeHelper::TransferSlotAfterSoo(CommonFields& c, size_t slot_size) { assert(was_soo_); assert(had_soo_slot_); assert(is_single_group(c.capacity())); std::memcpy(SlotAddress(c.slot_array(), SooSlotIndex(), slot_size), old_soo_data(), slot_size); PoisonSingleGroupEmptySlots(c, slot_size); } namespace { ABSL_ATTRIBUTE_NOINLINE FindInfo FindInsertPositionWithGrowthOrRehash(CommonFields& common, size_t hash, const PolicyFunctions& policy) { const size_t cap = common.capacity(); if (cap > Group::kWidth && common.size() * uint64_t{32} <= cap * uint64_t{25}) { DropDeletesWithoutResize(common, policy); } else { policy.resize(common, NextCapacity(cap), HashtablezInfoHandle{}); } return find_first_non_full(common, hash); } } const void* GetHashRefForEmptyHasher(const CommonFields& common) { return &common; } size_t PrepareInsertNonSoo(CommonFields& common, size_t hash, FindInfo target, const PolicyFunctions& policy) { const bool use_target_hint = !SwisstableGenerationsEnabled() && common.growth_info().HasNoDeletedAndGrowthLeft(); if (ABSL_PREDICT_FALSE(!use_target_hint)) { if (ABSL_PREDICT_TRUE(common.growth_info().HasNoGrowthLeftAndNoDeleted())) { const size_t old_capacity = common.capacity(); policy.resize(common, NextCapacity(old_capacity), HashtablezInfoHandle{}); target = HashSetResizeHelper::FindFirstNonFullAfterResize( common, old_capacity, hash); } else { const bool rehash_for_bug_detection = common.should_rehash_for_bug_detection_on_insert(); if (rehash_for_bug_detection) { const size_t cap = common.capacity(); policy.resize(common, common.growth_left() > 0 ? cap : NextCapacity(cap), HashtablezInfoHandle{}); } if (ABSL_PREDICT_TRUE(common.growth_left() > 0)) { target = find_first_non_full(common, hash); } else { target = FindInsertPositionWithGrowthOrRehash(common, hash, policy); } } } PrepareInsertCommon(common); common.growth_info().OverwriteControlAsFull(common.control()[target.offset]); SetCtrl(common, target.offset, H2(hash), policy.slot_size); common.infoz().RecordInsert(hash, target.probe_length); return target.offset; } } ABSL_NAMESPACE_END }
#include "absl/container/internal/raw_hash_set.h" #include <algorithm> #include <array> #include <atomic> #include <cmath> #include <cstddef> #include <cstdint> #include <deque> #include <functional> #include <iostream> #include <iterator> #include <list> #include <map> #include <memory> #include <numeric> #include <ostream> #include <random> #include <string> #include <tuple> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/cycleclock.h" #include "absl/base/prefetch.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/container/internal/container_memory.h" #include "absl/container/internal/hash_function_defaults.h" #include "absl/container/internal/hash_policy_testing.h" #include "absl/container/internal/hashtable_debug.h" #include "absl/container/internal/hashtablez_sampler.h" #include "absl/container/internal/test_allocator.h" #include "absl/container/internal/test_instance_tracker.h" #include "absl/container/node_hash_set.h" #include "absl/functional/function_ref.h" #include "absl/hash/hash.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { struct RawHashSetTestOnlyAccess { template <typename C> static auto GetCommon(const C& c) -> decltype(c.common()) { return c.common(); } template <typename C> static auto GetSlots(const C& c) -> decltype(c.slot_array()) { return c.slot_array(); } template <typename C> static size_t CountTombstones(const C& c) { return c.common().TombstonesCount(); } }; namespace { using ::testing::ElementsAre; using ::testing::ElementsAreArray; using ::testing::Eq; using ::testing::Ge; using ::testing::Lt; using ::testing::Pair; using ::testing::UnorderedElementsAre; ctrl_t CtrlT(int i) { return static_cast<ctrl_t>(i); } TEST(GrowthInfoTest, GetGrowthLeft) { GrowthInfo gi; gi.InitGrowthLeftNoDeleted(5); EXPECT_EQ(gi.GetGrowthLeft(), 5); gi.OverwriteFullAsDeleted(); EXPECT_EQ(gi.GetGrowthLeft(), 5); } TEST(GrowthInfoTest, HasNoDeleted) { GrowthInfo gi; gi.InitGrowthLeftNoDeleted(5); EXPECT_TRUE(gi.HasNoDeleted()); gi.OverwriteFullAsDeleted(); EXPECT_FALSE(gi.HasNoDeleted()); gi.InitGrowthLeftNoDeleted(5); EXPECT_TRUE(gi.HasNoDeleted()); } TEST(GrowthInfoTest, HasNoDeletedAndGrowthLeft) { GrowthInfo gi; gi.InitGrowthLeftNoDeleted(5); EXPECT_TRUE(gi.HasNoDeletedAndGrowthLeft()); gi.OverwriteFullAsDeleted(); EXPECT_FALSE(gi.HasNoDeletedAndGrowthLeft()); gi.InitGrowthLeftNoDeleted(0); EXPECT_FALSE(gi.HasNoDeletedAndGrowthLeft()); gi.OverwriteFullAsDeleted(); EXPECT_FALSE(gi.HasNoDeletedAndGrowthLeft()); gi.InitGrowthLeftNoDeleted(5); EXPECT_TRUE(gi.HasNoDeletedAndGrowthLeft()); } TEST(GrowthInfoTest, HasNoGrowthLeftAndNoDeleted) { GrowthInfo gi; gi.InitGrowthLeftNoDeleted(1); EXPECT_FALSE(gi.HasNoGrowthLeftAndNoDeleted()); gi.OverwriteEmptyAsFull(); EXPECT_TRUE(gi.HasNoGrowthLeftAndNoDeleted()); gi.OverwriteFullAsDeleted(); EXPECT_FALSE(gi.HasNoGrowthLeftAndNoDeleted()); gi.OverwriteFullAsEmpty(); EXPECT_FALSE(gi.HasNoGrowthLeftAndNoDeleted()); gi.InitGrowthLeftNoDeleted(0); EXPECT_TRUE(gi.HasNoGrowthLeftAndNoDeleted()); gi.OverwriteFullAsEmpty(); EXPECT_FALSE(gi.HasNoGrowthLeftAndNoDeleted()); } TEST(GrowthInfoTest, OverwriteFullAsEmpty) { GrowthInfo gi; gi.InitGrowthLeftNoDeleted(5); gi.OverwriteFullAsEmpty(); EXPECT_EQ(gi.GetGrowthLeft(), 6); gi.OverwriteFullAsDeleted(); EXPECT_EQ(gi.GetGrowthLeft(), 6); gi.OverwriteFullAsEmpty(); EXPECT_EQ(gi.GetGrowthLeft(), 7); EXPECT_FALSE(gi.HasNoDeleted()); } TEST(GrowthInfoTest, OverwriteEmptyAsFull) { GrowthInfo gi; gi.InitGrowthLeftNoDeleted(5); gi.OverwriteEmptyAsFull(); EXPECT_EQ(gi.GetGrowthLeft(), 4); gi.OverwriteFullAsDeleted(); EXPECT_EQ(gi.GetGrowthLeft(), 4); gi.OverwriteEmptyAsFull(); EXPECT_EQ(gi.GetGrowthLeft(), 3); EXPECT_FALSE(gi.HasNoDeleted()); } TEST(GrowthInfoTest, OverwriteControlAsFull) { GrowthInfo gi; gi.InitGrowthLeftNoDeleted(5); gi.OverwriteControlAsFull(ctrl_t::kEmpty); EXPECT_EQ(gi.GetGrowthLeft(), 4); gi.OverwriteControlAsFull(ctrl_t::kDeleted); EXPECT_EQ(gi.GetGrowthLeft(), 4); gi.OverwriteFullAsDeleted(); gi.OverwriteControlAsFull(ctrl_t::kDeleted); EXPECT_FALSE(gi.HasNoDeletedAndGrowthLeft()); EXPECT_FALSE(gi.HasNoDeleted()); } TEST(Util, NormalizeCapacity) { EXPECT_EQ(1, NormalizeCapacity(0)); EXPECT_EQ(1, NormalizeCapacity(1)); EXPECT_EQ(3, NormalizeCapacity(2)); EXPECT_EQ(3, NormalizeCapacity(3)); EXPECT_EQ(7, NormalizeCapacity(4)); EXPECT_EQ(7, NormalizeCapacity(7)); EXPECT_EQ(15, NormalizeCapacity(8)); EXPECT_EQ(15, NormalizeCapacity(15)); EXPECT_EQ(15 * 2 + 1, NormalizeCapacity(15 + 1)); EXPECT_EQ(15 * 2 + 1, NormalizeCapacity(15 + 2)); } TEST(Util, GrowthAndCapacity) { for (size_t growth = 0; growth < 10000; ++growth) { SCOPED_TRACE(growth); size_t capacity = NormalizeCapacity(GrowthToLowerboundCapacity(growth)); EXPECT_THAT(CapacityToGrowth(capacity), Ge(growth)); if (capacity + 1 < Group::kWidth) { EXPECT_THAT(CapacityToGrowth(capacity), Eq(capacity)); } else { EXPECT_THAT(CapacityToGrowth(capacity), Lt(capacity)); } if (growth != 0 && capacity > 1) { EXPECT_THAT(CapacityToGrowth(capacity / 2), Lt(growth)); } } for (size_t capacity = Group::kWidth - 1; capacity < 10000; capacity = 2 * capacity + 1) { SCOPED_TRACE(capacity); size_t growth = CapacityToGrowth(capacity); EXPECT_THAT(growth, Lt(capacity)); EXPECT_LE(GrowthToLowerboundCapacity(growth), capacity); EXPECT_EQ(NormalizeCapacity(GrowthToLowerboundCapacity(growth)), capacity); } } TEST(Util, probe_seq) { probe_seq<16> seq(0, 127); auto gen = [&]() { size_t res = seq.offset(); seq.next(); return res; }; std::vector<size_t> offsets(8); std::generate_n(offsets.begin(), 8, gen); EXPECT_THAT(offsets, ElementsAre(0, 16, 48, 96, 32, 112, 80, 64)); seq = probe_seq<16>(128, 127); std::generate_n(offsets.begin(), 8, gen); EXPECT_THAT(offsets, ElementsAre(0, 16, 48, 96, 32, 112, 80, 64)); } TEST(BitMask, Smoke) { EXPECT_FALSE((BitMask<uint8_t, 8>(0))); EXPECT_TRUE((BitMask<uint8_t, 8>(5))); EXPECT_THAT((BitMask<uint8_t, 8>(0)), ElementsAre()); EXPECT_THAT((BitMask<uint8_t, 8>(0x1)), ElementsAre(0)); EXPECT_THAT((BitMask<uint8_t, 8>(0x2)), ElementsAre(1)); EXPECT_THAT((BitMask<uint8_t, 8>(0x3)), ElementsAre(0, 1)); EXPECT_THAT((BitMask<uint8_t, 8>(0x4)), ElementsAre(2)); EXPECT_THAT((BitMask<uint8_t, 8>(0x5)), ElementsAre(0, 2)); EXPECT_THAT((BitMask<uint8_t, 8>(0x55)), ElementsAre(0, 2, 4, 6)); EXPECT_THAT((BitMask<uint8_t, 8>(0xAA)), ElementsAre(1, 3, 5, 7)); } TEST(BitMask, WithShift_MatchPortable) { uint64_t ctrl = 0x1716151413121110; uint64_t hash = 0x12; constexpr uint64_t lsbs = 0x0101010101010101ULL; auto x = ctrl ^ (lsbs * hash); uint64_t mask = (x - lsbs) & ~x & kMsbs8Bytes; EXPECT_EQ(0x0000000080800000, mask); BitMask<uint64_t, 8, 3> b(mask); EXPECT_EQ(*b, 2); } constexpr uint64_t kSome8BytesMask = 0x8000808080008000ULL; constexpr uint64_t kSome8BytesMaskAllOnes = 0xff00ffffff00ff00ULL; constexpr auto kSome8BytesMaskBits = std::array<int, 5>{1, 3, 4, 5, 7}; TEST(BitMask, WithShift_FullMask) { EXPECT_THAT((BitMask<uint64_t, 8, 3>(kMsbs8Bytes)), ElementsAre(0, 1, 2, 3, 4, 5, 6, 7)); EXPECT_THAT( (BitMask<uint64_t, 8, 3, true>(kMsbs8Bytes)), ElementsAre(0, 1, 2, 3, 4, 5, 6, 7)); EXPECT_THAT( (BitMask<uint64_t, 8, 3, true>(~uint64_t{0})), ElementsAre(0, 1, 2, 3, 4, 5, 6, 7)); } TEST(BitMask, WithShift_EmptyMask) { EXPECT_THAT((BitMask<uint64_t, 8, 3>(0)), ElementsAre()); EXPECT_THAT((BitMask<uint64_t, 8, 3, true>(0)), ElementsAre()); } TEST(BitMask, WithShift_SomeMask) { EXPECT_THAT((BitMask<uint64_t, 8, 3>(kSome8BytesMask)), ElementsAreArray(kSome8BytesMaskBits)); EXPECT_THAT((BitMask<uint64_t, 8, 3, true>( kSome8BytesMask)), ElementsAreArray(kSome8BytesMaskBits)); EXPECT_THAT((BitMask<uint64_t, 8, 3, true>( kSome8BytesMaskAllOnes)), ElementsAreArray(kSome8BytesMaskBits)); } TEST(BitMask, WithShift_SomeMaskExtraBitsForNullify) { uint64_t extra_bits = 77; for (int i = 0; i < 100; ++i) { uint64_t extra_mask = extra_bits & kSome8BytesMaskAllOnes; EXPECT_THAT((BitMask<uint64_t, 8, 3, true>( kSome8BytesMask | extra_mask)), ElementsAreArray(kSome8BytesMaskBits)) << i << " " << extra_mask; extra_bits = (extra_bits + 1) * 3; } } TEST(BitMask, LeadingTrailing) { EXPECT_EQ((BitMask<uint32_t, 16>(0x00001a40).LeadingZeros()), 3); EXPECT_EQ((BitMask<uint32_t, 16>(0x00001a40).TrailingZeros()), 6); EXPECT_EQ((BitMask<uint32_t, 16>(0x00000001).LeadingZeros()), 15); EXPECT_EQ((BitMask<uint32_t, 16>(0x00000001).TrailingZeros()), 0); EXPECT_EQ((BitMask<uint32_t, 16>(0x00008000).LeadingZeros()), 0); EXPECT_EQ((BitMask<uint32_t, 16>(0x00008000).TrailingZeros()), 15); EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000008080808000).LeadingZeros()), 3); EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000008080808000).TrailingZeros()), 1); EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000000000000080).LeadingZeros()), 7); EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x0000000000000080).TrailingZeros()), 0); EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x8000000000000000).LeadingZeros()), 0); EXPECT_EQ((BitMask<uint64_t, 8, 3>(0x8000000000000000).TrailingZeros()), 7); } TEST(Group, EmptyGroup) { for (h2_t h = 0; h != 128; ++h) EXPECT_FALSE(Group{EmptyGroup()}.Match(h)); } TEST(Group, Match) { if (Group::kWidth == 16) { ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted, CtrlT(3), ctrl_t::kEmpty, CtrlT(5), ctrl_t::kSentinel, CtrlT(7), CtrlT(7), CtrlT(5), CtrlT(3), CtrlT(1), CtrlT(1), CtrlT(1), CtrlT(1), CtrlT(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)); EXPECT_THAT(Group{group}.Match(5), ElementsAre(5, 9)); EXPECT_THAT(Group{group}.Match(7), ElementsAre(7, 8)); } else if (Group::kWidth == 8) { ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), CtrlT(2), ctrl_t::kDeleted, CtrlT(2), CtrlT(1), ctrl_t::kSentinel, CtrlT(1)}; EXPECT_THAT(Group{group}.Match(0), ElementsAre()); EXPECT_THAT(Group{group}.Match(1), ElementsAre(1, 5, 7)); EXPECT_THAT(Group{group}.Match(2), ElementsAre(2, 4)); } else { FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth; } } TEST(Group, MaskEmpty) { if (Group::kWidth == 16) { ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted, CtrlT(3), ctrl_t::kEmpty, CtrlT(5), ctrl_t::kSentinel, CtrlT(7), CtrlT(7), CtrlT(5), CtrlT(3), CtrlT(1), CtrlT(1), CtrlT(1), CtrlT(1), CtrlT(1)}; EXPECT_THAT(Group{group}.MaskEmpty().LowestBitSet(), 0); EXPECT_THAT(Group{group}.MaskEmpty().HighestBitSet(), 4); } else if (Group::kWidth == 8) { ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), CtrlT(2), ctrl_t::kDeleted, CtrlT(2), CtrlT(1), ctrl_t::kSentinel, CtrlT(1)}; EXPECT_THAT(Group{group}.MaskEmpty().LowestBitSet(), 0); EXPECT_THAT(Group{group}.MaskEmpty().HighestBitSet(), 0); } else { FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth; } } TEST(Group, MaskFull) { if (Group::kWidth == 16) { ctrl_t group[] = { ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted, CtrlT(3), ctrl_t::kEmpty, CtrlT(5), ctrl_t::kSentinel, CtrlT(7), CtrlT(7), CtrlT(5), ctrl_t::kDeleted, CtrlT(1), CtrlT(1), ctrl_t::kSentinel, ctrl_t::kEmpty, CtrlT(1)}; EXPECT_THAT(Group{group}.MaskFull(), ElementsAre(1, 3, 5, 7, 8, 9, 11, 12, 15)); } else if (Group::kWidth == 8) { ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kEmpty, ctrl_t::kDeleted, CtrlT(2), ctrl_t::kSentinel, ctrl_t::kSentinel, CtrlT(1)}; EXPECT_THAT(Group{group}.MaskFull(), ElementsAre(1, 4, 7)); } else { FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth; } } TEST(Group, MaskNonFull) { if (Group::kWidth == 16) { ctrl_t group[] = { ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted, CtrlT(3), ctrl_t::kEmpty, CtrlT(5), ctrl_t::kSentinel, CtrlT(7), CtrlT(7), CtrlT(5), ctrl_t::kDeleted, CtrlT(1), CtrlT(1), ctrl_t::kSentinel, ctrl_t::kEmpty, CtrlT(1)}; EXPECT_THAT(Group{group}.MaskNonFull(), ElementsAre(0, 2, 4, 6, 10, 13, 14)); } else if (Group::kWidth == 8) { ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kEmpty, ctrl_t::kDeleted, CtrlT(2), ctrl_t::kSentinel, ctrl_t::kSentinel, CtrlT(1)}; EXPECT_THAT(Group{group}.MaskNonFull(), ElementsAre(0, 2, 3, 5, 6)); } else { FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth; } } TEST(Group, MaskEmptyOrDeleted) { if (Group::kWidth == 16) { ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), ctrl_t::kEmpty, CtrlT(3), ctrl_t::kDeleted, CtrlT(5), ctrl_t::kSentinel, CtrlT(7), CtrlT(7), CtrlT(5), CtrlT(3), CtrlT(1), CtrlT(1), CtrlT(1), CtrlT(1), CtrlT(1)}; EXPECT_THAT(Group{group}.MaskEmptyOrDeleted().LowestBitSet(), 0); EXPECT_THAT(Group{group}.MaskEmptyOrDeleted().HighestBitSet(), 4); } else if (Group::kWidth == 8) { ctrl_t group[] = {ctrl_t::kEmpty, CtrlT(1), CtrlT(2), ctrl_t::kDeleted, CtrlT(2), CtrlT(1), ctrl_t::kSentinel, CtrlT(1)}; EXPECT_THAT(Group{group}.MaskEmptyOrDeleted().LowestBitSet(), 0); EXPECT_THAT(Group{group}.MaskEmptyOrDeleted().HighestBitSet(), 3); } else { FAIL() << "No test coverage for Group::kWidth==" << Group::kWidth; } } TEST(Batch, DropDeletes) { constexpr size_t kCapacity = 63; constexpr size_t kGroupWidth = container_internal::Group::kWidth; std::vector<ctrl_t> ctrl(kCapacity + 1 + kGroupWidth); ctrl[kCapacity] = ctrl_t::kSentinel; std::vector<ctrl_t> pattern = { ctrl_t::kEmpty, CtrlT(2), ctrl_t::kDeleted, CtrlT(2), ctrl_t::kEmpty, CtrlT(1), ctrl_t::kDeleted}; for (size_t i = 0; i != kCapacity; ++i) { ctrl[i] = pattern[i % pattern.size()]; if (i < kGroupWidth - 1) ctrl[i + kCapacity + 1] = pattern[i % pattern.size()]; } ConvertDeletedToEmptyAndFullToDeleted(ctrl.data(), kCapacity); ASSERT_EQ(ctrl[kCapacity], ctrl_t::kSentinel); for (size_t i = 0; i < kCapacity + kGroupWidth; ++i) { ctrl_t expected = pattern[i % (kCapacity + 1) % pattern.size()]; if (i == kCapacity) expected = ctrl_t::kSentinel; if (expected == ctrl_t::kDeleted) expected = ctrl_t::kEmpty; if (IsFull(expected)) expected = ctrl_t::kDeleted; EXPECT_EQ(ctrl[i], expected) << i << " " << static_cast<int>(pattern[i % pattern.size()]); } } TEST(Group, CountLeadingEmptyOrDeleted) { const std::vector<ctrl_t> empty_examples = {ctrl_t::kEmpty, ctrl_t::kDeleted}; const std::vector<ctrl_t> full_examples = { CtrlT(0), CtrlT(1), CtrlT(2), CtrlT(3), CtrlT(5), CtrlT(9), CtrlT(127), ctrl_t::kSentinel}; for (ctrl_t empty : empty_examples) { std::vector<ctrl_t> e(Group::kWidth, empty); EXPECT_EQ(Group::kWidth, Group{e.data()}.CountLeadingEmptyOrDeleted()); for (ctrl_t full : full_examples) { for (size_t i = 0; i != Group::kWidth; ++i) { std::vector<ctrl_t> f(Group::kWidth, empty); f[i] = full; EXPECT_EQ(i, Group{f.data()}.CountLeadingEmptyOrDeleted()); } std::vector<ctrl_t> f(Group::kWidth, empty); f[Group::kWidth * 2 / 3] = full; f[Group::kWidth / 2] = full; EXPECT_EQ(Group::kWidth / 2, Group{f.data()}.CountLeadingEmptyOrDeleted()); } } } template <class T, bool kTransferable = false, bool kSoo = false> struct ValuePolicy { using slot_type = T; using key_type = T; using init_type = T; template <class Allocator, class... Args> static void construct(Allocator* alloc, slot_type* slot, Args&&... args) { absl::allocator_traits<Allocator>::construct(*alloc, slot, std::forward<Args>(args)...); } template <class Allocator> static void destroy(Allocator* alloc, slot_type* slot) { absl::allocator_traits<Allocator>::destroy(*alloc, slot); } template <class Allocator> static std::integral_constant<bool, kTransferable> transfer( Allocator* alloc, slot_type* new_slot, slot_type* old_slot) { construct(alloc, new_slot, std::move(*old_slot)); destroy(alloc, old_slot); return {}; } static T& element(slot_type* slot) { return *slot; } template <class F, class... Args> static decltype(absl::container_internal::DecomposeValue( std::declval<F>(), std::declval<Args>()...)) apply(F&& f, Args&&... args) { return absl::container_internal::DecomposeValue( std::forward<F>(f), std::forward<Args>(args)...); } template <class Hash> static constexpr HashSlotFn get_hash_slot_fn() { return nullptr; } static constexpr bool soo_enabled() { return kSoo; } }; using IntPolicy = ValuePolicy<int64_t>; using Uint8Policy = ValuePolicy<uint8_t>; using TranferableIntPolicy = ValuePolicy<int64_t, true>; template <int N> class SizedValue { public: SizedValue(int64_t v) { vals_[0] = v; } SizedValue() : SizedValue(0) {} SizedValue(const SizedValue&) = default; SizedValue& operator=(const SizedValue&) = default; int64_t operator*() const { #if !defined(__clang__) && defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif return vals_[0]; #if !defined(__clang__) && defined(__GNUC__) #pragma GCC diagnostic pop #endif } explicit operator int() const { return **this; } explicit operator int64_t() const { return **this; } template <typename H> friend H AbslHashValue(H h, SizedValue sv) { return H::combine(std::move(h), *sv); } bool operator==(const SizedValue& rhs) const { return **this == *rhs; } private: int64_t vals_[N / sizeof(int64_t)]; }; template <int N, bool kSoo> using SizedValuePolicy = ValuePolicy<SizedValue<N>, true, kSoo>; class StringPolicy { template <class F, class K, class V, class = typename std::enable_if< std::is_convertible<const K&, absl::string_view>::value>::type> decltype(std::declval<F>()( std::declval<const absl::string_view&>(), std::piecewise_construct, std::declval<std::tuple<K>>(), std::declval<V>())) static apply_impl(F&& f, std::pair<std::tuple<K>, V> p) { const absl::string_view& key = std::get<0>(p.first); return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first), std::move(p.second)); } public: struct slot_type { struct ctor {}; template <class... Ts> explicit slot_type(ctor, Ts&&... ts) : pair(std::forward<Ts>(ts)...) {} std::pair<std::string, std::string> pair; }; using key_type = std::string; using init_type = std::pair<std::string, std::string>; template <class allocator_type, class... Args> static void construct(allocator_type* alloc, slot_type* slot, Args... args) { std::allocator_traits<allocator_type>::construct( *alloc, slot, typename slot_type::ctor(), std::forward<Args>(args)...); } template <class allocator_type> static void destroy(allocator_type* alloc, slot_type* slot) { std::allocator_traits<allocator_type>::destroy(*alloc, slot); } template <class allocator_type> 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); } static std::pair<std::string, std::string>& element(slot_type* slot) { return slot->pair; } template <class F, class... Args> static auto apply(F&& f, Args&&... args) -> decltype(apply_impl(std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) { return apply_impl(std::forward<F>(f), PairArgs(std::forward<Args>(args)...)); } template <class Hash> static constexpr HashSlotFn get_hash_slot_fn() { return nullptr; } }; struct StringHash : absl::Hash<absl::string_view> { using is_transparent = void; }; struct StringEq : std::equal_to<absl::string_view> { using is_transparent = void; }; struct StringTable : raw_hash_set<StringPolicy, StringHash, StringEq, std::allocator<int>> { using Base = typename StringTable::raw_hash_set; StringTable() = default; using Base::Base; }; template <typename T, bool kTransferable = false, bool kSoo = false> struct ValueTable : raw_hash_set<ValuePolicy<T, kTransferable, kSoo>, hash_default_hash<T>, std::equal_to<T>, std::allocator<T>> { using Base = typename ValueTable::raw_hash_set; using Base::Base; }; using IntTable = ValueTable<int64_t>; using Uint8Table = ValueTable<uint8_t>; using TransferableIntTable = ValueTable<int64_t, true>; constexpr size_t kNonSooSize = sizeof(HeapOrSoo) + 8; static_assert(sizeof(SizedValue<kNonSooSize>) >= kNonSooSize, "too small"); using NonSooIntTable = ValueTable<SizedValue<kNonSooSize>>; using SooIntTable = ValueTable<int64_t, true, true>; template <typename T> struct CustomAlloc : std::allocator<T> { CustomAlloc() = default; template <typename U> explicit CustomAlloc(const CustomAlloc<U>& ) {} template <class U> struct rebind { using other = CustomAlloc<U>; }; }; struct CustomAllocIntTable : raw_hash_set<IntPolicy, hash_default_hash<int64_t>, std::equal_to<int64_t>, CustomAlloc<int64_t>> { using Base = typename CustomAllocIntTable::raw_hash_set; using Base::Base; }; struct MinimumAlignmentUint8Table : raw_hash_set<Uint8Policy, hash_default_hash<uint8_t>, std::equal_to<uint8_t>, MinimumAlignmentAlloc<uint8_t>> { using Base = typename MinimumAlignmentUint8Table::raw_hash_set; using Base::Base; }; template <typename T> struct FreezableAlloc : std::allocator<T> { explicit FreezableAlloc(bool* f) : frozen(f) {} template <typename U> explicit FreezableAlloc(const FreezableAlloc<U>& other) : frozen(other.frozen) {} template <class U> struct rebind { using other = FreezableAlloc<U>; }; T* allocate(size_t n) { EXPECT_FALSE(*frozen); return std::allocator<T>::allocate(n); } bool* frozen; }; template <int N> struct FreezableSizedValueSooTable : raw_hash_set<SizedValuePolicy<N, true>, container_internal::hash_default_hash<SizedValue<N>>, std::equal_to<SizedValue<N>>, FreezableAlloc<SizedValue<N>>> { using Base = typename FreezableSizedValueSooTable::raw_hash_set; using Base::Base; }; struct BadFastHash { template <class T> size_t operator()(const T&) const { return 0; } }; struct BadHashFreezableIntTable : raw_hash_set<IntPolicy, BadFastHash, std::equal_to<int64_t>, FreezableAlloc<int64_t>> { using Base = typename BadHashFreezableIntTable::raw_hash_set; using Base::Base; }; struct BadTable : raw_hash_set<IntPolicy, BadFastHash, std::equal_to<int>, std::allocator<int>> { using Base = typename BadTable::raw_hash_set; BadTable() = default; using Base::Base; }; TEST(Table, EmptyFunctorOptimization) { static_assert(std::is_empty<std::equal_to<absl::string_view>>::value, ""); static_assert(std::is_empty<std::allocator<int>>::value, ""); struct MockTable { void* ctrl; void* slots; size_t size; size_t capacity; }; struct StatelessHash { size_t operator()(absl::string_view) const { return 0; } }; struct StatefulHash : StatelessHash { size_t dummy; }; struct GenerationData { size_t reserved_growth; size_t reservation_size; GenerationType* generation; }; #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" #endif constexpr size_t mock_size = sizeof(MockTable); constexpr size_t generation_size = SwisstableGenerationsEnabled() ? sizeof(GenerationData) : 0; #if defined(__clang__) #pragma clang diagnostic pop #endif EXPECT_EQ( mock_size + generation_size, sizeof( raw_hash_set<StringPolicy, StatelessHash, std::equal_to<absl::string_view>, std::allocator<int>>)); EXPECT_EQ( mock_size + sizeof(StatefulHash) + generation_size, sizeof( raw_hash_set<StringPolicy, StatefulHash, std::equal_to<absl::string_view>, std::allocator<int>>)); } template <class TableType> class SooTest : public testing::Test {}; using SooTableTypes = ::testing::Types<SooIntTable, NonSooIntTable>; TYPED_TEST_SUITE(SooTest, SooTableTypes); TYPED_TEST(SooTest, Empty) { TypeParam t; EXPECT_EQ(0, t.size()); EXPECT_TRUE(t.empty()); } TYPED_TEST(SooTest, LookupEmpty) { TypeParam t; auto it = t.find(0); EXPECT_TRUE(it == t.end()); } TYPED_TEST(SooTest, Insert1) { TypeParam t; EXPECT_TRUE(t.find(0) == t.end()); auto res = t.emplace(0); EXPECT_TRUE(res.second); EXPECT_THAT(*res.first, 0); EXPECT_EQ(1, t.size()); EXPECT_THAT(*t.find(0), 0); } TYPED_TEST(SooTest, Insert2) { TypeParam t; EXPECT_TRUE(t.find(0) == t.end()); auto res = t.emplace(0); EXPECT_TRUE(res.second); EXPECT_THAT(*res.first, 0); EXPECT_EQ(1, t.size()); EXPECT_TRUE(t.find(1) == t.end()); res = t.emplace(1); EXPECT_TRUE(res.second); EXPECT_THAT(*res.first, 1); EXPECT_EQ(2, t.size()); EXPECT_THAT(*t.find(0), 0); EXPECT_THAT(*t.find(1), 1); } TEST(Table, InsertCollision) { BadTable t; EXPECT_TRUE(t.find(1) == t.end()); auto res = t.emplace(1); EXPECT_TRUE(res.second); EXPECT_THAT(*res.first, 1); EXPECT_EQ(1, t.size()); EXPECT_TRUE(t.find(2) == t.end()); res = t.emplace(2); EXPECT_THAT(*res.first, 2); EXPECT_TRUE(res.second); EXPECT_EQ(2, t.size()); EXPECT_THAT(*t.find(1), 1); EXPECT_THAT(*t.find(2), 2); } TEST(Table, InsertCollisionAndFindAfterDelete) { BadTable t; constexpr size_t kNumInserts = Group::kWidth * 2 + 5; for (size_t i = 0; i < kNumInserts; ++i) { auto res = t.emplace(i); EXPECT_TRUE(res.second); EXPECT_THAT(*res.first, i); EXPECT_EQ(i + 1, t.size()); } for (size_t i = 0; i < kNumInserts; ++i) { EXPECT_EQ(1, t.erase(i)) << i; for (size_t j = i + 1; j < kNumInserts; ++j) { EXPECT_THAT(*t.find(j), j); auto res = t.emplace(j); EXPECT_FALSE(res.second) << i << " " << j; EXPECT_THAT(*res.first, j); EXPECT_EQ(kNumInserts - i - 1, t.size()); } } EXPECT_TRUE(t.empty()); } TYPED_TEST(SooTest, EraseInSmallTables) { for (int64_t size = 0; size < 64; ++size) { TypeParam t; for (int64_t i = 0; i < size; ++i) { t.insert(i); } for (int64_t i = 0; i < size; ++i) { t.erase(i); EXPECT_EQ(t.size(), size - i - 1); for (int64_t j = i + 1; j < size; ++j) { EXPECT_THAT(*t.find(j), j); } } EXPECT_TRUE(t.empty()); } } TYPED_TEST(SooTest, InsertWithinCapacity) { TypeParam t; t.reserve(10); const size_t original_capacity = t.capacity(); const auto addr = [&](int i) { return reinterpret_cast<uintptr_t>(&*t.find(i)); }; t.insert(0); EXPECT_THAT(t.capacity(), original_capacity); const uintptr_t original_addr_0 = addr(0); t.insert(1); EXPECT_THAT(t.capacity(), original_capacity); EXPECT_THAT(addr(0), original_addr_0); for (int i = 0; i < 100; ++i) { t.insert(i % 10); } EXPECT_THAT(t.capacity(), original_capacity); EXPECT_THAT(addr(0), original_addr_0); std::vector<int> dup_range; for (int i = 0; i < 100; ++i) { dup_range.push_back(i % 10); } t.insert(dup_range.begin(), dup_range.end()); EXPECT_THAT(t.capacity(), original_capacity); EXPECT_THAT(addr(0), original_addr_0); } template <class TableType> class SmallTableResizeTest : public testing::Test {}; using SmallTableTypes = ::testing::Types<IntTable, TransferableIntTable, SooIntTable>; TYPED_TEST_SUITE(SmallTableResizeTest, SmallTableTypes); TYPED_TEST(SmallTableResizeTest, InsertIntoSmallTable) { TypeParam t; for (int i = 0; i < 32; ++i) { t.insert(i); ASSERT_EQ(t.size(), i + 1); for (int j = 0; j < i + 1; ++j) { EXPECT_TRUE(t.find(j) != t.end()); EXPECT_EQ(*t.find(j), j); } } } TYPED_TEST(SmallTableResizeTest, ResizeGrowSmallTables) { for (size_t source_size = 0; source_size < 32; ++source_size) { for (size_t target_size = source_size; target_size < 32; ++target_size) { for (bool rehash : {false, true}) { TypeParam t; for (size_t i = 0; i < source_size; ++i) { t.insert(static_cast<int>(i)); } if (rehash) { t.rehash(target_size); } else { t.reserve(target_size); } for (size_t i = 0; i < source_size; ++i) { EXPECT_TRUE(t.find(static_cast<int>(i)) != t.end()); EXPECT_EQ(*t.find(static_cast<int>(i)), static_cast<int>(i)); } } } } } TYPED_TEST(SmallTableResizeTest, ResizeReduceSmallTables) { for (size_t source_size = 0; source_size < 32; ++source_size) { for (size_t target_size = 0; target_size <= source_size; ++target_size) { TypeParam t; size_t inserted_count = std::min<size_t>(source_size, 5); for (size_t i = 0; i < inserted_count; ++i) { t.insert(static_cast<int>(i)); } const size_t minimum_capacity = t.capacity(); t.reserve(source_size); t.rehash(target_size); if (target_size == 0) { EXPECT_EQ(t.capacity(), minimum_capacity) << "rehash(0) must resize to the minimum capacity"; } for (size_t i = 0; i < inserted_count; ++i) { EXPECT_TRUE(t.find(static_cast<int>(i)) != t.end()); EXPECT_EQ(*t.find(static_cast<int>(i)), static_cast<int>(i)); } } } } TEST(Table, LazyEmplace) { StringTable t; bool called = false; auto it = t.lazy_emplace("abc", [&](const StringTable::constructor& f) { called = true; f("abc", "ABC"); }); EXPECT_TRUE(called); EXPECT_THAT(*it, Pair("abc", "ABC")); called = false; it = t.lazy_emplace("abc", [&](const StringTable::constructor& f) { called = true; f("abc", "DEF"); }); EXPECT_FALSE(called); EXPECT_THAT(*it, Pair("abc", "ABC")); } TYPED_TEST(SooTest, ContainsEmpty) { TypeParam t; EXPECT_FALSE(t.contains(0)); } TYPED_TEST(SooTest, Contains1) { TypeParam t; EXPECT_TRUE(t.insert(0).second); EXPECT_TRUE(t.contains(0)); EXPECT_FALSE(t.contains(1)); EXPECT_EQ(1, t.erase(0)); EXPECT_FALSE(t.contains(0)); } TYPED_TEST(SooTest, Contains2) { TypeParam t; EXPECT_TRUE(t.insert(0).second); EXPECT_TRUE(t.contains(0)); EXPECT_FALSE(t.contains(1)); t.clear(); EXPECT_FALSE(t.contains(0)); } int decompose_constructed; int decompose_copy_constructed; int decompose_copy_assigned; int decompose_move_constructed; int decompose_move_assigned; struct DecomposeType { DecomposeType(int i = 0) : i(i) { ++decompose_constructed; } explicit DecomposeType(const char* d) : DecomposeType(*d) {} DecomposeType(const DecomposeType& other) : i(other.i) { ++decompose_copy_constructed; } DecomposeType& operator=(const DecomposeType& other) { ++decompose_copy_assigned; i = other.i; return *this; } DecomposeType(DecomposeType&& other) : i(other.i) { ++decompose_move_constructed; } DecomposeType& operator=(DecomposeType&& other) { ++decompose_move_assigned; i = other.i; return *this; } int i; }; struct DecomposeHash { using is_transparent = void; size_t operator()(const 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 { using is_transparent = void; bool operator()(const DecomposeType& a, const DecomposeType& b) const { return a.i == b.i; } bool operator()(const DecomposeType& a, int b) const { return a.i == b; } bool operator()(const DecomposeType& a, const char* b) const { return a.i == *b; } }; struct DecomposePolicy { using slot_type = DecomposeType; using key_type = DecomposeType; using init_type = DecomposeType; template <typename T> static void construct(void*, DecomposeType* slot, T&& v) { ::new (slot) DecomposeType(std::forward<T>(v)); } static void destroy(void*, DecomposeType* slot) { slot->~DecomposeType(); } static DecomposeType& element(slot_type* slot) { return *slot; } template <class F, class T> static auto apply(F&& f, const T& x) -> decltype(std::forward<F>(f)(x, x)) { return std::forward<F>(f)(x, x); } template <class Hash> static constexpr HashSlotFn get_hash_slot_fn() { return nullptr; } }; template <typename Hash, typename Eq> void TestDecompose(bool construct_three) { DecomposeType elem{0}; const int one = 1; const char* three_p = "3"; const auto& three = three_p; const int elem_vector_count = 256; std::vector<DecomposeType> elem_vector(elem_vector_count, DecomposeType{0}); std::iota(elem_vector.begin(), elem_vector.end(), 0); using DecomposeSet = raw_hash_set<DecomposePolicy, Hash, Eq, std::allocator<int>>; DecomposeSet set1; decompose_constructed = 0; int expected_constructed = 0; EXPECT_EQ(expected_constructed, decompose_constructed); set1.insert(elem); EXPECT_EQ(expected_constructed, decompose_constructed); set1.insert(1); EXPECT_EQ(++expected_constructed, decompose_constructed); set1.emplace("3"); EXPECT_EQ(++expected_constructed, decompose_constructed); EXPECT_EQ(expected_constructed, decompose_constructed); { set1.insert(1); EXPECT_EQ(expected_constructed, decompose_constructed); } { set1.insert(one); EXPECT_EQ(expected_constructed, decompose_constructed); } { set1.insert(set1.begin(), 1); EXPECT_EQ(expected_constructed, decompose_constructed); } { set1.insert(set1.begin(), one); EXPECT_EQ(expected_constructed, decompose_constructed); } { set1.emplace(1); EXPECT_EQ(expected_constructed, decompose_constructed); set1.emplace("3"); expected_constructed += construct_three; EXPECT_EQ(expected_constructed, decompose_constructed); set1.emplace(one); EXPECT_EQ(expected_constructed, decompose_constructed); set1.emplace(three); expected_constructed += construct_three; EXPECT_EQ(expected_constructed, decompose_constructed); } { set1.emplace_hint(set1.begin(), 1); EXPECT_EQ(expected_constructed, decompose_constructed); set1.emplace_hint(set1.begin(), "3"); expected_constructed += construct_three; EXPECT_EQ(expected_constructed, decompose_constructed); set1.emplace_hint(set1.begin(), one); EXPECT_EQ(expected_constructed, decompose_constructed); set1.emplace_hint(set1.begin(), three); expected_constructed += construct_three; EXPECT_EQ(expected_constructed, decompose_constructed); } decompose_copy_constructed = 0; decompose_copy_assigned = 0; decompose_move_constructed = 0; decompose_move_assigned = 0; int expected_copy_constructed = 0; int expected_move_constructed = 0; { DecomposeSet set2(elem_vector.begin(), elem_vector.end()); expected_copy_constructed += elem_vector_count; EXPECT_EQ(expected_copy_constructed, decompose_copy_constructed); EXPECT_EQ(expected_move_constructed, decompose_move_constructed); EXPECT_EQ(0, decompose_move_assigned); EXPECT_EQ(0, decompose_copy_assigned); } { std::list<DecomposeType> elem_list(elem_vector.begin(), elem_vector.end()); expected_copy_constructed = decompose_copy_constructed; DecomposeSet set2(elem_list.begin(), elem_list.end()); expected_copy_constructed += elem_vector_count; EXPECT_EQ(expected_copy_constructed, decompose_copy_constructed); expected_move_constructed += elem_vector_count; EXPECT_LT(expected_move_constructed, decompose_move_constructed); expected_move_constructed += elem_vector_count; EXPECT_GE(expected_move_constructed, decompose_move_constructed); EXPECT_EQ(0, decompose_move_assigned); EXPECT_EQ(0, decompose_copy_assigned); expected_copy_constructed = decompose_copy_constructed; expected_move_constructed = decompose_move_constructed; } { DecomposeSet set2; set2.insert(elem_vector.begin(), elem_vector.end()); const int expected_new_elements = elem_vector_count; const int expected_max_element_moves = 2 * elem_vector_count; expected_copy_constructed += expected_new_elements; EXPECT_EQ(expected_copy_constructed, decompose_copy_constructed); expected_move_constructed += expected_max_element_moves; EXPECT_GE(expected_move_constructed, decompose_move_constructed); EXPECT_EQ(0, decompose_move_assigned); EXPECT_EQ(0, decompose_copy_assigned); expected_copy_constructed = decompose_copy_constructed; expected_move_constructed = decompose_move_constructed; } } TEST(Table, Decompose) { if (SwisstableGenerationsEnabled()) { GTEST_SKIP() << "Generations being enabled causes extra rehashes."; } TestDecompose<DecomposeHash, DecomposeEq>(false); struct TransparentHashIntOverload { size_t operator()(const DecomposeType& a) const { return a.i; } size_t operator()(int a) const { return a; } }; struct TransparentEqIntOverload { bool operator()(const DecomposeType& a, const DecomposeType& b) const { return a.i == b.i; } bool operator()(const DecomposeType& a, int b) const { return a.i == b; } }; TestDecompose<TransparentHashIntOverload, DecomposeEq>(true); TestDecompose<TransparentHashIntOverload, TransparentEqIntOverload>(true); TestDecompose<DecomposeHash, TransparentEqIntOverload>(true); } size_t MaxDensitySize(size_t n) { IntTable t; t.reserve(n); for (size_t i = 0; i != n; ++i) t.emplace(i); const size_t c = t.bucket_count(); while (c == t.bucket_count()) t.emplace(n++); return t.size() - 1; } struct Modulo1000Hash { size_t operator()(int64_t x) const { return static_cast<size_t>(x) % 1000; } }; struct Modulo1000HashTable : public raw_hash_set<IntPolicy, Modulo1000Hash, std::equal_to<int>, std::allocator<int>> {}; TEST(Table, RehashWithNoResize) { if (SwisstableGenerationsEnabled()) { GTEST_SKIP() << "Generations being enabled causes extra rehashes."; } Modulo1000HashTable t; const size_t kMinFullGroups = 7; std::vector<int> keys; for (size_t i = 0; i < MaxDensitySize(Group::kWidth * kMinFullGroups); ++i) { int k = i * 1000; t.emplace(k); keys.push_back(k); } const size_t capacity = t.capacity(); const size_t erase_begin = Group::kWidth / 2; const size_t erase_end = (t.size() / Group::kWidth - 1) * Group::kWidth; for (size_t i = erase_begin; i < erase_end; ++i) { EXPECT_EQ(1, t.erase(keys[i])) << i; } keys.erase(keys.begin() + erase_begin, keys.begin() + erase_end); auto last_key = keys.back(); size_t last_key_num_probes = GetHashtableDebugNumProbes(t, last_key); ASSERT_GT(last_key_num_probes, kMinFullGroups); int x = 1; while (last_key_num_probes == GetHashtableDebugNumProbes(t, last_key)) { t.emplace(x); ASSERT_EQ(capacity, t.capacity()); ASSERT_TRUE(t.find(x) != t.end()) << x; for (const auto& k : keys) { ASSERT_TRUE(t.find(k) != t.end()) << k; } t.erase(x); ++x; } } TYPED_TEST(SooTest, InsertEraseStressTest) { TypeParam t; const size_t kMinElementCount = 250; std::deque<int> keys; size_t i = 0; for (; i < MaxDensitySize(kMinElementCount); ++i) { t.emplace(i); keys.push_back(i); } const size_t kNumIterations = 1000000; for (; i < kNumIterations; ++i) { ASSERT_EQ(1, t.erase(keys.front())); keys.pop_front(); t.emplace(i); keys.push_back(i); } } TEST(Table, InsertOverloads) { StringTable t; t.insert({{}, {}}); t.insert({"ABC", {}}); t.insert({"DEF", "!!!"}); EXPECT_THAT(t, UnorderedElementsAre(Pair("", ""), Pair("ABC", ""), Pair("DEF", "!!!"))); } TYPED_TEST(SooTest, LargeTable) { TypeParam t; for (int64_t i = 0; i != 100000; ++i) t.emplace(i << 40); for (int64_t i = 0; i != 100000; ++i) ASSERT_EQ(i << 40, static_cast<int64_t>(*t.find(i << 40))); } TYPED_TEST(SooTest, EnsureNonQuadraticAsInRust) { static const size_t kLargeSize = 1 << 15; TypeParam t; for (size_t i = 0; i != kLargeSize; ++i) { t.insert(i); } TypeParam t2; for (const auto& entry : t) t2.insert(entry); } TYPED_TEST(SooTest, ClearBug) { if (SwisstableGenerationsEnabled()) { GTEST_SKIP() << "Generations being enabled causes extra rehashes."; } TypeParam t; constexpr size_t capacity = container_internal::Group::kWidth - 1; constexpr size_t max_size = capacity / 2 + 1; for (size_t i = 0; i < max_size; ++i) { t.insert(i); } ASSERT_EQ(capacity, t.capacity()); intptr_t original = reinterpret_cast<intptr_t>(&*t.find(2)); t.clear(); ASSERT_EQ(capacity, t.capacity()); for (size_t i = 0; i < max_size; ++i) { t.insert(i); } ASSERT_EQ(capacity, t.capacity()); intptr_t second = reinterpret_cast<intptr_t>(&*t.find(2)); EXPECT_LT(static_cast<size_t>(std::abs(original - second)), capacity * sizeof(typename TypeParam::value_type)); } TYPED_TEST(SooTest, Erase) { TypeParam t; EXPECT_TRUE(t.find(0) == t.end()); auto res = t.emplace(0); EXPECT_TRUE(res.second); EXPECT_EQ(1, t.size()); t.erase(res.first); EXPECT_EQ(0, t.size()); EXPECT_TRUE(t.find(0) == t.end()); } TYPED_TEST(SooTest, EraseMaintainsValidIterator) { TypeParam t; const int kNumElements = 100; for (int i = 0; i < kNumElements; i++) { EXPECT_TRUE(t.emplace(i).second); } EXPECT_EQ(t.size(), kNumElements); int num_erase_calls = 0; auto it = t.begin(); while (it != t.end()) { t.erase(it++); num_erase_calls++; } EXPECT_TRUE(t.empty()); EXPECT_EQ(num_erase_calls, kNumElements); } TYPED_TEST(SooTest, EraseBeginEnd) { TypeParam t; for (int i = 0; i < 10; ++i) t.insert(i); EXPECT_EQ(t.size(), 10); t.erase(t.begin(), t.end()); EXPECT_EQ(t.size(), 0); } std::vector<int64_t> CollectBadMergeKeys(size_t N) { static constexpr int kGroupSize = Group::kWidth - 1; auto topk_range = [](size_t b, size_t e, IntTable* t) -> std::vector<int64_t> { for (size_t i = b; i != e; ++i) { t->emplace(i); } std::vector<int64_t> res; res.reserve(kGroupSize); auto it = t->begin(); for (size_t i = b; i != e && i != b + kGroupSize; ++i, ++it) { res.push_back(*it); } return res; }; std::vector<int64_t> bad_keys; bad_keys.reserve(N); IntTable t; t.reserve(N * 2); for (size_t b = 0; bad_keys.size() < N; b += N) { auto keys = topk_range(b, b + N, &t); bad_keys.insert(bad_keys.end(), keys.begin(), keys.end()); t.erase(t.begin(), t.end()); EXPECT_TRUE(t.empty()); } return bad_keys; } struct ProbeStats { std::vector<size_t> all_probes_histogram; std::vector<double> single_table_ratios; double AvgRatio() const { return std::accumulate(single_table_ratios.begin(), single_table_ratios.end(), 0.0) / single_table_ratios.size(); } double MaxRatio() const { return *std::max_element(single_table_ratios.begin(), single_table_ratios.end()); } double PercentileRatio(double Percentile = 0.95) const { auto r = single_table_ratios; auto mid = r.begin() + static_cast<size_t>(r.size() * Percentile); if (mid != r.end()) { std::nth_element(r.begin(), mid, r.end()); return *mid; } else { return MaxRatio(); } } size_t MaxProbe() const { return all_probes_histogram.size(); } std::vector<double> ProbeNormalizedHistogram() const { double total_elements = std::accumulate(all_probes_histogram.begin(), all_probes_histogram.end(), 0ull); std::vector<double> res; for (size_t p : all_probes_histogram) { res.push_back(p / total_elements); } return res; } size_t PercentileProbe(double Percentile = 0.99) const { size_t idx = 0; for (double p : ProbeNormalizedHistogram()) { if (Percentile > p) { Percentile -= p; ++idx; } else { return idx; } } return idx; } friend std::ostream& operator<<(std::ostream& out, const ProbeStats& s) { out << "{AvgRatio:" << s.AvgRatio() << ", MaxRatio:" << s.MaxRatio() << ", PercentileRatio:" << s.PercentileRatio() << ", MaxProbe:" << s.MaxProbe() << ", Probes=["; for (double p : s.ProbeNormalizedHistogram()) { out << p << ","; } out << "]}"; return out; } }; struct ExpectedStats { double avg_ratio; double max_ratio; std::vector<std::pair<double, double>> pecentile_ratios; std::vector<std::pair<double, double>> pecentile_probes; 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 << ", "; } out << "], PercentileProbes: ["; for (auto el : s.pecentile_probes) { out << el.first << ":" << el.second << ", "; } out << "]}"; return out; } }; 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; } for (auto pr : exp.pecentile_probes) { EXPECT_LE(stats.PercentileProbe(pr.first), pr.second) << size << " " << pr.first << " " << stats; } } using ProbeStatsPerSize = std::map<size_t, ProbeStats>; ProbeStats CollectProbeStatsOnKeysXoredWithSeed( const std::vector<int64_t>& keys, size_t num_iters) { const size_t reserve_size = keys.size() * 2; ProbeStats stats; int64_t seed = 0x71b1a19b907d6e33; while (num_iters--) { seed = static_cast<int64_t>(static_cast<uint64_t>(seed) * 17 + 13); IntTable t1; t1.reserve(reserve_size); for (const auto& key : keys) { t1.emplace(key ^ seed); } auto probe_histogram = GetHashtableDebugNumProbesHistogram(t1); 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(), stats.all_probes_histogram.begin(), std::plus<size_t>()); size_t total_probe_seq_length = 0; for (size_t i = 0; i < probe_histogram.size(); ++i) { total_probe_seq_length += i * probe_histogram[i]; } stats.single_table_ratios.push_back(total_probe_seq_length * 1.0 / keys.size()); t1.erase(t1.begin(), t1.end()); } return stats; } ExpectedStats XorSeedExpectedStats() { constexpr bool kRandomizesInserts = #ifdef NDEBUG false; #else true; #endif switch (container_internal::Group::kWidth) { case 8: if (kRandomizesInserts) { return {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}}}; } case 16: if (kRandomizesInserts) { return {0.1, 2.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}}}; } } LOG(FATAL) << "Unknown Group width"; return {}; } TEST(Table, DISABLED_EnsureNonQuadraticTopNXorSeedByProbeSeqLength) { ProbeStatsPerSize stats; std::vector<size_t> sizes = {Group::kWidth << 5, Group::kWidth << 10}; for (size_t size : sizes) { stats[size] = CollectProbeStatsOnKeysXoredWithSeed(CollectBadMergeKeys(size), 200); } auto expected = XorSeedExpectedStats(); for (size_t size : sizes) { auto& stat = stats[size]; VerifyStats(size, expected, stat); LOG(INFO) << size << " " << stat; } } ProbeStats CollectProbeStatsOnLinearlyTransformedKeys( const std::vector<int64_t>& 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::uniform_int_distribution<size_t> dist(0, keys.size() - 1); while (num_iters--) { IntTable t1; size_t num_keys = keys.size() / 10; size_t start = dist(rng); for (size_t i = 0; i != num_keys; ++i) { for (size_t j = 0; j != 10; ++j) { t1.emplace(linear_transform(keys[(i + start) % keys.size()], j)); } } auto probe_histogram = GetHashtableDebugNumProbesHistogram(t1); 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(), stats.all_probes_histogram.begin(), std::plus<size_t>()); size_t total_probe_seq_length = 0; for (size_t i = 0; i < probe_histogram.size(); ++i) { total_probe_seq_length += i * probe_histogram[i]; } stats.single_table_ratios.push_back(total_probe_seq_length * 1.0 / t1.size()); t1.erase(t1.begin(), t1.end()); } return stats; } ExpectedStats LinearTransformExpectedStats() { constexpr bool kRandomizesInserts = #ifdef NDEBUG false; #else true; #endif switch (container_internal::Group::kWidth) { case 8: if (kRandomizesInserts) { return {0.1, 0.5, {{0.95, 0.3}}, {{0.95, 0}, {0.99, 1}, {0.999, 8}, {0.9999, 15}}}; } else { return {0.4, 0.6, {{0.95, 0.5}}, {{0.95, 1}, {0.99, 14}, {0.999, 23}, {0.9999, 26}}}; } case 16: if (kRandomizesInserts) { return {0.1, 0.4, {{0.95, 0.3}}, {{0.95, 1}, {0.99, 2}, {0.999, 9}, {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}}}; } } LOG(FATAL) << "Unknown Group width"; return {}; } TEST(Table, DISABLED_EnsureNonQuadraticTopNLinearTransformByProbeSeqLength) { ProbeStatsPerSize stats; std::vector<size_t> sizes = {Group::kWidth << 5, Group::kWidth << 10}; for (size_t size : sizes) { stats[size] = CollectProbeStatsOnLinearlyTransformedKeys( CollectBadMergeKeys(size), 300); } auto expected = LinearTransformExpectedStats(); for (size_t size : sizes) { auto& stat = stats[size]; VerifyStats(size, expected, stat); LOG(INFO) << size << " " << stat; } } TEST(Table, EraseCollision) { BadTable t; t.emplace(1); t.emplace(2); t.emplace(3); EXPECT_THAT(*t.find(1), 1); EXPECT_THAT(*t.find(2), 2); EXPECT_THAT(*t.find(3), 3); EXPECT_EQ(3, t.size()); t.erase(t.find(2)); EXPECT_THAT(*t.find(1), 1); EXPECT_TRUE(t.find(2) == t.end()); EXPECT_THAT(*t.find(3), 3); EXPECT_EQ(2, t.size()); t.erase(t.find(1)); EXPECT_TRUE(t.find(1) == t.end()); EXPECT_TRUE(t.find(2) == t.end()); EXPECT_THAT(*t.find(3), 3); EXPECT_EQ(1, t.size()); t.erase(t.find(3)); EXPECT_TRUE(t.find(1) == t.end()); EXPECT_TRUE(t.find(2) == t.end()); EXPECT_TRUE(t.find(3) == t.end()); EXPECT_EQ(0, t.size()); } TEST(Table, EraseInsertProbing) { BadTable t(100); t.emplace(1); t.emplace(2); t.emplace(3); t.emplace(4); t.erase(t.find(2)); t.erase(t.find(4)); t.emplace(10); t.emplace(11); t.emplace(12); EXPECT_EQ(5, t.size()); EXPECT_THAT(t, UnorderedElementsAre(1, 10, 3, 11, 12)); } TEST(Table, GrowthInfoDeletedBit) { BadTable t; EXPECT_TRUE( RawHashSetTestOnlyAccess::GetCommon(t).growth_info().HasNoDeleted()); int64_t init_count = static_cast<int64_t>( CapacityToGrowth(NormalizeCapacity(Group::kWidth + 1))); for (int64_t i = 0; i < init_count; ++i) { t.insert(i); } EXPECT_TRUE( RawHashSetTestOnlyAccess::GetCommon(t).growth_info().HasNoDeleted()); t.erase(0); EXPECT_EQ(RawHashSetTestOnlyAccess::CountTombstones(t), 1); EXPECT_FALSE( RawHashSetTestOnlyAccess::GetCommon(t).growth_info().HasNoDeleted()); t.rehash(0); EXPECT_EQ(RawHashSetTestOnlyAccess::CountTombstones(t), 0); EXPECT_TRUE( RawHashSetTestOnlyAccess::GetCommon(t).growth_info().HasNoDeleted()); } TYPED_TEST(SooTest, Clear) { TypeParam t; EXPECT_TRUE(t.find(0) == t.end()); t.clear(); EXPECT_TRUE(t.find(0) == t.end()); auto res = t.emplace(0); EXPECT_TRUE(res.second); EXPECT_EQ(1, t.size()); t.clear(); EXPECT_EQ(0, t.size()); EXPECT_TRUE(t.find(0) == t.end()); } TYPED_TEST(SooTest, Swap) { TypeParam t; EXPECT_TRUE(t.find(0) == t.end()); auto res = t.emplace(0); EXPECT_TRUE(res.second); EXPECT_EQ(1, t.size()); TypeParam u; t.swap(u); EXPECT_EQ(0, t.size()); EXPECT_EQ(1, u.size()); EXPECT_TRUE(t.find(0) == t.end()); EXPECT_THAT(*u.find(0), 0); } TYPED_TEST(SooTest, Rehash) { TypeParam t; EXPECT_TRUE(t.find(0) == t.end()); t.emplace(0); t.emplace(1); EXPECT_EQ(2, t.size()); t.rehash(128); EXPECT_EQ(2, t.size()); EXPECT_THAT(*t.find(0), 0); EXPECT_THAT(*t.find(1), 1); } TYPED_TEST(SooTest, RehashDoesNotRehashWhenNotNecessary) { TypeParam t; t.emplace(0); t.emplace(1); auto* p = &*t.find(0); t.rehash(1); EXPECT_EQ(p, &*t.find(0)); } TEST(Table, RehashZeroDoesNotAllocateOnEmptyTable) { NonSooIntTable t; t.rehash(0); EXPECT_EQ(0, t.bucket_count()); } TEST(Table, RehashZeroDeallocatesEmptyTable) { NonSooIntTable t; t.emplace(0); t.clear(); EXPECT_NE(0, t.bucket_count()); t.rehash(0); EXPECT_EQ(0, t.bucket_count()); } TYPED_TEST(SooTest, RehashZeroForcesRehash) { TypeParam t; t.emplace(0); t.emplace(1); auto* p = &*t.find(0); t.rehash(0); EXPECT_NE(p, &*t.find(0)); } TEST(Table, ConstructFromInitList) { using P = std::pair<std::string, std::string>; struct Q { operator P() const { return {}; } }; StringTable t = {P(), Q(), {}, {{}, {}}}; } TYPED_TEST(SooTest, CopyConstruct) { TypeParam t; t.emplace(0); EXPECT_EQ(1, t.size()); { TypeParam u(t); EXPECT_EQ(1, u.size()); EXPECT_THAT(*u.find(0), 0); } { TypeParam u{t}; EXPECT_EQ(1, u.size()); EXPECT_THAT(*u.find(0), 0); } { TypeParam u = t; EXPECT_EQ(1, u.size()); EXPECT_THAT(*u.find(0), 0); } } TYPED_TEST(SooTest, CopyDifferentSizes) { TypeParam t; for (int i = 0; i < 100; ++i) { t.emplace(i); TypeParam c = t; for (int j = 0; j <= i; ++j) { ASSERT_TRUE(c.find(j) != c.end()) << "i=" << i << " j=" << j; } ASSERT_TRUE(c.find(-1) == c.end()); } } TYPED_TEST(SooTest, CopyDifferentCapacities) { for (int cap = 1; cap < 100; cap = cap * 2 + 1) { TypeParam t; t.reserve(static_cast<size_t>(cap)); for (int i = 0; i <= cap; ++i) { t.emplace(i); if (i != cap && i % 5 != 0) { continue; } TypeParam c = t; for (int j = 0; j <= i; ++j) { ASSERT_TRUE(c.find(j) != c.end()) << "cap=" << cap << " i=" << i << " j=" << j; } ASSERT_TRUE(c.find(-1) == c.end()); } } } TEST(Table, CopyConstructWithAlloc) { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1, t.size()); StringTable u(t, Alloc<std::pair<std::string, std::string>>()); EXPECT_EQ(1, u.size()); EXPECT_THAT(*u.find("a"), Pair("a", "b")); } struct ExplicitAllocIntTable : raw_hash_set<IntPolicy, hash_default_hash<int64_t>, std::equal_to<int64_t>, Alloc<int64_t>> { ExplicitAllocIntTable() = default; }; TEST(Table, AllocWithExplicitCtor) { ExplicitAllocIntTable t; EXPECT_EQ(0, t.size()); } TEST(Table, MoveConstruct) { { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1, t.size()); StringTable u(std::move(t)); EXPECT_EQ(1, u.size()); EXPECT_THAT(*u.find("a"), Pair("a", "b")); } { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1, t.size()); StringTable u{std::move(t)}; EXPECT_EQ(1, u.size()); EXPECT_THAT(*u.find("a"), Pair("a", "b")); } { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1, t.size()); StringTable u = std::move(t); EXPECT_EQ(1, u.size()); EXPECT_THAT(*u.find("a"), Pair("a", "b")); } } TEST(Table, MoveConstructWithAlloc) { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1, t.size()); StringTable u(std::move(t), Alloc<std::pair<std::string, std::string>>()); EXPECT_EQ(1, u.size()); EXPECT_THAT(*u.find("a"), Pair("a", "b")); } TEST(Table, CopyAssign) { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1, t.size()); StringTable u; u = t; EXPECT_EQ(1, u.size()); EXPECT_THAT(*u.find("a"), Pair("a", "b")); } TEST(Table, CopySelfAssign) { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1, t.size()); t = *&t; EXPECT_EQ(1, t.size()); EXPECT_THAT(*t.find("a"), Pair("a", "b")); } TEST(Table, MoveAssign) { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1, t.size()); StringTable u; u = std::move(t); EXPECT_EQ(1, u.size()); EXPECT_THAT(*u.find("a"), Pair("a", "b")); } TEST(Table, MoveSelfAssign) { StringTable t; t.emplace("a", "b"); EXPECT_EQ(1, t.size()); t = std::move(*&t); if (SwisstableGenerationsEnabled()) { EXPECT_DEATH_IF_SUPPORTED(t.contains("a"), "self-move-assigned"); } } TEST(Table, Equality) { StringTable t; std::vector<std::pair<std::string, std::string>> v = {{"a", "b"}, {"aa", "bb"}}; t.insert(std::begin(v), std::end(v)); StringTable u = t; EXPECT_EQ(u, t); } TEST(Table, Equality2) { StringTable t; std::vector<std::pair<std::string, std::string>> v1 = {{"a", "b"}, {"aa", "bb"}}; t.insert(std::begin(v1), std::end(v1)); StringTable u; std::vector<std::pair<std::string, std::string>> v2 = {{"a", "a"}, {"aa", "aa"}}; u.insert(std::begin(v2), std::end(v2)); EXPECT_NE(u, t); } TEST(Table, Equality3) { StringTable t; std::vector<std::pair<std::string, std::string>> v1 = {{"b", "b"}, {"bb", "bb"}}; t.insert(std::begin(v1), std::end(v1)); StringTable u; std::vector<std::pair<std::string, std::string>> v2 = {{"a", "a"}, {"aa", "aa"}}; u.insert(std::begin(v2), std::end(v2)); EXPECT_NE(u, t); } TYPED_TEST(SooTest, NumDeletedRegression) { TypeParam t; t.emplace(0); t.erase(t.find(0)); t.emplace(0); t.clear(); } TYPED_TEST(SooTest, FindFullDeletedRegression) { TypeParam t; for (int i = 0; i < 1000; ++i) { t.emplace(i); t.erase(t.find(i)); } EXPECT_EQ(0, t.size()); } TYPED_TEST(SooTest, ReplacingDeletedSlotDoesNotRehash) { SetHashtablezEnabled(false); size_t n; { TypeParam t; t.emplace(0); size_t c = t.bucket_count(); for (n = 1; c == t.bucket_count(); ++n) t.emplace(n); --n; } TypeParam t; t.rehash(n); const size_t c = t.bucket_count(); for (size_t i = 0; i != n; ++i) t.emplace(i); EXPECT_EQ(c, t.bucket_count()) << "rehashing threshold = " << n; t.erase(0); t.emplace(0); EXPECT_EQ(c, t.bucket_count()) << "rehashing threshold = " << n; } TEST(Table, NoThrowMoveConstruct) { ASSERT_TRUE( std::is_nothrow_copy_constructible<absl::Hash<absl::string_view>>::value); ASSERT_TRUE(std::is_nothrow_copy_constructible< std::equal_to<absl::string_view>>::value); ASSERT_TRUE(std::is_nothrow_copy_constructible<std::allocator<int>>::value); EXPECT_TRUE(std::is_nothrow_move_constructible<StringTable>::value); } TEST(Table, NoThrowMoveAssign) { ASSERT_TRUE( std::is_nothrow_move_assignable<absl::Hash<absl::string_view>>::value); ASSERT_TRUE( std::is_nothrow_move_assignable<std::equal_to<absl::string_view>>::value); ASSERT_TRUE(std::is_nothrow_move_assignable<std::allocator<int>>::value); ASSERT_TRUE( absl::allocator_traits<std::allocator<int>>::is_always_equal::value); EXPECT_TRUE(std::is_nothrow_move_assignable<StringTable>::value); } TEST(Table, NoThrowSwappable) { ASSERT_TRUE( container_internal::IsNoThrowSwappable<absl::Hash<absl::string_view>>()); ASSERT_TRUE(container_internal::IsNoThrowSwappable< std::equal_to<absl::string_view>>()); ASSERT_TRUE(container_internal::IsNoThrowSwappable<std::allocator<int>>()); EXPECT_TRUE(container_internal::IsNoThrowSwappable<StringTable>()); } TEST(Table, HeterogeneousLookup) { struct Hash { size_t operator()(int64_t i) const { return i; } size_t operator()(double i) const { ADD_FAILURE(); return i; } }; struct Eq { bool operator()(int64_t a, int64_t b) const { return a == b; } bool operator()(double a, int64_t b) const { ADD_FAILURE(); return a == b; } bool operator()(int64_t a, double b) const { ADD_FAILURE(); return a == b; } bool operator()(double a, double b) const { ADD_FAILURE(); return a == b; } }; struct THash { using is_transparent = void; size_t operator()(int64_t i) const { return i; } size_t operator()(double i) const { return i; } }; 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; } bool operator()(int64_t a, double b) const { return a == b; } bool operator()(double a, double b) const { return a == b; } }; raw_hash_set<IntPolicy, Hash, Eq, Alloc<int64_t>> s{0, 1, 2}; EXPECT_EQ(1, *s.find(double{1.1})); raw_hash_set<IntPolicy, THash, TEq, Alloc<int64_t>> ts{0, 1, 2}; EXPECT_TRUE(ts.find(1.1) == ts.end()); } template <class Table> using CallFind = decltype(std::declval<Table&>().find(17)); template <class Table> using CallErase = decltype(std::declval<Table&>().erase(17)); template <class Table> using CallExtract = decltype(std::declval<Table&>().extract(17)); template <class Table> using CallPrefetch = decltype(std::declval<Table&>().prefetch(17)); template <class Table> using CallCount = decltype(std::declval<Table&>().count(17)); template <template <typename> class C, class Table, class = void> struct VerifyResultOf : std::false_type {}; template <template <typename> class C, class Table> struct VerifyResultOf<C, Table, absl::void_t<C<Table>>> : std::true_type {}; TEST(Table, HeterogeneousLookupOverloads) { using NonTransparentTable = raw_hash_set<StringPolicy, absl::Hash<absl::string_view>, std::equal_to<absl::string_view>, std::allocator<int>>; EXPECT_FALSE((VerifyResultOf<CallFind, NonTransparentTable>())); EXPECT_FALSE((VerifyResultOf<CallErase, NonTransparentTable>())); EXPECT_FALSE((VerifyResultOf<CallExtract, NonTransparentTable>())); EXPECT_FALSE((VerifyResultOf<CallPrefetch, NonTransparentTable>())); EXPECT_FALSE((VerifyResultOf<CallCount, NonTransparentTable>())); using TransparentTable = raw_hash_set<StringPolicy, hash_default_hash<absl::string_view>, hash_default_eq<absl::string_view>, std::allocator<int>>; EXPECT_TRUE((VerifyResultOf<CallFind, TransparentTable>())); EXPECT_TRUE((VerifyResultOf<CallErase, TransparentTable>())); EXPECT_TRUE((VerifyResultOf<CallExtract, TransparentTable>())); EXPECT_TRUE((VerifyResultOf<CallPrefetch, TransparentTable>())); EXPECT_TRUE((VerifyResultOf<CallCount, TransparentTable>())); } TEST(Iterator, IsDefaultConstructible) { StringTable::iterator i; EXPECT_TRUE(i == StringTable::iterator()); } TEST(ConstIterator, IsDefaultConstructible) { StringTable::const_iterator i; EXPECT_TRUE(i == StringTable::const_iterator()); } TEST(Iterator, ConvertsToConstIterator) { StringTable::iterator i; EXPECT_TRUE(i == StringTable::const_iterator()); } 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) { StringTable t1, t2; t1.emplace("0", "-0"); t1.emplace("1", "-1"); t2.emplace("0", "~0"); t2.emplace("2", "~2"); EXPECT_THAT(t1, UnorderedElementsAre(Pair("0", "-0"), Pair("1", "-1"))); EXPECT_THAT(t2, UnorderedElementsAre(Pair("0", "~0"), Pair("2", "~2"))); t1.merge(t2); EXPECT_THAT(t1, UnorderedElementsAre(Pair("0", "-0"), Pair("1", "-1"), Pair("2", "~2"))); EXPECT_THAT(t2, UnorderedElementsAre(Pair("0", "~0"))); } TEST(Table, IteratorEmplaceConstructibleRequirement) { struct Value { explicit Value(absl::string_view view) : value(view) {} std::string value; bool operator==(const Value& other) const { return value == other.value; } }; struct H { size_t operator()(const Value& v) const { return absl::Hash<std::string>{}(v.value); } }; struct Table : raw_hash_set<ValuePolicy<Value>, H, std::equal_to<Value>, std::allocator<Value>> { using Base = typename Table::raw_hash_set; using Base::Base; }; std::string input[3]{"A", "B", "C"}; Table t(std::begin(input), std::end(input)); EXPECT_THAT(t, UnorderedElementsAre(Value{"A"}, Value{"B"}, Value{"C"})); input[0] = "D"; input[1] = "E"; input[2] = "F"; t.insert(std::begin(input), std::end(input)); EXPECT_THAT(t, UnorderedElementsAre(Value{"A"}, Value{"B"}, Value{"C"}, Value{"D"}, Value{"E"}, Value{"F"})); } TEST(Nodes, EmptyNodeType) { using node_type = StringTable::node_type; node_type n; EXPECT_FALSE(n); EXPECT_TRUE(n.empty()); EXPECT_TRUE((std::is_same<node_type::allocator_type, StringTable::allocator_type>::value)); } TEST(Nodes, ExtractInsert) { constexpr char k0[] = "Very long string zero."; constexpr char k1[] = "Very long string one."; constexpr char k2[] = "Very long string two."; StringTable t = {{k0, ""}, {k1, ""}, {k2, ""}}; EXPECT_THAT(t, UnorderedElementsAre(Pair(k0, ""), Pair(k1, ""), Pair(k2, ""))); auto node = t.extract(k0); EXPECT_THAT(t, UnorderedElementsAre(Pair(k1, ""), Pair(k2, ""))); EXPECT_TRUE(node); EXPECT_FALSE(node.empty()); StringTable t2; StringTable::insert_return_type res = t2.insert(std::move(node)); EXPECT_TRUE(res.inserted); EXPECT_THAT(*res.position, Pair(k0, "")); EXPECT_FALSE(res.node); EXPECT_THAT(t2, UnorderedElementsAre(Pair(k0, ""))); EXPECT_THAT(t, UnorderedElementsAre(Pair(k1, ""), Pair(k2, ""))); node = t.extract("Not there!"); EXPECT_THAT(t, UnorderedElementsAre(Pair(k1, ""), Pair(k2, ""))); EXPECT_FALSE(node); res = t2.insert(std::move(node)); EXPECT_FALSE(res.inserted); EXPECT_EQ(res.position, t2.end()); EXPECT_FALSE(res.node); EXPECT_THAT(t2, UnorderedElementsAre(Pair(k0, ""))); t.emplace(k0, "1"); node = t.extract(k0); res = t2.insert(std::move(node)); EXPECT_FALSE(res.inserted); EXPECT_THAT(*res.position, Pair(k0, "")); EXPECT_TRUE(res.node); EXPECT_FALSE(node); } TYPED_TEST(SooTest, HintInsert) { TypeParam t = {1, 2, 3}; auto node = t.extract(1); EXPECT_THAT(t, UnorderedElementsAre(2, 3)); auto it = t.insert(t.begin(), std::move(node)); EXPECT_THAT(t, UnorderedElementsAre(1, 2, 3)); EXPECT_EQ(*it, 1); EXPECT_FALSE(node); node = t.extract(2); EXPECT_THAT(t, UnorderedElementsAre(1, 3)); t.insert(2); EXPECT_THAT(t, UnorderedElementsAre(1, 2, 3)); it = t.insert(t.begin(), std::move(node)); EXPECT_EQ(*it, 2); EXPECT_TRUE(node); } template <typename T> T MakeSimpleTable(size_t size) { T t; while (t.size() < size) t.insert(t.size()); return t; } template <typename T> std::vector<int> OrderOfIteration(const T& t) { std::vector<int> res; for (auto i : t) res.push_back(static_cast<int>(i)); return res; } TYPED_TEST(SooTest, IterationOrderChangesByInstance) { for (size_t size : {2, 6, 12, 20}) { const auto reference_table = MakeSimpleTable<TypeParam>(size); const auto reference = OrderOfIteration(reference_table); std::vector<TypeParam> tables; bool found_difference = false; for (int i = 0; !found_difference && i < 5000; ++i) { tables.push_back(MakeSimpleTable<TypeParam>(size)); found_difference = OrderOfIteration(tables.back()) != reference; } if (!found_difference) { FAIL() << "Iteration order remained the same across many attempts with size " << size; } } } TYPED_TEST(SooTest, IterationOrderChangesOnRehash) { for (size_t size : std::vector<size_t>{2, 3, 6, 7, 12, 15, 20, 50}) { for (size_t rehash_size : { size_t{0}, size * 10 }) { std::vector<TypeParam> garbage; bool ok = false; for (int i = 0; i < 5000; ++i) { auto t = MakeSimpleTable<TypeParam>(size); const auto reference = OrderOfIteration(t); t.rehash(rehash_size); auto trial = OrderOfIteration(t); if (trial != reference) { ok = true; break; } garbage.push_back(std::move(t)); } EXPECT_TRUE(ok) << "Iteration order remained the same across many attempts " << size << "->" << rehash_size << "."; } } } TYPED_TEST(SooTest, UnstablePointers) { SetHashtablezEnabled(false); TypeParam table; const auto addr = [&](int i) { return reinterpret_cast<uintptr_t>(&*table.find(i)); }; table.insert(0); const uintptr_t old_ptr = addr(0); table.insert(1); EXPECT_NE(old_ptr, addr(0)); } TEST(TableDeathTest, InvalidIteratorAsserts) { if (!IsAssertEnabled() && !SwisstableGenerationsEnabled()) GTEST_SKIP() << "Assertions not enabled."; NonSooIntTable t; EXPECT_DEATH_IF_SUPPORTED(t.erase(t.end()), "erase.* called on end.. iterator."); typename NonSooIntTable::iterator iter; EXPECT_DEATH_IF_SUPPORTED( ++iter, "operator.* called on default-constructed iterator."); t.insert(0); iter = t.begin(); t.erase(iter); const char* const kErasedDeathMessage = SwisstableGenerationsEnabled() ? "operator.* called on invalid iterator.*was likely erased" : "operator.* called on invalid iterator.*might have been " "erased.*config=asan"; EXPECT_DEATH_IF_SUPPORTED(++iter, kErasedDeathMessage); } TEST(TableDeathTest, InvalidIteratorAssertsSoo) { if (!IsAssertEnabled() && !SwisstableGenerationsEnabled()) GTEST_SKIP() << "Assertions not enabled."; SooIntTable t; EXPECT_DEATH_IF_SUPPORTED(t.erase(t.end()), "erase.* called on end.. iterator."); typename SooIntTable::iterator iter; EXPECT_DEATH_IF_SUPPORTED( ++iter, "operator.* called on default-constructed iterator."); } constexpr const char* kInvalidIteratorDeathMessage = "use-after-free|use-of-uninitialized-value|invalidated " "iterator|Invalid iterator|invalid iterator"; #if defined(_MSC_VER) constexpr bool kMsvc = true; #else constexpr bool kMsvc = false; #endif TYPED_TEST(SooTest, IteratorInvalidAssertsEqualityOperator) { if (!IsAssertEnabled() && !SwisstableGenerationsEnabled()) GTEST_SKIP() << "Assertions not enabled."; TypeParam t; t.insert(1); t.insert(2); t.insert(3); auto iter1 = t.begin(); auto iter2 = std::next(iter1); ASSERT_NE(iter1, t.end()); ASSERT_NE(iter2, t.end()); t.erase(iter1); const char* const kErasedDeathMessage = SwisstableGenerationsEnabled() ? "Invalid iterator comparison.*was likely erased" : "Invalid iterator comparison.*might have been erased.*config=asan"; EXPECT_DEATH_IF_SUPPORTED(void(iter1 == iter2), kErasedDeathMessage); EXPECT_DEATH_IF_SUPPORTED(void(iter2 != iter1), kErasedDeathMessage); t.erase(iter2); EXPECT_DEATH_IF_SUPPORTED(void(iter1 == iter2), kErasedDeathMessage); TypeParam t1, t2; t1.insert(0); t2.insert(0); iter1 = t1.begin(); iter2 = t2.begin(); const char* const kContainerDiffDeathMessage = SwisstableGenerationsEnabled() ? "Invalid iterator comparison.*iterators from different.* hashtables" : "Invalid iterator comparison.*may be from different " ".*containers.*config=asan"; EXPECT_DEATH_IF_SUPPORTED(void(iter1 == iter2), kContainerDiffDeathMessage); EXPECT_DEATH_IF_SUPPORTED(void(iter2 == iter1), kContainerDiffDeathMessage); } TYPED_TEST(SooTest, IteratorInvalidAssertsEqualityOperatorRehash) { if (!IsAssertEnabled() && !SwisstableGenerationsEnabled()) GTEST_SKIP() << "Assertions not enabled."; if (kMsvc) GTEST_SKIP() << "MSVC doesn't support | in regex."; #ifdef ABSL_HAVE_THREAD_SANITIZER GTEST_SKIP() << "ThreadSanitizer test runs fail on use-after-free even in " "EXPECT_DEATH."; #endif TypeParam t; t.insert(0); auto iter = t.begin(); for (int i = 0; i < 10; ++i) t.insert(i); const char* const kRehashedDeathMessage = SwisstableGenerationsEnabled() ? kInvalidIteratorDeathMessage : "Invalid iterator comparison.*might have rehashed.*config=asan"; EXPECT_DEATH_IF_SUPPORTED(void(iter == t.begin()), kRehashedDeathMessage); } #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) template <typename T> class RawHashSamplerTest : public testing::Test {}; using RawHashSamplerTestTypes = ::testing::Types<SooIntTable, NonSooIntTable>; TYPED_TEST_SUITE(RawHashSamplerTest, RawHashSamplerTestTypes); TYPED_TEST(RawHashSamplerTest, Sample) { constexpr bool soo_enabled = std::is_same<SooIntTable, TypeParam>::value; SetHashtablezEnabled(true); SetHashtablezSampleParameter(100); auto& sampler = GlobalHashtablezSampler(); size_t start_size = 0; absl::flat_hash_set<const HashtablezInfo*> preexisting_info; start_size += sampler.Iterate([&](const HashtablezInfo& info) { preexisting_info.insert(&info); ++start_size; }); std::vector<TypeParam> tables; for (int i = 0; i < 1000000; ++i) { tables.emplace_back(); const bool do_reserve = (i % 10 > 5); const bool do_rehash = !do_reserve && (i % 10 > 0); if (do_reserve) { tables.back().reserve(10 * (i % 10)); } tables.back().insert(1); tables.back().insert(i % 5); if (do_rehash) { tables.back().rehash(10 * (i % 10)); } } size_t end_size = 0; absl::flat_hash_map<size_t, int> observed_checksums; absl::flat_hash_map<ssize_t, int> reservations; end_size += sampler.Iterate([&](const HashtablezInfo& info) { ++end_size; if (preexisting_info.contains(&info)) return; observed_checksums[info.hashes_bitwise_xor.load( std::memory_order_relaxed)]++; reservations[info.max_reserve.load(std::memory_order_relaxed)]++; EXPECT_EQ(info.inline_element_size, sizeof(typename TypeParam::value_type)); EXPECT_EQ(info.key_size, sizeof(typename TypeParam::key_type)); EXPECT_EQ(info.value_size, sizeof(typename TypeParam::value_type)); if (soo_enabled) { EXPECT_EQ(info.soo_capacity, SooCapacity()); } else { EXPECT_EQ(info.soo_capacity, 0); } }); EXPECT_NEAR((end_size - start_size) / static_cast<double>(tables.size()), 0.01, 0.005); EXPECT_EQ(observed_checksums.size(), 5); for (const auto& [_, count] : observed_checksums) { EXPECT_NEAR((100 * count) / static_cast<double>(tables.size()), 0.2, 0.05); } EXPECT_EQ(reservations.size(), 10); for (const auto& [reservation, count] : reservations) { EXPECT_GE(reservation, 0); EXPECT_LT(reservation, 100); EXPECT_NEAR((100 * count) / static_cast<double>(tables.size()), 0.1, 0.05) << reservation; } } std::vector<const HashtablezInfo*> SampleSooMutation( absl::FunctionRef<void(SooIntTable&)> mutate_table) { SetHashtablezEnabled(true); SetHashtablezSampleParameter(100); auto& sampler = GlobalHashtablezSampler(); size_t start_size = 0; absl::flat_hash_set<const HashtablezInfo*> preexisting_info; start_size += sampler.Iterate([&](const HashtablezInfo& info) { preexisting_info.insert(&info); ++start_size; }); std::vector<SooIntTable> tables; for (int i = 0; i < 1000000; ++i) { tables.emplace_back(); mutate_table(tables.back()); } size_t end_size = 0; std::vector<const HashtablezInfo*> infos; end_size += sampler.Iterate([&](const HashtablezInfo& info) { ++end_size; if (preexisting_info.contains(&info)) return; infos.push_back(&info); }); EXPECT_NEAR((end_size - start_size) / static_cast<double>(tables.size()), 0.01, 0.005); return infos; } TEST(RawHashSamplerTest, SooTableInsertToEmpty) { if (SooIntTable().capacity() != SooCapacity()) { CHECK_LT(sizeof(void*), 8) << "missing SOO coverage"; GTEST_SKIP() << "not SOO on this platform"; } std::vector<const HashtablezInfo*> infos = SampleSooMutation([](SooIntTable& t) { t.insert(1); }); for (const HashtablezInfo* info : infos) { ASSERT_EQ(info->inline_element_size, sizeof(typename SooIntTable::value_type)); ASSERT_EQ(info->soo_capacity, SooCapacity()); ASSERT_EQ(info->capacity, NextCapacity(SooCapacity())); ASSERT_EQ(info->size, 1); ASSERT_EQ(info->max_reserve, 0); ASSERT_EQ(info->num_erases, 0); ASSERT_EQ(info->max_probe_length, 0); ASSERT_EQ(info->total_probe_length, 0); } } TEST(RawHashSamplerTest, SooTableReserveToEmpty) { if (SooIntTable().capacity() != SooCapacity()) { CHECK_LT(sizeof(void*), 8) << "missing SOO coverage"; GTEST_SKIP() << "not SOO on this platform"; } std::vector<const HashtablezInfo*> infos = SampleSooMutation([](SooIntTable& t) { t.reserve(100); }); for (const HashtablezInfo* info : infos) { ASSERT_EQ(info->inline_element_size, sizeof(typename SooIntTable::value_type)); ASSERT_EQ(info->soo_capacity, SooCapacity()); ASSERT_GE(info->capacity, 100); ASSERT_EQ(info->size, 0); ASSERT_EQ(info->max_reserve, 100); ASSERT_EQ(info->num_erases, 0); ASSERT_EQ(info->max_probe_length, 0); ASSERT_EQ(info->total_probe_length, 0); } } TEST(RawHashSamplerTest, SooTableReserveToFullSoo) { if (SooIntTable().capacity() != SooCapacity()) { CHECK_LT(sizeof(void*), 8) << "missing SOO coverage"; GTEST_SKIP() << "not SOO on this platform"; } std::vector<const HashtablezInfo*> infos = SampleSooMutation([](SooIntTable& t) { t.insert(1); t.reserve(100); }); for (const HashtablezInfo* info : infos) { ASSERT_EQ(info->inline_element_size, sizeof(typename SooIntTable::value_type)); ASSERT_EQ(info->soo_capacity, SooCapacity()); ASSERT_GE(info->capacity, 100); ASSERT_EQ(info->size, 1); ASSERT_EQ(info->max_reserve, 100); ASSERT_EQ(info->num_erases, 0); ASSERT_EQ(info->max_probe_length, 0); ASSERT_EQ(info->total_probe_length, 0); } } TEST(RawHashSamplerTest, SooTableRehashShrinkWhenSizeFitsInSoo) { if (SooIntTable().capacity() != SooCapacity()) { CHECK_LT(sizeof(void*), 8) << "missing SOO coverage"; GTEST_SKIP() << "not SOO on this platform"; } std::vector<const HashtablezInfo*> infos = SampleSooMutation([](SooIntTable& t) { t.reserve(100); t.insert(1); EXPECT_GE(t.capacity(), 100); t.rehash(0); }); for (const HashtablezInfo* info : infos) { ASSERT_EQ(info->inline_element_size, sizeof(typename SooIntTable::value_type)); ASSERT_EQ(info->soo_capacity, SooCapacity()); ASSERT_EQ(info->capacity, NextCapacity(SooCapacity())); ASSERT_EQ(info->size, 1); ASSERT_EQ(info->max_reserve, 100); ASSERT_EQ(info->num_erases, 0); ASSERT_EQ(info->max_probe_length, 0); ASSERT_EQ(info->total_probe_length, 0); } } #endif TEST(RawHashSamplerTest, DoNotSampleCustomAllocators) { SetHashtablezEnabled(true); SetHashtablezSampleParameter(100); auto& sampler = GlobalHashtablezSampler(); size_t start_size = 0; start_size += sampler.Iterate([&](const HashtablezInfo&) { ++start_size; }); std::vector<CustomAllocIntTable> tables; for (int i = 0; i < 1000000; ++i) { tables.emplace_back(); tables.back().insert(1); } size_t end_size = 0; end_size += sampler.Iterate([&](const HashtablezInfo&) { ++end_size; }); EXPECT_NEAR((end_size - start_size) / static_cast<double>(tables.size()), 0.00, 0.001); } #ifdef ABSL_HAVE_ADDRESS_SANITIZER template <class TableType> class SanitizerTest : public testing::Test {}; using SanitizerTableTypes = ::testing::Types<IntTable, TransferableIntTable>; TYPED_TEST_SUITE(SanitizerTest, SanitizerTableTypes); TYPED_TEST(SanitizerTest, PoisoningUnused) { TypeParam t; for (size_t reserve_size = 2; reserve_size < 1024; reserve_size = reserve_size * 3 / 2) { t.reserve(reserve_size); int64_t& v = *t.insert(0).first; ASSERT_GT(t.capacity(), 1); int64_t* slots = RawHashSetTestOnlyAccess::GetSlots(t); for (size_t i = 0; i < t.capacity(); ++i) { EXPECT_EQ(slots + i != &v, __asan_address_is_poisoned(slots + i)) << i; } } } TEST(Sanitizer, PoisoningOnErase) { NonSooIntTable t; auto& v = *t.insert(0).first; EXPECT_FALSE(__asan_address_is_poisoned(&v)); t.erase(0); EXPECT_TRUE(__asan_address_is_poisoned(&v)); } #endif template <typename T> class AlignOneTest : public ::testing::Test {}; using AlignOneTestTypes = ::testing::Types<Uint8Table, MinimumAlignmentUint8Table>; TYPED_TEST_SUITE(AlignOneTest, AlignOneTestTypes); TYPED_TEST(AlignOneTest, AlignOne) { TypeParam t; std::unordered_set<uint8_t> verifier; for (int64_t i = 0; i < 100000; ++i) { SCOPED_TRACE(i); const uint8_t u = (i * -i) & 0xFF; auto it = t.find(u); auto verifier_it = verifier.find(u); if (it == t.end()) { ASSERT_EQ(verifier_it, verifier.end()); t.insert(u); verifier.insert(u); } else { ASSERT_NE(verifier_it, verifier.end()); t.erase(it); verifier.erase(verifier_it); } } EXPECT_EQ(t.size(), verifier.size()); for (uint8_t u : t) { EXPECT_EQ(verifier.count(u), 1); } } TEST(Iterator, InvalidUseCrashesWithSanitizers) { if (!SwisstableGenerationsEnabled()) GTEST_SKIP() << "Generations disabled."; if (kMsvc) GTEST_SKIP() << "MSVC doesn't support | in regexp."; NonSooIntTable t; t.insert(-1); for (int i = 0; i < 10; ++i) { auto it = t.begin(); t.insert(i); EXPECT_DEATH_IF_SUPPORTED(*it, kInvalidIteratorDeathMessage); EXPECT_DEATH_IF_SUPPORTED(void(it == t.begin()), kInvalidIteratorDeathMessage); } } TEST(Iterator, InvalidUseWithReserveCrashesWithSanitizers) { if (!SwisstableGenerationsEnabled()) GTEST_SKIP() << "Generations disabled."; if (kMsvc) GTEST_SKIP() << "MSVC doesn't support | in regexp."; IntTable t; t.reserve(10); t.insert(0); auto it = t.begin(); for (int i = 1; i < 10; ++i) { t.insert(i); EXPECT_EQ(*it, 0); } const int64_t* ptr = &*it; (void)ptr; t.erase(0); t.insert(10); EXPECT_DEATH_IF_SUPPORTED(*it, kInvalidIteratorDeathMessage); EXPECT_DEATH_IF_SUPPORTED(void(it == t.begin()), kInvalidIteratorDeathMessage); #ifdef ABSL_HAVE_ADDRESS_SANITIZER EXPECT_DEATH_IF_SUPPORTED(std::cout << *ptr, "heap-use-after-free"); #endif } TEST(Iterator, InvalidUseWithMoveCrashesWithSanitizers) { if (!SwisstableGenerationsEnabled()) GTEST_SKIP() << "Generations disabled."; if (kMsvc) GTEST_SKIP() << "MSVC doesn't support | in regexp."; NonSooIntTable t1, t2; t1.insert(1); auto it = t1.begin(); const auto* ptr = &*it; (void)ptr; t2 = std::move(t1); EXPECT_DEATH_IF_SUPPORTED(*it, kInvalidIteratorDeathMessage); EXPECT_DEATH_IF_SUPPORTED(void(it == t2.begin()), kInvalidIteratorDeathMessage); #ifdef ABSL_HAVE_ADDRESS_SANITIZER EXPECT_DEATH_IF_SUPPORTED(std::cout << **ptr, "heap-use-after-free"); #endif } TYPED_TEST(SooTest, ReservedGrowthUpdatesWhenTableDoesntGrow) { TypeParam t; for (int i = 0; i < 8; ++i) t.insert(i); const size_t cap = t.capacity(); t.reserve(t.size() + 2); ASSERT_EQ(cap, t.capacity()); auto it = t.find(0); t.insert(100); t.insert(200); EXPECT_EQ(*it, 0); } template <class TableType> class InstanceTrackerTest : public testing::Test {}; using ::absl::test_internal::CopyableMovableInstance; using ::absl::test_internal::InstanceTracker; struct InstanceTrackerHash { size_t operator()(const CopyableMovableInstance& t) const { return absl::HashOf(t.value()); } }; using InstanceTrackerTableTypes = ::testing::Types< absl::node_hash_set<CopyableMovableInstance, InstanceTrackerHash>, absl::flat_hash_set<CopyableMovableInstance, InstanceTrackerHash>>; TYPED_TEST_SUITE(InstanceTrackerTest, InstanceTrackerTableTypes); TYPED_TEST(InstanceTrackerTest, EraseIfAll) { using Table = TypeParam; InstanceTracker tracker; for (int size = 0; size < 100; ++size) { Table t; for (int i = 0; i < size; ++i) { t.emplace(i); } absl::erase_if(t, [](const auto&) { return true; }); ASSERT_EQ(t.size(), 0); } EXPECT_EQ(tracker.live_instances(), 0); } TYPED_TEST(InstanceTrackerTest, EraseIfNone) { using Table = TypeParam; InstanceTracker tracker; { Table t; for (size_t size = 0; size < 100; ++size) { absl::erase_if(t, [](const auto&) { return false; }); ASSERT_EQ(t.size(), size); t.emplace(size); } } EXPECT_EQ(tracker.live_instances(), 0); } TYPED_TEST(InstanceTrackerTest, EraseIfPartial) { using Table = TypeParam; InstanceTracker tracker; for (int mod : {0, 1}) { for (int size = 0; size < 100; ++size) { SCOPED_TRACE(absl::StrCat(mod, " ", size)); Table t; std::vector<CopyableMovableInstance> expected; for (int i = 0; i < size; ++i) { t.emplace(i); if (i % 2 != mod) { expected.emplace_back(i); } } absl::erase_if(t, [mod](const auto& x) { return x.value() % 2 == mod; }); ASSERT_THAT(t, testing::UnorderedElementsAreArray(expected)); } } EXPECT_EQ(tracker.live_instances(), 0); } TYPED_TEST(SooTest, EraseIfAll) { auto pred = [](const auto&) { return true; }; for (int size = 0; size < 100; ++size) { TypeParam t; for (int i = 0; i < size; ++i) t.insert(i); absl::container_internal::EraseIf(pred, &t); ASSERT_EQ(t.size(), 0); } } TYPED_TEST(SooTest, EraseIfNone) { auto pred = [](const auto&) { return false; }; TypeParam t; for (size_t size = 0; size < 100; ++size) { absl::container_internal::EraseIf(pred, &t); ASSERT_EQ(t.size(), size); t.insert(size); } } TYPED_TEST(SooTest, EraseIfPartial) { for (int mod : {0, 1}) { auto pred = [&](const auto& x) { return static_cast<int64_t>(x) % 2 == mod; }; for (int size = 0; size < 100; ++size) { SCOPED_TRACE(absl::StrCat(mod, " ", size)); TypeParam t; std::vector<int64_t> expected; for (int i = 0; i < size; ++i) { t.insert(i); if (i % 2 != mod) { expected.push_back(i); } } absl::container_internal::EraseIf(pred, &t); ASSERT_THAT(t, testing::UnorderedElementsAreArray(expected)); } } } TYPED_TEST(SooTest, ForEach) { TypeParam t; std::vector<int64_t> expected; for (int size = 0; size < 100; ++size) { SCOPED_TRACE(size); { SCOPED_TRACE("mutable iteration"); std::vector<int64_t> actual; auto f = [&](auto& x) { actual.push_back(static_cast<int64_t>(x)); }; absl::container_internal::ForEach(f, &t); ASSERT_THAT(actual, testing::UnorderedElementsAreArray(expected)); } { SCOPED_TRACE("const iteration"); std::vector<int64_t> actual; auto f = [&](auto& x) { static_assert( std::is_const<std::remove_reference_t<decltype(x)>>::value, "no mutable values should be passed to const ForEach"); actual.push_back(static_cast<int64_t>(x)); }; const auto& ct = t; absl::container_internal::ForEach(f, &ct); ASSERT_THAT(actual, testing::UnorderedElementsAreArray(expected)); } t.insert(size); expected.push_back(size); } } TEST(Table, ForEachMutate) { StringTable t; using ValueType = StringTable::value_type; std::vector<ValueType> expected; for (int size = 0; size < 100; ++size) { SCOPED_TRACE(size); std::vector<ValueType> actual; auto f = [&](ValueType& x) { actual.push_back(x); x.second += "a"; }; absl::container_internal::ForEach(f, &t); ASSERT_THAT(actual, testing::UnorderedElementsAreArray(expected)); for (ValueType& v : expected) { v.second += "a"; } ASSERT_THAT(t, testing::UnorderedElementsAreArray(expected)); t.emplace(std::to_string(size), std::to_string(size)); expected.emplace_back(std::to_string(size), std::to_string(size)); } } TYPED_TEST(SooTest, EraseIfReentryDeath) { if (!IsAssertEnabled()) GTEST_SKIP() << "Assertions not enabled."; auto erase_if_with_removal_reentrance = [](size_t reserve_size) { TypeParam t; t.reserve(reserve_size); int64_t first_value = -1; t.insert(1024); t.insert(5078); auto pred = [&](const auto& x) { if (first_value == -1) { first_value = static_cast<int64_t>(x); return false; } t.erase(first_value); return true; }; absl::container_internal::EraseIf(pred, &t); }; EXPECT_DEATH_IF_SUPPORTED(erase_if_with_removal_reentrance(1024 * 16), "hash table was modified unexpectedly"); EXPECT_DEATH_IF_SUPPORTED( erase_if_with_removal_reentrance(CapacityToGrowth(Group::kWidth - 1)), "hash table was modified unexpectedly"); } TYPED_TEST(SooTest, EraseIfReentrySingleElementDeath) { if (!IsAssertEnabled()) GTEST_SKIP() << "Assertions not enabled."; auto erase_if_with_removal_reentrance = []() { TypeParam t; t.insert(1024); auto pred = [&](const auto& x) { t.erase(static_cast<int64_t>(x)); return false; }; absl::container_internal::EraseIf(pred, &t); }; EXPECT_DEATH_IF_SUPPORTED(erase_if_with_removal_reentrance(), "hash table was modified unexpectedly"); } TEST(Table, EraseBeginEndResetsReservedGrowth) { bool frozen = false; BadHashFreezableIntTable t{FreezableAlloc<int64_t>(&frozen)}; t.reserve(100); const size_t cap = t.capacity(); frozen = true; for (int i = 0; i < 10; ++i) { for (int j = 0; j < 100; ++j) t.insert(j); for (int j = 30; j < 60; ++j) t.erase(j); EXPECT_EQ(t.size(), 70); EXPECT_EQ(t.capacity(), cap); ASSERT_EQ(RawHashSetTestOnlyAccess::CountTombstones(t), 30); t.erase(t.begin(), t.end()); EXPECT_EQ(t.size(), 0); EXPECT_EQ(t.capacity(), cap); ASSERT_EQ(RawHashSetTestOnlyAccess::CountTombstones(t), 0); } } TEST(Table, GenerationInfoResetsOnClear) { if (!SwisstableGenerationsEnabled()) GTEST_SKIP() << "Generations disabled."; if (kMsvc) GTEST_SKIP() << "MSVC doesn't support | in regexp."; NonSooIntTable t; for (int i = 0; i < 1000; ++i) t.insert(i); t.reserve(t.size() + 100); t.clear(); t.insert(0); auto it = t.begin(); t.insert(1); EXPECT_DEATH_IF_SUPPORTED(*it, kInvalidIteratorDeathMessage); } TEST(Table, InvalidReferenceUseCrashesWithSanitizers) { if (!SwisstableGenerationsEnabled()) GTEST_SKIP() << "Generations disabled."; #ifdef ABSL_HAVE_MEMORY_SANITIZER GTEST_SKIP() << "MSan fails to detect some of these rehashes."; #endif NonSooIntTable t; t.insert(0); int i = 0; while (t.capacity() <= RehashProbabilityConstant()) { const auto* ptr = &*t.begin(); t.insert(++i); EXPECT_DEATH_IF_SUPPORTED(std::cout << **ptr, "use-after-free") << i; } } TEST(Iterator, InvalidComparisonDifferentTables) { if (!SwisstableGenerationsEnabled()) GTEST_SKIP() << "Generations disabled."; NonSooIntTable t1, t2; NonSooIntTable::iterator default_constructed_iter; EXPECT_DEATH_IF_SUPPORTED(void(t1.end() == t2.end()), "Invalid iterator comparison.*empty hashtables"); EXPECT_DEATH_IF_SUPPORTED(void(t1.end() == default_constructed_iter), "Invalid iterator comparison.*default-constructed"); t1.insert(0); EXPECT_DEATH_IF_SUPPORTED(void(t1.begin() == t2.end()), "Invalid iterator comparison.*empty hashtable"); EXPECT_DEATH_IF_SUPPORTED(void(t1.begin() == default_constructed_iter), "Invalid iterator comparison.*default-constructed"); t2.insert(0); EXPECT_DEATH_IF_SUPPORTED(void(t1.begin() == t2.end()), "Invalid iterator comparison.*end.. iterator"); EXPECT_DEATH_IF_SUPPORTED(void(t1.begin() == t2.begin()), "Invalid iterator comparison.*non-end"); } template <typename Alloc> using RawHashSetAlloc = raw_hash_set<IntPolicy, hash_default_hash<int64_t>, std::equal_to<int64_t>, Alloc>; TEST(Table, AllocatorPropagation) { TestAllocPropagation<RawHashSetAlloc>(); } struct CountedHash { size_t operator()(int64_t value) const { ++count; return static_cast<size_t>(value); } mutable int count = 0; }; struct CountedHashIntTable : raw_hash_set<IntPolicy, CountedHash, std::equal_to<int>, std::allocator<int>> { using Base = typename CountedHashIntTable::raw_hash_set; using Base::Base; }; TEST(Table, CountedHash) { #ifdef NDEBUG constexpr bool kExpectMinimumHashes = true; #else constexpr bool kExpectMinimumHashes = false; #endif if (!kExpectMinimumHashes) { GTEST_SKIP() << "Only run under NDEBUG: `assert` statements may cause " "redundant hashing."; } using Table = CountedHashIntTable; auto HashCount = [](const Table& t) { return t.hash_function().count; }; { Table t; EXPECT_EQ(HashCount(t), 0); } { Table t; t.insert(1); EXPECT_EQ(HashCount(t), 1); t.erase(1); EXPECT_EQ(HashCount(t), 2); } { Table t; t.insert(3); EXPECT_EQ(HashCount(t), 1); auto node = t.extract(3); EXPECT_EQ(HashCount(t), 2); t.insert(std::move(node)); EXPECT_EQ(HashCount(t), 3); } { Table t; t.emplace(5); EXPECT_EQ(HashCount(t), 1); } { Table src; src.insert(7); Table dst; dst.merge(src); EXPECT_EQ(HashCount(dst), 1); } } TEST(Table, IterateOverFullSlotsEmpty) { NonSooIntTable t; auto fail_if_any = [](const ctrl_t*, auto* i) { FAIL() << "expected no slots " << **i; }; container_internal::IterateOverFullSlots( RawHashSetTestOnlyAccess::GetCommon(t), RawHashSetTestOnlyAccess::GetSlots(t), fail_if_any); for (size_t i = 0; i < 256; ++i) { t.reserve(i); container_internal::IterateOverFullSlots( RawHashSetTestOnlyAccess::GetCommon(t), RawHashSetTestOnlyAccess::GetSlots(t), fail_if_any); } } TEST(Table, IterateOverFullSlotsFull) { NonSooIntTable t; std::vector<int64_t> expected_slots; for (int64_t idx = 0; idx < 128; ++idx) { t.insert(idx); expected_slots.push_back(idx); std::vector<int64_t> slots; container_internal::IterateOverFullSlots( RawHashSetTestOnlyAccess::GetCommon(t), RawHashSetTestOnlyAccess::GetSlots(t), [&t, &slots](const ctrl_t* ctrl, auto* i) { ptrdiff_t ctrl_offset = ctrl - RawHashSetTestOnlyAccess::GetCommon(t).control(); ptrdiff_t slot_offset = i - RawHashSetTestOnlyAccess::GetSlots(t); ASSERT_EQ(ctrl_offset, slot_offset); slots.push_back(**i); }); EXPECT_THAT(slots, testing::UnorderedElementsAreArray(expected_slots)); } } TEST(Table, IterateOverFullSlotsDeathOnRemoval) { if (!IsAssertEnabled()) GTEST_SKIP() << "Assertions not enabled."; auto iterate_with_reentrant_removal = [](int64_t size, int64_t reserve_size = -1) { if (reserve_size == -1) reserve_size = size; for (int64_t idx = 0; idx < size; ++idx) { NonSooIntTable t; t.reserve(static_cast<size_t>(reserve_size)); for (int val = 0; val <= idx; ++val) { t.insert(val); } container_internal::IterateOverFullSlots( RawHashSetTestOnlyAccess::GetCommon(t), RawHashSetTestOnlyAccess::GetSlots(t), [&t](const ctrl_t*, auto* i) { int64_t value = **i; t.erase(value ^ 1); }); } }; EXPECT_DEATH_IF_SUPPORTED(iterate_with_reentrant_removal(128), "hash table was modified unexpectedly"); EXPECT_DEATH_IF_SUPPORTED(iterate_with_reentrant_removal(14, 1024 * 16), "hash table was modified unexpectedly"); EXPECT_DEATH_IF_SUPPORTED(iterate_with_reentrant_removal(static_cast<int64_t>( CapacityToGrowth(Group::kWidth - 1))), "hash table was modified unexpectedly"); } TEST(Table, IterateOverFullSlotsDeathOnInsert) { if (!IsAssertEnabled()) GTEST_SKIP() << "Assertions not enabled."; auto iterate_with_reentrant_insert = [](int64_t reserve_size, int64_t size_divisor = 2) { int64_t size = reserve_size / size_divisor; for (int64_t idx = 1; idx <= size; ++idx) { NonSooIntTable t; t.reserve(static_cast<size_t>(reserve_size)); for (int val = 1; val <= idx; ++val) { t.insert(val); } container_internal::IterateOverFullSlots( RawHashSetTestOnlyAccess::GetCommon(t), RawHashSetTestOnlyAccess::GetSlots(t), [&t](const ctrl_t*, auto* i) { int64_t value = **i; t.insert(-value); }); } }; EXPECT_DEATH_IF_SUPPORTED(iterate_with_reentrant_insert(128), "hash table was modified unexpectedly"); EXPECT_DEATH_IF_SUPPORTED(iterate_with_reentrant_insert(1024 * 16, 1024 * 2), "hash table was modified unexpectedly"); EXPECT_DEATH_IF_SUPPORTED(iterate_with_reentrant_insert(static_cast<int64_t>( CapacityToGrowth(Group::kWidth - 1))), "hash table was modified unexpectedly"); } template <typename T> class SooTable : public testing::Test {}; using FreezableSooTableTypes = ::testing::Types<FreezableSizedValueSooTable<8>, FreezableSizedValueSooTable<16>>; TYPED_TEST_SUITE(SooTable, FreezableSooTableTypes); TYPED_TEST(SooTable, Basic) { bool frozen = true; TypeParam t{FreezableAlloc<typename TypeParam::value_type>(&frozen)}; if (t.capacity() != SooCapacity()) { CHECK_LT(sizeof(void*), 8) << "missing SOO coverage"; GTEST_SKIP() << "not SOO on this platform"; } t.insert(0); EXPECT_EQ(t.capacity(), 1); auto it = t.find(0); EXPECT_EQ(it, t.begin()); ASSERT_NE(it, t.end()); EXPECT_EQ(*it, 0); EXPECT_EQ(++it, t.end()); EXPECT_EQ(t.find(1), t.end()); EXPECT_EQ(t.size(), 1); t.erase(0); EXPECT_EQ(t.size(), 0); t.insert(1); it = t.find(1); EXPECT_EQ(it, t.begin()); ASSERT_NE(it, t.end()); EXPECT_EQ(*it, 1); t.clear(); EXPECT_EQ(t.size(), 0); } TEST(Table, RehashToSooUnsampled) { SooIntTable t; if (t.capacity() != SooCapacity()) { CHECK_LT(sizeof(void*), 8) << "missing SOO coverage"; GTEST_SKIP() << "not SOO on this platform"; } SetHashtablezEnabled(false); t.reserve(100); t.insert(0); EXPECT_EQ(*t.begin(), 0); t.rehash(0); EXPECT_EQ(t.capacity(), SooCapacity()); EXPECT_EQ(t.size(), 1); EXPECT_EQ(*t.begin(), 0); EXPECT_EQ(t.find(0), t.begin()); EXPECT_EQ(t.find(1), t.end()); } TEST(Table, ReserveToNonSoo) { for (int reserve_capacity : {8, 100000}) { SooIntTable t; t.insert(0); t.reserve(reserve_capacity); EXPECT_EQ(t.find(0), t.begin()); EXPECT_EQ(t.size(), 1); EXPECT_EQ(*t.begin(), 0); EXPECT_EQ(t.find(1), t.end()); } } struct InconsistentHashEqType { InconsistentHashEqType(int v1, int v2) : v1(v1), v2(v2) {} template <typename H> friend H AbslHashValue(H h, InconsistentHashEqType t) { return H::combine(std::move(h), t.v1); } bool operator==(InconsistentHashEqType t) const { return v2 == t.v2; } int v1, v2; }; TEST(Iterator, InconsistentHashEqFunctorsValidation) { if (!IsAssertEnabled()) GTEST_SKIP() << "Assertions not enabled."; ValueTable<InconsistentHashEqType> t; for (int i = 0; i < 10; ++i) t.insert({i, i}); auto find_conflicting_elems = [&] { for (int i = 100; i < 20000; ++i) { EXPECT_EQ(t.find({i, 0}), t.end()); } }; EXPECT_DEATH_IF_SUPPORTED(find_conflicting_elems(), "hash/eq functors are inconsistent."); auto insert_conflicting_elems = [&] { for (int i = 100; i < 20000; ++i) { EXPECT_EQ(t.insert({i, 0}).second, false); } }; EXPECT_DEATH_IF_SUPPORTED(insert_conflicting_elems(), "hash/eq functors are inconsistent."); } struct ConstructCaller { explicit ConstructCaller(int v) : val(v) {} ConstructCaller(int v, absl::FunctionRef<void()> func) : val(v) { func(); } template <typename H> friend H AbslHashValue(H h, const ConstructCaller& d) { return H::combine(std::move(h), d.val); } bool operator==(const ConstructCaller& c) const { return val == c.val; } int val; }; struct DestroyCaller { explicit DestroyCaller(int v) : val(v) {} DestroyCaller(int v, absl::FunctionRef<void()> func) : val(v), destroy_func(func) {} DestroyCaller(DestroyCaller&& that) : val(that.val), destroy_func(std::move(that.destroy_func)) { that.Deactivate(); } ~DestroyCaller() { if (destroy_func) (*destroy_func)(); } void Deactivate() { destroy_func = absl::nullopt; } template <typename H> friend H AbslHashValue(H h, const DestroyCaller& d) { return H::combine(std::move(h), d.val); } bool operator==(const DestroyCaller& d) const { return val == d.val; } int val; absl::optional<absl::FunctionRef<void()>> destroy_func; }; TEST(Table, ReentrantCallsFail) { #ifdef NDEBUG GTEST_SKIP() << "Reentrant checks only enabled in debug mode."; #else { ValueTable<ConstructCaller> t; t.insert(ConstructCaller{0}); auto erase_begin = [&] { t.erase(t.begin()); }; EXPECT_DEATH_IF_SUPPORTED(t.emplace(1, erase_begin), ""); } { ValueTable<DestroyCaller> t; t.insert(DestroyCaller{0}); auto find_0 = [&] { t.find(DestroyCaller{0}); }; t.insert(DestroyCaller{1, find_0}); for (int i = 10; i < 20; ++i) t.insert(DestroyCaller{i}); EXPECT_DEATH_IF_SUPPORTED(t.clear(), ""); for (auto& elem : t) elem.Deactivate(); } { ValueTable<DestroyCaller> t; t.insert(DestroyCaller{0}); auto insert_1 = [&] { t.insert(DestroyCaller{1}); }; t.insert(DestroyCaller{1, insert_1}); for (int i = 10; i < 20; ++i) t.insert(DestroyCaller{i}); EXPECT_DEATH_IF_SUPPORTED(t.clear(), ""); for (auto& elem : t) elem.Deactivate(); } #endif } TEST(Table, DestroyedCallsFail) { #ifdef NDEBUG GTEST_SKIP() << "Destroyed checks only enabled in debug mode."; #else absl::optional<IntTable> t; t.emplace({1}); IntTable* t_ptr = &*t; EXPECT_TRUE(t_ptr->contains(1)); t.reset(); EXPECT_DEATH_IF_SUPPORTED(t_ptr->contains(1), ""); #endif } TEST(Table, MovedFromCallsFail) { if (!SwisstableGenerationsEnabled()) { GTEST_SKIP() << "Moved-from checks only enabled in sanitizer mode."; return; } { ABSL_ATTRIBUTE_UNUSED IntTable t1, t2, t3; t1.insert(1); t2 = std::move(t1); EXPECT_DEATH_IF_SUPPORTED(t1.contains(1), "moved-from"); EXPECT_DEATH_IF_SUPPORTED(t1.swap(t3), "moved-from"); EXPECT_DEATH_IF_SUPPORTED(t1.merge(t3), "moved-from"); EXPECT_DEATH_IF_SUPPORTED(IntTable{t1}, "moved-from"); EXPECT_DEATH_IF_SUPPORTED(t1.begin(), "moved-from"); EXPECT_DEATH_IF_SUPPORTED(t1.end(), "moved-from"); EXPECT_DEATH_IF_SUPPORTED(t1.size(), "moved-from"); } { ABSL_ATTRIBUTE_UNUSED IntTable t1; t1.insert(1); ABSL_ATTRIBUTE_UNUSED IntTable t2(std::move(t1)); EXPECT_DEATH_IF_SUPPORTED(t1.contains(1), "moved-from"); t1.clear(); } } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/raw_hash_set.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/raw_hash_set_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
09d4c8e3-37f0-41f7-a410-f45ec5df047e
cpp
abseil/abseil-cpp
hashtablez_sampler
absl/container/internal/hashtablez_sampler.cc
absl/container/internal/hashtablez_sampler_test.cc
#include "absl/container/internal/hashtablez_sampler.h" #include <algorithm> #include <atomic> #include <cassert> #include <cmath> #include <cstddef> #include <cstdint> #include <functional> #include <limits> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/per_thread_tls.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/macros.h" #include "absl/base/no_destructor.h" #include "absl/base/optimization.h" #include "absl/debugging/stacktrace.h" #include "absl/memory/memory.h" #include "absl/profiling/internal/exponential_biased.h" #include "absl/profiling/internal/sample_recorder.h" #include "absl/synchronization/mutex.h" #include "absl/time/clock.h" #include "absl/utility/utility.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL constexpr int HashtablezInfo::kMaxStackDepth; #endif namespace { ABSL_CONST_INIT std::atomic<bool> g_hashtablez_enabled{ false }; ABSL_CONST_INIT std::atomic<int32_t> g_hashtablez_sample_parameter{1 << 10}; std::atomic<HashtablezConfigListener> g_hashtablez_config_listener{nullptr}; #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) ABSL_PER_THREAD_TLS_KEYWORD absl::profiling_internal::ExponentialBiased g_exponential_biased_generator; #endif void TriggerHashtablezConfigListener() { auto* listener = g_hashtablez_config_listener.load(std::memory_order_acquire); if (listener != nullptr) listener(); } } #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) ABSL_PER_THREAD_TLS_KEYWORD SamplingState global_next_sample = {0, 0}; #endif HashtablezSampler& GlobalHashtablezSampler() { static absl::NoDestructor<HashtablezSampler> sampler; return *sampler; } HashtablezInfo::HashtablezInfo() = default; HashtablezInfo::~HashtablezInfo() = default; void HashtablezInfo::PrepareForSampling(int64_t stride, size_t inline_element_size_value, size_t key_size_value, size_t value_size_value, uint16_t soo_capacity_value) { capacity.store(0, std::memory_order_relaxed); size.store(0, std::memory_order_relaxed); num_erases.store(0, std::memory_order_relaxed); num_rehashes.store(0, std::memory_order_relaxed); max_probe_length.store(0, std::memory_order_relaxed); total_probe_length.store(0, std::memory_order_relaxed); hashes_bitwise_or.store(0, std::memory_order_relaxed); hashes_bitwise_and.store(~size_t{}, std::memory_order_relaxed); hashes_bitwise_xor.store(0, std::memory_order_relaxed); max_reserve.store(0, std::memory_order_relaxed); create_time = absl::Now(); weight = stride; depth = absl::GetStackTrace(stack, HashtablezInfo::kMaxStackDepth, 0); inline_element_size = inline_element_size_value; key_size = key_size_value; value_size = value_size_value; soo_capacity = soo_capacity_value; } static bool ShouldForceSampling() { enum ForceState { kDontForce, kForce, kUninitialized }; ABSL_CONST_INIT static std::atomic<ForceState> global_state{ kUninitialized}; ForceState state = global_state.load(std::memory_order_relaxed); if (ABSL_PREDICT_TRUE(state == kDontForce)) return false; if (state == kUninitialized) { state = ABSL_INTERNAL_C_SYMBOL(AbslContainerInternalSampleEverything)() ? kForce : kDontForce; global_state.store(state, std::memory_order_relaxed); } return state == kForce; } HashtablezInfo* SampleSlow(SamplingState& next_sample, size_t inline_element_size, size_t key_size, size_t value_size, uint16_t soo_capacity) { if (ABSL_PREDICT_FALSE(ShouldForceSampling())) { next_sample.next_sample = 1; const int64_t old_stride = exchange(next_sample.sample_stride, 1); HashtablezInfo* result = GlobalHashtablezSampler().Register( old_stride, inline_element_size, key_size, value_size, soo_capacity); return result; } #if !defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) next_sample = { std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max(), }; return nullptr; #else bool first = next_sample.next_sample < 0; const int64_t next_stride = g_exponential_biased_generator.GetStride( g_hashtablez_sample_parameter.load(std::memory_order_relaxed)); next_sample.next_sample = next_stride; const int64_t old_stride = exchange(next_sample.sample_stride, next_stride); ABSL_ASSERT(next_stride >= 1); if (!g_hashtablez_enabled.load(std::memory_order_relaxed)) return nullptr; if (first) { if (ABSL_PREDICT_TRUE(--next_sample.next_sample > 0)) return nullptr; return SampleSlow(next_sample, inline_element_size, key_size, value_size, soo_capacity); } return GlobalHashtablezSampler().Register(old_stride, inline_element_size, key_size, value_size, soo_capacity); #endif } void UnsampleSlow(HashtablezInfo* info) { GlobalHashtablezSampler().Unregister(info); } void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length) { #ifdef ABSL_INTERNAL_HAVE_SSE2 total_probe_length /= 16; #else total_probe_length /= 8; #endif info->total_probe_length.store(total_probe_length, std::memory_order_relaxed); info->num_erases.store(0, std::memory_order_relaxed); info->num_rehashes.store( 1 + info->num_rehashes.load(std::memory_order_relaxed), std::memory_order_relaxed); } void RecordReservationSlow(HashtablezInfo* info, size_t target_capacity) { info->max_reserve.store( (std::max)(info->max_reserve.load(std::memory_order_relaxed), target_capacity), std::memory_order_relaxed); } void RecordClearedReservationSlow(HashtablezInfo* info) { info->max_reserve.store(0, std::memory_order_relaxed); } void RecordStorageChangedSlow(HashtablezInfo* info, size_t size, size_t capacity) { info->size.store(size, std::memory_order_relaxed); info->capacity.store(capacity, std::memory_order_relaxed); if (size == 0) { info->total_probe_length.store(0, std::memory_order_relaxed); info->num_erases.store(0, std::memory_order_relaxed); } } void RecordInsertSlow(HashtablezInfo* info, size_t hash, size_t distance_from_desired) { size_t probe_length = distance_from_desired; #ifdef ABSL_INTERNAL_HAVE_SSE2 probe_length /= 16; #else probe_length /= 8; #endif info->hashes_bitwise_and.fetch_and(hash, std::memory_order_relaxed); info->hashes_bitwise_or.fetch_or(hash, std::memory_order_relaxed); info->hashes_bitwise_xor.fetch_xor(hash, std::memory_order_relaxed); info->max_probe_length.store( std::max(info->max_probe_length.load(std::memory_order_relaxed), probe_length), std::memory_order_relaxed); info->total_probe_length.fetch_add(probe_length, std::memory_order_relaxed); info->size.fetch_add(1, std::memory_order_relaxed); } void RecordEraseSlow(HashtablezInfo* info) { info->size.fetch_sub(1, std::memory_order_relaxed); info->num_erases.store(1 + info->num_erases.load(std::memory_order_relaxed), std::memory_order_relaxed); } void SetHashtablezConfigListener(HashtablezConfigListener l) { g_hashtablez_config_listener.store(l, std::memory_order_release); } bool IsHashtablezEnabled() { return g_hashtablez_enabled.load(std::memory_order_acquire); } void SetHashtablezEnabled(bool enabled) { SetHashtablezEnabledInternal(enabled); TriggerHashtablezConfigListener(); } void SetHashtablezEnabledInternal(bool enabled) { g_hashtablez_enabled.store(enabled, std::memory_order_release); } int32_t GetHashtablezSampleParameter() { return g_hashtablez_sample_parameter.load(std::memory_order_acquire); } void SetHashtablezSampleParameter(int32_t rate) { SetHashtablezSampleParameterInternal(rate); TriggerHashtablezConfigListener(); } void SetHashtablezSampleParameterInternal(int32_t rate) { if (rate > 0) { g_hashtablez_sample_parameter.store(rate, std::memory_order_release); } else { ABSL_RAW_LOG(ERROR, "Invalid hashtablez sample rate: %lld", static_cast<long long>(rate)); } } size_t GetHashtablezMaxSamples() { return GlobalHashtablezSampler().GetMaxSamples(); } void SetHashtablezMaxSamples(size_t max) { SetHashtablezMaxSamplesInternal(max); TriggerHashtablezConfigListener(); } void SetHashtablezMaxSamplesInternal(size_t max) { if (max > 0) { GlobalHashtablezSampler().SetMaxSamples(max); } else { ABSL_RAW_LOG(ERROR, "Invalid hashtablez max samples: 0"); } } } ABSL_NAMESPACE_END }
#include "absl/container/internal/hashtablez_sampler.h" #include <atomic> #include <cassert> #include <cstddef> #include <cstdint> #include <limits> #include <random> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/profiling/internal/sample_recorder.h" #include "absl/synchronization/blocking_counter.h" #include "absl/synchronization/internal/thread_pool.h" #include "absl/synchronization/mutex.h" #include "absl/synchronization/notification.h" #include "absl/time/clock.h" #include "absl/time/time.h" #ifdef ABSL_INTERNAL_HAVE_SSE2 constexpr int kProbeLength = 16; #else constexpr int kProbeLength = 8; #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) class HashtablezInfoHandlePeer { public: static HashtablezInfo* GetInfo(HashtablezInfoHandle* h) { return h->info_; } }; #else class HashtablezInfoHandlePeer { public: static HashtablezInfo* GetInfo(HashtablezInfoHandle*) { return nullptr; } }; #endif namespace { using ::absl::synchronization_internal::ThreadPool; using ::testing::IsEmpty; using ::testing::UnorderedElementsAre; std::vector<size_t> GetSizes(HashtablezSampler* s) { std::vector<size_t> res; s->Iterate([&](const HashtablezInfo& info) { res.push_back(info.size.load(std::memory_order_acquire)); }); return res; } HashtablezInfo* Register(HashtablezSampler* s, size_t size) { const int64_t test_stride = 123; const size_t test_element_size = 17; const size_t test_key_size = 3; const size_t test_value_size = 5; auto* info = s->Register(test_stride, test_element_size, test_key_size, test_value_size, 0); assert(info != nullptr); info->size.store(size); return info; } TEST(HashtablezInfoTest, PrepareForSampling) { absl::Time test_start = absl::Now(); const int64_t test_stride = 123; const size_t test_element_size = 17; const size_t test_key_size = 15; const size_t test_value_size = 13; HashtablezInfo info; absl::MutexLock l(&info.init_mu); info.PrepareForSampling(test_stride, test_element_size, test_key_size, test_value_size, 1); EXPECT_EQ(info.capacity.load(), 0); EXPECT_EQ(info.size.load(), 0); EXPECT_EQ(info.num_erases.load(), 0); EXPECT_EQ(info.num_rehashes.load(), 0); EXPECT_EQ(info.max_probe_length.load(), 0); EXPECT_EQ(info.total_probe_length.load(), 0); EXPECT_EQ(info.hashes_bitwise_or.load(), 0); EXPECT_EQ(info.hashes_bitwise_and.load(), ~size_t{}); EXPECT_EQ(info.hashes_bitwise_xor.load(), 0); EXPECT_EQ(info.max_reserve.load(), 0); EXPECT_GE(info.create_time, test_start); EXPECT_EQ(info.weight, test_stride); EXPECT_EQ(info.inline_element_size, test_element_size); EXPECT_EQ(info.key_size, test_key_size); EXPECT_EQ(info.value_size, test_value_size); EXPECT_EQ(info.soo_capacity, 1); info.capacity.store(1, std::memory_order_relaxed); info.size.store(1, std::memory_order_relaxed); info.num_erases.store(1, std::memory_order_relaxed); info.max_probe_length.store(1, std::memory_order_relaxed); info.total_probe_length.store(1, std::memory_order_relaxed); info.hashes_bitwise_or.store(1, std::memory_order_relaxed); info.hashes_bitwise_and.store(1, std::memory_order_relaxed); info.hashes_bitwise_xor.store(1, std::memory_order_relaxed); info.max_reserve.store(1, std::memory_order_relaxed); info.create_time = test_start - absl::Hours(20); info.PrepareForSampling(test_stride * 2, test_element_size, test_key_size, test_value_size, 0); EXPECT_EQ(info.capacity.load(), 0); EXPECT_EQ(info.size.load(), 0); EXPECT_EQ(info.num_erases.load(), 0); EXPECT_EQ(info.num_rehashes.load(), 0); EXPECT_EQ(info.max_probe_length.load(), 0); EXPECT_EQ(info.total_probe_length.load(), 0); EXPECT_EQ(info.hashes_bitwise_or.load(), 0); EXPECT_EQ(info.hashes_bitwise_and.load(), ~size_t{}); EXPECT_EQ(info.hashes_bitwise_xor.load(), 0); EXPECT_EQ(info.max_reserve.load(), 0); EXPECT_EQ(info.weight, 2 * test_stride); EXPECT_EQ(info.inline_element_size, test_element_size); EXPECT_EQ(info.key_size, test_key_size); EXPECT_EQ(info.value_size, test_value_size); EXPECT_GE(info.create_time, test_start); EXPECT_EQ(info.soo_capacity, 0); } TEST(HashtablezInfoTest, RecordStorageChanged) { HashtablezInfo info; absl::MutexLock l(&info.init_mu); const int64_t test_stride = 21; const size_t test_element_size = 19; const size_t test_key_size = 17; const size_t test_value_size = 15; info.PrepareForSampling(test_stride, test_element_size, test_key_size, test_value_size, 0); RecordStorageChangedSlow(&info, 17, 47); EXPECT_EQ(info.size.load(), 17); EXPECT_EQ(info.capacity.load(), 47); RecordStorageChangedSlow(&info, 20, 20); EXPECT_EQ(info.size.load(), 20); EXPECT_EQ(info.capacity.load(), 20); } TEST(HashtablezInfoTest, RecordInsert) { HashtablezInfo info; absl::MutexLock l(&info.init_mu); const int64_t test_stride = 25; const size_t test_element_size = 23; const size_t test_key_size = 21; const size_t test_value_size = 19; info.PrepareForSampling(test_stride, test_element_size, test_key_size, test_value_size, 0); EXPECT_EQ(info.max_probe_length.load(), 0); RecordInsertSlow(&info, 0x0000FF00, 6 * kProbeLength); EXPECT_EQ(info.max_probe_length.load(), 6); EXPECT_EQ(info.hashes_bitwise_and.load(), 0x0000FF00); EXPECT_EQ(info.hashes_bitwise_or.load(), 0x0000FF00); EXPECT_EQ(info.hashes_bitwise_xor.load(), 0x0000FF00); RecordInsertSlow(&info, 0x000FF000, 4 * kProbeLength); EXPECT_EQ(info.max_probe_length.load(), 6); EXPECT_EQ(info.hashes_bitwise_and.load(), 0x0000F000); EXPECT_EQ(info.hashes_bitwise_or.load(), 0x000FFF00); EXPECT_EQ(info.hashes_bitwise_xor.load(), 0x000F0F00); RecordInsertSlow(&info, 0x00FF0000, 12 * kProbeLength); EXPECT_EQ(info.max_probe_length.load(), 12); EXPECT_EQ(info.hashes_bitwise_and.load(), 0x00000000); EXPECT_EQ(info.hashes_bitwise_or.load(), 0x00FFFF00); EXPECT_EQ(info.hashes_bitwise_xor.load(), 0x00F00F00); } TEST(HashtablezInfoTest, RecordErase) { const int64_t test_stride = 31; const size_t test_element_size = 29; const size_t test_key_size = 27; const size_t test_value_size = 25; HashtablezInfo info; absl::MutexLock l(&info.init_mu); info.PrepareForSampling(test_stride, test_element_size, test_key_size, test_value_size, 1); EXPECT_EQ(info.num_erases.load(), 0); EXPECT_EQ(info.size.load(), 0); RecordInsertSlow(&info, 0x0000FF00, 6 * kProbeLength); EXPECT_EQ(info.size.load(), 1); RecordEraseSlow(&info); EXPECT_EQ(info.size.load(), 0); EXPECT_EQ(info.num_erases.load(), 1); EXPECT_EQ(info.inline_element_size, test_element_size); EXPECT_EQ(info.key_size, test_key_size); EXPECT_EQ(info.value_size, test_value_size); EXPECT_EQ(info.soo_capacity, 1); } TEST(HashtablezInfoTest, RecordRehash) { const int64_t test_stride = 33; const size_t test_element_size = 31; const size_t test_key_size = 29; const size_t test_value_size = 27; HashtablezInfo info; absl::MutexLock l(&info.init_mu); info.PrepareForSampling(test_stride, test_element_size, test_key_size, test_value_size, 0); RecordInsertSlow(&info, 0x1, 0); RecordInsertSlow(&info, 0x2, kProbeLength); RecordInsertSlow(&info, 0x4, kProbeLength); RecordInsertSlow(&info, 0x8, 2 * kProbeLength); EXPECT_EQ(info.size.load(), 4); EXPECT_EQ(info.total_probe_length.load(), 4); RecordEraseSlow(&info); RecordEraseSlow(&info); EXPECT_EQ(info.size.load(), 2); EXPECT_EQ(info.total_probe_length.load(), 4); EXPECT_EQ(info.num_erases.load(), 2); RecordRehashSlow(&info, 3 * kProbeLength); EXPECT_EQ(info.size.load(), 2); EXPECT_EQ(info.total_probe_length.load(), 3); EXPECT_EQ(info.num_erases.load(), 0); EXPECT_EQ(info.num_rehashes.load(), 1); EXPECT_EQ(info.inline_element_size, test_element_size); EXPECT_EQ(info.key_size, test_key_size); EXPECT_EQ(info.value_size, test_value_size); EXPECT_EQ(info.soo_capacity, 0); } TEST(HashtablezInfoTest, RecordReservation) { HashtablezInfo info; absl::MutexLock l(&info.init_mu); const int64_t test_stride = 35; const size_t test_element_size = 33; const size_t test_key_size = 31; const size_t test_value_size = 29; info.PrepareForSampling(test_stride, test_element_size, test_key_size, test_value_size, 0); RecordReservationSlow(&info, 3); EXPECT_EQ(info.max_reserve.load(), 3); RecordReservationSlow(&info, 2); EXPECT_EQ(info.max_reserve.load(), 3); RecordReservationSlow(&info, 10); EXPECT_EQ(info.max_reserve.load(), 10); } #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE) TEST(HashtablezSamplerTest, SmallSampleParameter) { const size_t test_element_size = 31; const size_t test_key_size = 33; const size_t test_value_size = 35; SetHashtablezEnabled(true); SetHashtablezSampleParameter(100); for (int i = 0; i < 1000; ++i) { SamplingState next_sample = {0, 0}; HashtablezInfo* sample = SampleSlow(next_sample, test_element_size, test_key_size, test_value_size, 0); EXPECT_GT(next_sample.next_sample, 0); EXPECT_EQ(next_sample.next_sample, next_sample.sample_stride); EXPECT_NE(sample, nullptr); UnsampleSlow(sample); } } TEST(HashtablezSamplerTest, LargeSampleParameter) { const size_t test_element_size = 31; const size_t test_key_size = 33; const size_t test_value_size = 35; SetHashtablezEnabled(true); SetHashtablezSampleParameter(std::numeric_limits<int32_t>::max()); for (int i = 0; i < 1000; ++i) { SamplingState next_sample = {0, 0}; HashtablezInfo* sample = SampleSlow(next_sample, test_element_size, test_key_size, test_value_size, 0); EXPECT_GT(next_sample.next_sample, 0); EXPECT_EQ(next_sample.next_sample, next_sample.sample_stride); EXPECT_NE(sample, nullptr); UnsampleSlow(sample); } } TEST(HashtablezSamplerTest, Sample) { const size_t test_element_size = 31; const size_t test_key_size = 33; const size_t test_value_size = 35; SetHashtablezEnabled(true); SetHashtablezSampleParameter(100); int64_t num_sampled = 0; int64_t total = 0; double sample_rate = 0.0; for (int i = 0; i < 1000000; ++i) { HashtablezInfoHandle h = Sample(test_element_size, test_key_size, test_value_size, 0); ++total; if (h.IsSampled()) { ++num_sampled; } sample_rate = static_cast<double>(num_sampled) / total; if (0.005 < sample_rate && sample_rate < 0.015) break; } EXPECT_NEAR(sample_rate, 0.01, 0.005); } TEST(HashtablezSamplerTest, Handle) { auto& sampler = GlobalHashtablezSampler(); const int64_t test_stride = 41; const size_t test_element_size = 39; const size_t test_key_size = 37; const size_t test_value_size = 35; HashtablezInfoHandle h(sampler.Register(test_stride, test_element_size, test_key_size, test_value_size, 0)); auto* info = HashtablezInfoHandlePeer::GetInfo(&h); info->hashes_bitwise_and.store(0x12345678, std::memory_order_relaxed); bool found = false; sampler.Iterate([&](const HashtablezInfo& h) { if (&h == info) { EXPECT_EQ(h.weight, test_stride); EXPECT_EQ(h.hashes_bitwise_and.load(), 0x12345678); found = true; } }); EXPECT_TRUE(found); h.Unregister(); h = HashtablezInfoHandle(); found = false; sampler.Iterate([&](const HashtablezInfo& h) { if (&h == info) { if (h.hashes_bitwise_and.load() == 0x12345678) { found = true; } } }); EXPECT_FALSE(found); } #endif TEST(HashtablezSamplerTest, Registration) { HashtablezSampler sampler; auto* info1 = Register(&sampler, 1); EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(1)); auto* info2 = Register(&sampler, 2); EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(1, 2)); info1->size.store(3); EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(3, 2)); sampler.Unregister(info1); sampler.Unregister(info2); } TEST(HashtablezSamplerTest, Unregistration) { HashtablezSampler sampler; std::vector<HashtablezInfo*> infos; for (size_t i = 0; i < 3; ++i) { infos.push_back(Register(&sampler, i)); } EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 1, 2)); sampler.Unregister(infos[1]); EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 2)); infos.push_back(Register(&sampler, 3)); infos.push_back(Register(&sampler, 4)); EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 2, 3, 4)); sampler.Unregister(infos[3]); EXPECT_THAT(GetSizes(&sampler), UnorderedElementsAre(0, 2, 4)); sampler.Unregister(infos[0]); sampler.Unregister(infos[2]); sampler.Unregister(infos[4]); EXPECT_THAT(GetSizes(&sampler), IsEmpty()); } TEST(HashtablezSamplerTest, MultiThreaded) { HashtablezSampler sampler; Notification stop; ThreadPool pool(10); for (int i = 0; i < 10; ++i) { const int64_t sampling_stride = 11 + i % 3; const size_t elt_size = 10 + i % 2; const size_t key_size = 12 + i % 4; const size_t value_size = 13 + i % 5; pool.Schedule([&sampler, &stop, sampling_stride, elt_size, key_size, value_size]() { std::random_device rd; std::mt19937 gen(rd()); std::vector<HashtablezInfo*> infoz; while (!stop.HasBeenNotified()) { if (infoz.empty()) { infoz.push_back(sampler.Register(sampling_stride, elt_size, key_size, value_size, 0)); } switch (std::uniform_int_distribution<>(0, 2)(gen)) { case 0: { infoz.push_back(sampler.Register(sampling_stride, elt_size, key_size, value_size, 0)); break; } case 1: { size_t p = std::uniform_int_distribution<>(0, infoz.size() - 1)(gen); HashtablezInfo* info = infoz[p]; infoz[p] = infoz.back(); infoz.pop_back(); EXPECT_EQ(info->weight, sampling_stride); sampler.Unregister(info); break; } case 2: { absl::Duration oldest = absl::ZeroDuration(); sampler.Iterate([&](const HashtablezInfo& info) { oldest = std::max(oldest, absl::Now() - info.create_time); }); ASSERT_GE(oldest, absl::ZeroDuration()); break; } } } }); } absl::SleepFor(absl::Seconds(3)); stop.Notify(); } TEST(HashtablezSamplerTest, Callback) { HashtablezSampler sampler; auto* info1 = Register(&sampler, 1); auto* info2 = Register(&sampler, 2); static const HashtablezInfo* expected; auto callback = [](const HashtablezInfo& info) { EXPECT_EQ(&info, expected); }; EXPECT_EQ(sampler.SetDisposeCallback(callback), nullptr); expected = info1; sampler.Unregister(info1); EXPECT_EQ(callback, sampler.SetDisposeCallback(nullptr)); expected = nullptr; sampler.Unregister(info2); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/hashtablez_sampler.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/hashtablez_sampler_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
a64fe2e8-586b-45ce-a76d-0ae8985f6baf
cpp
abseil/abseil-cpp
test_instance_tracker
absl/container/internal/test_instance_tracker.cc
absl/container/internal/test_instance_tracker_test.cc
#include "absl/container/internal/test_instance_tracker.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace test_internal { int BaseCountedInstance::num_instances_ = 0; int BaseCountedInstance::num_live_instances_ = 0; int BaseCountedInstance::num_moves_ = 0; int BaseCountedInstance::num_copies_ = 0; int BaseCountedInstance::num_swaps_ = 0; int BaseCountedInstance::num_comparisons_ = 0; } ABSL_NAMESPACE_END }
#include "absl/container/internal/test_instance_tracker.h" #include "gtest/gtest.h" namespace { using absl::test_internal::CopyableMovableInstance; using absl::test_internal::CopyableOnlyInstance; using absl::test_internal::InstanceTracker; using absl::test_internal::MovableOnlyInstance; TEST(TestInstanceTracker, CopyableMovable) { InstanceTracker tracker; CopyableMovableInstance src(1); EXPECT_EQ(1, src.value()) << src; CopyableMovableInstance copy(src); CopyableMovableInstance move(std::move(src)); EXPECT_EQ(1, tracker.copies()); EXPECT_EQ(1, tracker.moves()); EXPECT_EQ(0, tracker.swaps()); EXPECT_EQ(3, tracker.instances()); EXPECT_EQ(2, tracker.live_instances()); tracker.ResetCopiesMovesSwaps(); CopyableMovableInstance copy_assign(1); copy_assign = copy; CopyableMovableInstance move_assign(1); move_assign = std::move(move); EXPECT_EQ(1, tracker.copies()); EXPECT_EQ(1, tracker.moves()); EXPECT_EQ(0, tracker.swaps()); EXPECT_EQ(5, tracker.instances()); EXPECT_EQ(3, tracker.live_instances()); tracker.ResetCopiesMovesSwaps(); { using std::swap; swap(move_assign, copy); swap(copy, move_assign); EXPECT_EQ(2, tracker.swaps()); EXPECT_EQ(0, tracker.copies()); EXPECT_EQ(0, tracker.moves()); EXPECT_EQ(5, tracker.instances()); EXPECT_EQ(3, tracker.live_instances()); } } TEST(TestInstanceTracker, CopyableOnly) { InstanceTracker tracker; CopyableOnlyInstance src(1); EXPECT_EQ(1, src.value()) << src; CopyableOnlyInstance copy(src); CopyableOnlyInstance copy2(std::move(src)); EXPECT_EQ(2, tracker.copies()); EXPECT_EQ(0, tracker.moves()); EXPECT_EQ(3, tracker.instances()); EXPECT_EQ(3, tracker.live_instances()); tracker.ResetCopiesMovesSwaps(); CopyableOnlyInstance copy_assign(1); copy_assign = copy; CopyableOnlyInstance copy_assign2(1); copy_assign2 = std::move(copy2); EXPECT_EQ(2, tracker.copies()); EXPECT_EQ(0, tracker.moves()); EXPECT_EQ(5, tracker.instances()); EXPECT_EQ(5, tracker.live_instances()); tracker.ResetCopiesMovesSwaps(); { using std::swap; swap(src, copy); swap(copy, src); EXPECT_EQ(2, tracker.swaps()); EXPECT_EQ(0, tracker.copies()); EXPECT_EQ(0, tracker.moves()); EXPECT_EQ(5, tracker.instances()); EXPECT_EQ(5, tracker.live_instances()); } } TEST(TestInstanceTracker, MovableOnly) { InstanceTracker tracker; MovableOnlyInstance src(1); EXPECT_EQ(1, src.value()) << src; MovableOnlyInstance move(std::move(src)); MovableOnlyInstance move_assign(2); move_assign = std::move(move); EXPECT_EQ(3, tracker.instances()); EXPECT_EQ(1, tracker.live_instances()); EXPECT_EQ(2, tracker.moves()); EXPECT_EQ(0, tracker.copies()); tracker.ResetCopiesMovesSwaps(); { using std::swap; MovableOnlyInstance other(2); swap(move_assign, other); swap(other, move_assign); EXPECT_EQ(2, tracker.swaps()); EXPECT_EQ(0, tracker.copies()); EXPECT_EQ(0, tracker.moves()); EXPECT_EQ(4, tracker.instances()); EXPECT_EQ(2, tracker.live_instances()); } } TEST(TestInstanceTracker, ExistingInstances) { CopyableMovableInstance uncounted_instance(1); CopyableMovableInstance uncounted_live_instance( std::move(uncounted_instance)); InstanceTracker tracker; EXPECT_EQ(0, tracker.instances()); EXPECT_EQ(0, tracker.live_instances()); EXPECT_EQ(0, tracker.copies()); { CopyableMovableInstance instance1(1); EXPECT_EQ(1, tracker.instances()); EXPECT_EQ(1, tracker.live_instances()); EXPECT_EQ(0, tracker.copies()); EXPECT_EQ(0, tracker.moves()); { InstanceTracker tracker2; CopyableMovableInstance instance2(instance1); CopyableMovableInstance instance3(std::move(instance2)); EXPECT_EQ(3, tracker.instances()); EXPECT_EQ(2, tracker.live_instances()); EXPECT_EQ(1, tracker.copies()); EXPECT_EQ(1, tracker.moves()); EXPECT_EQ(2, tracker2.instances()); EXPECT_EQ(1, tracker2.live_instances()); EXPECT_EQ(1, tracker2.copies()); EXPECT_EQ(1, tracker2.moves()); } EXPECT_EQ(1, tracker.instances()); EXPECT_EQ(1, tracker.live_instances()); EXPECT_EQ(1, tracker.copies()); EXPECT_EQ(1, tracker.moves()); } EXPECT_EQ(0, tracker.instances()); EXPECT_EQ(0, tracker.live_instances()); EXPECT_EQ(1, tracker.copies()); EXPECT_EQ(1, tracker.moves()); } TEST(TestInstanceTracker, Comparisons) { InstanceTracker tracker; MovableOnlyInstance one(1), two(2); EXPECT_EQ(0, tracker.comparisons()); EXPECT_FALSE(one == two); EXPECT_EQ(1, tracker.comparisons()); EXPECT_TRUE(one != two); EXPECT_EQ(2, tracker.comparisons()); EXPECT_TRUE(one < two); EXPECT_EQ(3, tracker.comparisons()); EXPECT_FALSE(one > two); EXPECT_EQ(4, tracker.comparisons()); EXPECT_TRUE(one <= two); EXPECT_EQ(5, tracker.comparisons()); EXPECT_FALSE(one >= two); EXPECT_EQ(6, tracker.comparisons()); EXPECT_TRUE(one.compare(two) < 0); EXPECT_EQ(7, tracker.comparisons()); tracker.ResetCopiesMovesSwaps(); EXPECT_EQ(0, tracker.comparisons()); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/test_instance_tracker.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/test_instance_tracker_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
94b8365d-2887-4f6d-aed7-97c5bded3b23
cpp
abseil/abseil-cpp
int128
absl/numeric/int128.cc
absl/numeric/int128_test.cc
#include "absl/numeric/int128.h" #include <stddef.h> #include <cassert> #include <iomanip> #include <ostream> #include <sstream> #include <string> #include <type_traits> #include "absl/base/optimization.h" #include "absl/numeric/bits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { inline ABSL_ATTRIBUTE_ALWAYS_INLINE int Fls128(uint128 n) { if (uint64_t hi = Uint128High64(n)) { ABSL_ASSUME(hi != 0); return 127 - countl_zero(hi); } const uint64_t low = Uint128Low64(n); ABSL_ASSUME(low != 0); return 63 - countl_zero(low); } inline void DivModImpl(uint128 dividend, uint128 divisor, uint128* quotient_ret, uint128* remainder_ret) { assert(divisor != 0); if (divisor > dividend) { *quotient_ret = 0; *remainder_ret = dividend; return; } if (divisor == dividend) { *quotient_ret = 1; *remainder_ret = 0; return; } uint128 denominator = divisor; uint128 quotient = 0; const int shift = Fls128(dividend) - Fls128(denominator); denominator <<= shift; for (int i = 0; i <= shift; ++i) { quotient <<= 1; if (dividend >= denominator) { dividend -= denominator; quotient |= 1; } denominator >>= 1; } *quotient_ret = quotient; *remainder_ret = dividend; } template <typename T> uint128 MakeUint128FromFloat(T v) { static_assert(std::is_floating_point<T>::value, ""); assert(std::isfinite(v) && v > -1 && (std::numeric_limits<T>::max_exponent <= 128 || v < std::ldexp(static_cast<T>(1), 128))); if (v >= std::ldexp(static_cast<T>(1), 64)) { uint64_t hi = static_cast<uint64_t>(std::ldexp(v, -64)); uint64_t lo = static_cast<uint64_t>(v - std::ldexp(static_cast<T>(hi), 64)); return MakeUint128(hi, lo); } return MakeUint128(0, static_cast<uint64_t>(v)); } #if defined(__clang__) && (__clang_major__ < 9) && !defined(__SSE3__) uint128 MakeUint128FromFloat(long double v) { static_assert(std::numeric_limits<double>::digits >= 50, ""); static_assert(std::numeric_limits<long double>::digits <= 150, ""); assert(std::isfinite(v) && v > -1 && v < std::ldexp(1.0L, 128)); v = std::ldexp(v, -100); uint64_t w0 = static_cast<uint64_t>(static_cast<double>(std::trunc(v))); v = std::ldexp(v - static_cast<double>(w0), 50); uint64_t w1 = static_cast<uint64_t>(static_cast<double>(std::trunc(v))); v = std::ldexp(v - static_cast<double>(w1), 50); uint64_t w2 = static_cast<uint64_t>(static_cast<double>(std::trunc(v))); return (static_cast<uint128>(w0) << 100) | (static_cast<uint128>(w1) << 50) | static_cast<uint128>(w2); } #endif } uint128::uint128(float v) : uint128(MakeUint128FromFloat(v)) {} uint128::uint128(double v) : uint128(MakeUint128FromFloat(v)) {} uint128::uint128(long double v) : uint128(MakeUint128FromFloat(v)) {} #if !defined(ABSL_HAVE_INTRINSIC_INT128) uint128 operator/(uint128 lhs, uint128 rhs) { uint128 quotient = 0; uint128 remainder = 0; DivModImpl(lhs, rhs, &quotient, &remainder); return quotient; } uint128 operator%(uint128 lhs, uint128 rhs) { uint128 quotient = 0; uint128 remainder = 0; DivModImpl(lhs, rhs, &quotient, &remainder); return remainder; } #endif namespace { std::string Uint128ToFormattedString(uint128 v, std::ios_base::fmtflags flags) { uint128 div; int div_base_log; switch (flags & std::ios::basefield) { case std::ios::hex: div = 0x1000000000000000; div_base_log = 15; break; case std::ios::oct: div = 01000000000000000000000; div_base_log = 21; break; default: div = 10000000000000000000u; div_base_log = 19; break; } std::ostringstream os; std::ios_base::fmtflags copy_mask = std::ios::basefield | std::ios::showbase | std::ios::uppercase; os.setf(flags & copy_mask, copy_mask); uint128 high = v; uint128 low; DivModImpl(high, div, &high, &low); uint128 mid; DivModImpl(high, div, &high, &mid); if (Uint128Low64(high) != 0) { os << Uint128Low64(high); os << std::noshowbase << std::setfill('0') << std::setw(div_base_log); os << Uint128Low64(mid); os << std::setw(div_base_log); } else if (Uint128Low64(mid) != 0) { os << Uint128Low64(mid); os << std::noshowbase << std::setfill('0') << std::setw(div_base_log); } os << Uint128Low64(low); return os.str(); } } std::string uint128::ToString() const { return Uint128ToFormattedString(*this, std::ios_base::dec); } std::ostream& operator<<(std::ostream& os, uint128 v) { std::ios_base::fmtflags flags = os.flags(); std::string rep = Uint128ToFormattedString(v, flags); std::streamsize width = os.width(0); if (static_cast<size_t>(width) > rep.size()) { const size_t count = static_cast<size_t>(width) - rep.size(); std::ios::fmtflags adjustfield = flags & std::ios::adjustfield; if (adjustfield == std::ios::left) { rep.append(count, os.fill()); } else if (adjustfield == std::ios::internal && (flags & std::ios::showbase) && (flags & std::ios::basefield) == std::ios::hex && v != 0) { rep.insert(size_t{2}, count, os.fill()); } else { rep.insert(size_t{0}, count, os.fill()); } } return os << rep; } namespace { uint128 UnsignedAbsoluteValue(int128 v) { return Int128High64(v) < 0 ? -uint128(v) : uint128(v); } } #if !defined(ABSL_HAVE_INTRINSIC_INT128) namespace { template <typename T> int128 MakeInt128FromFloat(T v) { assert(std::isfinite(v) && (std::numeric_limits<T>::max_exponent <= 127 || (v >= -std::ldexp(static_cast<T>(1), 127) && v < std::ldexp(static_cast<T>(1), 127)))); uint128 result = v < 0 ? -MakeUint128FromFloat(-v) : MakeUint128FromFloat(v); return MakeInt128(int128_internal::BitCastToSigned(Uint128High64(result)), Uint128Low64(result)); } } int128::int128(float v) : int128(MakeInt128FromFloat(v)) {} int128::int128(double v) : int128(MakeInt128FromFloat(v)) {} int128::int128(long double v) : int128(MakeInt128FromFloat(v)) {} int128 operator/(int128 lhs, int128 rhs) { assert(lhs != Int128Min() || rhs != -1); uint128 quotient = 0; uint128 remainder = 0; DivModImpl(UnsignedAbsoluteValue(lhs), UnsignedAbsoluteValue(rhs), &quotient, &remainder); if ((Int128High64(lhs) < 0) != (Int128High64(rhs) < 0)) quotient = -quotient; return MakeInt128(int128_internal::BitCastToSigned(Uint128High64(quotient)), Uint128Low64(quotient)); } int128 operator%(int128 lhs, int128 rhs) { assert(lhs != Int128Min() || rhs != -1); uint128 quotient = 0; uint128 remainder = 0; DivModImpl(UnsignedAbsoluteValue(lhs), UnsignedAbsoluteValue(rhs), &quotient, &remainder); if (Int128High64(lhs) < 0) remainder = -remainder; return MakeInt128(int128_internal::BitCastToSigned(Uint128High64(remainder)), Uint128Low64(remainder)); } #endif std::string int128::ToString() const { std::string rep; if (Int128High64(*this) < 0) rep = "-"; rep.append(Uint128ToFormattedString(UnsignedAbsoluteValue(*this), std::ios_base::dec)); return rep; } std::ostream& operator<<(std::ostream& os, int128 v) { std::ios_base::fmtflags flags = os.flags(); std::string rep; bool print_as_decimal = (flags & std::ios::basefield) == std::ios::dec || (flags & std::ios::basefield) == std::ios_base::fmtflags(); if (print_as_decimal) { if (Int128High64(v) < 0) { rep = "-"; } else if (flags & std::ios::showpos) { rep = "+"; } } rep.append(Uint128ToFormattedString( print_as_decimal ? UnsignedAbsoluteValue(v) : uint128(v), os.flags())); std::streamsize width = os.width(0); if (static_cast<size_t>(width) > rep.size()) { const size_t count = static_cast<size_t>(width) - rep.size(); switch (flags & std::ios::adjustfield) { case std::ios::left: rep.append(count, os.fill()); break; case std::ios::internal: if (print_as_decimal && (rep[0] == '+' || rep[0] == '-')) { rep.insert(size_t{1}, count, os.fill()); } else if ((flags & std::ios::basefield) == std::ios::hex && (flags & std::ios::showbase) && v != 0) { rep.insert(size_t{2}, count, os.fill()); } else { rep.insert(size_t{0}, count, os.fill()); } break; default: rep.insert(size_t{0}, count, os.fill()); break; } } return os << rep; } ABSL_NAMESPACE_END } #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL namespace std { constexpr bool numeric_limits<absl::uint128>::is_specialized; constexpr bool numeric_limits<absl::uint128>::is_signed; constexpr bool numeric_limits<absl::uint128>::is_integer; constexpr bool numeric_limits<absl::uint128>::is_exact; constexpr bool numeric_limits<absl::uint128>::has_infinity; constexpr bool numeric_limits<absl::uint128>::has_quiet_NaN; constexpr bool numeric_limits<absl::uint128>::has_signaling_NaN; constexpr float_denorm_style numeric_limits<absl::uint128>::has_denorm; constexpr bool numeric_limits<absl::uint128>::has_denorm_loss; constexpr float_round_style numeric_limits<absl::uint128>::round_style; constexpr bool numeric_limits<absl::uint128>::is_iec559; constexpr bool numeric_limits<absl::uint128>::is_bounded; constexpr bool numeric_limits<absl::uint128>::is_modulo; constexpr int numeric_limits<absl::uint128>::digits; constexpr int numeric_limits<absl::uint128>::digits10; constexpr int numeric_limits<absl::uint128>::max_digits10; constexpr int numeric_limits<absl::uint128>::radix; constexpr int numeric_limits<absl::uint128>::min_exponent; constexpr int numeric_limits<absl::uint128>::min_exponent10; constexpr int numeric_limits<absl::uint128>::max_exponent; constexpr int numeric_limits<absl::uint128>::max_exponent10; constexpr bool numeric_limits<absl::uint128>::traps; constexpr bool numeric_limits<absl::uint128>::tinyness_before; constexpr bool numeric_limits<absl::int128>::is_specialized; constexpr bool numeric_limits<absl::int128>::is_signed; constexpr bool numeric_limits<absl::int128>::is_integer; constexpr bool numeric_limits<absl::int128>::is_exact; constexpr bool numeric_limits<absl::int128>::has_infinity; constexpr bool numeric_limits<absl::int128>::has_quiet_NaN; constexpr bool numeric_limits<absl::int128>::has_signaling_NaN; constexpr float_denorm_style numeric_limits<absl::int128>::has_denorm; constexpr bool numeric_limits<absl::int128>::has_denorm_loss; constexpr float_round_style numeric_limits<absl::int128>::round_style; constexpr bool numeric_limits<absl::int128>::is_iec559; constexpr bool numeric_limits<absl::int128>::is_bounded; constexpr bool numeric_limits<absl::int128>::is_modulo; constexpr int numeric_limits<absl::int128>::digits; constexpr int numeric_limits<absl::int128>::digits10; constexpr int numeric_limits<absl::int128>::max_digits10; constexpr int numeric_limits<absl::int128>::radix; constexpr int numeric_limits<absl::int128>::min_exponent; constexpr int numeric_limits<absl::int128>::min_exponent10; constexpr int numeric_limits<absl::int128>::max_exponent; constexpr int numeric_limits<absl::int128>::max_exponent10; constexpr bool numeric_limits<absl::int128>::traps; constexpr bool numeric_limits<absl::int128>::tinyness_before; } #endif
#include "absl/numeric/int128.h" #include <algorithm> #include <limits> #include <random> #include <type_traits> #include <utility> #include <vector> #include "gtest/gtest.h" #include "absl/base/internal/cycleclock.h" #include "absl/hash/hash_testing.h" #include "absl/meta/type_traits.h" #include "absl/types/compare.h" #define MAKE_INT128(HI, LO) absl::MakeInt128(static_cast<int64_t>(HI), LO) namespace { template <typename T> class Uint128IntegerTraitsTest : public ::testing::Test {}; typedef ::testing::Types<bool, char, signed char, unsigned char, char16_t, char32_t, wchar_t, short, unsigned short, int, unsigned int, long, unsigned long, long long, unsigned long long> IntegerTypes; template <typename T> class Uint128FloatTraitsTest : public ::testing::Test {}; typedef ::testing::Types<float, double, long double> FloatingPointTypes; TYPED_TEST_SUITE(Uint128IntegerTraitsTest, IntegerTypes); TYPED_TEST(Uint128IntegerTraitsTest, ConstructAssignTest) { static_assert(std::is_constructible<absl::uint128, TypeParam>::value, "absl::uint128 must be constructible from TypeParam"); static_assert(std::is_assignable<absl::uint128&, TypeParam>::value, "absl::uint128 must be assignable from TypeParam"); static_assert(!std::is_assignable<TypeParam&, absl::uint128>::value, "TypeParam must not be assignable from absl::uint128"); } TYPED_TEST_SUITE(Uint128FloatTraitsTest, FloatingPointTypes); TYPED_TEST(Uint128FloatTraitsTest, ConstructAssignTest) { static_assert(std::is_constructible<absl::uint128, TypeParam>::value, "absl::uint128 must be constructible from TypeParam"); static_assert(!std::is_assignable<absl::uint128&, TypeParam>::value, "absl::uint128 must not be assignable from TypeParam"); static_assert(!std::is_assignable<TypeParam&, absl::uint128>::value, "TypeParam must not be assignable from absl::uint128"); } #ifdef ABSL_HAVE_INTRINSIC_INT128 TEST(Uint128, IntrinsicTypeTraitsTest) { static_assert(std::is_constructible<absl::uint128, __int128>::value, "absl::uint128 must be constructible from __int128"); static_assert(std::is_assignable<absl::uint128&, __int128>::value, "absl::uint128 must be assignable from __int128"); static_assert(!std::is_assignable<__int128&, absl::uint128>::value, "__int128 must not be assignable from absl::uint128"); static_assert(std::is_constructible<absl::uint128, unsigned __int128>::value, "absl::uint128 must be constructible from unsigned __int128"); static_assert(std::is_assignable<absl::uint128&, unsigned __int128>::value, "absl::uint128 must be assignable from unsigned __int128"); static_assert(!std::is_assignable<unsigned __int128&, absl::uint128>::value, "unsigned __int128 must not be assignable from absl::uint128"); } #endif TEST(Uint128, TrivialTraitsTest) { static_assert(absl::is_trivially_default_constructible<absl::uint128>::value, ""); static_assert(absl::is_trivially_copy_constructible<absl::uint128>::value, ""); static_assert(absl::is_trivially_copy_assignable<absl::uint128>::value, ""); static_assert(std::is_trivially_destructible<absl::uint128>::value, ""); } TEST(Uint128, AllTests) { absl::uint128 zero = 0; absl::uint128 one = 1; absl::uint128 one_2arg = absl::MakeUint128(0, 1); absl::uint128 two = 2; absl::uint128 three = 3; absl::uint128 big = absl::MakeUint128(2000, 2); absl::uint128 big_minus_one = absl::MakeUint128(2000, 1); absl::uint128 bigger = absl::MakeUint128(2001, 1); absl::uint128 biggest = absl::Uint128Max(); absl::uint128 high_low = absl::MakeUint128(1, 0); absl::uint128 low_high = absl::MakeUint128(0, std::numeric_limits<uint64_t>::max()); EXPECT_LT(one, two); EXPECT_GT(two, one); EXPECT_LT(one, big); EXPECT_LT(one, big); EXPECT_EQ(one, one_2arg); EXPECT_NE(one, two); EXPECT_GT(big, one); EXPECT_GE(big, two); EXPECT_GE(big, big_minus_one); EXPECT_GT(big, big_minus_one); EXPECT_LT(big_minus_one, big); EXPECT_LE(big_minus_one, big); EXPECT_NE(big_minus_one, big); EXPECT_LT(big, biggest); EXPECT_LE(big, biggest); EXPECT_GT(biggest, big); EXPECT_GE(biggest, big); EXPECT_EQ(big, ~~big); EXPECT_EQ(one, one | one); EXPECT_EQ(big, big | big); EXPECT_EQ(one, one | zero); EXPECT_EQ(one, one & one); EXPECT_EQ(big, big & big); EXPECT_EQ(zero, one & zero); EXPECT_EQ(zero, big & ~big); EXPECT_EQ(zero, one ^ one); EXPECT_EQ(zero, big ^ big); EXPECT_EQ(one, one ^ zero); EXPECT_EQ(big, big << 0); EXPECT_EQ(big, big >> 0); EXPECT_GT(big << 1, big); EXPECT_LT(big >> 1, big); EXPECT_EQ(big, (big << 10) >> 10); EXPECT_EQ(big, (big >> 1) << 1); EXPECT_EQ(one, (one << 80) >> 80); EXPECT_EQ(zero, (one >> 80) << 80); absl::uint128 big_copy = big; EXPECT_EQ(big << 0, big_copy <<= 0); big_copy = big; EXPECT_EQ(big >> 0, big_copy >>= 0); big_copy = big; EXPECT_EQ(big << 1, big_copy <<= 1); big_copy = big; EXPECT_EQ(big >> 1, big_copy >>= 1); big_copy = big; EXPECT_EQ(big << 10, big_copy <<= 10); big_copy = big; EXPECT_EQ(big >> 10, big_copy >>= 10); big_copy = big; EXPECT_EQ(big << 64, big_copy <<= 64); big_copy = big; EXPECT_EQ(big >> 64, big_copy >>= 64); big_copy = big; EXPECT_EQ(big << 73, big_copy <<= 73); big_copy = big; EXPECT_EQ(big >> 73, big_copy >>= 73); EXPECT_EQ(absl::Uint128High64(biggest), std::numeric_limits<uint64_t>::max()); EXPECT_EQ(absl::Uint128Low64(biggest), std::numeric_limits<uint64_t>::max()); EXPECT_EQ(zero + one, one); EXPECT_EQ(one + one, two); EXPECT_EQ(big_minus_one + one, big); EXPECT_EQ(one - one, zero); EXPECT_EQ(one - zero, one); EXPECT_EQ(zero - one, biggest); EXPECT_EQ(big - big, zero); EXPECT_EQ(big - one, big_minus_one); EXPECT_EQ(big + std::numeric_limits<uint64_t>::max(), bigger); EXPECT_EQ(biggest + 1, zero); EXPECT_EQ(zero - 1, biggest); EXPECT_EQ(high_low - one, low_high); EXPECT_EQ(low_high + one, high_low); EXPECT_EQ(absl::Uint128High64((absl::uint128(1) << 64) - 1), 0); EXPECT_EQ(absl::Uint128Low64((absl::uint128(1) << 64) - 1), std::numeric_limits<uint64_t>::max()); EXPECT_TRUE(!!one); EXPECT_TRUE(!!high_low); EXPECT_FALSE(!!zero); EXPECT_FALSE(!one); EXPECT_FALSE(!high_low); EXPECT_TRUE(!zero); EXPECT_TRUE(zero == 0); EXPECT_FALSE(zero != 0); EXPECT_FALSE(one == 0); EXPECT_TRUE(one != 0); EXPECT_FALSE(high_low == 0); EXPECT_TRUE(high_low != 0); absl::uint128 test = zero; EXPECT_EQ(++test, one); EXPECT_EQ(test, one); EXPECT_EQ(test++, one); EXPECT_EQ(test, two); EXPECT_EQ(test -= 2, zero); EXPECT_EQ(test, zero); EXPECT_EQ(test += 2, two); EXPECT_EQ(test, two); EXPECT_EQ(--test, one); EXPECT_EQ(test, one); EXPECT_EQ(test--, one); EXPECT_EQ(test, zero); EXPECT_EQ(test |= three, three); EXPECT_EQ(test &= one, one); EXPECT_EQ(test ^= three, two); EXPECT_EQ(test >>= 1, one); EXPECT_EQ(test <<= 1, two); EXPECT_EQ(big, +big); EXPECT_EQ(two, +two); EXPECT_EQ(absl::Uint128Max(), +absl::Uint128Max()); EXPECT_EQ(zero, +zero); EXPECT_EQ(big, -(-big)); EXPECT_EQ(two, -((-one) - 1)); EXPECT_EQ(absl::Uint128Max(), -one); EXPECT_EQ(zero, -zero); } TEST(Int128, RightShiftOfNegativeNumbers) { absl::int128 minus_six = -6; absl::int128 minus_three = -3; absl::int128 minus_two = -2; absl::int128 minus_one = -1; if ((-6 >> 1) == -3) { EXPECT_EQ(minus_six >> 1, minus_three); EXPECT_EQ(minus_six >> 2, minus_two); EXPECT_EQ(minus_six >> 65, minus_one); } else { EXPECT_EQ(minus_six >> 1, absl::int128(absl::uint128(minus_six) >> 1)); EXPECT_EQ(minus_six >> 2, absl::int128(absl::uint128(minus_six) >> 2)); EXPECT_EQ(minus_six >> 65, absl::int128(absl::uint128(minus_six) >> 65)); } } TEST(Uint128, ConversionTests) { EXPECT_TRUE(absl::MakeUint128(1, 0)); #ifdef ABSL_HAVE_INTRINSIC_INT128 unsigned __int128 intrinsic = (static_cast<unsigned __int128>(0x3a5b76c209de76f6) << 64) + 0x1f25e1d63a2b46c5; absl::uint128 custom = absl::MakeUint128(0x3a5b76c209de76f6, 0x1f25e1d63a2b46c5); EXPECT_EQ(custom, absl::uint128(intrinsic)); EXPECT_EQ(custom, absl::uint128(static_cast<__int128>(intrinsic))); EXPECT_EQ(intrinsic, static_cast<unsigned __int128>(custom)); EXPECT_EQ(intrinsic, static_cast<__int128>(custom)); #endif double precise_double = 0x530e * std::pow(2.0, 64.0) + 0xda74000000000000; absl::uint128 from_precise_double(precise_double); absl::uint128 from_precise_ints = absl::MakeUint128(0x530e, 0xda74000000000000); EXPECT_EQ(from_precise_double, from_precise_ints); EXPECT_DOUBLE_EQ(static_cast<double>(from_precise_ints), precise_double); double approx_double = static_cast<double>(0xffffeeeeddddcccc) * std::pow(2.0, 64.0) + static_cast<double>(0xbbbbaaaa99998888); absl::uint128 from_approx_double(approx_double); EXPECT_DOUBLE_EQ(static_cast<double>(from_approx_double), approx_double); double round_to_zero = 0.7; double round_to_five = 5.8; double round_to_nine = 9.3; EXPECT_EQ(static_cast<absl::uint128>(round_to_zero), 0); EXPECT_EQ(static_cast<absl::uint128>(round_to_five), 5); EXPECT_EQ(static_cast<absl::uint128>(round_to_nine), 9); absl::uint128 highest_precision_in_long_double = ~absl::uint128{} >> (128 - std::numeric_limits<long double>::digits); EXPECT_EQ(highest_precision_in_long_double, static_cast<absl::uint128>( static_cast<long double>(highest_precision_in_long_double))); const absl::uint128 arbitrary_mask = absl::MakeUint128(0xa29f622677ded751, 0xf8ca66add076f468); EXPECT_EQ(highest_precision_in_long_double & arbitrary_mask, static_cast<absl::uint128>(static_cast<long double>( highest_precision_in_long_double & arbitrary_mask))); EXPECT_EQ(static_cast<absl::uint128>(-0.1L), 0); } TEST(Uint128, OperatorAssignReturnRef) { absl::uint128 v(1); (v += 4) -= 3; EXPECT_EQ(2, v); } TEST(Uint128, Multiply) { absl::uint128 a, b, c; a = 0; b = 0; c = a * b; EXPECT_EQ(0, c); a = absl::uint128(0) - 1; b = absl::uint128(0) - 1; c = a * b; EXPECT_EQ(1, c); c = absl::uint128(0) - 1; c *= c; EXPECT_EQ(1, c); for (int i = 0; i < 64; ++i) { for (int j = 0; j < 64; ++j) { a = absl::uint128(1) << i; b = absl::uint128(1) << j; c = a * b; EXPECT_EQ(absl::uint128(1) << (i + j), c); } } a = absl::MakeUint128(0xffffeeeeddddcccc, 0xbbbbaaaa99998888); b = absl::MakeUint128(0x7777666655554444, 0x3333222211110000); c = a * b; EXPECT_EQ(absl::MakeUint128(0x530EDA741C71D4C3, 0xBF25975319080000), c); EXPECT_EQ(0, c - b * a); EXPECT_EQ(a*a - b*b, (a+b) * (a-b)); a = absl::MakeUint128(0x0123456789abcdef, 0xfedcba9876543210); b = absl::MakeUint128(0x02468ace13579bdf, 0xfdb97531eca86420); c = a * b; EXPECT_EQ(absl::MakeUint128(0x97a87f4f261ba3f2, 0x342d0bbf48948200), c); EXPECT_EQ(0, c - b * a); EXPECT_EQ(a*a - b*b, (a+b) * (a-b)); } TEST(Uint128, AliasTests) { absl::uint128 x1 = absl::MakeUint128(1, 2); absl::uint128 x2 = absl::MakeUint128(2, 4); x1 += x1; EXPECT_EQ(x2, x1); absl::uint128 x3 = absl::MakeUint128(1, static_cast<uint64_t>(1) << 63); absl::uint128 x4 = absl::MakeUint128(3, 0); x3 += x3; EXPECT_EQ(x4, x3); } TEST(Uint128, DivideAndMod) { using std::swap; absl::uint128 a, b, q, r; a = 0; b = 123; q = a / b; r = a % b; EXPECT_EQ(0, q); EXPECT_EQ(0, r); a = absl::MakeUint128(0x530eda741c71d4c3, 0xbf25975319080000); q = absl::MakeUint128(0x4de2cab081, 0x14c34ab4676e4bab); b = absl::uint128(0x1110001); r = absl::uint128(0x3eb455); ASSERT_EQ(a, q * b + r); absl::uint128 result_q, result_r; result_q = a / b; result_r = a % b; EXPECT_EQ(q, result_q); EXPECT_EQ(r, result_r); swap(q, b); result_q = a / b; result_r = a % b; EXPECT_EQ(q, result_q); EXPECT_EQ(r, result_r); swap(b, q); swap(a, b); result_q = a / b; result_r = a % b; EXPECT_EQ(0, result_q); EXPECT_EQ(a, result_r); swap(a, q); result_q = a / b; result_r = a % b; EXPECT_EQ(0, result_q); EXPECT_EQ(a, result_r); swap(q, a); swap(b, a); b = a / 2 + 1; absl::uint128 expected_r = absl::MakeUint128(0x29876d3a0e38ea61, 0xdf92cba98c83ffff); ASSERT_EQ(a / 2 - 1, expected_r); ASSERT_EQ(a, b + expected_r); result_q = a / b; result_r = a % b; EXPECT_EQ(1, result_q); EXPECT_EQ(expected_r, result_r); } TEST(Uint128, DivideAndModRandomInputs) { const int kNumIters = 1 << 18; std::minstd_rand random(testing::UnitTest::GetInstance()->random_seed()); std::uniform_int_distribution<uint64_t> uniform_uint64; for (int i = 0; i < kNumIters; ++i) { const absl::uint128 a = absl::MakeUint128(uniform_uint64(random), uniform_uint64(random)); const absl::uint128 b = absl::MakeUint128(uniform_uint64(random), uniform_uint64(random)); if (b == 0) { continue; } const absl::uint128 q = a / b; const absl::uint128 r = a % b; ASSERT_EQ(a, b * q + r); } } TEST(Uint128, ConstexprTest) { constexpr absl::uint128 zero = absl::uint128(); constexpr absl::uint128 one = 1; constexpr absl::uint128 minus_two = -2; EXPECT_EQ(zero, absl::uint128(0)); EXPECT_EQ(one, absl::uint128(1)); EXPECT_EQ(minus_two, absl::MakeUint128(-1, -2)); } TEST(Uint128, NumericLimitsTest) { static_assert(std::numeric_limits<absl::uint128>::is_specialized, ""); static_assert(!std::numeric_limits<absl::uint128>::is_signed, ""); static_assert(std::numeric_limits<absl::uint128>::is_integer, ""); EXPECT_EQ(static_cast<int>(128 * std::log10(2)), std::numeric_limits<absl::uint128>::digits10); EXPECT_EQ(0, std::numeric_limits<absl::uint128>::min()); EXPECT_EQ(0, std::numeric_limits<absl::uint128>::lowest()); EXPECT_EQ(absl::Uint128Max(), std::numeric_limits<absl::uint128>::max()); } TEST(Uint128, Hash) { EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({ absl::uint128{0}, absl::uint128{1}, ~absl::uint128{}, absl::uint128{std::numeric_limits<int64_t>::max()}, absl::uint128{std::numeric_limits<uint64_t>::max()} + 0, absl::uint128{std::numeric_limits<uint64_t>::max()} + 1, absl::uint128{std::numeric_limits<uint64_t>::max()} + 2, absl::uint128{1} << 62, absl::uint128{1} << 63, absl::uint128{1} << 64, absl::uint128{1} << 65, std::numeric_limits<absl::uint128>::max(), std::numeric_limits<absl::uint128>::max() - 1, std::numeric_limits<absl::uint128>::min() + 1, std::numeric_limits<absl::uint128>::min(), })); } TEST(Int128Uint128, ConversionTest) { absl::int128 nonnegative_signed_values[] = { 0, 1, 0xffeeddccbbaa9988, absl::MakeInt128(0x7766554433221100, 0), absl::MakeInt128(0x1234567890abcdef, 0xfedcba0987654321), absl::Int128Max()}; for (absl::int128 value : nonnegative_signed_values) { EXPECT_EQ(value, absl::int128(absl::uint128(value))); absl::uint128 assigned_value; assigned_value = value; EXPECT_EQ(value, absl::int128(assigned_value)); } absl::int128 negative_values[] = { -1, -0x1234567890abcdef, absl::MakeInt128(-0x5544332211ffeedd, 0), -absl::MakeInt128(0x76543210fedcba98, 0xabcdef0123456789)}; for (absl::int128 value : negative_values) { EXPECT_EQ(absl::uint128(-value), -absl::uint128(value)); absl::uint128 assigned_value; assigned_value = value; EXPECT_EQ(absl::uint128(-value), -assigned_value); } } template <typename T> class Int128IntegerTraitsTest : public ::testing::Test {}; TYPED_TEST_SUITE(Int128IntegerTraitsTest, IntegerTypes); TYPED_TEST(Int128IntegerTraitsTest, ConstructAssignTest) { static_assert(std::is_constructible<absl::int128, TypeParam>::value, "absl::int128 must be constructible from TypeParam"); static_assert(std::is_assignable<absl::int128&, TypeParam>::value, "absl::int128 must be assignable from TypeParam"); static_assert(!std::is_assignable<TypeParam&, absl::int128>::value, "TypeParam must not be assignable from absl::int128"); } template <typename T> class Int128FloatTraitsTest : public ::testing::Test {}; TYPED_TEST_SUITE(Int128FloatTraitsTest, FloatingPointTypes); TYPED_TEST(Int128FloatTraitsTest, ConstructAssignTest) { static_assert(std::is_constructible<absl::int128, TypeParam>::value, "absl::int128 must be constructible from TypeParam"); static_assert(!std::is_assignable<absl::int128&, TypeParam>::value, "absl::int128 must not be assignable from TypeParam"); static_assert(!std::is_assignable<TypeParam&, absl::int128>::value, "TypeParam must not be assignable from absl::int128"); } #ifdef ABSL_HAVE_INTRINSIC_INT128 TEST(Int128, IntrinsicTypeTraitsTest) { static_assert(std::is_constructible<absl::int128, __int128>::value, "absl::int128 must be constructible from __int128"); static_assert(std::is_assignable<absl::int128&, __int128>::value, "absl::int128 must be assignable from __int128"); static_assert(!std::is_assignable<__int128&, absl::int128>::value, "__int128 must not be assignable from absl::int128"); static_assert(std::is_constructible<absl::int128, unsigned __int128>::value, "absl::int128 must be constructible from unsigned __int128"); static_assert(!std::is_assignable<absl::int128&, unsigned __int128>::value, "absl::int128 must be assignable from unsigned __int128"); static_assert(!std::is_assignable<unsigned __int128&, absl::int128>::value, "unsigned __int128 must not be assignable from absl::int128"); } #endif TEST(Int128, TrivialTraitsTest) { static_assert(absl::is_trivially_default_constructible<absl::int128>::value, ""); static_assert(absl::is_trivially_copy_constructible<absl::int128>::value, ""); static_assert(absl::is_trivially_copy_assignable<absl::int128>::value, ""); static_assert(std::is_trivially_destructible<absl::int128>::value, ""); } TEST(Int128, BoolConversionTest) { EXPECT_FALSE(absl::int128(0)); for (int i = 0; i < 64; ++i) { EXPECT_TRUE(absl::MakeInt128(0, uint64_t{1} << i)); } for (int i = 0; i < 63; ++i) { EXPECT_TRUE(absl::MakeInt128(int64_t{1} << i, 0)); } EXPECT_TRUE(absl::Int128Min()); EXPECT_EQ(absl::int128(1), absl::int128(true)); EXPECT_EQ(absl::int128(0), absl::int128(false)); } template <typename T> class Int128IntegerConversionTest : public ::testing::Test {}; TYPED_TEST_SUITE(Int128IntegerConversionTest, IntegerTypes); TYPED_TEST(Int128IntegerConversionTest, RoundTripTest) { EXPECT_EQ(TypeParam{0}, static_cast<TypeParam>(absl::int128(0))); EXPECT_EQ(std::numeric_limits<TypeParam>::min(), static_cast<TypeParam>( absl::int128(std::numeric_limits<TypeParam>::min()))); EXPECT_EQ(std::numeric_limits<TypeParam>::max(), static_cast<TypeParam>( absl::int128(std::numeric_limits<TypeParam>::max()))); } template <typename T> class Int128FloatConversionTest : public ::testing::Test {}; TYPED_TEST_SUITE(Int128FloatConversionTest, FloatingPointTypes); TYPED_TEST(Int128FloatConversionTest, ConstructAndCastTest) { for (int i = 0; i < 110; ++i) { SCOPED_TRACE(::testing::Message() << "i = " << i); TypeParam float_value = std::ldexp(static_cast<TypeParam>(0x9f5b), i); absl::int128 int_value = absl::int128(0x9f5b) << i; EXPECT_EQ(float_value, static_cast<TypeParam>(int_value)); EXPECT_EQ(-float_value, static_cast<TypeParam>(-int_value)); EXPECT_EQ(int_value, absl::int128(float_value)); EXPECT_EQ(-int_value, absl::int128(-float_value)); } uint64_t values[] = {0x6d4492c24fb86199, 0x26ead65e4cb359b5, 0x2c43407433ba3fd1, 0x3b574ec668df6b55, 0x1c750e55a29f4f0f}; for (uint64_t value : values) { for (int i = 0; i <= 64; ++i) { SCOPED_TRACE(::testing::Message() << "value = " << value << "; i = " << i); TypeParam fvalue = std::ldexp(static_cast<TypeParam>(value), i); EXPECT_DOUBLE_EQ(fvalue, static_cast<TypeParam>(absl::int128(fvalue))); EXPECT_DOUBLE_EQ(-fvalue, static_cast<TypeParam>(-absl::int128(fvalue))); EXPECT_DOUBLE_EQ(-fvalue, static_cast<TypeParam>(absl::int128(-fvalue))); EXPECT_DOUBLE_EQ(fvalue, static_cast<TypeParam>(-absl::int128(-fvalue))); } } absl::int128 large_values[] = { absl::MakeInt128(0x5b0640d96c7b3d9f, 0xb7a7189e51d18622), absl::MakeInt128(0x34bed042c6f65270, 0x73b236570669a089), absl::MakeInt128(0x43deba9e6da12724, 0xf7f0f83da686797d), absl::MakeInt128(0x71e8d383be4e5589, 0x75c3f96fb00752b6)}; for (absl::int128 value : large_values) { value >>= (127 - std::numeric_limits<TypeParam>::digits); value |= absl::int128(1) << (std::numeric_limits<TypeParam>::digits - 1); value |= 1; for (int i = 0; i < 127 - std::numeric_limits<TypeParam>::digits; ++i) { absl::int128 int_value = value << i; EXPECT_EQ(int_value, static_cast<absl::int128>(static_cast<TypeParam>(int_value))); EXPECT_EQ(-int_value, static_cast<absl::int128>(static_cast<TypeParam>(-int_value))); } } EXPECT_EQ(0, absl::int128(TypeParam(0.1))); EXPECT_EQ(17, absl::int128(TypeParam(17.8))); EXPECT_EQ(0, absl::int128(TypeParam(-0.8))); EXPECT_EQ(-53, absl::int128(TypeParam(-53.1))); EXPECT_EQ(0, absl::int128(TypeParam(0.5))); EXPECT_EQ(0, absl::int128(TypeParam(-0.5))); TypeParam just_lt_one = std::nexttoward(TypeParam(1), TypeParam(0)); EXPECT_EQ(0, absl::int128(just_lt_one)); TypeParam just_gt_minus_one = std::nexttoward(TypeParam(-1), TypeParam(0)); EXPECT_EQ(0, absl::int128(just_gt_minus_one)); EXPECT_DOUBLE_EQ(std::ldexp(static_cast<TypeParam>(1), 127), static_cast<TypeParam>(absl::Int128Max())); EXPECT_DOUBLE_EQ(-std::ldexp(static_cast<TypeParam>(1), 127), static_cast<TypeParam>(absl::Int128Min())); } TEST(Int128, FactoryTest) { EXPECT_EQ(absl::int128(-1), absl::MakeInt128(-1, -1)); EXPECT_EQ(absl::int128(-31), absl::MakeInt128(-1, -31)); EXPECT_EQ(absl::int128(std::numeric_limits<int64_t>::min()), absl::MakeInt128(-1, std::numeric_limits<int64_t>::min())); EXPECT_EQ(absl::int128(0), absl::MakeInt128(0, 0)); EXPECT_EQ(absl::int128(1), absl::MakeInt128(0, 1)); EXPECT_EQ(absl::int128(std::numeric_limits<int64_t>::max()), absl::MakeInt128(0, std::numeric_limits<int64_t>::max())); } TEST(Int128, HighLowTest) { struct HighLowPair { int64_t high; uint64_t low; }; HighLowPair values[]{{0, 0}, {0, 1}, {1, 0}, {123, 456}, {-654, 321}}; for (const HighLowPair& pair : values) { absl::int128 value = absl::MakeInt128(pair.high, pair.low); EXPECT_EQ(pair.low, absl::Int128Low64(value)); EXPECT_EQ(pair.high, absl::Int128High64(value)); } } TEST(Int128, LimitsTest) { EXPECT_EQ(absl::MakeInt128(0x7fffffffffffffff, 0xffffffffffffffff), absl::Int128Max()); EXPECT_EQ(absl::Int128Max(), ~absl::Int128Min()); } #if defined(ABSL_HAVE_INTRINSIC_INT128) TEST(Int128, IntrinsicConversionTest) { __int128 intrinsic = (static_cast<__int128>(0x3a5b76c209de76f6) << 64) + 0x1f25e1d63a2b46c5; absl::int128 custom = absl::MakeInt128(0x3a5b76c209de76f6, 0x1f25e1d63a2b46c5); EXPECT_EQ(custom, absl::int128(intrinsic)); EXPECT_EQ(intrinsic, static_cast<__int128>(custom)); } #endif TEST(Int128, ConstexprTest) { constexpr absl::int128 zero = absl::int128(); constexpr absl::int128 one = 1; constexpr absl::int128 minus_two = -2; constexpr absl::int128 min = absl::Int128Min(); constexpr absl::int128 max = absl::Int128Max(); EXPECT_EQ(zero, absl::int128(0)); EXPECT_EQ(one, absl::int128(1)); EXPECT_EQ(minus_two, absl::MakeInt128(-1, -2)); EXPECT_GT(max, one); EXPECT_LT(min, minus_two); } TEST(Int128, ComparisonTest) { struct TestCase { absl::int128 smaller; absl::int128 larger; }; TestCase cases[] = { {absl::int128(0), absl::int128(123)}, {absl::MakeInt128(-12, 34), absl::MakeInt128(12, 34)}, {absl::MakeInt128(1, 1000), absl::MakeInt128(1000, 1)}, {absl::MakeInt128(-1000, 1000), absl::MakeInt128(-1, 1)}, }; for (const TestCase& pair : cases) { SCOPED_TRACE(::testing::Message() << "pair.smaller = " << pair.smaller << "; pair.larger = " << pair.larger); EXPECT_TRUE(pair.smaller == pair.smaller); EXPECT_TRUE(pair.larger == pair.larger); EXPECT_FALSE(pair.smaller == pair.larger); EXPECT_TRUE(pair.smaller != pair.larger); EXPECT_FALSE(pair.smaller != pair.smaller); EXPECT_FALSE(pair.larger != pair.larger); EXPECT_TRUE(pair.smaller < pair.larger); EXPECT_FALSE(pair.larger < pair.smaller); EXPECT_TRUE(pair.larger > pair.smaller); EXPECT_FALSE(pair.smaller > pair.larger); EXPECT_TRUE(pair.smaller <= pair.larger); EXPECT_FALSE(pair.larger <= pair.smaller); EXPECT_TRUE(pair.smaller <= pair.smaller); EXPECT_TRUE(pair.larger <= pair.larger); EXPECT_TRUE(pair.larger >= pair.smaller); EXPECT_FALSE(pair.smaller >= pair.larger); EXPECT_TRUE(pair.smaller >= pair.smaller); EXPECT_TRUE(pair.larger >= pair.larger); #ifdef __cpp_impl_three_way_comparison EXPECT_EQ(pair.smaller <=> pair.larger, absl::strong_ordering::less); EXPECT_EQ(pair.larger <=> pair.smaller, absl::strong_ordering::greater); EXPECT_EQ(pair.smaller <=> pair.smaller, absl::strong_ordering::equal); EXPECT_EQ(pair.larger <=> pair.larger, absl::strong_ordering::equal); #endif } } TEST(Int128, UnaryPlusTest) { int64_t values64[] = {0, 1, 12345, 0x4000000000000000, std::numeric_limits<int64_t>::max()}; for (int64_t value : values64) { SCOPED_TRACE(::testing::Message() << "value = " << value); EXPECT_EQ(absl::int128(value), +absl::int128(value)); EXPECT_EQ(absl::int128(-value), +absl::int128(-value)); EXPECT_EQ(absl::MakeInt128(value, 0), +absl::MakeInt128(value, 0)); EXPECT_EQ(absl::MakeInt128(-value, 0), +absl::MakeInt128(-value, 0)); } } TEST(Int128, UnaryNegationTest) { int64_t values64[] = {0, 1, 12345, 0x4000000000000000, std::numeric_limits<int64_t>::max()}; for (int64_t value : values64) { SCOPED_TRACE(::testing::Message() << "value = " << value); EXPECT_EQ(absl::int128(-value), -absl::int128(value)); EXPECT_EQ(absl::int128(value), -absl::int128(-value)); EXPECT_EQ(absl::MakeInt128(-value, 0), -absl::MakeInt128(value, 0)); EXPECT_EQ(absl::MakeInt128(value, 0), -absl::MakeInt128(-value, 0)); } } TEST(Int128, LogicalNotTest) { EXPECT_TRUE(!absl::int128(0)); for (int i = 0; i < 64; ++i) { EXPECT_FALSE(!absl::MakeInt128(0, uint64_t{1} << i)); } for (int i = 0; i < 63; ++i) { EXPECT_FALSE(!absl::MakeInt128(int64_t{1} << i, 0)); } } TEST(Int128, AdditionSubtractionTest) { std::pair<int64_t, int64_t> cases[]{ {0, 0}, {0, 2945781290834}, {1908357619234, 0}, {0, -1204895918245}, {-2957928523560, 0}, {89023982312461, 98346012567134}, {-63454234568239, -23456235230773}, {98263457263502, -21428561935925}, {-88235237438467, 15923659234573}, }; for (const auto& pair : cases) { SCOPED_TRACE(::testing::Message() << "pair = {" << pair.first << ", " << pair.second << '}'); EXPECT_EQ(absl::int128(pair.first + pair.second), absl::int128(pair.first) + absl::int128(pair.second)); EXPECT_EQ(absl::int128(pair.second + pair.first), absl::int128(pair.second) += absl::int128(pair.first)); EXPECT_EQ(absl::int128(pair.first - pair.second), absl::int128(pair.first) - absl::int128(pair.second)); EXPECT_EQ(absl::int128(pair.second - pair.first), absl::int128(pair.second) -= absl::int128(pair.first)); EXPECT_EQ( absl::MakeInt128(pair.second + pair.first, 0), absl::MakeInt128(pair.second, 0) + absl::MakeInt128(pair.first, 0)); EXPECT_EQ( absl::MakeInt128(pair.first + pair.second, 0), absl::MakeInt128(pair.first, 0) += absl::MakeInt128(pair.second, 0)); EXPECT_EQ( absl::MakeInt128(pair.second - pair.first, 0), absl::MakeInt128(pair.second, 0) - absl::MakeInt128(pair.first, 0)); EXPECT_EQ( absl::MakeInt128(pair.first - pair.second, 0), absl::MakeInt128(pair.first, 0) -= absl::MakeInt128(pair.second, 0)); } EXPECT_EQ(absl::MakeInt128(31, 0), absl::MakeInt128(20, 1) + absl::MakeInt128(10, std::numeric_limits<uint64_t>::max())); } TEST(Int128, IncrementDecrementTest) { absl::int128 value = 0; EXPECT_EQ(0, value++); EXPECT_EQ(1, value); EXPECT_EQ(1, value--); EXPECT_EQ(0, value); EXPECT_EQ(-1, --value); EXPECT_EQ(-1, value); EXPECT_EQ(0, ++value); EXPECT_EQ(0, value); } TEST(Int128, MultiplicationTest) { for (int i = 0; i < 64; ++i) { for (int j = 0; j < 127 - i; ++j) { SCOPED_TRACE(::testing::Message() << "i = " << i << "; j = " << j); absl::int128 a = absl::int128(1) << i; absl::int128 b = absl::int128(1) << j; absl::int128 c = absl::int128(1) << (i + j); EXPECT_EQ(c, a * b); EXPECT_EQ(-c, -a * b); EXPECT_EQ(-c, a * -b); EXPECT_EQ(c, -a * -b); EXPECT_EQ(c, absl::int128(a) *= b); EXPECT_EQ(-c, absl::int128(-a) *= b); EXPECT_EQ(-c, absl::int128(a) *= -b); EXPECT_EQ(c, absl::int128(-a) *= -b); } } std::pair<int64_t, int64_t> small_values[] = { {0x5e61, 0xf29f79ca14b4}, {0x3e033b, -0x612c0ee549}, {-0x052ce7e8, 0x7c728f0f}, {-0x3af7054626, -0xfb1e1d}, }; for (const std::pair<int64_t, int64_t>& pair : small_values) { SCOPED_TRACE(::testing::Message() << "pair = {" << pair.first << ", " << pair.second << '}'); EXPECT_EQ(absl::int128(pair.first * pair.second), absl::int128(pair.first) * absl::int128(pair.second)); EXPECT_EQ(absl::int128(pair.first * pair.second), absl::int128(pair.first) *= absl::int128(pair.second)); EXPECT_EQ(absl::MakeInt128(pair.first * pair.second, 0), absl::MakeInt128(pair.first, 0) * absl::int128(pair.second)); EXPECT_EQ(absl::MakeInt128(pair.first * pair.second, 0), absl::MakeInt128(pair.first, 0) *= absl::int128(pair.second)); } std::pair<int64_t, int64_t> small_values2[] = { {0x1bb0a110, 0x31487671}, {0x4792784e, 0x28add7d7}, {0x7b66553a, 0x11dff8ef}, }; for (const std::pair<int64_t, int64_t>& pair : small_values2) { SCOPED_TRACE(::testing::Message() << "pair = {" << pair.first << ", " << pair.second << '}'); absl::int128 a = absl::int128(pair.first << 32); absl::int128 b = absl::int128(pair.second << 32); absl::int128 c = absl::MakeInt128(pair.first * pair.second, 0); EXPECT_EQ(c, a * b); EXPECT_EQ(-c, -a * b); EXPECT_EQ(-c, a * -b); EXPECT_EQ(c, -a * -b); EXPECT_EQ(c, absl::int128(a) *= b); EXPECT_EQ(-c, absl::int128(-a) *= b); EXPECT_EQ(-c, absl::int128(a) *= -b); EXPECT_EQ(c, absl::int128(-a) *= -b); } absl::int128 large_values[] = { {absl::MakeInt128(0xd66f061af02d0408, 0x727d2846cb475b53)}, {absl::MakeInt128(0x27b8d5ed6104452d, 0x03f8a33b0ee1df4f)}, {-absl::MakeInt128(0x621b6626b9e8d042, 0x27311ac99df00938)}, {-absl::MakeInt128(0x34e0656f1e95fb60, 0x4281cfd731257a47)}, }; for (absl::int128 value : large_values) { EXPECT_EQ(0, 0 * value); EXPECT_EQ(0, value * 0); EXPECT_EQ(0, absl::int128(0) *= value); EXPECT_EQ(0, value *= 0); EXPECT_EQ(value, 1 * value); EXPECT_EQ(value, value * 1); EXPECT_EQ(value, absl::int128(1) *= value); EXPECT_EQ(value, value *= 1); EXPECT_EQ(-value, -1 * value); EXPECT_EQ(-value, value * -1); EXPECT_EQ(-value, absl::int128(-1) *= value); EXPECT_EQ(-value, value *= -1); } EXPECT_EQ(absl::MakeInt128(0xcd0efd3442219bb, 0xde47c05bcd9df6e1), absl::MakeInt128(0x7c6448, 0x3bc4285c47a9d253) * 0x1a6037537b); EXPECT_EQ(-absl::MakeInt128(0x1f8f149850b1e5e6, 0x1e50d6b52d272c3e), -absl::MakeInt128(0x23, 0x2e68a513ca1b8859) * 0xe5a434cd14866e); EXPECT_EQ(-absl::MakeInt128(0x55cae732029d1fce, 0xca6474b6423263e4), 0xa9b98a8ddf66bc * -absl::MakeInt128(0x81, 0x672e58231e2469d7)); EXPECT_EQ(absl::MakeInt128(0x19c8b7620b507dc4, 0xfec042b71a5f29a4), -0x3e39341147 * -absl::MakeInt128(0x6a14b2, 0x5ed34cca42327b3c)); EXPECT_EQ(absl::MakeInt128(0xcd0efd3442219bb, 0xde47c05bcd9df6e1), absl::MakeInt128(0x7c6448, 0x3bc4285c47a9d253) *= 0x1a6037537b); EXPECT_EQ(-absl::MakeInt128(0x1f8f149850b1e5e6, 0x1e50d6b52d272c3e), -absl::MakeInt128(0x23, 0x2e68a513ca1b8859) *= 0xe5a434cd14866e); EXPECT_EQ(-absl::MakeInt128(0x55cae732029d1fce, 0xca6474b6423263e4), absl::int128(0xa9b98a8ddf66bc) *= -absl::MakeInt128(0x81, 0x672e58231e2469d7)); EXPECT_EQ(absl::MakeInt128(0x19c8b7620b507dc4, 0xfec042b71a5f29a4), absl::int128(-0x3e39341147) *= -absl::MakeInt128(0x6a14b2, 0x5ed34cca42327b3c)); } TEST(Int128, DivisionAndModuloTest) { std::pair<int64_t, int64_t> small_pairs[] = { {0x15f2a64138, 0x67da05}, {0x5e56d194af43045f, 0xcf1543fb99}, {0x15e61ed052036a, -0xc8e6}, {0x88125a341e85, -0xd23fb77683}, {-0xc06e20, 0x5a}, {-0x4f100219aea3e85d, 0xdcc56cb4efe993}, {-0x168d629105, -0xa7}, {-0x7b44e92f03ab2375, -0x6516}, }; for (const std::pair<int64_t, int64_t>& pair : small_pairs) { SCOPED_TRACE(::testing::Message() << "pair = {" << pair.first << ", " << pair.second << '}'); absl::int128 dividend = pair.first; absl::int128 divisor = pair.second; int64_t quotient = pair.first / pair.second; int64_t remainder = pair.first % pair.second; EXPECT_EQ(quotient, dividend / divisor); EXPECT_EQ(quotient, absl::int128(dividend) /= divisor); EXPECT_EQ(remainder, dividend % divisor); EXPECT_EQ(remainder, absl::int128(dividend) %= divisor); } absl::int128 values[] = { absl::MakeInt128(0x63d26ee688a962b2, 0x9e1411abda5c1d70), absl::MakeInt128(0x152f385159d6f986, 0xbf8d48ef63da395d), -absl::MakeInt128(0x3098d7567030038c, 0x14e7a8a098dc2164), -absl::MakeInt128(0x49a037aca35c809f, 0xa6a87525480ef330), }; for (absl::int128 value : values) { SCOPED_TRACE(::testing::Message() << "value = " << value); EXPECT_EQ(0, 0 / value); EXPECT_EQ(0, absl::int128(0) /= value); EXPECT_EQ(0, 0 % value); EXPECT_EQ(0, absl::int128(0) %= value); EXPECT_EQ(value, value / 1); EXPECT_EQ(value, absl::int128(value) /= 1); EXPECT_EQ(0, value % 1); EXPECT_EQ(0, absl::int128(value) %= 1); EXPECT_EQ(-value, value / -1); EXPECT_EQ(-value, absl::int128(value) /= -1); EXPECT_EQ(0, value % -1); EXPECT_EQ(0, absl::int128(value) %= -1); } EXPECT_EQ(0, absl::Int128Max() / absl::Int128Min()); EXPECT_EQ(absl::Int128Max(), absl::Int128Max() % absl::Int128Min()); EXPECT_EQ(-1, absl::Int128Min() / absl::Int128Max()); EXPECT_EQ(-1, absl::Int128Min() % absl::Int128Max()); absl::int128 positive_values[] = { absl::MakeInt128(0x21e1a1cc69574620, 0xe7ac447fab2fc869), absl::MakeInt128(0x32c2ff3ab89e66e8, 0x03379a613fd1ce74), absl::MakeInt128(0x6f32ca786184dcaf, 0x046f9c9ecb3a9ce1), absl::MakeInt128(0x1aeb469dd990e0ee, 0xda2740f243cd37eb), }; for (absl::int128 value : positive_values) { for (int i = 0; i < 127; ++i) { SCOPED_TRACE(::testing::Message() << "value = " << value << "; i = " << i); absl::int128 power_of_two = absl::int128(1) << i; EXPECT_EQ(value >> i, value / power_of_two); EXPECT_EQ(value >> i, absl::int128(value) /= power_of_two); EXPECT_EQ(value & (power_of_two - 1), value % power_of_two); EXPECT_EQ(value & (power_of_two - 1), absl::int128(value) %= power_of_two); } } struct DivisionModCase { absl::int128 dividend; absl::int128 divisor; absl::int128 quotient; absl::int128 remainder; }; DivisionModCase manual_cases[] = { {absl::MakeInt128(0x6ada48d489007966, 0x3c9c5c98150d5d69), absl::MakeInt128(0x8bc308fb, 0x8cb9cc9a3b803344), 0xc3b87e08, absl::MakeInt128(0x1b7db5e1, 0xd9eca34b7af04b49)}, {absl::MakeInt128(0xd6946511b5b, 0x4886c5c96546bf5f), -absl::MakeInt128(0x263b, 0xfd516279efcfe2dc), -0x59cbabf0, absl::MakeInt128(0x622, 0xf462909155651d1f)}, {-absl::MakeInt128(0x33db734f9e8d1399, 0x8447ac92482bca4d), 0x37495078240, -absl::MakeInt128(0xf01f1, 0xbc0368bf9a77eae8), -0x21a508f404d}, {-absl::MakeInt128(0x13f837b409a07e7d, 0x7fc8e248a7d73560), -0x1b9f, absl::MakeInt128(0xb9157556d724, 0xb14f635714d7563e), -0x1ade}, }; for (const DivisionModCase test_case : manual_cases) { EXPECT_EQ(test_case.quotient, test_case.dividend / test_case.divisor); EXPECT_EQ(test_case.quotient, absl::int128(test_case.dividend) /= test_case.divisor); EXPECT_EQ(test_case.remainder, test_case.dividend % test_case.divisor); EXPECT_EQ(test_case.remainder, absl::int128(test_case.dividend) %= test_case.divisor); } } TEST(Int128, BitwiseLogicTest) { EXPECT_EQ(absl::int128(-1), ~absl::int128(0)); absl::int128 values[]{ 0, -1, 0xde400bee05c3ff6b, absl::MakeInt128(0x7f32178dd81d634a, 0), absl::MakeInt128(0xaf539057055613a9, 0x7d104d7d946c2e4d)}; for (absl::int128 value : values) { EXPECT_EQ(value, ~~value); EXPECT_EQ(value, value | value); EXPECT_EQ(value, value & value); EXPECT_EQ(0, value ^ value); EXPECT_EQ(value, absl::int128(value) |= value); EXPECT_EQ(value, absl::int128(value) &= value); EXPECT_EQ(0, absl::int128(value) ^= value); EXPECT_EQ(value, value | 0); EXPECT_EQ(0, value & 0); EXPECT_EQ(value, value ^ 0); EXPECT_EQ(absl::int128(-1), value | absl::int128(-1)); EXPECT_EQ(value, value & absl::int128(-1)); EXPECT_EQ(~value, value ^ absl::int128(-1)); } std::pair<int64_t, int64_t> pairs64[]{ {0x7f86797f5e991af4, 0x1ee30494fb007c97}, {0x0b278282bacf01af, 0x58780e0a57a49e86}, {0x059f266ccb93a666, 0x3d5b731bae9286f5}, {0x63c0c4820f12108c, 0x58166713c12e1c3a}, {0x381488bb2ed2a66e, 0x2220a3eb76a3698c}, {0x2a0a0dfb81e06f21, 0x4b60585927f5523c}, {0x555b1c3a03698537, 0x25478cd19d8e53cb}, {0x4750f6f27d779225, 0x16397553c6ff05fc}, }; for (const std::pair<int64_t, int64_t>& pair : pairs64) { SCOPED_TRACE(::testing::Message() << "pair = {" << pair.first << ", " << pair.second << '}'); EXPECT_EQ(absl::MakeInt128(~pair.first, ~pair.second), ~absl::MakeInt128(pair.first, pair.second)); EXPECT_EQ(absl::int128(pair.first & pair.second), absl::int128(pair.first) & absl::int128(pair.second)); EXPECT_EQ(absl::int128(pair.first | pair.second), absl::int128(pair.first) | absl::int128(pair.second)); EXPECT_EQ(absl::int128(pair.first ^ pair.second), absl::int128(pair.first) ^ absl::int128(pair.second)); EXPECT_EQ(absl::int128(pair.first & pair.second), absl::int128(pair.first) &= absl::int128(pair.second)); EXPECT_EQ(absl::int128(pair.first | pair.second), absl::int128(pair.first) |= absl::int128(pair.second)); EXPECT_EQ(absl::int128(pair.first ^ pair.second), absl::int128(pair.first) ^= absl::int128(pair.second)); EXPECT_EQ( absl::MakeInt128(pair.first & pair.second, 0), absl::MakeInt128(pair.first, 0) & absl::MakeInt128(pair.second, 0)); EXPECT_EQ( absl::MakeInt128(pair.first | pair.second, 0), absl::MakeInt128(pair.first, 0) | absl::MakeInt128(pair.second, 0)); EXPECT_EQ( absl::MakeInt128(pair.first ^ pair.second, 0), absl::MakeInt128(pair.first, 0) ^ absl::MakeInt128(pair.second, 0)); EXPECT_EQ( absl::MakeInt128(pair.first & pair.second, 0), absl::MakeInt128(pair.first, 0) &= absl::MakeInt128(pair.second, 0)); EXPECT_EQ( absl::MakeInt128(pair.first | pair.second, 0), absl::MakeInt128(pair.first, 0) |= absl::MakeInt128(pair.second, 0)); EXPECT_EQ( absl::MakeInt128(pair.first ^ pair.second, 0), absl::MakeInt128(pair.first, 0) ^= absl::MakeInt128(pair.second, 0)); } } TEST(Int128, BitwiseShiftTest) { for (int i = 0; i < 64; ++i) { for (int j = 0; j <= i; ++j) { SCOPED_TRACE(::testing::Message() << "i = " << i << "; j = " << j); EXPECT_EQ(uint64_t{1} << i, absl::int128(uint64_t{1} << j) << (i - j)); EXPECT_EQ(uint64_t{1} << i, absl::int128(uint64_t{1} << j) <<= (i - j)); } } for (int i = 0; i < 63; ++i) { for (int j = 0; j < 64; ++j) { SCOPED_TRACE(::testing::Message() << "i = " << i << "; j = " << j); EXPECT_EQ(absl::MakeInt128(uint64_t{1} << i, 0), absl::int128(uint64_t{1} << j) << (i + 64 - j)); EXPECT_EQ(absl::MakeInt128(uint64_t{1} << i, 0), absl::int128(uint64_t{1} << j) <<= (i + 64 - j)); } for (int j = 0; j <= i; ++j) { SCOPED_TRACE(::testing::Message() << "i = " << i << "; j = " << j); EXPECT_EQ(absl::MakeInt128(uint64_t{1} << i, 0), absl::MakeInt128(uint64_t{1} << j, 0) << (i - j)); EXPECT_EQ(absl::MakeInt128(uint64_t{1} << i, 0), absl::MakeInt128(uint64_t{1} << j, 0) <<= (i - j)); } } for (int i = 0; i < 64; ++i) { for (int j = i; j < 64; ++j) { SCOPED_TRACE(::testing::Message() << "i = " << i << "; j = " << j); EXPECT_EQ(uint64_t{1} << i, absl::int128(uint64_t{1} << j) >> (j - i)); EXPECT_EQ(uint64_t{1} << i, absl::int128(uint64_t{1} << j) >>= (j - i)); } for (int j = 0; j < 63; ++j) { SCOPED_TRACE(::testing::Message() << "i = " << i << "; j = " << j); EXPECT_EQ(uint64_t{1} << i, absl::MakeInt128(uint64_t{1} << j, 0) >> (j + 64 - i)); EXPECT_EQ(uint64_t{1} << i, absl::MakeInt128(uint64_t{1} << j, 0) >>= (j + 64 - i)); } } for (int i = 0; i < 63; ++i) { for (int j = i; j < 63; ++j) { SCOPED_TRACE(::testing::Message() << "i = " << i << "; j = " << j); EXPECT_EQ(absl::MakeInt128(uint64_t{1} << i, 0), absl::MakeInt128(uint64_t{1} << j, 0) >> (j - i)); EXPECT_EQ(absl::MakeInt128(uint64_t{1} << i, 0), absl::MakeInt128(uint64_t{1} << j, 0) >>= (j - i)); } } absl::int128 val1 = MAKE_INT128(0x123456789abcdef0, 0x123456789abcdef0); absl::int128 val2 = MAKE_INT128(0xfedcba0987654321, 0xfedcba0987654321); EXPECT_EQ(val1 << 63, MAKE_INT128(0x91a2b3c4d5e6f78, 0x0)); EXPECT_EQ(val1 << 64, MAKE_INT128(0x123456789abcdef0, 0x0)); EXPECT_EQ(val2 << 63, MAKE_INT128(0xff6e5d04c3b2a190, 0x8000000000000000)); EXPECT_EQ(val2 << 64, MAKE_INT128(0xfedcba0987654321, 0x0)); EXPECT_EQ(val1 << 126, MAKE_INT128(0x0, 0x0)); EXPECT_EQ(val2 << 126, MAKE_INT128(0x4000000000000000, 0x0)); EXPECT_EQ(val1 >> 63, MAKE_INT128(0x0, 0x2468acf13579bde0)); EXPECT_EQ(val1 >> 64, MAKE_INT128(0x0, 0x123456789abcdef0)); EXPECT_EQ(val2 >> 63, MAKE_INT128(0xffffffffffffffff, 0xfdb974130eca8643)); EXPECT_EQ(val2 >> 64, MAKE_INT128(0xffffffffffffffff, 0xfedcba0987654321)); EXPECT_EQ(val1 >> 126, MAKE_INT128(0x0, 0x0)); EXPECT_EQ(val2 >> 126, MAKE_INT128(0xffffffffffffffff, 0xffffffffffffffff)); } TEST(Int128, NumericLimitsTest) { static_assert(std::numeric_limits<absl::int128>::is_specialized, ""); static_assert(std::numeric_limits<absl::int128>::is_signed, ""); static_assert(std::numeric_limits<absl::int128>::is_integer, ""); EXPECT_EQ(static_cast<int>(127 * std::log10(2)), std::numeric_limits<absl::int128>::digits10); EXPECT_EQ(absl::Int128Min(), std::numeric_limits<absl::int128>::min()); EXPECT_EQ(absl::Int128Min(), std::numeric_limits<absl::int128>::lowest()); EXPECT_EQ(absl::Int128Max(), std::numeric_limits<absl::int128>::max()); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/numeric/int128.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/numeric/int128_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
71e6de22-7854-442a-a961-5d2995db949f
cpp
abseil/abseil-cpp
periodic_sampler
absl/profiling/internal/periodic_sampler.cc
absl/profiling/internal/periodic_sampler_test.cc
#include "absl/profiling/internal/periodic_sampler.h" #include <atomic> #include "absl/profiling/internal/exponential_biased.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace profiling_internal { int64_t PeriodicSamplerBase::GetExponentialBiased(int period) noexcept { return rng_.GetStride(period); } bool PeriodicSamplerBase::SubtleConfirmSample() noexcept { int current_period = period(); if (ABSL_PREDICT_FALSE(current_period < 2)) { stride_ = 0; return current_period == 1; } if (ABSL_PREDICT_FALSE(stride_ == 1)) { stride_ = static_cast<uint64_t>(-GetExponentialBiased(current_period)); if (static_cast<int64_t>(stride_) < -1) { ++stride_; return false; } } stride_ = static_cast<uint64_t>(-GetExponentialBiased(current_period)); return true; } } ABSL_NAMESPACE_END }
#include "absl/profiling/internal/periodic_sampler.h" #include <thread> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/macros.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace profiling_internal { namespace { using testing::Eq; using testing::Return; using testing::StrictMock; class MockPeriodicSampler : public PeriodicSamplerBase { public: virtual ~MockPeriodicSampler() = default; MOCK_METHOD(int, period, (), (const, noexcept)); MOCK_METHOD(int64_t, GetExponentialBiased, (int), (noexcept)); }; TEST(PeriodicSamplerBaseTest, Sample) { StrictMock<MockPeriodicSampler> sampler; EXPECT_CALL(sampler, period()).Times(3).WillRepeatedly(Return(16)); EXPECT_CALL(sampler, GetExponentialBiased(16)) .WillOnce(Return(2)) .WillOnce(Return(3)) .WillOnce(Return(4)); EXPECT_FALSE(sampler.Sample()); EXPECT_TRUE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); EXPECT_TRUE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); } TEST(PeriodicSamplerBaseTest, ImmediatelySample) { StrictMock<MockPeriodicSampler> sampler; EXPECT_CALL(sampler, period()).Times(2).WillRepeatedly(Return(16)); EXPECT_CALL(sampler, GetExponentialBiased(16)) .WillOnce(Return(1)) .WillOnce(Return(2)) .WillOnce(Return(3)); EXPECT_TRUE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); EXPECT_TRUE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); } TEST(PeriodicSamplerBaseTest, Disabled) { StrictMock<MockPeriodicSampler> sampler; EXPECT_CALL(sampler, period()).Times(3).WillRepeatedly(Return(0)); EXPECT_FALSE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); } TEST(PeriodicSamplerBaseTest, AlwaysOn) { StrictMock<MockPeriodicSampler> sampler; EXPECT_CALL(sampler, period()).Times(3).WillRepeatedly(Return(1)); EXPECT_TRUE(sampler.Sample()); EXPECT_TRUE(sampler.Sample()); EXPECT_TRUE(sampler.Sample()); } TEST(PeriodicSamplerBaseTest, Disable) { StrictMock<MockPeriodicSampler> sampler; EXPECT_CALL(sampler, period()).WillOnce(Return(16)); EXPECT_CALL(sampler, GetExponentialBiased(16)).WillOnce(Return(3)); EXPECT_FALSE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); EXPECT_CALL(sampler, period()).Times(2).WillRepeatedly(Return(0)); EXPECT_FALSE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); } TEST(PeriodicSamplerBaseTest, Enable) { StrictMock<MockPeriodicSampler> sampler; EXPECT_CALL(sampler, period()).WillOnce(Return(0)); EXPECT_FALSE(sampler.Sample()); EXPECT_CALL(sampler, period()).Times(2).WillRepeatedly(Return(16)); EXPECT_CALL(sampler, GetExponentialBiased(16)) .Times(2) .WillRepeatedly(Return(3)); EXPECT_FALSE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); EXPECT_TRUE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); EXPECT_FALSE(sampler.Sample()); } TEST(PeriodicSamplerTest, ConstructConstInit) { struct Tag {}; ABSL_CONST_INIT static PeriodicSampler<Tag> sampler; (void)sampler; } TEST(PeriodicSamplerTest, DefaultPeriod0) { struct Tag {}; PeriodicSampler<Tag> sampler; EXPECT_THAT(sampler.period(), Eq(0)); } TEST(PeriodicSamplerTest, DefaultPeriod) { struct Tag {}; PeriodicSampler<Tag, 100> sampler; EXPECT_THAT(sampler.period(), Eq(100)); } TEST(PeriodicSamplerTest, SetGlobalPeriod) { struct Tag1 {}; struct Tag2 {}; PeriodicSampler<Tag1, 25> sampler1; PeriodicSampler<Tag2, 50> sampler2; EXPECT_THAT(sampler1.period(), Eq(25)); EXPECT_THAT(sampler2.period(), Eq(50)); std::thread thread([] { PeriodicSampler<Tag1, 25> sampler1; PeriodicSampler<Tag2, 50> sampler2; EXPECT_THAT(sampler1.period(), Eq(25)); EXPECT_THAT(sampler2.period(), Eq(50)); sampler1.SetGlobalPeriod(10); sampler2.SetGlobalPeriod(20); }); thread.join(); EXPECT_THAT(sampler1.period(), Eq(10)); EXPECT_THAT(sampler2.period(), Eq(20)); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/profiling/internal/periodic_sampler.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/profiling/internal/periodic_sampler_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
08e41a57-7975-4039-80b9-0c4350a2cee0
cpp
abseil/abseil-cpp
exponential_biased
absl/profiling/internal/exponential_biased.cc
absl/profiling/internal/exponential_biased_test.cc
#include "absl/profiling/internal/exponential_biased.h" #include <stdint.h> #include <algorithm> #include <atomic> #include <cmath> #include <limits> #include "absl/base/attributes.h" #include "absl/base/optimization.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace profiling_internal { int64_t ExponentialBiased::GetSkipCount(int64_t mean) { if (ABSL_PREDICT_FALSE(!initialized_)) { Initialize(); } uint64_t rng = NextRandom(rng_); rng_ = rng; double q = static_cast<uint32_t>(rng >> (kPrngNumBits - 26)) + 1.0; double interval = bias_ + (std::log2(q) - 26) * (-std::log(2.0) * mean); if (interval > static_cast<double>(std::numeric_limits<int64_t>::max() / 2)) { return std::numeric_limits<int64_t>::max() / 2; } double value = std::rint(interval); bias_ = interval - value; return value; } int64_t ExponentialBiased::GetStride(int64_t mean) { return GetSkipCount(mean - 1) + 1; } void ExponentialBiased::Initialize() { ABSL_CONST_INIT static std::atomic<uint32_t> global_rand(0); uint64_t r = reinterpret_cast<uint64_t>(this) + global_rand.fetch_add(1, std::memory_order_relaxed); for (int i = 0; i < 20; ++i) { r = NextRandom(r); } rng_ = r; initialized_ = true; } } ABSL_NAMESPACE_END }
#include "absl/profiling/internal/exponential_biased.h" #include <stddef.h> #include <cmath> #include <cstdint> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_cat.h" using ::testing::Ge; namespace absl { ABSL_NAMESPACE_BEGIN namespace profiling_internal { namespace { MATCHER_P2(IsBetween, a, b, absl::StrCat(std::string(negation ? "isn't" : "is"), " between ", a, " and ", b)) { return a <= arg && arg <= b; } double AndersonDarlingInf(double z) { if (z < 2) { return exp(-1.2337141 / z) / sqrt(z) * (2.00012 + (0.247105 - (0.0649821 - (0.0347962 - (0.011672 - 0.00168691 * z) * z) * z) * z) * z); } return exp( -exp(1.0776 - (2.30695 - (0.43424 - (0.082433 - (0.008056 - 0.0003146 * z) * z) * z) * z) * z)); } double AndersonDarlingErrFix(int n, double x) { if (x > 0.8) { return (-130.2137 + (745.2337 - (1705.091 - (1950.646 - (1116.360 - 255.7844 * x) * x) * x) * x) * x) / n; } double cutoff = 0.01265 + 0.1757 / n; if (x < cutoff) { double t = x / cutoff; t = sqrt(t) * (1 - t) * (49 * t - 102); return t * (0.0037 / (n * n) + 0.00078 / n + 0.00006) / n; } else { double t = (x - cutoff) / (0.8 - cutoff); t = -0.00022633 + (6.54034 - (14.6538 - (14.458 - (8.259 - 1.91864 * t) * t) * t) * t) * t; return t * (0.04213 + 0.01365 / n) / n; } } double AndersonDarlingPValue(int n, double z) { double ad = AndersonDarlingInf(z); double errfix = AndersonDarlingErrFix(n, ad); return ad + errfix; } double AndersonDarlingStatistic(const std::vector<double>& random_sample) { size_t n = random_sample.size(); double ad_sum = 0; for (size_t i = 0; i < n; i++) { ad_sum += (2 * i + 1) * std::log(random_sample[i] * (1 - random_sample[n - 1 - i])); } const auto n_as_double = static_cast<double>(n); double ad_statistic = -n_as_double - 1 / n_as_double * ad_sum; return ad_statistic; } double AndersonDarlingTest(const std::vector<double>& random_sample) { double ad_statistic = AndersonDarlingStatistic(random_sample); double p = AndersonDarlingPValue(static_cast<int>(random_sample.size()), ad_statistic); return p; } TEST(ExponentialBiasedTest, CoinTossDemoWithGetSkipCount) { ExponentialBiased eb; for (int runs = 0; runs < 10; ++runs) { for (int64_t flips = eb.GetSkipCount(1); flips > 0; --flips) { printf("head..."); } printf("tail\n"); } int heads = 0; for (int i = 0; i < 10000000; i += 1 + eb.GetSkipCount(1)) { ++heads; } printf("Heads = %d (%f%%)\n", heads, 100.0 * heads / 10000000); } TEST(ExponentialBiasedTest, SampleDemoWithStride) { ExponentialBiased eb; int64_t stride = eb.GetStride(10); int samples = 0; for (int i = 0; i < 10000000; ++i) { if (--stride == 0) { ++samples; stride = eb.GetStride(10); } } printf("Samples = %d (%f%%)\n", samples, 100.0 * samples / 10000000); } TEST(ExponentialBiasedTest, TestNextRandom) { for (auto n : std::vector<size_t>({ 10, 100, 1000, 10000 })) { uint64_t x = 1; uint64_t max_prng_value = static_cast<uint64_t>(1) << 48; for (int i = 1; i <= 20; i++) { x = ExponentialBiased::NextRandom(x); } std::vector<uint64_t> int_random_sample(n); for (size_t i = 0; i < n; i++) { int_random_sample[i] = x; x = ExponentialBiased::NextRandom(x); } std::sort(int_random_sample.begin(), int_random_sample.end()); std::vector<double> random_sample(n); for (size_t i = 0; i < n; i++) { random_sample[i] = static_cast<double>(int_random_sample[i]) / max_prng_value; } double ad_pvalue = AndersonDarlingTest(random_sample); EXPECT_GT(std::min(ad_pvalue, 1 - ad_pvalue), 0.0001) << "prng is not uniform: n = " << n << " p = " << ad_pvalue; } } TEST(ExponentialBiasedTest, InitializationModes) { ABSL_CONST_INIT static ExponentialBiased eb_static; EXPECT_THAT(eb_static.GetSkipCount(2), Ge(0)); #ifdef ABSL_HAVE_THREAD_LOCAL thread_local ExponentialBiased eb_thread; EXPECT_THAT(eb_thread.GetSkipCount(2), Ge(0)); #endif ExponentialBiased eb_stack; EXPECT_THAT(eb_stack.GetSkipCount(2), Ge(0)); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/profiling/internal/exponential_biased.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/profiling/internal/exponential_biased_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
32a1da58-6a50-46e1-baa4-989c776d2ebd
cpp
abseil/abseil-cpp
die_if_null
absl/log/die_if_null.cc
absl/log/die_if_null_test.cc
#include "absl/log/die_if_null.h" #include "absl/base/config.h" #include "absl/log/log.h" #include "absl/strings/str_cat.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace log_internal { void DieBecauseNull(const char* file, int line, const char* exprtext) { LOG(FATAL).AtLocation(file, line) << absl::StrCat("Check failed: '", exprtext, "' Must be non-null"); } } ABSL_NAMESPACE_END }
#include "absl/log/die_if_null.h" #include <stdint.h> #include <memory> #include <utility> #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/log/internal/test_helpers.h" namespace { auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment( new absl::log_internal::LogTestEnvironment); TEST(AbslDieIfNull, Simple) { int64_t t; void* ptr = static_cast<void*>(&t); void* ref = ABSL_DIE_IF_NULL(ptr); ASSERT_EQ(ptr, ref); char* t_as_char; t_as_char = ABSL_DIE_IF_NULL(reinterpret_cast<char*>(&t)); (void)t_as_char; unsigned char* t_as_uchar; t_as_uchar = ABSL_DIE_IF_NULL(reinterpret_cast<unsigned char*>(&t)); (void)t_as_uchar; int* t_as_int; t_as_int = ABSL_DIE_IF_NULL(reinterpret_cast<int*>(&t)); (void)t_as_int; int64_t* t_as_int64_t; t_as_int64_t = ABSL_DIE_IF_NULL(reinterpret_cast<int64_t*>(&t)); (void)t_as_int64_t; std::unique_ptr<int64_t> sptr(new int64_t); EXPECT_EQ(sptr.get(), ABSL_DIE_IF_NULL(sptr).get()); ABSL_DIE_IF_NULL(sptr).reset(); int64_t* int_ptr = new int64_t(); EXPECT_EQ(int_ptr, ABSL_DIE_IF_NULL(std::unique_ptr<int64_t>(int_ptr)).get()); } #if GTEST_HAS_DEATH_TEST TEST(DeathCheckAbslDieIfNull, Simple) { void* ptr; ASSERT_DEATH({ ptr = ABSL_DIE_IF_NULL(nullptr); }, ""); (void)ptr; std::unique_ptr<int64_t> sptr; ASSERT_DEATH(ptr = ABSL_DIE_IF_NULL(sptr).get(), ""); } #endif TEST(AbslDieIfNull, DoesNotCompareSmartPointerToNULL) { std::unique_ptr<int> up(new int); EXPECT_EQ(&up, &ABSL_DIE_IF_NULL(up)); ABSL_DIE_IF_NULL(up).reset(); std::shared_ptr<int> sp(new int); EXPECT_EQ(&sp, &ABSL_DIE_IF_NULL(sp)); ABSL_DIE_IF_NULL(sp).reset(); } TEST(AbslDieIfNull, PreservesRValues) { int64_t* ptr = new int64_t(); auto uptr = ABSL_DIE_IF_NULL(std::unique_ptr<int64_t>(ptr)); EXPECT_EQ(ptr, uptr.get()); } TEST(AbslDieIfNull, PreservesLValues) { int64_t array[2] = {0}; int64_t* a = array + 0; int64_t* b = array + 1; using std::swap; swap(ABSL_DIE_IF_NULL(a), ABSL_DIE_IF_NULL(b)); EXPECT_EQ(array + 1, a); EXPECT_EQ(array + 0, b); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/die_if_null.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/die_if_null_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
773e8676-b15b-43ea-bce2-eabce4530c4d
cpp
abseil/abseil-cpp
scoped_mock_log
absl/log/scoped_mock_log.cc
absl/log/scoped_mock_log_test.cc
#include "absl/log/scoped_mock_log.h" #include <atomic> #include <string> #include "gmock/gmock.h" #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/log/log_entry.h" #include "absl/log/log_sink.h" #include "absl/log/log_sink_registry.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN ScopedMockLog::ScopedMockLog(MockLogDefault default_exp) : sink_(this), is_capturing_logs_(false), is_triggered_(false) { if (default_exp == MockLogDefault::kIgnoreUnexpected) { EXPECT_CALL(*this, Log).Times(::testing::AnyNumber()); } else { EXPECT_CALL(*this, Log).Times(0); } EXPECT_CALL(*this, Send) .Times(::testing::AnyNumber()) .WillRepeatedly([this](const absl::LogEntry& entry) { is_triggered_.store(true, std::memory_order_relaxed); Log(entry.log_severity(), std::string(entry.source_filename()), std::string(entry.text_message())); }); EXPECT_CALL(*this, Flush).Times(::testing::AnyNumber()); } ScopedMockLog::~ScopedMockLog() { ABSL_RAW_CHECK(is_triggered_.load(std::memory_order_relaxed), "Did you forget to call StartCapturingLogs()?"); if (is_capturing_logs_) StopCapturingLogs(); } void ScopedMockLog::StartCapturingLogs() { ABSL_RAW_CHECK(!is_capturing_logs_, "StartCapturingLogs() can be called only when the " "absl::ScopedMockLog object is not capturing logs."); is_capturing_logs_ = true; is_triggered_.store(true, std::memory_order_relaxed); absl::AddLogSink(&sink_); } void ScopedMockLog::StopCapturingLogs() { ABSL_RAW_CHECK(is_capturing_logs_, "StopCapturingLogs() can be called only when the " "absl::ScopedMockLog object is capturing logs."); is_capturing_logs_ = false; absl::RemoveLogSink(&sink_); } absl::LogSink& ScopedMockLog::UseAsLocalSink() { is_triggered_.store(true, std::memory_order_relaxed); return sink_; } ABSL_NAMESPACE_END }
#include "absl/log/scoped_mock_log.h" #include <memory> #include <thread> #include "gmock/gmock.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/log_severity.h" #include "absl/log/globals.h" #include "absl/log/internal/test_helpers.h" #include "absl/log/internal/test_matchers.h" #include "absl/log/log.h" #include "absl/memory/memory.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/synchronization/barrier.h" #include "absl/synchronization/notification.h" namespace { using ::testing::_; using ::testing::AnyNumber; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::InSequence; using ::testing::Lt; using ::testing::Truly; using absl::log_internal::SourceBasename; using absl::log_internal::SourceFilename; using absl::log_internal::SourceLine; using absl::log_internal::TextMessageWithPrefix; using absl::log_internal::ThreadID; auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment( new absl::log_internal::LogTestEnvironment); #if GTEST_HAS_DEATH_TEST TEST(ScopedMockLogDeathTest, StartCapturingLogsCannotBeCalledWhenAlreadyCapturing) { EXPECT_DEATH( { absl::ScopedMockLog log; log.StartCapturingLogs(); log.StartCapturingLogs(); }, "StartCapturingLogs"); } TEST(ScopedMockLogDeathTest, StopCapturingLogsCannotBeCalledWhenNotCapturing) { EXPECT_DEATH( { absl::ScopedMockLog log; log.StopCapturingLogs(); }, "StopCapturingLogs"); } TEST(ScopedMockLogDeathTest, FailsCheckIfStartCapturingLogsIsNeverCalled) { EXPECT_DEATH({ absl::ScopedMockLog log; }, "Did you forget to call StartCapturingLogs"); } #endif TEST(ScopedMockLogTest, LogMockCatchAndMatchStrictExpectations) { absl::ScopedMockLog log; InSequence s; EXPECT_CALL(log, Log(absl::LogSeverity::kWarning, HasSubstr(__FILE__), "Danger.")); EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "Working...")).Times(2); EXPECT_CALL(log, Log(absl::LogSeverity::kError, _, "Bad!!")); log.StartCapturingLogs(); LOG(WARNING) << "Danger."; LOG(INFO) << "Working..."; LOG(INFO) << "Working..."; LOG(ERROR) << "Bad!!"; } TEST(ScopedMockLogTest, LogMockCatchAndMatchSendExpectations) { absl::ScopedMockLog log; EXPECT_CALL( log, Send(AllOf(SourceFilename(Eq("/my/very/very/very_long_source_file.cc")), SourceBasename(Eq("very_long_source_file.cc")), SourceLine(Eq(777)), ThreadID(Eq(absl::LogEntry::tid_t{1234})), TextMessageWithPrefix(Truly([](absl::string_view msg) { return absl::EndsWith( msg, " very_long_source_file.cc:777] Info message"); }))))); log.StartCapturingLogs(); LOG(INFO) .AtLocation("/my/very/very/very_long_source_file.cc", 777) .WithThreadID(1234) << "Info message"; } TEST(ScopedMockLogTest, ScopedMockLogCanBeNice) { absl::ScopedMockLog log; InSequence s; EXPECT_CALL(log, Log(absl::LogSeverity::kWarning, HasSubstr(__FILE__), "Danger.")); EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "Working...")).Times(2); EXPECT_CALL(log, Log(absl::LogSeverity::kError, _, "Bad!!")); log.StartCapturingLogs(); LOG(INFO) << "Info message."; LOG(WARNING).AtLocation("SomeOtherFile.cc", 100) << "Danger "; LOG(WARNING) << "Danger."; LOG(INFO) << "Info message."; LOG(WARNING).AtLocation("SomeOtherFile.cc", 100) << "Danger "; LOG(INFO) << "Working..."; LOG(INFO) << "Info message."; LOG(WARNING).AtLocation("SomeOtherFile.cc", 100) << "Danger "; LOG(INFO) << "Working..."; LOG(INFO) << "Info message."; LOG(WARNING).AtLocation("SomeOtherFile.cc", 100) << "Danger "; LOG(ERROR) << "Bad!!"; LOG(INFO) << "Info message."; LOG(WARNING).AtLocation("SomeOtherFile.cc", 100) << "Danger "; } TEST(ScopedMockLogTest, RejectsUnexpectedLogs) { EXPECT_NONFATAL_FAILURE( { absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(log, Log(Lt(absl::LogSeverity::kError), _, _)) .Times(AnyNumber()); log.StartCapturingLogs(); LOG(INFO) << "Ignored"; LOG(WARNING) << "Ignored"; LOG(ERROR) << "Should not be ignored"; }, "Should not be ignored"); } TEST(ScopedMockLogTest, CapturesLogsAfterStartCapturingLogs) { absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfinity); absl::ScopedMockLog log; LOG(INFO) << "Ignored info"; LOG(WARNING) << "Ignored warning"; LOG(ERROR) << "Ignored error"; EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "Expected info")); log.StartCapturingLogs(); LOG(INFO) << "Expected info"; } TEST(ScopedMockLogTest, DoesNotCaptureLogsAfterStopCapturingLogs) { absl::ScopedMockLog log; EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, "Expected info")); log.StartCapturingLogs(); LOG(INFO) << "Expected info"; log.StopCapturingLogs(); LOG(INFO) << "Ignored info"; LOG(WARNING) << "Ignored warning"; LOG(ERROR) << "Ignored error"; } TEST(ScopedMockLogTest, LogFromMultipleThreads) { absl::ScopedMockLog log; EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, __FILE__, "Thread 1")); EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, __FILE__, "Thread 2")); log.StartCapturingLogs(); absl::Barrier barrier(2); std::thread thread1([&barrier]() { barrier.Block(); LOG(INFO) << "Thread 1"; }); std::thread thread2([&barrier]() { barrier.Block(); LOG(INFO) << "Thread 2"; }); thread1.join(); thread2.join(); } TEST(ScopedMockLogTest, NoSequenceWithMultipleThreads) { absl::ScopedMockLog log; absl::Barrier barrier(2); EXPECT_CALL(log, Log(absl::LogSeverity::kInfo, _, _)) .Times(2) .WillRepeatedly([&barrier]() { barrier.Block(); }); log.StartCapturingLogs(); std::thread thread1([]() { LOG(INFO) << "Thread 1"; }); std::thread thread2([]() { LOG(INFO) << "Thread 2"; }); thread1.join(); thread2.join(); } TEST(ScopedMockLogTsanTest, ScopedMockLogCanBeDeletedWhenAnotherThreadIsLogging) { auto log = absl::make_unique<absl::ScopedMockLog>(); EXPECT_CALL(*log, Log(absl::LogSeverity::kInfo, __FILE__, "Thread log")) .Times(AnyNumber()); log->StartCapturingLogs(); absl::Notification logging_started; std::thread thread([&logging_started]() { for (int i = 0; i < 100; ++i) { if (i == 50) logging_started.Notify(); LOG(INFO) << "Thread log"; } }); logging_started.WaitForNotification(); log.reset(); thread.join(); } TEST(ScopedMockLogTest, AsLocalSink) { absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(log, Log(_, _, "two")); EXPECT_CALL(log, Log(_, _, "three")); LOG(INFO) << "one"; LOG(INFO).ToSinkOnly(&log.UseAsLocalSink()) << "two"; LOG(INFO).ToSinkAlso(&log.UseAsLocalSink()) << "three"; } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/scoped_mock_log.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/scoped_mock_log_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
9f641e69-b766-49cc-9efc-fb43469c2b28
cpp
abseil/abseil-cpp
globals
absl/log/internal/globals.cc
absl/log/globals_test.cc
#include "absl/log/internal/globals.h" #include <atomic> #include <cstdio> #if defined(__EMSCRIPTEN__) #include <emscripten/console.h> #endif #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/log_severity.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/time/time.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace log_internal { namespace { ABSL_CONST_INIT std::atomic<bool> logging_initialized(false); ABSL_CONST_INIT std::atomic<absl::TimeZone*> timezone_ptr{nullptr}; ABSL_CONST_INIT std::atomic<bool> symbolize_stack_trace(true); ABSL_CONST_INIT std::atomic<int> max_frames_in_stack_trace(64); ABSL_CONST_INIT std::atomic<bool> exit_on_dfatal(true); ABSL_CONST_INIT std::atomic<bool> suppress_sigabort_trace(false); } bool IsInitialized() { return logging_initialized.load(std::memory_order_acquire); } void SetInitialized() { logging_initialized.store(true, std::memory_order_release); } void WriteToStderr(absl::string_view message, absl::LogSeverity severity) { if (message.empty()) return; #if defined(__EMSCRIPTEN__) const auto message_minus_newline = absl::StripSuffix(message, "\n"); #if ABSL_INTERNAL_EMSCRIPTEN_VERSION >= 3001043 emscripten_errn(message_minus_newline.data(), message_minus_newline.size()); #else std::string null_terminated_message(message_minus_newline); _emscripten_err(null_terminated_message.c_str()); #endif #else std::fwrite(message.data(), message.size(), 1, stderr); #endif #if defined(_WIN64) || defined(_WIN32) || defined(_WIN16) if (severity >= absl::LogSeverity::kWarning) { std::fflush(stderr); } #else (void)severity; #endif } void SetTimeZone(absl::TimeZone tz) { absl::TimeZone* expected = nullptr; absl::TimeZone* new_tz = new absl::TimeZone(tz); if (!timezone_ptr.compare_exchange_strong(expected, new_tz, std::memory_order_release, std::memory_order_relaxed)) { ABSL_RAW_LOG(FATAL, "absl::log_internal::SetTimeZone() has already been called"); } } const absl::TimeZone* TimeZone() { return timezone_ptr.load(std::memory_order_acquire); } bool ShouldSymbolizeLogStackTrace() { return symbolize_stack_trace.load(std::memory_order_acquire); } void EnableSymbolizeLogStackTrace(bool on_off) { symbolize_stack_trace.store(on_off, std::memory_order_release); } int MaxFramesInLogStackTrace() { return max_frames_in_stack_trace.load(std::memory_order_acquire); } void SetMaxFramesInLogStackTrace(int max_num_frames) { max_frames_in_stack_trace.store(max_num_frames, std::memory_order_release); } bool ExitOnDFatal() { return exit_on_dfatal.load(std::memory_order_acquire); } void SetExitOnDFatal(bool on_off) { exit_on_dfatal.store(on_off, std::memory_order_release); } bool SuppressSigabortTrace() { return suppress_sigabort_trace.load(std::memory_order_acquire); } bool SetSuppressSigabortTrace(bool on_off) { return suppress_sigabort_trace.exchange(on_off); } } ABSL_NAMESPACE_END }
#include "absl/log/globals.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/log_severity.h" #include "absl/log/internal/globals.h" #include "absl/log/internal/test_helpers.h" #include "absl/log/log.h" #include "absl/log/scoped_mock_log.h" namespace { using ::testing::_; using ::testing::StrEq; auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment( new absl::log_internal::LogTestEnvironment); constexpr static absl::LogSeverityAtLeast DefaultMinLogLevel() { return absl::LogSeverityAtLeast::kInfo; } constexpr static absl::LogSeverityAtLeast DefaultStderrThreshold() { return absl::LogSeverityAtLeast::kError; } TEST(TestGlobals, MinLogLevel) { EXPECT_EQ(absl::MinLogLevel(), DefaultMinLogLevel()); absl::SetMinLogLevel(absl::LogSeverityAtLeast::kError); EXPECT_EQ(absl::MinLogLevel(), absl::LogSeverityAtLeast::kError); absl::SetMinLogLevel(DefaultMinLogLevel()); } TEST(TestGlobals, ScopedMinLogLevel) { EXPECT_EQ(absl::MinLogLevel(), DefaultMinLogLevel()); { absl::log_internal::ScopedMinLogLevel scoped_stderr_threshold( absl::LogSeverityAtLeast::kError); EXPECT_EQ(absl::MinLogLevel(), absl::LogSeverityAtLeast::kError); } EXPECT_EQ(absl::MinLogLevel(), DefaultMinLogLevel()); } TEST(TestGlobals, StderrThreshold) { EXPECT_EQ(absl::StderrThreshold(), DefaultStderrThreshold()); absl::SetStderrThreshold(absl::LogSeverityAtLeast::kError); EXPECT_EQ(absl::StderrThreshold(), absl::LogSeverityAtLeast::kError); absl::SetStderrThreshold(DefaultStderrThreshold()); } TEST(TestGlobals, ScopedStderrThreshold) { EXPECT_EQ(absl::StderrThreshold(), DefaultStderrThreshold()); { absl::ScopedStderrThreshold scoped_stderr_threshold( absl::LogSeverityAtLeast::kError); EXPECT_EQ(absl::StderrThreshold(), absl::LogSeverityAtLeast::kError); } EXPECT_EQ(absl::StderrThreshold(), DefaultStderrThreshold()); } TEST(TestGlobals, LogBacktraceAt) { EXPECT_FALSE(absl::log_internal::ShouldLogBacktraceAt("some_file.cc", 111)); absl::SetLogBacktraceLocation("some_file.cc", 111); EXPECT_TRUE(absl::log_internal::ShouldLogBacktraceAt("some_file.cc", 111)); EXPECT_FALSE( absl::log_internal::ShouldLogBacktraceAt("another_file.cc", 222)); } TEST(TestGlobals, LogPrefix) { EXPECT_TRUE(absl::ShouldPrependLogPrefix()); absl::EnableLogPrefix(false); EXPECT_FALSE(absl::ShouldPrependLogPrefix()); absl::EnableLogPrefix(true); EXPECT_TRUE(absl::ShouldPrependLogPrefix()); } TEST(TestGlobals, SetGlobalVLogLevel) { EXPECT_EQ(absl::SetGlobalVLogLevel(42), 0); EXPECT_EQ(absl::SetGlobalVLogLevel(1337), 42); EXPECT_EQ(absl::SetGlobalVLogLevel(0), 1337); } TEST(TestGlobals, SetVLogLevel) { EXPECT_EQ(absl::SetVLogLevel("setvloglevel", 42), 0); EXPECT_EQ(absl::SetVLogLevel("setvloglevel", 1337), 42); EXPECT_EQ(absl::SetVLogLevel("othersetvloglevel", 50), 0); EXPECT_EQ(absl::SetVLogLevel("*pattern*", 1), 0); EXPECT_EQ(absl::SetVLogLevel("*less_generic_pattern*", 2), 1); EXPECT_EQ(absl::SetVLogLevel("pattern_match", 3), 1); EXPECT_EQ(absl::SetVLogLevel("less_generic_pattern_match", 4), 2); } TEST(TestGlobals, AndroidLogTag) { EXPECT_DEATH_IF_SUPPORTED(absl::SetAndroidNativeTag(nullptr), ".*"); EXPECT_THAT(absl::log_internal::GetAndroidNativeTag(), StrEq("native")); absl::SetAndroidNativeTag("test_tag"); EXPECT_THAT(absl::log_internal::GetAndroidNativeTag(), StrEq("test_tag")); EXPECT_DEATH_IF_SUPPORTED(absl::SetAndroidNativeTag("test_tag_fail"), ".*"); } TEST(TestExitOnDFatal, OffTest) { absl::log_internal::SetExitOnDFatal(false); EXPECT_FALSE(absl::log_internal::ExitOnDFatal()); { absl::ScopedMockLog log(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(log, Log(absl::kLogDebugFatal, _, "This should not be fatal")); log.StartCapturingLogs(); LOG(DFATAL) << "This should not be fatal"; } } #if GTEST_HAS_DEATH_TEST TEST(TestDeathWhileExitOnDFatal, OnTest) { absl::log_internal::SetExitOnDFatal(true); EXPECT_TRUE(absl::log_internal::ExitOnDFatal()); EXPECT_DEBUG_DEATH({ LOG(DFATAL) << "This should be fatal in debug mode"; }, "This should be fatal in debug mode"); } #endif }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/internal/globals.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/globals_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
5b701727-1be1-444f-9d6e-3f418b5d3490
cpp
abseil/abseil-cpp
flags
absl/log/flags.cc
absl/log/flags_test.cc
#include "absl/log/internal/flags.h" #include <stddef.h> #include <algorithm> #include <cstdlib> #include <string> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/log_severity.h" #include "absl/flags/flag.h" #include "absl/flags/marshalling.h" #include "absl/log/globals.h" #include "absl/log/internal/config.h" #include "absl/log/internal/vlog_config.h" #include "absl/strings/numbers.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace log_internal { namespace { void SyncLoggingFlags() { absl::SetFlag(&FLAGS_minloglevel, static_cast<int>(absl::MinLogLevel())); absl::SetFlag(&FLAGS_log_prefix, absl::ShouldPrependLogPrefix()); } bool RegisterSyncLoggingFlags() { log_internal::SetLoggingGlobalsListener(&SyncLoggingFlags); return true; } ABSL_ATTRIBUTE_UNUSED const bool unused = RegisterSyncLoggingFlags(); template <typename T> T GetFromEnv(const char* varname, T dflt) { const char* val = ::getenv(varname); if (val != nullptr) { std::string err; ABSL_INTERNAL_CHECK(absl::ParseFlag(val, &dflt, &err), err.c_str()); } return dflt; } constexpr absl::LogSeverityAtLeast StderrThresholdDefault() { return absl::LogSeverityAtLeast::kError; } } } ABSL_NAMESPACE_END } ABSL_FLAG(int, stderrthreshold, static_cast<int>(absl::log_internal::StderrThresholdDefault()), "Log messages at or above this threshold level are copied to stderr.") .OnUpdate([] { absl::log_internal::RawSetStderrThreshold( static_cast<absl::LogSeverityAtLeast>( absl::GetFlag(FLAGS_stderrthreshold))); }); ABSL_FLAG(int, minloglevel, static_cast<int>(absl::LogSeverityAtLeast::kInfo), "Messages logged at a lower level than this don't actually " "get logged anywhere") .OnUpdate([] { absl::log_internal::RawSetMinLogLevel( static_cast<absl::LogSeverityAtLeast>( absl::GetFlag(FLAGS_minloglevel))); }); ABSL_FLAG(std::string, log_backtrace_at, "", "Emit a backtrace when logging at file:linenum.") .OnUpdate([] { const std::string log_backtrace_at = absl::GetFlag(FLAGS_log_backtrace_at); if (log_backtrace_at.empty()) { absl::ClearLogBacktraceLocation(); return; } const size_t last_colon = log_backtrace_at.rfind(':'); if (last_colon == log_backtrace_at.npos) { absl::ClearLogBacktraceLocation(); return; } const absl::string_view file = absl::string_view(log_backtrace_at).substr(0, last_colon); int line; if (!absl::SimpleAtoi( absl::string_view(log_backtrace_at).substr(last_colon + 1), &line)) { absl::ClearLogBacktraceLocation(); return; } absl::SetLogBacktraceLocation(file, line); }); ABSL_FLAG(bool, log_prefix, true, "Prepend the log prefix to the start of each log line") .OnUpdate([] { absl::log_internal::RawEnableLogPrefix(absl::GetFlag(FLAGS_log_prefix)); }); ABSL_FLAG(int, v, 0, "Show all VLOG(m) messages for m <= this. Overridable by --vmodule.") .OnUpdate([] { absl::log_internal::UpdateGlobalVLogLevel(absl::GetFlag(FLAGS_v)); }); ABSL_FLAG( std::string, vmodule, "", "per-module log verbosity level." " Argument is a comma-separated list of <module name>=<log level>." " <module name> is a glob pattern, matched against the filename base" " (that is, name ignoring .cc/.h./-inl.h)." " A pattern without slashes matches just the file name portion, otherwise" " the whole file path below the workspace root" " (still without .cc/.h./-inl.h) is matched." " ? and * in the glob pattern match any single or sequence of characters" " respectively including slashes." " <log level> overrides any value given by --v.") .OnUpdate([] { absl::log_internal::UpdateVModule(absl::GetFlag(FLAGS_vmodule)); });
#include "absl/log/internal/flags.h" #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/log_severity.h" #include "absl/flags/flag.h" #include "absl/flags/reflection.h" #include "absl/log/globals.h" #include "absl/log/internal/test_helpers.h" #include "absl/log/internal/test_matchers.h" #include "absl/log/log.h" #include "absl/log/scoped_mock_log.h" #include "absl/strings/str_cat.h" namespace { using ::absl::log_internal::TextMessage; using ::testing::HasSubstr; using ::testing::Not; auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment( new absl::log_internal::LogTestEnvironment); constexpr static absl::LogSeverityAtLeast DefaultStderrThreshold() { return absl::LogSeverityAtLeast::kError; } class LogFlagsTest : public ::testing::Test { protected: absl::FlagSaver flag_saver_; }; TEST_F(LogFlagsTest, DISABLED_StderrKnobsDefault) { EXPECT_EQ(absl::StderrThreshold(), DefaultStderrThreshold()); } TEST_F(LogFlagsTest, SetStderrThreshold) { absl::SetFlag(&FLAGS_stderrthreshold, static_cast<int>(absl::LogSeverityAtLeast::kInfo)); EXPECT_EQ(absl::StderrThreshold(), absl::LogSeverityAtLeast::kInfo); absl::SetFlag(&FLAGS_stderrthreshold, static_cast<int>(absl::LogSeverityAtLeast::kError)); EXPECT_EQ(absl::StderrThreshold(), absl::LogSeverityAtLeast::kError); } TEST_F(LogFlagsTest, SetMinLogLevel) { absl::SetFlag(&FLAGS_minloglevel, static_cast<int>(absl::LogSeverityAtLeast::kError)); EXPECT_EQ(absl::MinLogLevel(), absl::LogSeverityAtLeast::kError); absl::log_internal::ScopedMinLogLevel scoped_min_log_level( absl::LogSeverityAtLeast::kWarning); EXPECT_EQ(absl::GetFlag(FLAGS_minloglevel), static_cast<int>(absl::LogSeverityAtLeast::kWarning)); } TEST_F(LogFlagsTest, PrependLogPrefix) { absl::SetFlag(&FLAGS_log_prefix, false); EXPECT_EQ(absl::ShouldPrependLogPrefix(), false); absl::EnableLogPrefix(true); EXPECT_EQ(absl::GetFlag(FLAGS_log_prefix), true); } TEST_F(LogFlagsTest, EmptyBacktraceAtFlag) { absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo); absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:"))))); test_sink.StartCapturingLogs(); absl::SetFlag(&FLAGS_log_backtrace_at, ""); LOG(INFO) << "hello world"; } TEST_F(LogFlagsTest, BacktraceAtNonsense) { absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo); absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:"))))); test_sink.StartCapturingLogs(); absl::SetFlag(&FLAGS_log_backtrace_at, "gibberish"); LOG(INFO) << "hello world"; } TEST_F(LogFlagsTest, BacktraceAtWrongFile) { absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo); const int log_line = __LINE__ + 1; auto do_log = [] { LOG(INFO) << "hello world"; }; absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:"))))); test_sink.StartCapturingLogs(); absl::SetFlag(&FLAGS_log_backtrace_at, absl::StrCat("some_other_file.cc:", log_line)); do_log(); } TEST_F(LogFlagsTest, BacktraceAtWrongLine) { absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo); const int log_line = __LINE__ + 1; auto do_log = [] { LOG(INFO) << "hello world"; }; absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:"))))); test_sink.StartCapturingLogs(); absl::SetFlag(&FLAGS_log_backtrace_at, absl::StrCat("flags_test.cc:", log_line + 1)); do_log(); } TEST_F(LogFlagsTest, BacktraceAtWholeFilename) { absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo); const int log_line = __LINE__ + 1; auto do_log = [] { LOG(INFO) << "hello world"; }; absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:"))))); test_sink.StartCapturingLogs(); absl::SetFlag(&FLAGS_log_backtrace_at, absl::StrCat(__FILE__, ":", log_line)); do_log(); } TEST_F(LogFlagsTest, BacktraceAtNonmatchingSuffix) { absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo); const int log_line = __LINE__ + 1; auto do_log = [] { LOG(INFO) << "hello world"; }; absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:"))))); test_sink.StartCapturingLogs(); absl::SetFlag(&FLAGS_log_backtrace_at, absl::StrCat("flags_test.cc:", log_line, "gibberish")); do_log(); } TEST_F(LogFlagsTest, LogsBacktrace) { absl::SetMinLogLevel(absl::LogSeverityAtLeast::kInfo); const int log_line = __LINE__ + 1; auto do_log = [] { LOG(INFO) << "hello world"; }; absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); testing::InSequence seq; EXPECT_CALL(test_sink, Send(TextMessage(HasSubstr("(stacktrace:")))); EXPECT_CALL(test_sink, Send(TextMessage(Not(HasSubstr("(stacktrace:"))))); test_sink.StartCapturingLogs(); absl::SetFlag(&FLAGS_log_backtrace_at, absl::StrCat("flags_test.cc:", log_line)); do_log(); absl::SetFlag(&FLAGS_log_backtrace_at, ""); do_log(); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/flags.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/flags_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
32f38623-1d99-4128-9f44-0ec7c874d2fa
cpp
abseil/abseil-cpp
log_entry
absl/log/log_entry.cc
absl/log/log_entry_test.cc
#include "absl/log/log_entry.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL constexpr int LogEntry::kNoVerbosityLevel; constexpr int LogEntry::kNoVerboseLevel; #endif #ifdef __APPLE__ namespace log_internal { extern const char kAvoidEmptyLogEntryLibraryWarning; const char kAvoidEmptyLogEntryLibraryWarning = 0; } #endif ABSL_NAMESPACE_END }
#include "absl/log/log_entry.h" #include <stddef.h> #include <stdint.h> #include <cstring> #include <limits> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/log_severity.h" #include "absl/log/internal/append_truncated.h" #include "absl/log/internal/log_format.h" #include "absl/log/internal/test_helpers.h" #include "absl/strings/numbers.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/time/civil_time.h" #include "absl/time/time.h" #include "absl/types/span.h" namespace { using ::absl::log_internal::LogEntryTestPeer; using ::testing::Eq; using ::testing::IsTrue; using ::testing::StartsWith; using ::testing::StrEq; auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment( new absl::log_internal::LogTestEnvironment); } namespace absl { ABSL_NAMESPACE_BEGIN namespace log_internal { class LogEntryTestPeer { public: LogEntryTestPeer(absl::string_view base_filename, int line, bool prefix, absl::LogSeverity severity, absl::string_view timestamp, absl::LogEntry::tid_t tid, PrefixFormat format, absl::string_view text_message) : format_{format}, buf_(15000, '\0') { entry_.base_filename_ = base_filename; entry_.line_ = line; entry_.prefix_ = prefix; entry_.severity_ = severity; std::string time_err; EXPECT_THAT( absl::ParseTime("%Y-%m-%d%ET%H:%M:%E*S", timestamp, absl::LocalTimeZone(), &entry_.timestamp_, &time_err), IsTrue()) << "Failed to parse time " << timestamp << ": " << time_err; entry_.tid_ = tid; std::pair<absl::string_view, std::string> timestamp_bits = absl::StrSplit(timestamp, absl::ByChar('.')); EXPECT_THAT(absl::ParseCivilTime(timestamp_bits.first, &ci_.cs), IsTrue()) << "Failed to parse time " << timestamp_bits.first; timestamp_bits.second.resize(9, '0'); int64_t nanos = 0; EXPECT_THAT(absl::SimpleAtoi(timestamp_bits.second, &nanos), IsTrue()) << "Failed to parse time " << timestamp_bits.first; ci_.subsecond = absl::Nanoseconds(nanos); absl::Span<char> view = absl::MakeSpan(buf_); view.remove_suffix(2); entry_.prefix_len_ = entry_.prefix_ ? log_internal::FormatLogPrefix( entry_.log_severity(), entry_.timestamp(), entry_.tid(), entry_.source_basename(), entry_.source_line(), format_, view) : 0; EXPECT_THAT(entry_.prefix_len_, Eq(static_cast<size_t>(view.data() - buf_.data()))); log_internal::AppendTruncated(text_message, view); view = absl::Span<char>(view.data(), view.size() + 2); view[0] = '\n'; view[1] = '\0'; view.remove_prefix(2); buf_.resize(static_cast<size_t>(view.data() - buf_.data())); entry_.text_message_with_prefix_and_newline_and_nul_ = absl::MakeSpan(buf_); } LogEntryTestPeer(const LogEntryTestPeer&) = delete; LogEntryTestPeer& operator=(const LogEntryTestPeer&) = delete; std::string FormatLogMessage() const { return log_internal::FormatLogMessage( entry_.log_severity(), ci_.cs, ci_.subsecond, entry_.tid(), entry_.source_basename(), entry_.source_line(), format_, entry_.text_message()); } std::string FormatPrefixIntoSizedBuffer(size_t sz) { std::string str(sz, '\0'); absl::Span<char> buf(&str[0], str.size()); const size_t prefix_size = log_internal::FormatLogPrefix( entry_.log_severity(), entry_.timestamp(), entry_.tid(), entry_.source_basename(), entry_.source_line(), format_, buf); EXPECT_THAT(prefix_size, Eq(static_cast<size_t>(buf.data() - str.data()))); str.resize(prefix_size); return str; } const absl::LogEntry& entry() const { return entry_; } private: absl::LogEntry entry_; PrefixFormat format_; absl::TimeZone::CivilInfo ci_; std::vector<char> buf_; }; } ABSL_NAMESPACE_END } namespace { constexpr bool kUsePrefix = true, kNoPrefix = false; TEST(LogEntryTest, Baseline) { LogEntryTestPeer entry("foo.cc", 1234, kUsePrefix, absl::LogSeverity::kInfo, "2020-01-02T03:04:05.6789", 451, absl::log_internal::PrefixFormat::kNotRaw, "hello world"); EXPECT_THAT(entry.FormatLogMessage(), Eq("I0102 03:04:05.678900 451 foo.cc:1234] hello world")); EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000), Eq("I0102 03:04:05.678900 451 foo.cc:1234] ")); for (size_t sz = strlen("I0102 03:04:05.678900 451 foo.cc:1234] ") + 20; sz != std::numeric_limits<size_t>::max(); sz--) EXPECT_THAT("I0102 03:04:05.678900 451 foo.cc:1234] ", StartsWith(entry.FormatPrefixIntoSizedBuffer(sz))); EXPECT_THAT(entry.entry().text_message_with_prefix_and_newline(), Eq("I0102 03:04:05.678900 451 foo.cc:1234] hello world\n")); EXPECT_THAT( entry.entry().text_message_with_prefix_and_newline_c_str(), StrEq("I0102 03:04:05.678900 451 foo.cc:1234] hello world\n")); EXPECT_THAT(entry.entry().text_message_with_prefix(), Eq("I0102 03:04:05.678900 451 foo.cc:1234] hello world")); EXPECT_THAT(entry.entry().text_message(), Eq("hello world")); } TEST(LogEntryTest, NoPrefix) { LogEntryTestPeer entry("foo.cc", 1234, kNoPrefix, absl::LogSeverity::kInfo, "2020-01-02T03:04:05.6789", 451, absl::log_internal::PrefixFormat::kNotRaw, "hello world"); EXPECT_THAT(entry.FormatLogMessage(), Eq("I0102 03:04:05.678900 451 foo.cc:1234] hello world")); EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000), Eq("I0102 03:04:05.678900 451 foo.cc:1234] ")); for (size_t sz = strlen("I0102 03:04:05.678900 451 foo.cc:1234] ") + 20; sz != std::numeric_limits<size_t>::max(); sz--) EXPECT_THAT("I0102 03:04:05.678900 451 foo.cc:1234] ", StartsWith(entry.FormatPrefixIntoSizedBuffer(sz))); EXPECT_THAT(entry.entry().text_message_with_prefix_and_newline(), Eq("hello world\n")); EXPECT_THAT(entry.entry().text_message_with_prefix_and_newline_c_str(), StrEq("hello world\n")); EXPECT_THAT(entry.entry().text_message_with_prefix(), Eq("hello world")); EXPECT_THAT(entry.entry().text_message(), Eq("hello world")); } TEST(LogEntryTest, EmptyFields) { LogEntryTestPeer entry("", 0, kUsePrefix, absl::LogSeverity::kInfo, "2020-01-02T03:04:05", 0, absl::log_internal::PrefixFormat::kNotRaw, ""); const std::string format_message = entry.FormatLogMessage(); EXPECT_THAT(format_message, Eq("I0102 03:04:05.000000 0 :0] ")); EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000), Eq(format_message)); for (size_t sz = format_message.size() + 20; sz != std::numeric_limits<size_t>::max(); sz--) EXPECT_THAT(format_message, StartsWith(entry.FormatPrefixIntoSizedBuffer(sz))); EXPECT_THAT(entry.entry().text_message_with_prefix_and_newline(), Eq("I0102 03:04:05.000000 0 :0] \n")); EXPECT_THAT(entry.entry().text_message_with_prefix_and_newline_c_str(), StrEq("I0102 03:04:05.000000 0 :0] \n")); EXPECT_THAT(entry.entry().text_message_with_prefix(), Eq("I0102 03:04:05.000000 0 :0] ")); EXPECT_THAT(entry.entry().text_message(), Eq("")); } TEST(LogEntryTest, NegativeFields) { if (std::is_signed<absl::LogEntry::tid_t>::value) { LogEntryTestPeer entry( "foo.cc", -1234, kUsePrefix, absl::LogSeverity::kInfo, "2020-01-02T03:04:05.6789", static_cast<absl::LogEntry::tid_t>(-451), absl::log_internal::PrefixFormat::kNotRaw, "hello world"); EXPECT_THAT(entry.FormatLogMessage(), Eq("I0102 03:04:05.678900 -451 foo.cc:-1234] hello world")); EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000), Eq("I0102 03:04:05.678900 -451 foo.cc:-1234] ")); for (size_t sz = strlen("I0102 03:04:05.678900 -451 foo.cc:-1234] ") + 20; sz != std::numeric_limits<size_t>::max(); sz--) EXPECT_THAT("I0102 03:04:05.678900 -451 foo.cc:-1234] ", StartsWith(entry.FormatPrefixIntoSizedBuffer(sz))); EXPECT_THAT( entry.entry().text_message_with_prefix_and_newline(), Eq("I0102 03:04:05.678900 -451 foo.cc:-1234] hello world\n")); EXPECT_THAT( entry.entry().text_message_with_prefix_and_newline_c_str(), StrEq("I0102 03:04:05.678900 -451 foo.cc:-1234] hello world\n")); EXPECT_THAT(entry.entry().text_message_with_prefix(), Eq("I0102 03:04:05.678900 -451 foo.cc:-1234] hello world")); EXPECT_THAT(entry.entry().text_message(), Eq("hello world")); } else { LogEntryTestPeer entry("foo.cc", -1234, kUsePrefix, absl::LogSeverity::kInfo, "2020-01-02T03:04:05.6789", 451, absl::log_internal::PrefixFormat::kNotRaw, "hello world"); EXPECT_THAT(entry.FormatLogMessage(), Eq("I0102 03:04:05.678900 451 foo.cc:-1234] hello world")); EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000), Eq("I0102 03:04:05.678900 451 foo.cc:-1234] ")); for (size_t sz = strlen("I0102 03:04:05.678900 451 foo.cc:-1234] ") + 20; sz != std::numeric_limits<size_t>::max(); sz--) EXPECT_THAT("I0102 03:04:05.678900 451 foo.cc:-1234] ", StartsWith(entry.FormatPrefixIntoSizedBuffer(sz))); EXPECT_THAT( entry.entry().text_message_with_prefix_and_newline(), Eq("I0102 03:04:05.678900 451 foo.cc:-1234] hello world\n")); EXPECT_THAT( entry.entry().text_message_with_prefix_and_newline_c_str(), StrEq("I0102 03:04:05.678900 451 foo.cc:-1234] hello world\n")); EXPECT_THAT(entry.entry().text_message_with_prefix(), Eq("I0102 03:04:05.678900 451 foo.cc:-1234] hello world")); EXPECT_THAT(entry.entry().text_message(), Eq("hello world")); } } TEST(LogEntryTest, LongFields) { LogEntryTestPeer entry( "I am the very model of a modern Major-General / " "I've information vegetable, animal, and mineral.", 2147483647, kUsePrefix, absl::LogSeverity::kInfo, "2020-01-02T03:04:05.678967896789", 2147483647, absl::log_internal::PrefixFormat::kNotRaw, "I know the kings of England, and I quote the fights historical / " "From Marathon to Waterloo, in order categorical."); EXPECT_THAT(entry.FormatLogMessage(), Eq("I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:2147483647] I know the kings of England, and I " "quote the fights historical / From Marathon to Waterloo, in " "order categorical.")); EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000), Eq("I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:2147483647] ")); for (size_t sz = strlen("I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:2147483647] ") + 20; sz != std::numeric_limits<size_t>::max(); sz--) EXPECT_THAT( "I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:2147483647] ", StartsWith(entry.FormatPrefixIntoSizedBuffer(sz))); EXPECT_THAT(entry.entry().text_message_with_prefix_and_newline(), Eq("I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:2147483647] I know the kings of England, and I " "quote the fights historical / From Marathon to Waterloo, in " "order categorical.\n")); EXPECT_THAT( entry.entry().text_message_with_prefix_and_newline_c_str(), StrEq("I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:2147483647] I know the kings of England, and I " "quote the fights historical / From Marathon to Waterloo, in " "order categorical.\n")); EXPECT_THAT(entry.entry().text_message_with_prefix(), Eq("I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:2147483647] I know the kings of England, and I " "quote the fights historical / From Marathon to Waterloo, in " "order categorical.")); EXPECT_THAT( entry.entry().text_message(), Eq("I know the kings of England, and I quote the fights historical / " "From Marathon to Waterloo, in order categorical.")); } TEST(LogEntryTest, LongNegativeFields) { if (std::is_signed<absl::LogEntry::tid_t>::value) { LogEntryTestPeer entry( "I am the very model of a modern Major-General / " "I've information vegetable, animal, and mineral.", -2147483647, kUsePrefix, absl::LogSeverity::kInfo, "2020-01-02T03:04:05.678967896789", static_cast<absl::LogEntry::tid_t>(-2147483647), absl::log_internal::PrefixFormat::kNotRaw, "I know the kings of England, and I quote the fights historical / " "From Marathon to Waterloo, in order categorical."); EXPECT_THAT( entry.FormatLogMessage(), Eq("I0102 03:04:05.678967 -2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] I know the kings of England, and I " "quote the fights historical / From Marathon to Waterloo, in " "order categorical.")); EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000), Eq("I0102 03:04:05.678967 -2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] ")); for (size_t sz = strlen( "I0102 03:04:05.678967 -2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] ") + 20; sz != std::numeric_limits<size_t>::max(); sz--) EXPECT_THAT( "I0102 03:04:05.678967 -2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] ", StartsWith(entry.FormatPrefixIntoSizedBuffer(sz))); EXPECT_THAT( entry.entry().text_message_with_prefix_and_newline(), Eq("I0102 03:04:05.678967 -2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] I know the kings of England, and I " "quote the fights historical / From Marathon to Waterloo, in " "order categorical.\n")); EXPECT_THAT( entry.entry().text_message_with_prefix_and_newline_c_str(), StrEq("I0102 03:04:05.678967 -2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] I know the kings of England, and I " "quote the fights historical / From Marathon to Waterloo, in " "order categorical.\n")); EXPECT_THAT( entry.entry().text_message_with_prefix(), Eq("I0102 03:04:05.678967 -2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] I know the kings of England, and I " "quote the fights historical / From Marathon to Waterloo, in " "order categorical.")); EXPECT_THAT( entry.entry().text_message(), Eq("I know the kings of England, and I quote the fights historical / " "From Marathon to Waterloo, in order categorical.")); } else { LogEntryTestPeer entry( "I am the very model of a modern Major-General / " "I've information vegetable, animal, and mineral.", -2147483647, kUsePrefix, absl::LogSeverity::kInfo, "2020-01-02T03:04:05.678967896789", 2147483647, absl::log_internal::PrefixFormat::kNotRaw, "I know the kings of England, and I quote the fights historical / " "From Marathon to Waterloo, in order categorical."); EXPECT_THAT( entry.FormatLogMessage(), Eq("I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] I know the kings of England, and I " "quote the fights historical / From Marathon to Waterloo, in " "order categorical.")); EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000), Eq("I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] ")); for (size_t sz = strlen( "I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] ") + 20; sz != std::numeric_limits<size_t>::max(); sz--) EXPECT_THAT( "I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] ", StartsWith(entry.FormatPrefixIntoSizedBuffer(sz))); EXPECT_THAT( entry.entry().text_message_with_prefix_and_newline(), Eq("I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] I know the kings of England, and I " "quote the fights historical / From Marathon to Waterloo, in " "order categorical.\n")); EXPECT_THAT( entry.entry().text_message_with_prefix_and_newline_c_str(), StrEq("I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] I know the kings of England, and I " "quote the fights historical / From Marathon to Waterloo, in " "order categorical.\n")); EXPECT_THAT( entry.entry().text_message_with_prefix(), Eq("I0102 03:04:05.678967 2147483647 I am the very model of a " "modern Major-General / I've information vegetable, animal, " "and mineral.:-2147483647] I know the kings of England, and I " "quote the fights historical / From Marathon to Waterloo, in " "order categorical.")); EXPECT_THAT( entry.entry().text_message(), Eq("I know the kings of England, and I quote the fights historical / " "From Marathon to Waterloo, in order categorical.")); } } TEST(LogEntryTest, Raw) { LogEntryTestPeer entry("foo.cc", 1234, kUsePrefix, absl::LogSeverity::kInfo, "2020-01-02T03:04:05.6789", 451, absl::log_internal::PrefixFormat::kRaw, "hello world"); EXPECT_THAT( entry.FormatLogMessage(), Eq("I0102 03:04:05.678900 451 foo.cc:1234] RAW: hello world")); EXPECT_THAT(entry.FormatPrefixIntoSizedBuffer(1000), Eq("I0102 03:04:05.678900 451 foo.cc:1234] RAW: ")); for (size_t sz = strlen("I0102 03:04:05.678900 451 foo.cc:1234] RAW: ") + 20; sz != std::numeric_limits<size_t>::max(); sz--) EXPECT_THAT("I0102 03:04:05.678900 451 foo.cc:1234] RAW: ", StartsWith(entry.FormatPrefixIntoSizedBuffer(sz))); EXPECT_THAT( entry.entry().text_message_with_prefix_and_newline(), Eq("I0102 03:04:05.678900 451 foo.cc:1234] RAW: hello world\n")); EXPECT_THAT( entry.entry().text_message_with_prefix_and_newline_c_str(), StrEq("I0102 03:04:05.678900 451 foo.cc:1234] RAW: hello world\n")); EXPECT_THAT( entry.entry().text_message_with_prefix(), Eq("I0102 03:04:05.678900 451 foo.cc:1234] RAW: hello world")); EXPECT_THAT(entry.entry().text_message(), Eq("hello world")); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/log_entry.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/log_entry_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
ef563995-4f4a-4728-a5e7-fddb5d036e01
cpp
abseil/abseil-cpp
log_sink
absl/log/log_sink.cc
absl/log/log_sink_test.cc
#include "absl/log/log_sink.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN void LogSink::KeyFunction() const {} ABSL_NAMESPACE_END }
#include "absl/log/log_sink.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/log/internal/test_actions.h" #include "absl/log/internal/test_helpers.h" #include "absl/log/internal/test_matchers.h" #include "absl/log/log.h" #include "absl/log/log_sink_registry.h" #include "absl/log/scoped_mock_log.h" #include "absl/strings/string_view.h" namespace { using ::absl::log_internal::DeathTestExpectedLogging; using ::absl::log_internal::DeathTestUnexpectedLogging; using ::absl::log_internal::DeathTestValidateExpectations; using ::absl::log_internal::DiedOfFatal; using ::testing::_; using ::testing::AnyNumber; using ::testing::HasSubstr; using ::testing::InSequence; auto* test_env ABSL_ATTRIBUTE_UNUSED = ::testing::AddGlobalTestEnvironment( new absl::log_internal::LogTestEnvironment); TEST(LogSinkRegistryTest, AddLogSink) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); InSequence s; EXPECT_CALL(test_sink, Log(_, _, "hello world")).Times(0); EXPECT_CALL(test_sink, Log(absl::LogSeverity::kInfo, __FILE__, "Test : 42")); EXPECT_CALL(test_sink, Log(absl::LogSeverity::kWarning, __FILE__, "Danger ahead")); EXPECT_CALL(test_sink, Log(absl::LogSeverity::kError, __FILE__, "This is an error")); LOG(INFO) << "hello world"; test_sink.StartCapturingLogs(); LOG(INFO) << "Test : " << 42; LOG(WARNING) << "Danger" << ' ' << "ahead"; LOG(ERROR) << "This is an error"; test_sink.StopCapturingLogs(); LOG(INFO) << "Goodby world"; } TEST(LogSinkRegistryTest, MultipleLogSinks) { absl::ScopedMockLog test_sink1(absl::MockLogDefault::kDisallowUnexpected); absl::ScopedMockLog test_sink2(absl::MockLogDefault::kDisallowUnexpected); ::testing::InSequence seq; EXPECT_CALL(test_sink1, Log(absl::LogSeverity::kInfo, _, "First")).Times(1); EXPECT_CALL(test_sink2, Log(absl::LogSeverity::kInfo, _, "First")).Times(0); EXPECT_CALL(test_sink1, Log(absl::LogSeverity::kInfo, _, "Second")).Times(1); EXPECT_CALL(test_sink2, Log(absl::LogSeverity::kInfo, _, "Second")).Times(1); EXPECT_CALL(test_sink1, Log(absl::LogSeverity::kInfo, _, "Third")).Times(0); EXPECT_CALL(test_sink2, Log(absl::LogSeverity::kInfo, _, "Third")).Times(1); LOG(INFO) << "Before first"; test_sink1.StartCapturingLogs(); LOG(INFO) << "First"; test_sink2.StartCapturingLogs(); LOG(INFO) << "Second"; test_sink1.StopCapturingLogs(); LOG(INFO) << "Third"; test_sink2.StopCapturingLogs(); LOG(INFO) << "Fourth"; } TEST(LogSinkRegistrationDeathTest, DuplicateSinkRegistration) { ASSERT_DEATH_IF_SUPPORTED( { absl::ScopedMockLog sink; sink.StartCapturingLogs(); absl::AddLogSink(&sink.UseAsLocalSink()); }, HasSubstr("Duplicate log sinks")); } TEST(LogSinkRegistrationDeathTest, MismatchSinkRemoval) { ASSERT_DEATH_IF_SUPPORTED( { absl::ScopedMockLog sink; absl::RemoveLogSink(&sink.UseAsLocalSink()); }, HasSubstr("Mismatched log sink")); } TEST(LogSinkTest, FlushSinks) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Flush()).Times(2); test_sink.StartCapturingLogs(); absl::FlushLogSinks(); absl::FlushLogSinks(); } TEST(LogSinkDeathTest, DeathInSend) { class FatalSendSink : public absl::LogSink { public: void Send(const absl::LogEntry&) override { LOG(FATAL) << "goodbye world"; } }; FatalSendSink sink; EXPECT_EXIT({ LOG(INFO).ToSinkAlso(&sink) << "hello world"; }, DiedOfFatal, _); } TEST(LogSinkTest, ToSinkAlso) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); absl::ScopedMockLog another_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Log(_, _, "hello world")); EXPECT_CALL(another_sink, Log(_, _, "hello world")); test_sink.StartCapturingLogs(); LOG(INFO).ToSinkAlso(&another_sink.UseAsLocalSink()) << "hello world"; } TEST(LogSinkTest, ToSinkOnly) { absl::ScopedMockLog another_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(another_sink, Log(_, _, "hello world")); LOG(INFO).ToSinkOnly(&another_sink.UseAsLocalSink()) << "hello world"; } TEST(LogSinkTest, ToManySinks) { absl::ScopedMockLog sink1(absl::MockLogDefault::kDisallowUnexpected); absl::ScopedMockLog sink2(absl::MockLogDefault::kDisallowUnexpected); absl::ScopedMockLog sink3(absl::MockLogDefault::kDisallowUnexpected); absl::ScopedMockLog sink4(absl::MockLogDefault::kDisallowUnexpected); absl::ScopedMockLog sink5(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(sink3, Log(_, _, "hello world")); EXPECT_CALL(sink4, Log(_, _, "hello world")); EXPECT_CALL(sink5, Log(_, _, "hello world")); LOG(INFO) .ToSinkAlso(&sink1.UseAsLocalSink()) .ToSinkAlso(&sink2.UseAsLocalSink()) .ToSinkOnly(&sink3.UseAsLocalSink()) .ToSinkAlso(&sink4.UseAsLocalSink()) .ToSinkAlso(&sink5.UseAsLocalSink()) << "hello world"; } class ReentrancyTest : public ::testing::Test { protected: ReentrancyTest() = default; enum class LogMode : int { kNormal, kToSinkAlso, kToSinkOnly }; class ReentrantSendLogSink : public absl::LogSink { public: explicit ReentrantSendLogSink(absl::LogSeverity severity, absl::LogSink* sink, LogMode mode) : severity_(severity), sink_(sink), mode_(mode) {} explicit ReentrantSendLogSink(absl::LogSeverity severity) : ReentrantSendLogSink(severity, nullptr, LogMode::kNormal) {} void Send(const absl::LogEntry&) override { switch (mode_) { case LogMode::kNormal: LOG(LEVEL(severity_)) << "The log is coming from *inside the sink*."; break; case LogMode::kToSinkAlso: LOG(LEVEL(severity_)).ToSinkAlso(sink_) << "The log is coming from *inside the sink*."; break; case LogMode::kToSinkOnly: LOG(LEVEL(severity_)).ToSinkOnly(sink_) << "The log is coming from *inside the sink*."; break; default: LOG(FATAL) << "Invalid mode " << static_cast<int>(mode_); } } private: absl::LogSeverity severity_; absl::LogSink* sink_; LogMode mode_; }; static absl::string_view LogAndReturn(absl::LogSeverity severity, absl::string_view to_log, absl::string_view to_return) { LOG(LEVEL(severity)) << to_log; return to_return; } }; TEST_F(ReentrancyTest, LogFunctionThatLogs) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); InSequence seq; EXPECT_CALL(test_sink, Log(absl::LogSeverity::kInfo, _, "hello")); EXPECT_CALL(test_sink, Log(absl::LogSeverity::kInfo, _, "world")); EXPECT_CALL(test_sink, Log(absl::LogSeverity::kWarning, _, "danger")); EXPECT_CALL(test_sink, Log(absl::LogSeverity::kInfo, _, "here")); test_sink.StartCapturingLogs(); LOG(INFO) << LogAndReturn(absl::LogSeverity::kInfo, "hello", "world"); LOG(INFO) << LogAndReturn(absl::LogSeverity::kWarning, "danger", "here"); } TEST_F(ReentrancyTest, RegisteredLogSinkThatLogsInSend) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); ReentrantSendLogSink renentrant_sink(absl::LogSeverity::kInfo); EXPECT_CALL(test_sink, Log(_, _, "hello world")); test_sink.StartCapturingLogs(); absl::AddLogSink(&renentrant_sink); LOG(INFO) << "hello world"; absl::RemoveLogSink(&renentrant_sink); } TEST_F(ReentrancyTest, AlsoLogSinkThatLogsInSend) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kInfo); EXPECT_CALL(test_sink, Log(_, _, "hello world")); EXPECT_CALL(test_sink, Log(_, _, "The log is coming from *inside the sink*.")); test_sink.StartCapturingLogs(); LOG(INFO).ToSinkAlso(&reentrant_sink) << "hello world"; } TEST_F(ReentrancyTest, RegisteredAlsoLogSinkThatLogsInSend) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kInfo); EXPECT_CALL(test_sink, Log(_, _, "hello world")); EXPECT_CALL(test_sink, Log(_, _, "The log is coming from *inside the sink*.")); test_sink.StartCapturingLogs(); absl::AddLogSink(&reentrant_sink); LOG(INFO).ToSinkAlso(&reentrant_sink) << "hello world"; absl::RemoveLogSink(&reentrant_sink); } TEST_F(ReentrancyTest, OnlyLogSinkThatLogsInSend) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kInfo); EXPECT_CALL(test_sink, Log(_, _, "The log is coming from *inside the sink*.")); test_sink.StartCapturingLogs(); LOG(INFO).ToSinkOnly(&reentrant_sink) << "hello world"; } TEST_F(ReentrancyTest, RegisteredOnlyLogSinkThatLogsInSend) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kInfo); EXPECT_CALL(test_sink, Log(_, _, "The log is coming from *inside the sink*.")); test_sink.StartCapturingLogs(); absl::AddLogSink(&reentrant_sink); LOG(INFO).ToSinkOnly(&reentrant_sink) << "hello world"; absl::RemoveLogSink(&reentrant_sink); } using ReentrancyDeathTest = ReentrancyTest; TEST_F(ReentrancyDeathTest, LogFunctionThatLogsFatal) { EXPECT_EXIT( { absl::ScopedMockLog test_sink; EXPECT_CALL(test_sink, Log) .Times(AnyNumber()) .WillRepeatedly(DeathTestUnexpectedLogging()); EXPECT_CALL(test_sink, Log(_, _, "hello")) .WillOnce(DeathTestExpectedLogging()); test_sink.StartCapturingLogs(); LOG(INFO) << LogAndReturn(absl::LogSeverity::kFatal, "hello", "world"); }, DiedOfFatal, DeathTestValidateExpectations()); } TEST_F(ReentrancyDeathTest, RegisteredLogSinkThatLogsFatalInSend) { EXPECT_EXIT( { absl::ScopedMockLog test_sink; ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal); EXPECT_CALL(test_sink, Log) .Times(AnyNumber()) .WillRepeatedly(DeathTestUnexpectedLogging()); EXPECT_CALL(test_sink, Log(_, _, "hello world")) .WillOnce(DeathTestExpectedLogging()); test_sink.StartCapturingLogs(); absl::AddLogSink(&reentrant_sink); LOG(INFO) << "hello world"; }, DiedOfFatal, DeathTestValidateExpectations()); } TEST_F(ReentrancyDeathTest, AlsoLogSinkThatLogsFatalInSend) { EXPECT_EXIT( { absl::ScopedMockLog test_sink; ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal); EXPECT_CALL(test_sink, Log) .Times(AnyNumber()) .WillRepeatedly(DeathTestUnexpectedLogging()); EXPECT_CALL(test_sink, Log(_, _, "hello world")) .WillOnce(DeathTestExpectedLogging()); EXPECT_CALL(test_sink, Log(_, _, "The log is coming from *inside the sink*.")) .WillOnce(DeathTestExpectedLogging()); test_sink.StartCapturingLogs(); LOG(INFO).ToSinkAlso(&reentrant_sink) << "hello world"; }, DiedOfFatal, DeathTestValidateExpectations()); } TEST_F(ReentrancyDeathTest, RegisteredAlsoLogSinkThatLogsFatalInSend) { EXPECT_EXIT( { absl::ScopedMockLog test_sink; ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal); EXPECT_CALL(test_sink, Log) .Times(AnyNumber()) .WillRepeatedly(DeathTestUnexpectedLogging()); EXPECT_CALL(test_sink, Log(_, _, "hello world")) .WillOnce(DeathTestExpectedLogging()); EXPECT_CALL(test_sink, Log(_, _, "The log is coming from *inside the sink*.")) .WillOnce(DeathTestExpectedLogging()); test_sink.StartCapturingLogs(); absl::AddLogSink(&reentrant_sink); LOG(INFO).ToSinkAlso(&reentrant_sink) << "hello world"; }, DiedOfFatal, DeathTestValidateExpectations()); } TEST_F(ReentrancyDeathTest, OnlyLogSinkThatLogsFatalInSend) { EXPECT_EXIT( { absl::ScopedMockLog test_sink; ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal); EXPECT_CALL(test_sink, Log) .Times(AnyNumber()) .WillRepeatedly(DeathTestUnexpectedLogging()); EXPECT_CALL(test_sink, Log(_, _, "The log is coming from *inside the sink*.")) .WillOnce(DeathTestExpectedLogging()); test_sink.StartCapturingLogs(); LOG(INFO).ToSinkOnly(&reentrant_sink) << "hello world"; }, DiedOfFatal, DeathTestValidateExpectations()); } TEST_F(ReentrancyDeathTest, RegisteredOnlyLogSinkThatLogsFatalInSend) { EXPECT_EXIT( { absl::ScopedMockLog test_sink; ReentrantSendLogSink reentrant_sink(absl::LogSeverity::kFatal); EXPECT_CALL(test_sink, Log) .Times(AnyNumber()) .WillRepeatedly(DeathTestUnexpectedLogging()); EXPECT_CALL(test_sink, Log(_, _, "The log is coming from *inside the sink*.")) .WillOnce(DeathTestExpectedLogging()); test_sink.StartCapturingLogs(); absl::AddLogSink(&reentrant_sink); LOG(INFO).ToSinkOnly(&reentrant_sink) << "hello world"; }, DiedOfFatal, DeathTestValidateExpectations()); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/log_sink.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/log_sink_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
9e8b4207-ffdb-4612-9278-ec5bc36c4141
cpp
abseil/abseil-cpp
fnmatch
absl/log/internal/fnmatch.cc
absl/log/internal/fnmatch_test.cc
#include "absl/log/internal/fnmatch.h" #include <cstddef> #include "absl/base/config.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace log_internal { bool FNMatch(absl::string_view pattern, absl::string_view str) { bool in_wildcard_match = false; while (true) { if (pattern.empty()) { return in_wildcard_match || str.empty(); } if (str.empty()) { return pattern.find_first_not_of('*') == pattern.npos; } switch (pattern.front()) { case '*': pattern.remove_prefix(1); in_wildcard_match = true; break; case '?': pattern.remove_prefix(1); str.remove_prefix(1); break; default: if (in_wildcard_match) { absl::string_view fixed_portion = pattern; const size_t end = fixed_portion.find_first_of("*?"); if (end != fixed_portion.npos) { fixed_portion = fixed_portion.substr(0, end); } const size_t match = str.find(fixed_portion); if (match == str.npos) { return false; } pattern.remove_prefix(fixed_portion.size()); str.remove_prefix(match + fixed_portion.size()); in_wildcard_match = false; } else { if (pattern.front() != str.front()) { return false; } pattern.remove_prefix(1); str.remove_prefix(1); } break; } } } } ABSL_NAMESPACE_END }
#include "absl/log/internal/fnmatch.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace { using ::testing::IsFalse; using ::testing::IsTrue; TEST(FNMatchTest, Works) { using absl::log_internal::FNMatch; EXPECT_THAT(FNMatch("foo", "foo"), IsTrue()); EXPECT_THAT(FNMatch("foo", "bar"), IsFalse()); EXPECT_THAT(FNMatch("foo", "fo"), IsFalse()); EXPECT_THAT(FNMatch("foo", "foo2"), IsFalse()); EXPECT_THAT(FNMatch("bar/foo.ext", "bar/foo.ext"), IsTrue()); EXPECT_THAT(FNMatch("*ba*r/fo*o.ext*", "bar/foo.ext"), IsTrue()); EXPECT_THAT(FNMatch("bar/foo.ext", "bar/baz.ext"), IsFalse()); EXPECT_THAT(FNMatch("bar/foo.ext", "bar/foo"), IsFalse()); EXPECT_THAT(FNMatch("bar/foo.ext", "bar/foo.ext.zip"), IsFalse()); EXPECT_THAT(FNMatch("ba?/*.ext", "bar/foo.ext"), IsTrue()); EXPECT_THAT(FNMatch("ba?/*.ext", "baZ/FOO.ext"), IsTrue()); EXPECT_THAT(FNMatch("ba?/*.ext", "barr/foo.ext"), IsFalse()); EXPECT_THAT(FNMatch("ba?/*.ext", "bar/foo.ext2"), IsFalse()); EXPECT_THAT(FNMatch("ba?/*", "bar/foo.ext2"), IsTrue()); EXPECT_THAT(FNMatch("ba?/*", "bar/"), IsTrue()); EXPECT_THAT(FNMatch("ba?/?", "bar/"), IsFalse()); EXPECT_THAT(FNMatch("ba?/*", "bar"), IsFalse()); EXPECT_THAT(FNMatch("?x", "zx"), IsTrue()); EXPECT_THAT(FNMatch("*b", "aab"), IsTrue()); EXPECT_THAT(FNMatch("a*b", "aXb"), IsTrue()); EXPECT_THAT(FNMatch("", ""), IsTrue()); EXPECT_THAT(FNMatch("", "a"), IsFalse()); EXPECT_THAT(FNMatch("ab*", "ab"), IsTrue()); EXPECT_THAT(FNMatch("ab**", "ab"), IsTrue()); EXPECT_THAT(FNMatch("ab*?", "ab"), IsFalse()); EXPECT_THAT(FNMatch("*", "bbb"), IsTrue()); EXPECT_THAT(FNMatch("*", ""), IsTrue()); EXPECT_THAT(FNMatch("?", ""), IsFalse()); EXPECT_THAT(FNMatch("***", "**p"), IsTrue()); EXPECT_THAT(FNMatch("**", "*"), IsTrue()); EXPECT_THAT(FNMatch("*?", "*"), IsTrue()); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/internal/fnmatch.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/internal/fnmatch_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
7aae3b80-e7af-4d6f-83db-331cfbf07047
cpp
abseil/abseil-cpp
log_format
absl/log/internal/log_format.cc
absl/log/log_format_test.cc
#include "absl/log/internal/log_format.h" #include <string.h> #ifdef _MSC_VER #include <winsock2.h> #else #include <sys/time.h> #endif #include <cstddef> #include <cstdint> #include <limits> #include <string> #include <type_traits> #include "absl/base/config.h" #include "absl/base/log_severity.h" #include "absl/base/optimization.h" #include "absl/log/internal/append_truncated.h" #include "absl/log/internal/config.h" #include "absl/log/internal/globals.h" #include "absl/strings/numbers.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/time/civil_time.h" #include "absl/time/time.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace log_internal { namespace { template <typename T> inline std::enable_if_t<!std::is_signed<T>::value> PutLeadingWhitespace(T tid, char*& p) { if (tid < 10) *p++ = ' '; if (tid < 100) *p++ = ' '; if (tid < 1000) *p++ = ' '; if (tid < 10000) *p++ = ' '; if (tid < 100000) *p++ = ' '; if (tid < 1000000) *p++ = ' '; } template <typename T> inline std::enable_if_t<std::is_signed<T>::value> PutLeadingWhitespace(T tid, char*& p) { if (tid >= 0 && tid < 10) *p++ = ' '; if (tid > -10 && tid < 100) *p++ = ' '; if (tid > -100 && tid < 1000) *p++ = ' '; if (tid > -1000 && tid < 10000) *p++ = ' '; if (tid > -10000 && tid < 100000) *p++ = ' '; if (tid > -100000 && tid < 1000000) *p++ = ' '; } size_t FormatBoundedFields(absl::LogSeverity severity, absl::Time timestamp, log_internal::Tid tid, absl::Span<char>& buf) { constexpr size_t kBoundedFieldsMaxLen = sizeof("SMMDD HH:MM:SS.NNNNNN ") + (1 + std::numeric_limits<log_internal::Tid>::digits10 + 1) - sizeof(""); if (ABSL_PREDICT_FALSE(buf.size() < kBoundedFieldsMaxLen)) { buf.remove_suffix(buf.size()); return 0; } const absl::TimeZone* tz = absl::log_internal::TimeZone(); if (ABSL_PREDICT_FALSE(tz == nullptr)) { auto tv = absl::ToTimeval(timestamp); int snprintf_result = absl::SNPrintF( buf.data(), buf.size(), "%c0000 00:00:%02d.%06d %7d ", absl::LogSeverityName(severity)[0], static_cast<int>(tv.tv_sec), static_cast<int>(tv.tv_usec), static_cast<int>(tid)); if (snprintf_result >= 0) { buf.remove_prefix(static_cast<size_t>(snprintf_result)); return static_cast<size_t>(snprintf_result); } return 0; } char* p = buf.data(); *p++ = absl::LogSeverityName(severity)[0]; const absl::TimeZone::CivilInfo ci = tz->At(timestamp); absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(ci.cs.month()), p); p += 2; absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(ci.cs.day()), p); p += 2; *p++ = ' '; absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(ci.cs.hour()), p); p += 2; *p++ = ':'; absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(ci.cs.minute()), p); p += 2; *p++ = ':'; absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(ci.cs.second()), p); p += 2; *p++ = '.'; const int64_t usecs = absl::ToInt64Microseconds(ci.subsecond); absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(usecs / 10000), p); p += 2; absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(usecs / 100 % 100), p); p += 2; absl::numbers_internal::PutTwoDigits(static_cast<uint32_t>(usecs % 100), p); p += 2; *p++ = ' '; PutLeadingWhitespace(tid, p); p = absl::numbers_internal::FastIntToBuffer(tid, p); *p++ = ' '; const size_t bytes_formatted = static_cast<size_t>(p - buf.data()); buf.remove_prefix(bytes_formatted); return bytes_formatted; } size_t FormatLineNumber(int line, absl::Span<char>& buf) { constexpr size_t kLineFieldMaxLen = sizeof(":] ") + (1 + std::numeric_limits<int>::digits10 + 1) - sizeof(""); if (ABSL_PREDICT_FALSE(buf.size() < kLineFieldMaxLen)) { buf.remove_suffix(buf.size()); return 0; } char* p = buf.data(); *p++ = ':'; p = absl::numbers_internal::FastIntToBuffer(line, p); *p++ = ']'; *p++ = ' '; const size_t bytes_formatted = static_cast<size_t>(p - buf.data()); buf.remove_prefix(bytes_formatted); return bytes_formatted; } } std::string FormatLogMessage(absl::LogSeverity severity, absl::CivilSecond civil_second, absl::Duration subsecond, log_internal::Tid tid, absl::string_view basename, int line, PrefixFormat format, absl::string_view message) { return absl::StrFormat( "%c%02d%02d %02d:%02d:%02d.%06d %7d %s:%d] %s%s", absl::LogSeverityName(severity)[0], civil_second.month(), civil_second.day(), civil_second.hour(), civil_second.minute(), civil_second.second(), absl::ToInt64Microseconds(subsecond), tid, basename, line, format == PrefixFormat::kRaw ? "RAW: " : "", message); } size_t FormatLogPrefix(absl::LogSeverity severity, absl::Time timestamp, log_internal::Tid tid, absl::string_view basename, int line, PrefixFormat format, absl::Span<char>& buf) { auto prefix_size = FormatBoundedFields(severity, timestamp, tid, buf); prefix_size += log_internal::AppendTruncated(basename, buf); prefix_size += FormatLineNumber(line, buf); if (format == PrefixFormat::kRaw) prefix_size += log_internal::AppendTruncated("RAW: ", buf); return prefix_size; } } ABSL_NAMESPACE_END }
#include <math.h> #include <iomanip> #include <ios> #include <limits> #include <ostream> #include <sstream> #include <string> #include <type_traits> #ifdef __ANDROID__ #include <android/api-level.h> #endif #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/check.h" #include "absl/log/internal/test_matchers.h" #include "absl/log/log.h" #include "absl/log/scoped_mock_log.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" namespace { using ::absl::log_internal::AsString; using ::absl::log_internal::MatchesOstream; using ::absl::log_internal::RawEncodedMessage; using ::absl::log_internal::TextMessage; using ::absl::log_internal::TextPrefix; using ::testing::AllOf; using ::testing::AnyOf; using ::testing::Each; using ::testing::EndsWith; using ::testing::Eq; using ::testing::Ge; using ::testing::IsEmpty; using ::testing::Le; using ::testing::SizeIs; using ::testing::Types; std::ostringstream ComparisonStream() { std::ostringstream str; str.setf(std::ios_base::showbase | std::ios_base::boolalpha | std::ios_base::internal); return str; } TEST(LogFormatTest, NoMessage) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int log_line = __LINE__ + 1; auto do_log = [] { LOG(INFO); }; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(ComparisonStream())), TextPrefix(AsString(EndsWith(absl::StrCat( " log_format_test.cc:", log_line, "] ")))), TextMessage(IsEmpty()), ENCODED_MESSAGE(HasValues(IsEmpty()))))); test_sink.StartCapturingLogs(); do_log(); } template <typename T> class CharLogFormatTest : public testing::Test {}; using CharTypes = Types<char, signed char, unsigned char>; TYPED_TEST_SUITE(CharLogFormatTest, CharTypes); TYPED_TEST(CharLogFormatTest, Printable) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = 'x'; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("x")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "x")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(CharLogFormatTest, Unprintable) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); constexpr auto value = static_cast<TypeParam>(0xeeu); auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("\xee")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "\xee")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } template <typename T> class UnsignedIntLogFormatTest : public testing::Test {}; using UnsignedIntTypes = Types<unsigned short, unsigned int, unsigned long, unsigned long long>; TYPED_TEST_SUITE(UnsignedIntLogFormatTest, UnsignedIntTypes); TYPED_TEST(UnsignedIntLogFormatTest, Positive) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = 224; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("224")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "224")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(UnsignedIntLogFormatTest, BitfieldPositive) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const struct { TypeParam bits : 6; } value{42}; auto comparison_stream = ComparisonStream(); comparison_stream << value.bits; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("42")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "42")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value.bits; } template <typename T> class SignedIntLogFormatTest : public testing::Test {}; using SignedIntTypes = Types<signed short, signed int, signed long, signed long long>; TYPED_TEST_SUITE(SignedIntLogFormatTest, SignedIntTypes); TYPED_TEST(SignedIntLogFormatTest, Positive) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = 224; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("224")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "224")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(SignedIntLogFormatTest, Negative) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = -112; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("-112")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "-112")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(SignedIntLogFormatTest, BitfieldPositive) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const struct { TypeParam bits : 6; } value{21}; auto comparison_stream = ComparisonStream(); comparison_stream << value.bits; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("21")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "21")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value.bits; } TYPED_TEST(SignedIntLogFormatTest, BitfieldNegative) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const struct { TypeParam bits : 6; } value{-21}; auto comparison_stream = ComparisonStream(); comparison_stream << value.bits; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("-21")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "-21")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value.bits; } #if !defined(__GNUC__) || defined(__clang__) enum MyUnsignedEnum { MyUnsignedEnum_ZERO = 0, MyUnsignedEnum_FORTY_TWO = 42, MyUnsignedEnum_TWO_HUNDRED_TWENTY_FOUR = 224, }; enum MyUnsignedIntEnum : unsigned int { MyUnsignedIntEnum_ZERO = 0, MyUnsignedIntEnum_FORTY_TWO = 42, MyUnsignedIntEnum_TWO_HUNDRED_TWENTY_FOUR = 224, }; template <typename T> class UnsignedEnumLogFormatTest : public testing::Test {}; using UnsignedEnumTypes = std::conditional< std::is_signed<std::underlying_type<MyUnsignedEnum>::type>::value, Types<MyUnsignedIntEnum>, Types<MyUnsignedEnum, MyUnsignedIntEnum>>::type; TYPED_TEST_SUITE(UnsignedEnumLogFormatTest, UnsignedEnumTypes); TYPED_TEST(UnsignedEnumLogFormatTest, Positive) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = static_cast<TypeParam>(224); auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("224")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "224")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(UnsignedEnumLogFormatTest, BitfieldPositive) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const struct { TypeParam bits : 6; } value{static_cast<TypeParam>(42)}; auto comparison_stream = ComparisonStream(); comparison_stream << value.bits; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("42")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "42")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value.bits; } enum MySignedEnum { MySignedEnum_NEGATIVE_ONE_HUNDRED_TWELVE = -112, MySignedEnum_NEGATIVE_TWENTY_ONE = -21, MySignedEnum_ZERO = 0, MySignedEnum_TWENTY_ONE = 21, MySignedEnum_TWO_HUNDRED_TWENTY_FOUR = 224, }; enum MySignedIntEnum : signed int { MySignedIntEnum_NEGATIVE_ONE_HUNDRED_TWELVE = -112, MySignedIntEnum_NEGATIVE_TWENTY_ONE = -21, MySignedIntEnum_ZERO = 0, MySignedIntEnum_TWENTY_ONE = 21, MySignedIntEnum_TWO_HUNDRED_TWENTY_FOUR = 224, }; template <typename T> class SignedEnumLogFormatTest : public testing::Test {}; using SignedEnumTypes = std::conditional< std::is_signed<std::underlying_type<MyUnsignedEnum>::type>::value, Types<MyUnsignedEnum, MySignedEnum, MySignedIntEnum>, Types<MySignedEnum, MySignedIntEnum>>::type; TYPED_TEST_SUITE(SignedEnumLogFormatTest, SignedEnumTypes); TYPED_TEST(SignedEnumLogFormatTest, Positive) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = static_cast<TypeParam>(224); auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("224")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "224")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(SignedEnumLogFormatTest, Negative) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = static_cast<TypeParam>(-112); auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("-112")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "-112")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(SignedEnumLogFormatTest, BitfieldPositive) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const struct { TypeParam bits : 6; } value{static_cast<TypeParam>(21)}; auto comparison_stream = ComparisonStream(); comparison_stream << value.bits; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("21")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "21")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value.bits; } TYPED_TEST(SignedEnumLogFormatTest, BitfieldNegative) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const struct { TypeParam bits : 6; } value{static_cast<TypeParam>(-21)}; auto comparison_stream = ComparisonStream(); comparison_stream << value.bits; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("-21")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "-21")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value.bits; } #endif TEST(FloatLogFormatTest, Positive) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const float value = 6.02e23f; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("6.02e+23")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "6.02e+23")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TEST(FloatLogFormatTest, Negative) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const float value = -6.02e23f; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("-6.02e+23")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "-6.02e+23")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TEST(FloatLogFormatTest, NegativeExponent) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const float value = 6.02e-23f; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("6.02e-23")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "6.02e-23")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TEST(DoubleLogFormatTest, Positive) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const double value = 6.02e23; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("6.02e+23")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "6.02e+23")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TEST(DoubleLogFormatTest, Negative) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const double value = -6.02e23; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("-6.02e+23")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "-6.02e+23")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TEST(DoubleLogFormatTest, NegativeExponent) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const double value = 6.02e-23; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("6.02e-23")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "6.02e-23")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } template <typename T> class FloatingPointLogFormatTest : public testing::Test {}; using FloatingPointTypes = Types<float, double>; TYPED_TEST_SUITE(FloatingPointLogFormatTest, FloatingPointTypes); TYPED_TEST(FloatingPointLogFormatTest, Zero) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = 0.0; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("0")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "0")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(FloatingPointLogFormatTest, Integer) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = 1.0; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("1")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "1")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(FloatingPointLogFormatTest, Infinity) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = std::numeric_limits<TypeParam>::infinity(); auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(AnyOf(Eq("inf"), Eq("Inf"))), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "inf")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(FloatingPointLogFormatTest, NegativeInfinity) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = -std::numeric_limits<TypeParam>::infinity(); auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(AnyOf(Eq("-inf"), Eq("-Inf"))), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "-inf")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(FloatingPointLogFormatTest, NaN) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = std::numeric_limits<TypeParam>::quiet_NaN(); auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(AnyOf(Eq("nan"), Eq("NaN"))), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "nan")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(FloatingPointLogFormatTest, NegativeNaN) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = std::copysign(std::numeric_limits<TypeParam>::quiet_NaN(), -1.0); auto comparison_stream = ComparisonStream(); comparison_stream << value; #ifdef __riscv EXPECT_CALL( test_sink, Send(AllOf( TextMessage(AnyOf(Eq("-nan"), Eq("nan"), Eq("NaN"), Eq("-nan(ind)"))), ENCODED_MESSAGE(HasValues( ElementsAre(AnyOf(EqualsProto(R"pb(str: "-nan")pb"), EqualsProto(R"pb(str: "nan")pb"), EqualsProto(R"pb(str: "-nan(ind)")pb")))))))); #else EXPECT_CALL( test_sink, Send(AllOf( TextMessage(MatchesOstream(comparison_stream)), TextMessage(AnyOf(Eq("-nan"), Eq("nan"), Eq("NaN"), Eq("-nan(ind)"))), ENCODED_MESSAGE(HasValues( ElementsAre(AnyOf(EqualsProto(R"pb(str: "-nan")pb"), EqualsProto(R"pb(str: "nan")pb"), EqualsProto(R"pb(str: "-nan(ind)")pb")))))))); #endif test_sink.StartCapturingLogs(); LOG(INFO) << value; } template <typename T> class VoidPtrLogFormatTest : public testing::Test {}; using VoidPtrTypes = Types<void *, const void *>; TYPED_TEST_SUITE(VoidPtrLogFormatTest, VoidPtrTypes); TYPED_TEST(VoidPtrLogFormatTest, Null) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = nullptr; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL( test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(AnyOf(Eq("(nil)"), Eq("0"), Eq("0x0"), Eq("00000000"), Eq("0000000000000000")))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(VoidPtrLogFormatTest, NonNull) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = reinterpret_cast<TypeParam>(0xdeadbeefULL); auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL( test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(AnyOf(Eq("0xdeadbeef"), Eq("DEADBEEF"), Eq("00000000DEADBEEF"))), ENCODED_MESSAGE(HasValues(ElementsAre( AnyOf(EqualsProto(R"pb(str: "0xdeadbeef")pb"), EqualsProto(R"pb(str: "00000000DEADBEEF")pb")))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } template <typename T> class VolatilePtrLogFormatTest : public testing::Test {}; using VolatilePtrTypes = Types<volatile void*, const volatile void*, volatile char*, const volatile char*, volatile signed char*, const volatile signed char*, volatile unsigned char*, const volatile unsigned char*>; TYPED_TEST_SUITE(VolatilePtrLogFormatTest, VolatilePtrTypes); TYPED_TEST(VolatilePtrLogFormatTest, Null) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = nullptr; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("false")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "false")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(VolatilePtrLogFormatTest, NonNull) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const TypeParam value = reinterpret_cast<TypeParam>(0xdeadbeefLL); auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("true")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "true")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } template <typename T> class CharPtrLogFormatTest : public testing::Test {}; using CharPtrTypes = Types<char, const char, signed char, const signed char, unsigned char, const unsigned char>; TYPED_TEST_SUITE(CharPtrLogFormatTest, CharPtrTypes); TYPED_TEST(CharPtrLogFormatTest, Null) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); TypeParam* const value = nullptr; EXPECT_CALL( test_sink, Send(AllOf( TextMessage(Eq("(null)")), ENCODED_MESSAGE( HasValues(ElementsAre(EqualsProto(R"pb(str: "(null)")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TYPED_TEST(CharPtrLogFormatTest, NonNull) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); TypeParam data[] = {'v', 'a', 'l', 'u', 'e', '\0'}; TypeParam* const value = data; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("value")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "value")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TEST(BoolLogFormatTest, True) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const bool value = true; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("true")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "true")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TEST(BoolLogFormatTest, False) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const bool value = false; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("false")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "false")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } TEST(LogFormatTest, StringLiteral) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); auto comparison_stream = ComparisonStream(); comparison_stream << "value"; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("value")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(literal: "value")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << "value"; } TEST(LogFormatTest, CharArray) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); char value[] = "value"; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("value")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "value")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } class CustomClass {}; std::ostream& operator<<(std::ostream& os, const CustomClass&) { return os << "CustomClass{}"; } TEST(LogFormatTest, Custom) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); CustomClass value; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("CustomClass{}")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "CustomClass{}")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } class CustomClassNonCopyable { public: CustomClassNonCopyable() = default; CustomClassNonCopyable(const CustomClassNonCopyable&) = delete; CustomClassNonCopyable& operator=(const CustomClassNonCopyable&) = delete; }; std::ostream& operator<<(std::ostream& os, const CustomClassNonCopyable&) { return os << "CustomClassNonCopyable{}"; } TEST(LogFormatTest, CustomNonCopyable) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); CustomClassNonCopyable value; auto comparison_stream = ComparisonStream(); comparison_stream << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("CustomClassNonCopyable{}")), ENCODED_MESSAGE(HasValues(ElementsAre(EqualsProto( R"pb(str: "CustomClassNonCopyable{}")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value; } struct Point { template <typename Sink> friend void AbslStringify(Sink& sink, const Point& p) { absl::Format(&sink, "(%d, %d)", p.x, p.y); } int x = 10; int y = 20; }; TEST(LogFormatTest, AbslStringifyExample) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); Point p; EXPECT_CALL( test_sink, Send(AllOf(TextMessage(Eq("(10, 20)")), TextMessage(Eq(absl::StrCat(p))), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "(10, 20)")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << p; } struct PointWithAbslStringifiyAndOstream { template <typename Sink> friend void AbslStringify(Sink& sink, const PointWithAbslStringifiyAndOstream& p) { absl::Format(&sink, "(%d, %d)", p.x, p.y); } int x = 10; int y = 20; }; ABSL_ATTRIBUTE_UNUSED std::ostream& operator<<( std::ostream& os, const PointWithAbslStringifiyAndOstream&) { return os << "Default to AbslStringify()"; } TEST(LogFormatTest, CustomWithAbslStringifyAndOstream) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); PointWithAbslStringifiyAndOstream p; EXPECT_CALL( test_sink, Send(AllOf(TextMessage(Eq("(10, 20)")), TextMessage(Eq(absl::StrCat(p))), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "(10, 20)")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << p; } struct PointStreamsNothing { template <typename Sink> friend void AbslStringify(Sink&, const PointStreamsNothing&) {} int x = 10; int y = 20; }; TEST(LogFormatTest, AbslStringifyStreamsNothing) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); PointStreamsNothing p; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(Eq("77")), TextMessage(Eq(absl::StrCat(p, 77))), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "77")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << p << 77; } struct PointMultipleAppend { template <typename Sink> friend void AbslStringify(Sink& sink, const PointMultipleAppend& p) { sink.Append("("); sink.Append(absl::StrCat(p.x, ", ", p.y, ")")); } int x = 10; int y = 20; }; TEST(LogFormatTest, AbslStringifyMultipleAppend) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); PointMultipleAppend p; EXPECT_CALL( test_sink, Send(AllOf(TextMessage(Eq("(10, 20)")), TextMessage(Eq(absl::StrCat(p))), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "(")pb"), EqualsProto(R"pb(str: "10, 20)")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << p; } TEST(ManipulatorLogFormatTest, BoolAlphaTrue) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const bool value = true; auto comparison_stream = ComparisonStream(); comparison_stream << std::noboolalpha << value << " " << std::boolalpha << value << " " << std::noboolalpha << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("1 true 1")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "1")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "true")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "1")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::noboolalpha << value << " " << std::boolalpha << value << " " << std::noboolalpha << value; } TEST(ManipulatorLogFormatTest, BoolAlphaFalse) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const bool value = false; auto comparison_stream = ComparisonStream(); comparison_stream << std::noboolalpha << value << " " << std::boolalpha << value << " " << std::noboolalpha << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("0 false 0")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "0")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "false")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "0")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::noboolalpha << value << " " << std::boolalpha << value << " " << std::noboolalpha << value; } TEST(ManipulatorLogFormatTest, ShowPoint) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const double value = 77.0; auto comparison_stream = ComparisonStream(); comparison_stream << std::noshowpoint << value << " " << std::showpoint << value << " " << std::noshowpoint << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("77 77.0000 77")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "77")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "77.0000")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "77")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::noshowpoint << value << " " << std::showpoint << value << " " << std::noshowpoint << value; } TEST(ManipulatorLogFormatTest, ShowPos) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = 77; auto comparison_stream = ComparisonStream(); comparison_stream << std::noshowpos << value << " " << std::showpos << value << " " << std::noshowpos << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("77 +77 77")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "77")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "+77")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "77")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::noshowpos << value << " " << std::showpos << value << " " << std::noshowpos << value; } TEST(ManipulatorLogFormatTest, UppercaseFloat) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const double value = 7.7e7; auto comparison_stream = ComparisonStream(); comparison_stream << std::nouppercase << value << " " << std::uppercase << value << " " << std::nouppercase << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("7.7e+07 7.7E+07 7.7e+07")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "7.7e+07")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "7.7E+07")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "7.7e+07")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::nouppercase << value << " " << std::uppercase << value << " " << std::nouppercase << value; } TEST(ManipulatorLogFormatTest, Hex) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = 0x77; auto comparison_stream = ComparisonStream(); comparison_stream << std::hex << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("0x77")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "0x77")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::hex << value; } TEST(ManipulatorLogFormatTest, Oct) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = 077; auto comparison_stream = ComparisonStream(); comparison_stream << std::oct << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("077")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "077")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::oct << value; } TEST(ManipulatorLogFormatTest, Dec) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = 77; auto comparison_stream = ComparisonStream(); comparison_stream << std::hex << std::dec << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("77")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "77")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::hex << std::dec << value; } TEST(ManipulatorLogFormatTest, ShowbaseHex) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = 0x77; auto comparison_stream = ComparisonStream(); comparison_stream << std::hex << std::noshowbase << value << " " << std::showbase << value << " " << std::noshowbase << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("77 0x77 77")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "77")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "0x77")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "77")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::hex << std::noshowbase << value << " " << std::showbase << value << " " << std::noshowbase << value; } TEST(ManipulatorLogFormatTest, ShowbaseOct) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = 077; auto comparison_stream = ComparisonStream(); comparison_stream << std::oct << std::noshowbase << value << " " << std::showbase << value << " " << std::noshowbase << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("77 077 77")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "77")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "077")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "77")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::oct << std::noshowbase << value << " " << std::showbase << value << " " << std::noshowbase << value; } TEST(ManipulatorLogFormatTest, UppercaseHex) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = 0xbeef; auto comparison_stream = ComparisonStream(); comparison_stream << std::hex << std::nouppercase << value << " " << std::uppercase << value << " " << std::nouppercase << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("0xbeef 0XBEEF 0xbeef")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "0xbeef")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "0XBEEF")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "0xbeef")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::hex << std::nouppercase << value << " " << std::uppercase << value << " " << std::nouppercase << value; } TEST(ManipulatorLogFormatTest, FixedFloat) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const double value = 7.7e7; auto comparison_stream = ComparisonStream(); comparison_stream << std::fixed << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("77000000.000000")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "77000000.000000")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::fixed << value; } TEST(ManipulatorLogFormatTest, ScientificFloat) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const double value = 7.7e7; auto comparison_stream = ComparisonStream(); comparison_stream << std::scientific << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("7.700000e+07")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "7.700000e+07")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::scientific << value; } #if defined(__BIONIC__) && (!defined(__ANDROID_API__) || __ANDROID_API__ < 22) #elif defined(__GLIBCXX__) && __cplusplus < 201402L #else TEST(ManipulatorLogFormatTest, FixedAndScientificFloat) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const double value = 7.7e7; auto comparison_stream = ComparisonStream(); comparison_stream << std::setiosflags(std::ios_base::scientific | std::ios_base::fixed) << value; EXPECT_CALL( test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(AnyOf(Eq("0x1.25bb50p+26"), Eq("0x1.25bb5p+26"), Eq("0x1.25bb500000000p+26"))), ENCODED_MESSAGE(HasValues(ElementsAre(AnyOf( EqualsProto(R"pb(str: "0x1.25bb5p+26")pb"), EqualsProto(R"pb(str: "0x1.25bb500000000p+26")pb")))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::setiosflags(std::ios_base::scientific | std::ios_base::fixed) << value; } #endif #if defined(__BIONIC__) && (!defined(__ANDROID_API__) || __ANDROID_API__ < 22) #elif defined(__GLIBCXX__) && __cplusplus < 201402L #else TEST(ManipulatorLogFormatTest, HexfloatFloat) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const double value = 7.7e7; auto comparison_stream = ComparisonStream(); comparison_stream << std::hexfloat << value; EXPECT_CALL( test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(AnyOf(Eq("0x1.25bb50p+26"), Eq("0x1.25bb5p+26"), Eq("0x1.25bb500000000p+26"))), ENCODED_MESSAGE(HasValues(ElementsAre(AnyOf( EqualsProto(R"pb(str: "0x1.25bb5p+26")pb"), EqualsProto(R"pb(str: "0x1.25bb500000000p+26")pb")))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::hexfloat << value; } #endif TEST(ManipulatorLogFormatTest, DefaultFloatFloat) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const double value = 7.7e7; auto comparison_stream = ComparisonStream(); comparison_stream << std::hexfloat << std::defaultfloat << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("7.7e+07")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "7.7e+07")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::hexfloat << std::defaultfloat << value; } TEST(ManipulatorLogFormatTest, Ends) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); auto comparison_stream = ComparisonStream(); comparison_stream << std::ends; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq(absl::string_view("\0", 1))), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "\0")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::ends; } TEST(ManipulatorLogFormatTest, Endl) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); auto comparison_stream = ComparisonStream(); comparison_stream << std::endl; EXPECT_CALL( test_sink, Send(AllOf( TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("\n")), ENCODED_MESSAGE(HasValues(ElementsAre(EqualsProto(R"pb(str: "\n")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::endl; } TEST(ManipulatorLogFormatTest, SetIosFlags) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = 0x77; auto comparison_stream = ComparisonStream(); comparison_stream << std::resetiosflags(std::ios_base::basefield) << std::setiosflags(std::ios_base::hex) << value << " " << std::resetiosflags(std::ios_base::basefield) << std::setiosflags(std::ios_base::dec) << value; EXPECT_CALL( test_sink, Send(AllOf( TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("0x77 119")), ENCODED_MESSAGE( HasValues(ElementsAre(EqualsProto(R"pb(str: "0x77")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "119")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::resetiosflags(std::ios_base::basefield) << std::setiosflags(std::ios_base::hex) << value << " " << std::resetiosflags(std::ios_base::basefield) << std::setiosflags(std::ios_base::dec) << value; } TEST(ManipulatorLogFormatTest, SetBase) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = 0x77; auto comparison_stream = ComparisonStream(); comparison_stream << std::setbase(16) << value << " " << std::setbase(0) << value; EXPECT_CALL( test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("0x77 119")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "0x77")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "119")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::setbase(16) << value << " " << std::setbase(0) << value; } TEST(ManipulatorLogFormatTest, SetPrecision) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const double value = 6.022140857e23; auto comparison_stream = ComparisonStream(); comparison_stream << std::setprecision(4) << value; EXPECT_CALL( test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("6.022e+23")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "6.022e+23")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::setprecision(4) << value; } TEST(ManipulatorLogFormatTest, SetPrecisionOverflow) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const double value = 6.022140857e23; auto comparison_stream = ComparisonStream(); comparison_stream << std::setprecision(200) << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("602214085700000015187968")), ENCODED_MESSAGE(HasValues(ElementsAre(EqualsProto( R"pb(str: "602214085700000015187968")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::setprecision(200) << value; } TEST(ManipulatorLogFormatTest, SetW) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = 77; auto comparison_stream = ComparisonStream(); comparison_stream << std::setw(8) << value; EXPECT_CALL( test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq(" 77")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: " 77")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::setw(8) << value; } TEST(ManipulatorLogFormatTest, Left) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = -77; auto comparison_stream = ComparisonStream(); comparison_stream << std::left << std::setw(8) << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("-77 ")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "-77 ")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::left << std::setw(8) << value; } TEST(ManipulatorLogFormatTest, Right) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = -77; auto comparison_stream = ComparisonStream(); comparison_stream << std::right << std::setw(8) << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq(" -77")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: " -77")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::right << std::setw(8) << value; } TEST(ManipulatorLogFormatTest, Internal) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = -77; auto comparison_stream = ComparisonStream(); comparison_stream << std::internal << std::setw(8) << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("- 77")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "- 77")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::internal << std::setw(8) << value; } TEST(ManipulatorLogFormatTest, SetFill) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); const int value = 77; auto comparison_stream = ComparisonStream(); comparison_stream << std::setfill('0') << std::setw(8) << value; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("00000077")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "00000077")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::setfill('0') << std::setw(8) << value; } class FromCustomClass {}; std::ostream& operator<<(std::ostream& os, const FromCustomClass&) { return os << "FromCustomClass{}" << std::hex; } TEST(ManipulatorLogFormatTest, FromCustom) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); FromCustomClass value; auto comparison_stream = ComparisonStream(); comparison_stream << value << " " << 0x77; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("FromCustomClass{} 0x77")), ENCODED_MESSAGE(HasValues(ElementsAre( EqualsProto(R"pb(str: "FromCustomClass{}")pb"), EqualsProto(R"pb(literal: " ")pb"), EqualsProto(R"pb(str: "0x77")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value << " " << 0x77; } class StreamsNothing {}; std::ostream& operator<<(std::ostream& os, const StreamsNothing&) { return os; } TEST(ManipulatorLogFormatTest, CustomClassStreamsNothing) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); StreamsNothing value; auto comparison_stream = ComparisonStream(); comparison_stream << value << 77; EXPECT_CALL(test_sink, Send(AllOf(TextMessage(MatchesOstream(comparison_stream)), TextMessage(Eq("77")), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "77")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << value << 77; } struct PointPercentV { template <typename Sink> friend void AbslStringify(Sink& sink, const PointPercentV& p) { absl::Format(&sink, "(%v, %v)", p.x, p.y); } int x = 10; int y = 20; }; TEST(ManipulatorLogFormatTest, IOManipsDoNotAffectAbslStringify) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); PointPercentV p; EXPECT_CALL( test_sink, Send(AllOf(TextMessage(Eq("(10, 20)")), TextMessage(Eq(absl::StrCat(p))), ENCODED_MESSAGE(HasValues( ElementsAre(EqualsProto(R"pb(str: "(10, 20)")pb"))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::hex << p; } TEST(StructuredLoggingOverflowTest, TruncatesStrings) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL( test_sink, Send(AllOf( TextMessage(AllOf( SizeIs(AllOf(Ge(absl::log_internal::kLogMessageBufferSize - 256), Le(absl::log_internal::kLogMessageBufferSize))), Each(Eq('x')))), ENCODED_MESSAGE(HasOneStrThat(AllOf( SizeIs(AllOf(Ge(absl::log_internal::kLogMessageBufferSize - 256), Le(absl::log_internal::kLogMessageBufferSize))), Each(Eq('x')))))))); test_sink.StartCapturingLogs(); LOG(INFO) << std::string(2 * absl::log_internal::kLogMessageBufferSize, 'x'); } struct StringLike { absl::string_view data; }; std::ostream& operator<<(std::ostream& os, StringLike str) { return os << str.data; } TEST(StructuredLoggingOverflowTest, TruncatesInsertionOperators) { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL( test_sink, Send(AllOf( TextMessage(AllOf( SizeIs(AllOf(Ge(absl::log_internal::kLogMessageBufferSize - 256), Le(absl::log_internal::kLogMessageBufferSize))), Each(Eq('x')))), ENCODED_MESSAGE(HasOneStrThat(AllOf( SizeIs(AllOf(Ge(absl::log_internal::kLogMessageBufferSize - 256), Le(absl::log_internal::kLogMessageBufferSize))), Each(Eq('x')))))))); test_sink.StartCapturingLogs(); LOG(INFO) << StringLike{ std::string(2 * absl::log_internal::kLogMessageBufferSize, 'x')}; } size_t MaxLogFieldLengthNoPrefix() { class StringLengthExtractorSink : public absl::LogSink { public: void Send(const absl::LogEntry& entry) override { CHECK(!size_.has_value()); CHECK_EQ(entry.text_message().find_first_not_of('x'), absl::string_view::npos); size_.emplace(entry.text_message().size()); } size_t size() const { CHECK(size_.has_value()); return *size_; } private: absl::optional<size_t> size_; } extractor_sink; LOG(INFO).NoPrefix().ToSinkOnly(&extractor_sink) << std::string(2 * absl::log_internal::kLogMessageBufferSize, 'x'); return extractor_sink.size(); } TEST(StructuredLoggingOverflowTest, TruncatesStringsCleanly) { const size_t longest_fit = MaxLogFieldLengthNoPrefix(); { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(AllOf(ENCODED_MESSAGE(HasOneStrThat( AllOf(SizeIs(longest_fit), Each(Eq('x'))))), RawEncodedMessage(AsString(EndsWith("x")))))); test_sink.StartCapturingLogs(); LOG(INFO).NoPrefix() << std::string(longest_fit, 'x') << "y"; } { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(AllOf(ENCODED_MESSAGE(HasOneStrThat( AllOf(SizeIs(longest_fit - 1), Each(Eq('x'))))), RawEncodedMessage(AsString(EndsWith("x")))))); test_sink.StartCapturingLogs(); LOG(INFO).NoPrefix() << std::string(longest_fit - 1, 'x') << "y"; } { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(AllOf(ENCODED_MESSAGE(HasOneStrThat( AllOf(SizeIs(longest_fit - 2), Each(Eq('x'))))), RawEncodedMessage(AsString(EndsWith("x")))))); test_sink.StartCapturingLogs(); LOG(INFO).NoPrefix() << std::string(longest_fit - 2, 'x') << "y"; } { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(AllOf(ENCODED_MESSAGE(HasOneStrThat( AllOf(SizeIs(longest_fit - 3), Each(Eq('x'))))), RawEncodedMessage(AsString(EndsWith("x")))))); test_sink.StartCapturingLogs(); LOG(INFO).NoPrefix() << std::string(longest_fit - 3, 'x') << "y"; } { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(AllOf(ENCODED_MESSAGE(HasOneStrAndOneLiteralThat( AllOf(SizeIs(longest_fit - 4), Each(Eq('x'))), IsEmpty())), RawEncodedMessage(Not(AsString(EndsWith("x"))))))); test_sink.StartCapturingLogs(); LOG(INFO).NoPrefix() << std::string(longest_fit - 4, 'x') << "y"; } { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL( test_sink, Send(AllOf(ENCODED_MESSAGE(HasOneStrAndOneLiteralThat( AllOf(SizeIs(longest_fit - 5), Each(Eq('x'))), Eq("y"))), RawEncodedMessage(AsString(EndsWith("y")))))); test_sink.StartCapturingLogs(); LOG(INFO).NoPrefix() << std::string(longest_fit - 5, 'x') << "y"; } } TEST(StructuredLoggingOverflowTest, TruncatesInsertionOperatorsCleanly) { const size_t longest_fit = MaxLogFieldLengthNoPrefix(); { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(AllOf(ENCODED_MESSAGE(HasOneStrThat( AllOf(SizeIs(longest_fit), Each(Eq('x'))))), RawEncodedMessage(AsString(EndsWith("x")))))); test_sink.StartCapturingLogs(); LOG(INFO).NoPrefix() << std::string(longest_fit, 'x') << StringLike{"y"}; } { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(AllOf(ENCODED_MESSAGE(HasOneStrThat( AllOf(SizeIs(longest_fit - 1), Each(Eq('x'))))), RawEncodedMessage(AsString(EndsWith("x")))))); test_sink.StartCapturingLogs(); LOG(INFO).NoPrefix() << std::string(longest_fit - 1, 'x') << StringLike{"y"}; } { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(AllOf(ENCODED_MESSAGE(HasOneStrThat( AllOf(SizeIs(longest_fit - 2), Each(Eq('x'))))), RawEncodedMessage(AsString(EndsWith("x")))))); test_sink.StartCapturingLogs(); LOG(INFO).NoPrefix() << std::string(longest_fit - 2, 'x') << StringLike{"y"}; } { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(AllOf(ENCODED_MESSAGE(HasOneStrThat( AllOf(SizeIs(longest_fit - 3), Each(Eq('x'))))), RawEncodedMessage(AsString(EndsWith("x")))))); test_sink.StartCapturingLogs(); LOG(INFO).NoPrefix() << std::string(longest_fit - 3, 'x') << StringLike{"y"}; } { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL(test_sink, Send(AllOf(ENCODED_MESSAGE(HasOneStrThat( AllOf(SizeIs(longest_fit - 4), Each(Eq('x'))))), RawEncodedMessage(AsString(EndsWith("x")))))); test_sink.StartCapturingLogs(); LOG(INFO).NoPrefix() << std::string(longest_fit - 4, 'x') << StringLike{"y"}; } { absl::ScopedMockLog test_sink(absl::MockLogDefault::kDisallowUnexpected); EXPECT_CALL( test_sink, Send(AllOf(ENCODED_MESSAGE(HasTwoStrsThat( AllOf(SizeIs(longest_fit - 5), Each(Eq('x'))), Eq("y"))), RawEncodedMessage(AsString(EndsWith("y")))))); test_sink.StartCapturingLogs(); LOG(INFO).NoPrefix() << std::string(longest_fit - 5, 'x') << StringLike{"y"}; } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/internal/log_format.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/log_format_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
54d68a94-04d4-4a1e-9f32-a3aab696534c
cpp
abseil/abseil-cpp
gaussian_distribution
absl/random/gaussian_distribution.cc
absl/random/gaussian_distribution_test.cc
#include "absl/random/gaussian_distribution.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { const gaussian_distribution_base::Tables gaussian_distribution_base::zg_ = { {3.7130862467425505, 3.442619855899000214, 3.223084984581141565, 3.083228858216868318, 2.978696252647779819, 2.894344007021528942, 2.82312535054891045, 2.761169372387176857, 2.706113573121819549, 2.656406411261359679, 2.610972248431847387, 2.56903362592493778, 2.530009672388827457, 2.493454522095372106, 2.459018177411830486, 2.426420645533749809, 2.395434278011062457, 2.365871370117638595, 2.337575241339236776, 2.310413683698762988, 2.284274059677471769, 2.25905957386919809, 2.234686395590979036, 2.21108140887870297, 2.188180432076048731, 2.165926793748921497, 2.144270182360394905, 2.123165708673976138, 2.102573135189237608, 2.082456237992015957, 2.062782274508307978, 2.043521536655067194, 2.02464697337738464, 2.006133869963471206, 1.987959574127619033, 1.970103260854325633, 1.952545729553555764, 1.935269228296621957, 1.918257300864508963, 1.901494653105150423, 1.884967035707758143, 1.868661140994487768, 1.852564511728090002, 1.836665460258444904, 1.820952996596124418, 1.805416764219227366, 1.790046982599857506, 1.77483439558606837, 1.759770224899592339, 1.744846128113799244, 1.730054160563729182, 1.71538674071366648, 1.700836618569915748, 1.686396846779167014, 1.6720607540975998, 1.657821920954023254, 1.643674156862867441, 1.629611479470633562, 1.615628095043159629, 1.601718380221376581, 1.587876864890574558, 1.574098216022999264, 1.560377222366167382, 1.546708779859908844, 1.533087877674041755, 1.519509584765938559, 1.505969036863201937, 1.492461423781352714, 1.478981976989922842, 1.465525957342709296, 1.452088642889222792, 1.438665316684561546, 1.425251254514058319, 1.411841712447055919, 1.398431914131003539, 1.385017037732650058, 1.371592202427340812, 1.358152454330141534, 1.34469275175354519, 1.331207949665625279, 1.317692783209412299, 1.304141850128615054, 1.290549591926194894, 1.27691027356015363, 1.263217961454619287, 1.249466499573066436, 1.23564948326336066, 1.221760230539994385, 1.207791750415947662, 1.193736707833126465, 1.17958738466398616, 1.165335636164750222, 1.150972842148865416, 1.136489852013158774, 1.121876922582540237, 1.107123647534034028, 1.092218876907275371, 1.077150624892893482, 1.061905963694822042, 1.046470900764042922, 1.030830236068192907, 1.014967395251327842, 0.9988642334929808131, 0.9825008035154263464, 0.9658550794011470098, 0.9489026255113034436, 0.9316161966151479401, 0.9139652510230292792, 0.8959153525809346874, 0.8774274291129204872, 0.8584568431938099931, 0.8389522142975741614, 0.8188539067003538507, 0.7980920606440534693, 0.7765839878947563557, 0.7542306644540520688, 0.7309119106424850631, 0.7064796113354325779, 0.6807479186691505202, 0.6534786387399710295, 0.6243585973360461505, 0.5929629424714434327, 0.5586921784081798625, 0.5206560387620546848, 0.4774378372966830431, 0.4265479863554152429, 0.3628714310970211909, 0.2723208648139477384, 0}, {0.001014352564120377413, 0.002669629083880922793, 0.005548995220771345792, 0.008624484412859888607, 0.01183947865788486861, 0.01516729801054656976, 0.01859210273701129151, 0.02210330461592709475, 0.02569329193593428151, 0.02935631744000685023, 0.03308788614622575758, 0.03688438878665621645, 0.04074286807444417458, 0.04466086220049143157, 0.04863629585986780496, 0.05266740190305100461, 0.05675266348104984759, 0.06089077034804041277, 0.06508058521306804567, 0.06932111739357792179, 0.07361150188411341722, 0.07795098251397346301, 0.08233889824223575293, 0.08677467189478028919, 0.09125780082683036809, 0.095787849121731522, 0.1003644410286559929, 0.1049872554094214289, 0.1096560210148404546, 0.1143705124488661323, 0.1191305467076509556, 0.1239359802028679736, 0.1287867061959434012, 0.1336826525834396151, 0.1386237799845948804, 0.1436100800906280339, 0.1486415742423425057, 0.1537183122081819397, 0.1588403711394795748, 0.1640078546834206341, 0.1692208922373653057, 0.1744796383307898324, 0.1797842721232958407, 0.1851349970089926078, 0.1905320403191375633, 0.1959756531162781534, 0.2014661100743140865, 0.2070037094399269362, 0.2125887730717307134, 0.2182216465543058426, 0.2239026993850088965, 0.229632325232116602, 0.2354109422634795556, 0.2412389935454402889, 0.2471169475123218551, 0.2530452985073261551, 0.2590245673962052742, 0.2650553022555897087, 0.271138079138385224, 0.2772735029191887857, 0.2834622082232336471, 0.2897048604429605656, 0.2960021568469337061, 0.3023548277864842593, 0.3087636380061818397, 0.3152293880650116065, 0.3217529158759855901, 0.3283350983728509642, 0.3349768533135899506, 0.3416791412315512977, 0.3484429675463274756, 0.355269384847918035, 0.3621594953693184626, 0.3691144536644731522, 0.376135469510563536, 0.3832238110559021416, 0.3903808082373155797, 0.3976078564938743676, 0.404906420807223999, 0.4122780401026620578, 0.4197243320495753771, 0.4272469983049970721, 0.4348478302499918513, 0.4425287152754694975, 0.4502916436820402768, 0.458138716267873114, 0.4660721526894572309, 0.4740943006930180559, 0.4822076463294863724, 0.4904148252838453348, 0.4987186354709807201, 0.5071220510755701794, 0.5156282382440030565, 0.5242405726729852944, 0.5329626593838373561, 0.5417983550254266145, 0.5507517931146057588, 0.5598274127040882009, 0.5690299910679523787, 0.5783646811197646898, 0.5878370544347081283, 0.5974531509445183408, 0.6072195366251219584, 0.6171433708188825973, 0.6272324852499290282, 0.6374954773350440806, 0.6479418211102242475, 0.6585820000500898219, 0.6694276673488921414, 0.6804918409973358395, 0.6917891434366769676, 0.7033360990161600101, 0.7151515074105005976, 0.7272569183441868201, 0.7396772436726493094, 0.7524415591746134169, 0.7655841738977066102, 0.7791460859296898134, 0.7931770117713072832, 0.8077382946829627652, 0.8229072113814113187, 0.8387836052959920519, 0.8555006078694531446, 0.873243048910072206, 0.8922816507840289901, 0.9130436479717434217, 0.9362826816850632339, 0.9635996931270905952, 1}}; } ABSL_NAMESPACE_END }
#include "absl/random/gaussian_distribution.h" #include <algorithm> #include <cmath> #include <cstddef> #include <ios> #include <iterator> #include <random> #include <string> #include <type_traits> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/macros.h" #include "absl/log/log.h" #include "absl/numeric/internal/representation.h" #include "absl/random/internal/chi_square.h" #include "absl/random/internal/distribution_test_util.h" #include "absl/random/internal/sequence_urbg.h" #include "absl/random/random.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" #include "absl/strings/strip.h" namespace { using absl::random_internal::kChiSquared; template <typename RealType> class GaussianDistributionInterfaceTest : public ::testing::Test {}; using RealTypes = std::conditional<absl::numeric_internal::IsDoubleDouble(), ::testing::Types<float, double>, ::testing::Types<float, double, long double>>::type; TYPED_TEST_SUITE(GaussianDistributionInterfaceTest, RealTypes); TYPED_TEST(GaussianDistributionInterfaceTest, SerializeTest) { using param_type = typename absl::gaussian_distribution<TypeParam>::param_type; const TypeParam kParams[] = { 1, std::nextafter(TypeParam(1), TypeParam(0)), std::nextafter(TypeParam(1), TypeParam(2)), TypeParam(1e-8), TypeParam(1e-4), TypeParam(2), TypeParam(1e4), TypeParam(1e8), TypeParam(1e20), TypeParam(2.5), std::numeric_limits<TypeParam>::infinity(), std::numeric_limits<TypeParam>::max(), std::numeric_limits<TypeParam>::epsilon(), std::nextafter(std::numeric_limits<TypeParam>::min(), TypeParam(1)), std::numeric_limits<TypeParam>::min(), std::numeric_limits<TypeParam>::denorm_min(), std::numeric_limits<TypeParam>::min() / 2, std::nextafter(std::numeric_limits<TypeParam>::min(), TypeParam(0)), }; constexpr int kCount = 1000; absl::InsecureBitGen gen; for (const auto mod : {0, 1, 2, 3}) { for (const auto x : kParams) { if (!std::isfinite(x)) continue; for (const auto y : kParams) { const TypeParam mean = (mod & 0x1) ? -x : x; const TypeParam stddev = (mod & 0x2) ? -y : y; const param_type param(mean, stddev); absl::gaussian_distribution<TypeParam> before(mean, stddev); EXPECT_EQ(before.mean(), param.mean()); EXPECT_EQ(before.stddev(), param.stddev()); { absl::gaussian_distribution<TypeParam> via_param(param); EXPECT_EQ(via_param, before); EXPECT_EQ(via_param.param(), before.param()); } auto sample_min = before.max(); auto sample_max = before.min(); for (int i = 0; i < kCount; i++) { auto sample = before(gen); if (sample > sample_max) sample_max = sample; if (sample < sample_min) sample_min = sample; EXPECT_GE(sample, before.min()) << before; EXPECT_LE(sample, before.max()) << before; } if (!std::is_same<TypeParam, long double>::value) { LOG(INFO) << "Range{" << mean << ", " << stddev << "}: " << sample_min << ", " << sample_max; } std::stringstream ss; ss << before; if (!std::isfinite(mean) || !std::isfinite(stddev)) { continue; } absl::gaussian_distribution<TypeParam> after(-0.53f, 2.3456f); EXPECT_NE(before.mean(), after.mean()); EXPECT_NE(before.stddev(), after.stddev()); EXPECT_NE(before.param(), after.param()); EXPECT_NE(before, after); ss >> after; EXPECT_EQ(before.mean(), after.mean()); EXPECT_EQ(before.stddev(), after.stddev()) << ss.str() << " " << (ss.good() ? "good " : "") << (ss.bad() ? "bad " : "") << (ss.eof() ? "eof " : "") << (ss.fail() ? "fail " : ""); } } } } class GaussianModel { public: GaussianModel(double mean, double stddev) : mean_(mean), stddev_(stddev) {} double mean() const { return mean_; } double variance() const { return stddev() * stddev(); } double stddev() const { return stddev_; } double skew() const { return 0; } double kurtosis() const { return 3.0; } double InverseCDF(double p) { ABSL_ASSERT(p >= 0.0); ABSL_ASSERT(p < 1.0); return mean() + stddev() * -absl::random_internal::InverseNormalSurvival(p); } private: const double mean_; const double stddev_; }; struct Param { double mean; double stddev; double p_fail; int trials; }; class GaussianDistributionTests : public testing::TestWithParam<Param>, public GaussianModel { public: GaussianDistributionTests() : GaussianModel(GetParam().mean, GetParam().stddev) {} template <typename D> bool SingleZTest(const double p, const size_t samples); template <typename D> double SingleChiSquaredTest(); absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6}; }; template <typename D> bool GaussianDistributionTests::SingleZTest(const double p, const size_t samples) { D dis(mean(), stddev()); std::vector<double> data; data.reserve(samples); for (size_t i = 0; i < samples; i++) { const double x = dis(rng_); data.push_back(x); } const double max_err = absl::random_internal::MaxErrorTolerance(p); const auto m = absl::random_internal::ComputeDistributionMoments(data); const double z = absl::random_internal::ZScore(mean(), m); const bool pass = absl::random_internal::Near("z", z, 0.0, max_err); const double jb = static_cast<double>(m.n) / 6.0 * (std::pow(m.skewness, 2.0) + std::pow(m.kurtosis - 3.0, 2.0) / 4.0); if (!pass || jb > 9.21) { LOG(INFO) << "p=" << p << " max_err=" << max_err << "\n" " mean=" << m.mean << " vs. " << mean() << "\n" " stddev=" << std::sqrt(m.variance) << " vs. " << stddev() << "\n" " skewness=" << m.skewness << " vs. " << skew() << "\n" " kurtosis=" << m.kurtosis << " vs. " << kurtosis() << "\n" " z=" << z << " vs. 0\n" " jb=" << jb << " vs. 9.21"; } return pass; } template <typename D> double GaussianDistributionTests::SingleChiSquaredTest() { const size_t kSamples = 10000; const int kBuckets = 50; std::vector<double> cutoffs; const double kInc = 1.0 / static_cast<double>(kBuckets); for (double p = kInc; p < 1.0; p += kInc) { cutoffs.push_back(InverseCDF(p)); } if (cutoffs.back() != std::numeric_limits<double>::infinity()) { cutoffs.push_back(std::numeric_limits<double>::infinity()); } D dis(mean(), stddev()); std::vector<int32_t> counts(cutoffs.size(), 0); for (int j = 0; j < kSamples; j++) { const double x = dis(rng_); auto it = std::upper_bound(cutoffs.begin(), cutoffs.end(), x); counts[std::distance(cutoffs.begin(), it)]++; } const int dof = static_cast<int>(counts.size()) - 1; const double threshold = absl::random_internal::ChiSquareValue(dof, 0.98); const double expected = static_cast<double>(kSamples) / static_cast<double>(counts.size()); double chi_square = absl::random_internal::ChiSquareWithExpected( std::begin(counts), std::end(counts), expected); double p = absl::random_internal::ChiSquarePValue(chi_square, dof); if (chi_square > threshold) { for (size_t i = 0; i < cutoffs.size(); i++) { LOG(INFO) << i << " : (" << cutoffs[i] << ") = " << counts[i]; } LOG(INFO) << "mean=" << mean() << " stddev=" << stddev() << "\n" " expected " << expected << "\n" << kChiSquared << " " << chi_square << " (" << p << ")\n" << kChiSquared << " @ 0.98 = " << threshold; } return p; } TEST_P(GaussianDistributionTests, ZTest) { const size_t kSamples = 10000; const auto& param = GetParam(); const int expected_failures = std::max(1, static_cast<int>(std::ceil(param.trials * param.p_fail))); const double p = absl::random_internal::RequiredSuccessProbability( param.p_fail, param.trials); int failures = 0; for (int i = 0; i < param.trials; i++) { failures += SingleZTest<absl::gaussian_distribution<double>>(p, kSamples) ? 0 : 1; } EXPECT_LE(failures, expected_failures); } TEST_P(GaussianDistributionTests, ChiSquaredTest) { const int kTrials = 20; int failures = 0; for (int i = 0; i < kTrials; i++) { double p_value = SingleChiSquaredTest<absl::gaussian_distribution<double>>(); if (p_value < 0.0025) { failures++; } } EXPECT_LE(failures, 4); } std::vector<Param> GenParams() { return { Param{0.0, 1.0, 0.01, 100}, Param{0.0, 1e2, 0.01, 100}, Param{0.0, 1e4, 0.01, 100}, Param{0.0, 1e8, 0.01, 100}, Param{0.0, 1e16, 0.01, 100}, Param{0.0, 1e-3, 0.01, 100}, Param{0.0, 1e-5, 0.01, 100}, Param{0.0, 1e-9, 0.01, 100}, Param{0.0, 1e-17, 0.01, 100}, Param{1.0, 1.0, 0.01, 100}, Param{1.0, 1e2, 0.01, 100}, Param{1.0, 1e-2, 0.01, 100}, Param{1e2, 1.0, 0.01, 100}, Param{-1e2, 1.0, 0.01, 100}, Param{1e2, 1e6, 0.01, 100}, Param{-1e2, 1e6, 0.01, 100}, Param{1e4, 1e4, 0.01, 100}, Param{1e8, 1e4, 0.01, 100}, Param{1e12, 1e4, 0.01, 100}, }; } std::string ParamName(const ::testing::TestParamInfo<Param>& info) { const auto& p = info.param; std::string name = absl::StrCat("mean_", absl::SixDigits(p.mean), "__stddev_", absl::SixDigits(p.stddev)); return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}}); } INSTANTIATE_TEST_SUITE_P(All, GaussianDistributionTests, ::testing::ValuesIn(GenParams()), ParamName); TEST(GaussianDistributionTest, StabilityTest) { absl::random_internal::sequence_urbg urbg( {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull}); std::vector<int> output(11); { absl::gaussian_distribution<double> dist; std::generate(std::begin(output), std::end(output), [&] { return static_cast<int>(10000000.0 * dist(urbg)); }); EXPECT_EQ(13, urbg.invocations()); EXPECT_THAT(output, testing::ElementsAre(1494, 25518841, 9991550, 1351856, -20373238, 3456682, 333530, -6804981, -15279580, -16459654, 1494)); } urbg.reset(); { absl::gaussian_distribution<float> dist; std::generate(std::begin(output), std::end(output), [&] { return static_cast<int>(1000000.0f * dist(urbg)); }); EXPECT_EQ(13, urbg.invocations()); EXPECT_THAT( output, testing::ElementsAre(149, 2551884, 999155, 135185, -2037323, 345668, 33353, -680498, -1527958, -1645965, 149)); } } TEST(GaussianDistributionTest, AlgorithmBounds) { absl::gaussian_distribution<double> dist; const uint64_t kValues[] = { 0x1000000000000100ull, 0x2000000000000100ull, 0x3000000000000100ull, 0x4000000000000100ull, 0x5000000000000100ull, 0x6000000000000100ull, 0x9000000000000100ull, 0xa000000000000100ull, 0xb000000000000100ull, 0xc000000000000100ull, 0xd000000000000100ull, 0xe000000000000100ull}; const uint64_t kExtraValues[] = { 0x7000000000000100ull, 0x7800000000000100ull, 0x7c00000000000100ull, 0x7e00000000000100ull, 0xf000000000000100ull, 0xf800000000000100ull, 0xfc00000000000100ull, 0xfe00000000000100ull}; auto make_box = [](uint64_t v, uint64_t box) { return (v & 0xffffffffffffff80ull) | box; }; for (uint64_t box = 0; box < 0x7f; box++) { for (const uint64_t v : kValues) { absl::random_internal::sequence_urbg urbg( {make_box(v, box), 0x0003eb76f6f7f755ull, 0x5FCEA50FDB2F953Bull}); auto a = dist(urbg); EXPECT_EQ(1, urbg.invocations()) << box << " " << std::hex << v; if (v & 0x8000000000000000ull) { EXPECT_LT(a, 0.0) << box << " " << std::hex << v; } else { EXPECT_GT(a, 0.0) << box << " " << std::hex << v; } } if (box > 10 && box < 100) { for (const uint64_t v : kExtraValues) { absl::random_internal::sequence_urbg urbg( {make_box(v, box), 0x0003eb76f6f7f755ull, 0x5FCEA50FDB2F953Bull}); auto a = dist(urbg); EXPECT_EQ(1, urbg.invocations()) << box << " " << std::hex << v; if (v & 0x8000000000000000ull) { EXPECT_LT(a, 0.0) << box << " " << std::hex << v; } else { EXPECT_GT(a, 0.0) << box << " " << std::hex << v; } } } } auto make_fallback = [](uint64_t v) { return (v & 0xffffffffffffff80ull); }; double tail[2]; { absl::random_internal::sequence_urbg urbg( {make_fallback(0x7800000000000000ull), 0x13CCA830EB61BD96ull, 0x00000076f6f7f755ull}); tail[0] = dist(urbg); EXPECT_EQ(3, urbg.invocations()); EXPECT_GT(tail[0], 0); } { absl::random_internal::sequence_urbg urbg( {make_fallback(0xf800000000000000ull), 0x13CCA830EB61BD96ull, 0x00000076f6f7f755ull}); tail[1] = dist(urbg); EXPECT_EQ(3, urbg.invocations()); EXPECT_LT(tail[1], 0); } EXPECT_EQ(tail[0], -tail[1]); EXPECT_EQ(418610, static_cast<int64_t>(tail[0] * 100000.0)); { absl::random_internal::sequence_urbg urbg( {make_box(0x7f00000000000000ull, 120), 0xe000000000000001ull, 0x13CCA830EB61BD96ull}); tail[0] = dist(urbg); EXPECT_EQ(2, urbg.invocations()); EXPECT_GT(tail[0], 0); } { absl::random_internal::sequence_urbg urbg( {make_box(0xff00000000000000ull, 120), 0xe000000000000001ull, 0x13CCA830EB61BD96ull}); tail[1] = dist(urbg); EXPECT_EQ(2, urbg.invocations()); EXPECT_LT(tail[1], 0); } EXPECT_EQ(tail[0], -tail[1]); EXPECT_EQ(61948, static_cast<int64_t>(tail[0] * 100000.0)); { absl::random_internal::sequence_urbg urbg( {make_box(0xff00000000000000ull, 120), 0x1000000000000001, make_box(0x1000000000000100ull, 50), 0x13CCA830EB61BD96ull}); dist(urbg); EXPECT_EQ(3, urbg.invocations()); } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/gaussian_distribution.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/gaussian_distribution_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
aad1395a-30ae-4ff6-8d6a-8503c99579ca
cpp
abseil/abseil-cpp
discrete_distribution
absl/random/discrete_distribution.cc
absl/random/discrete_distribution_test.cc
#include "absl/random/discrete_distribution.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { std::vector<std::pair<double, size_t>> InitDiscreteDistribution( std::vector<double>* probabilities) { assert(probabilities); assert(!probabilities->empty()); double sum = std::accumulate(std::begin(*probabilities), std::end(*probabilities), 0.0); if (std::fabs(sum - 1.0) > 1e-6) { for (double& item : *probabilities) { item = item / sum; } } const size_t n = probabilities->size(); std::vector<std::pair<double, size_t>> q; q.reserve(n); std::vector<size_t> over; std::vector<size_t> under; size_t idx = 0; for (const double item : *probabilities) { assert(item >= 0); const double v = item * n; q.emplace_back(v, 0); if (v < 1.0) { under.push_back(idx++); } else { over.push_back(idx++); } } while (!over.empty() && !under.empty()) { auto lo = under.back(); under.pop_back(); auto hi = over.back(); over.pop_back(); q[lo].second = hi; const double r = q[hi].first - (1.0 - q[lo].first); q[hi].first = r; if (r < 1.0) { under.push_back(hi); } else { over.push_back(hi); } } for (auto i : over) { q[i] = {1.0, i}; } for (auto i : under) { q[i] = {1.0, i}; } return q; } } ABSL_NAMESPACE_END }
#include "absl/random/discrete_distribution.h" #include <cmath> #include <cstddef> #include <cstdint> #include <iterator> #include <numeric> #include <random> #include <sstream> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/log.h" #include "absl/random/internal/chi_square.h" #include "absl/random/internal/distribution_test_util.h" #include "absl/random/internal/pcg_engine.h" #include "absl/random/internal/sequence_urbg.h" #include "absl/random/random.h" #include "absl/strings/str_cat.h" #include "absl/strings/strip.h" namespace { template <typename IntType> class DiscreteDistributionTypeTest : public ::testing::Test {}; using IntTypes = ::testing::Types<int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t, int64_t, uint64_t>; TYPED_TEST_SUITE(DiscreteDistributionTypeTest, IntTypes); TYPED_TEST(DiscreteDistributionTypeTest, ParamSerializeTest) { using param_type = typename absl::discrete_distribution<TypeParam>::param_type; absl::discrete_distribution<TypeParam> empty; EXPECT_THAT(empty.probabilities(), testing::ElementsAre(1.0)); absl::discrete_distribution<TypeParam> before({1.0, 2.0, 1.0}); double s = 0; for (const auto& x : before.probabilities()) { s += x; } EXPECT_EQ(s, 1.0); EXPECT_THAT(before.probabilities(), testing::ElementsAre(0.25, 0.5, 0.25)); { std::vector<double> data({1.0, 2.0, 1.0}); absl::discrete_distribution<TypeParam> via_param{ param_type(std::begin(data), std::end(data))}; EXPECT_EQ(via_param, before); } std::stringstream ss; ss << before; absl::discrete_distribution<TypeParam> after; EXPECT_NE(before, after); ss >> after; EXPECT_EQ(before, after); } TYPED_TEST(DiscreteDistributionTypeTest, Constructor) { auto fn = [](double x) { return x; }; { absl::discrete_distribution<int> unary(0, 1.0, 9.0, fn); EXPECT_THAT(unary.probabilities(), testing::ElementsAre(1.0)); } { absl::discrete_distribution<int> unary(2, 1.0, 9.0, fn); EXPECT_THAT(unary.probabilities(), testing::ElementsAre(0.3, 0.7)); } } TEST(DiscreteDistributionTest, InitDiscreteDistribution) { using testing::_; using testing::Pair; { std::vector<double> p({1.0, 2.0, 3.0}); std::vector<std::pair<double, size_t>> q = absl::random_internal::InitDiscreteDistribution(&p); EXPECT_THAT(p, testing::ElementsAre(1 / 6.0, 2 / 6.0, 3 / 6.0)); EXPECT_THAT(q, testing::ElementsAre(Pair(0.5, 2), Pair(1.0, _), Pair(1.0, _))); } { std::vector<double> p({1.0, 2.0, 3.0, 5.0, 2.0}); std::vector<std::pair<double, size_t>> q = absl::random_internal::InitDiscreteDistribution(&p); EXPECT_THAT(p, testing::ElementsAre(1 / 13.0, 2 / 13.0, 3 / 13.0, 5 / 13.0, 2 / 13.0)); constexpr double b0 = 1.0 / 13.0 / 0.2; constexpr double b1 = 2.0 / 13.0 / 0.2; constexpr double b3 = (5.0 / 13.0 / 0.2) - ((1 - b0) + (1 - b1) + (1 - b1)); EXPECT_THAT(q, testing::ElementsAre(Pair(b0, 3), Pair(b1, 3), Pair(1.0, _), Pair(b3, 2), Pair(b1, 3))); } } TEST(DiscreteDistributionTest, ChiSquaredTest50) { using absl::random_internal::kChiSquared; constexpr size_t kTrials = 10000; constexpr int kBuckets = 50; const int kThreshold = absl::random_internal::ChiSquareValue(kBuckets, 0.99999); std::vector<double> weights(kBuckets, 0); std::iota(std::begin(weights), std::end(weights), 1); absl::discrete_distribution<int> dist(std::begin(weights), std::end(weights)); absl::random_internal::pcg64_2018_engine rng(0x2B7E151628AED2A6); std::vector<int32_t> counts(kBuckets, 0); for (size_t i = 0; i < kTrials; i++) { auto x = dist(rng); counts[x]++; } double sum = 0; for (double x : weights) { sum += x; } for (double& x : weights) { x = kTrials * (x / sum); } double chi_square = absl::random_internal::ChiSquare(std::begin(counts), std::end(counts), std::begin(weights), std::end(weights)); if (chi_square > kThreshold) { double p_value = absl::random_internal::ChiSquarePValue(chi_square, kBuckets); std::string msg; for (size_t i = 0; i < counts.size(); i++) { absl::StrAppend(&msg, i, ": ", counts[i], " vs ", weights[i], "\n"); } absl::StrAppend(&msg, kChiSquared, " p-value ", p_value, "\n"); absl::StrAppend(&msg, "High ", kChiSquared, " value: ", chi_square, " > ", kThreshold); LOG(INFO) << msg; FAIL() << msg; } } TEST(DiscreteDistributionTest, StabilityTest) { absl::random_internal::sequence_urbg urbg( {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull, 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull}); std::vector<int> output(6); { absl::discrete_distribution<int32_t> dist({1.0, 2.0, 3.0, 5.0, 2.0}); EXPECT_EQ(0, dist.min()); EXPECT_EQ(4, dist.max()); for (auto& v : output) { v = dist(urbg); } EXPECT_EQ(12, urbg.invocations()); } EXPECT_THAT(output, testing::ElementsAre(3, 3, 1, 3, 3, 3)); { urbg.reset(); absl::discrete_distribution<int64_t> dist({1.0, 2.0, 3.0, 5.0, 2.0}); EXPECT_EQ(0, dist.min()); EXPECT_EQ(4, dist.max()); for (auto& v : output) { v = dist(urbg); } EXPECT_EQ(12, urbg.invocations()); } EXPECT_THAT(output, testing::ElementsAre(3, 3, 0, 3, 0, 4)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/discrete_distribution.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/discrete_distribution_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
bd9bc4b7-6f85-4f51-abe9-f426720e4b12
cpp
abseil/abseil-cpp
seed_sequences
absl/random/seed_sequences.cc
absl/random/seed_sequences_test.cc
#include "absl/random/seed_sequences.h" #include "absl/random/internal/pool_urbg.h" namespace absl { ABSL_NAMESPACE_BEGIN SeedSeq MakeSeedSeq() { SeedSeq::result_type seed_material[8]; random_internal::RandenPool<uint32_t>::Fill(absl::MakeSpan(seed_material)); return SeedSeq(std::begin(seed_material), std::end(seed_material)); } ABSL_NAMESPACE_END }
#include "absl/random/seed_sequences.h" #include <iterator> #include <random> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/random/internal/nonsecure_base.h" #include "absl/random/random.h" namespace { TEST(SeedSequences, Examples) { { absl::SeedSeq seed_seq({1, 2, 3}); absl::BitGen bitgen(seed_seq); EXPECT_NE(0, bitgen()); } { absl::BitGen engine; auto seed_seq = absl::CreateSeedSeqFrom(&engine); absl::BitGen bitgen(seed_seq); EXPECT_NE(engine(), bitgen()); } { auto seed_seq = absl::MakeSeedSeq(); std::mt19937 random(seed_seq); EXPECT_NE(0, random()); } } TEST(CreateSeedSeqFrom, CompatibleWithStdTypes) { using ExampleNonsecureURBG = absl::random_internal::NonsecureURBGBase<std::minstd_rand0>; ExampleNonsecureURBG rng; auto seq_from_rng = absl::CreateSeedSeqFrom(&rng); std::mt19937_64{seq_from_rng}; } TEST(CreateSeedSeqFrom, CompatibleWithBitGenerator) { absl::BitGen rng; auto seq_from_rng = absl::CreateSeedSeqFrom(&rng); std::mt19937_64{seq_from_rng}; } TEST(CreateSeedSeqFrom, CompatibleWithInsecureBitGen) { absl::InsecureBitGen rng; auto seq_from_rng = absl::CreateSeedSeqFrom(&rng); std::mt19937_64{seq_from_rng}; } TEST(CreateSeedSeqFrom, CompatibleWithRawURBG) { std::random_device urandom; auto seq_from_rng = absl::CreateSeedSeqFrom(&urandom); std::mt19937_64{seq_from_rng}; } template <typename URBG> void TestReproducibleVariateSequencesForNonsecureURBG() { const size_t kNumVariates = 1000; URBG rng; auto reusable_seed = absl::CreateSeedSeqFrom(&rng); typename URBG::result_type variates[kNumVariates]; { URBG child(reusable_seed); for (auto& variate : variates) { variate = child(); } } { URBG child(reusable_seed); for (auto& variate : variates) { ASSERT_EQ(variate, child()); } } } TEST(CreateSeedSeqFrom, ReproducesVariateSequencesForInsecureBitGen) { TestReproducibleVariateSequencesForNonsecureURBG<absl::InsecureBitGen>(); } TEST(CreateSeedSeqFrom, ReproducesVariateSequencesForBitGenerator) { TestReproducibleVariateSequencesForNonsecureURBG<absl::BitGen>(); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/seed_sequences.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/seed_sequences_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
132c165c-1757-47bc-8569-281f3996738a
cpp
abseil/abseil-cpp
nanobenchmark
absl/random/internal/nanobenchmark.cc
absl/random/internal/nanobenchmark_test.cc
#include "absl/random/internal/nanobenchmark.h" #include <sys/types.h> #include <algorithm> #include <atomic> #include <cstddef> #include <cstdint> #include <cstdlib> #include <cstring> #include <limits> #include <string> #include <utility> #include <vector> #include "absl/base/attributes.h" #include "absl/base/internal/raw_logging.h" #include "absl/random/internal/platform.h" #include "absl/random/internal/randen_engine.h" #if defined(_WIN32) || defined(_WIN64) #define ABSL_OS_WIN #include <windows.h> #elif defined(__ANDROID__) #define ABSL_OS_ANDROID #elif defined(__linux__) #define ABSL_OS_LINUX #include <sched.h> #include <sys/syscall.h> #endif #if defined(ABSL_ARCH_X86_64) && !defined(ABSL_OS_WIN) #include <cpuid.h> #endif #if defined(ABSL_ARCH_PPC) #include <sys/platform/ppc.h> #endif #if defined(ABSL_ARCH_ARM) || defined(ABSL_ARCH_AARCH64) #include <time.h> #endif #if ABSL_HAVE_ATTRIBUTE(noinline) || (defined(__GNUC__) && !defined(__clang__)) #define ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE __attribute__((noinline)) #elif defined(_MSC_VER) #define ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE __declspec(noinline) #else #define ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal_nanobenchmark { namespace { namespace platform { #if defined(ABSL_ARCH_X86_64) void Cpuid(const uint32_t level, const uint32_t count, uint32_t* ABSL_RANDOM_INTERNAL_RESTRICT abcd) { #if defined(ABSL_OS_WIN) int regs[4]; __cpuidex(regs, level, count); for (int i = 0; i < 4; ++i) { abcd[i] = regs[i]; } #else uint32_t a, b, c, d; __cpuid_count(level, count, a, b, c, d); abcd[0] = a; abcd[1] = b; abcd[2] = c; abcd[3] = d; #endif } std::string BrandString() { char brand_string[49]; uint32_t abcd[4]; Cpuid(0x80000000U, 0, abcd); if (abcd[0] < 0x80000004U) { return std::string(); } for (int i = 0; i < 3; ++i) { Cpuid(0x80000002U + i, 0, abcd); memcpy(brand_string + i * 16, &abcd, sizeof(abcd)); } brand_string[48] = 0; return brand_string; } double NominalClockRate() { const std::string& brand_string = BrandString(); const char* prefixes[3] = {"MHz", "GHz", "THz"}; const double multipliers[3] = {1E6, 1E9, 1E12}; for (size_t i = 0; i < 3; ++i) { const size_t pos_prefix = brand_string.find(prefixes[i]); if (pos_prefix != std::string::npos) { const size_t pos_space = brand_string.rfind(' ', pos_prefix - 1); if (pos_space != std::string::npos) { const std::string digits = brand_string.substr(pos_space + 1, pos_prefix - pos_space - 1); return std::stod(digits) * multipliers[i]; } } } return 0.0; } #endif } template <class T> inline void PreventElision(T&& output) { #ifndef ABSL_OS_WIN asm volatile("" : "+r"(output) : : "memory"); #else static std::atomic<T> dummy(T{}); dummy.store(output, std::memory_order_relaxed); #endif } namespace timer { inline uint64_t Start64() { uint64_t t; #if defined(ABSL_ARCH_PPC) asm volatile("mfspr %0, %1" : "=r"(t) : "i"(268)); #elif defined(ABSL_ARCH_X86_64) #if defined(ABSL_OS_WIN) _ReadWriteBarrier(); _mm_lfence(); _ReadWriteBarrier(); t = __rdtsc(); _ReadWriteBarrier(); _mm_lfence(); _ReadWriteBarrier(); #else asm volatile( "lfence\n\t" "rdtsc\n\t" "shl $32, %%rdx\n\t" "or %%rdx, %0\n\t" "lfence" : "=a"(t) : : "rdx", "memory", "cc"); #endif #else timespec ts; clock_gettime(CLOCK_REALTIME, &ts); t = ts.tv_sec * 1000000000LL + ts.tv_nsec; #endif return t; } inline uint64_t Stop64() { uint64_t t; #if defined(ABSL_ARCH_X86_64) #if defined(ABSL_OS_WIN) _ReadWriteBarrier(); unsigned aux; t = __rdtscp(&aux); _ReadWriteBarrier(); _mm_lfence(); _ReadWriteBarrier(); #else asm volatile( "rdtscp\n\t" "shl $32, %%rdx\n\t" "or %%rdx, %0\n\t" "lfence" : "=a"(t) : : "rcx", "rdx", "memory", "cc"); #endif #else t = Start64(); #endif return t; } inline uint32_t Start32() { uint32_t t; #if defined(ABSL_ARCH_X86_64) #if defined(ABSL_OS_WIN) _ReadWriteBarrier(); _mm_lfence(); _ReadWriteBarrier(); t = static_cast<uint32_t>(__rdtsc()); _ReadWriteBarrier(); _mm_lfence(); _ReadWriteBarrier(); #else asm volatile( "lfence\n\t" "rdtsc\n\t" "lfence" : "=a"(t) : : "rdx", "memory"); #endif #else t = static_cast<uint32_t>(Start64()); #endif return t; } inline uint32_t Stop32() { uint32_t t; #if defined(ABSL_ARCH_X86_64) #if defined(ABSL_OS_WIN) _ReadWriteBarrier(); unsigned aux; t = static_cast<uint32_t>(__rdtscp(&aux)); _ReadWriteBarrier(); _mm_lfence(); _ReadWriteBarrier(); #else asm volatile( "rdtscp\n\t" "lfence" : "=a"(t) : : "rcx", "rdx", "memory"); #endif #else t = static_cast<uint32_t>(Stop64()); #endif return t; } } namespace robust_statistics { template <class T> void CountingSort(T* values, size_t num_values) { using Unique = std::pair<T, int>; std::vector<Unique> unique; for (size_t i = 0; i < num_values; ++i) { const T value = values[i]; const auto pos = std::find_if(unique.begin(), unique.end(), [value](const Unique u) { return u.first == value; }); if (pos == unique.end()) { unique.push_back(std::make_pair(value, 1)); } else { ++pos->second; } } std::sort(unique.begin(), unique.end()); T* ABSL_RANDOM_INTERNAL_RESTRICT p = values; for (const auto& value_count : unique) { std::fill_n(p, value_count.second, value_count.first); p += value_count.second; } ABSL_RAW_CHECK(p == values + num_values, "Did not produce enough output"); } template <typename T> size_t MinRange(const T* const ABSL_RANDOM_INTERNAL_RESTRICT sorted, const size_t idx_begin, const size_t half_count) { T min_range = (std::numeric_limits<T>::max)(); size_t min_idx = 0; for (size_t idx = idx_begin; idx < idx_begin + half_count; ++idx) { ABSL_RAW_CHECK(sorted[idx] <= sorted[idx + half_count], "Not sorted"); const T range = sorted[idx + half_count] - sorted[idx]; if (range < min_range) { min_range = range; min_idx = idx; } } return min_idx; } template <typename T> T ModeOfSorted(const T* const ABSL_RANDOM_INTERNAL_RESTRICT sorted, const size_t num_values) { size_t idx_begin = 0; size_t half_count = num_values / 2; while (half_count > 1) { idx_begin = MinRange(sorted, idx_begin, half_count); half_count >>= 1; } const T x = sorted[idx_begin + 0]; if (half_count == 0) { return x; } ABSL_RAW_CHECK(half_count == 1, "Should stop at half_count=1"); const T average = (x + sorted[idx_begin + 1] + 1) / 2; return average; } template <typename T> T Mode(T* values, const size_t num_values) { CountingSort(values, num_values); return ModeOfSorted(values, num_values); } template <typename T, size_t N> T Mode(T (&values)[N]) { return Mode(&values[0], N); } template <typename T> T Median(T* values, const size_t num_values) { ABSL_RAW_CHECK(num_values != 0, "Empty input"); std::sort(values, values + num_values); const size_t half = num_values / 2; if (num_values % 2) { return values[half]; } return (values[half] + values[half - 1] + 1) / 2; } template <typename T> T MedianAbsoluteDeviation(const T* values, const size_t num_values, const T median) { ABSL_RAW_CHECK(num_values != 0, "Empty input"); std::vector<T> abs_deviations; abs_deviations.reserve(num_values); for (size_t i = 0; i < num_values; ++i) { const int64_t abs = std::abs(int64_t(values[i]) - int64_t(median)); abs_deviations.push_back(static_cast<T>(abs)); } return Median(abs_deviations.data(), num_values); } } using Ticks = uint32_t; Ticks TimerResolution() { Ticks repetitions[Params::kTimerSamples]; for (size_t rep = 0; rep < Params::kTimerSamples; ++rep) { Ticks samples[Params::kTimerSamples]; for (size_t i = 0; i < Params::kTimerSamples; ++i) { const Ticks t0 = timer::Start32(); const Ticks t1 = timer::Stop32(); samples[i] = t1 - t0; } repetitions[rep] = robust_statistics::Mode(samples); } return robust_statistics::Mode(repetitions); } static const Ticks timer_resolution = TimerResolution(); template <class Lambda> Ticks SampleUntilStable(const double max_rel_mad, double* rel_mad, const Params& p, const Lambda& lambda) { auto measure_duration = [&lambda]() -> Ticks { const Ticks t0 = timer::Start32(); lambda(); const Ticks t1 = timer::Stop32(); return t1 - t0; }; Ticks est = measure_duration(); static const double ticks_per_second = InvariantTicksPerSecond(); const size_t ticks_per_eval = ticks_per_second * p.seconds_per_eval; size_t samples_per_eval = ticks_per_eval / est; samples_per_eval = (std::max)(samples_per_eval, p.min_samples_per_eval); std::vector<Ticks> samples; samples.reserve(1 + samples_per_eval); samples.push_back(est); const Ticks max_abs_mad = (timer_resolution + 99) / 100; *rel_mad = 0.0; for (size_t eval = 0; eval < p.max_evals; ++eval, samples_per_eval *= 2) { samples.reserve(samples.size() + samples_per_eval); for (size_t i = 0; i < samples_per_eval; ++i) { const Ticks r = measure_duration(); samples.push_back(r); } if (samples.size() >= p.min_mode_samples) { est = robust_statistics::Mode(samples.data(), samples.size()); } else { est = robust_statistics::Median(samples.data(), samples.size()); } ABSL_RAW_CHECK(est != 0, "Estimator returned zero duration"); const Ticks abs_mad = robust_statistics::MedianAbsoluteDeviation( samples.data(), samples.size(), est); *rel_mad = static_cast<double>(static_cast<int>(abs_mad)) / est; if (*rel_mad <= max_rel_mad || abs_mad <= max_abs_mad) { if (p.verbose) { ABSL_RAW_LOG(INFO, "%6zu samples => %5u (abs_mad=%4u, rel_mad=%4.2f%%)\n", samples.size(), est, abs_mad, *rel_mad * 100.0); } return est; } } if (p.verbose) { ABSL_RAW_LOG(WARNING, "rel_mad=%4.2f%% still exceeds %4.2f%% after %6zu samples.\n", *rel_mad * 100.0, max_rel_mad * 100.0, samples.size()); } return est; } using InputVec = std::vector<FuncInput>; InputVec UniqueInputs(const FuncInput* inputs, const size_t num_inputs) { InputVec unique(inputs, inputs + num_inputs); std::sort(unique.begin(), unique.end()); unique.erase(std::unique(unique.begin(), unique.end()), unique.end()); return unique; } size_t NumSkip(const Func func, const void* arg, const InputVec& unique, const Params& p) { Ticks min_duration = ~0u; for (const FuncInput input : unique) { const uint64_t t0 = timer::Start64(); PreventElision(func(arg, input)); const uint64_t t1 = timer::Stop64(); const uint64_t elapsed = t1 - t0; if (elapsed >= (1ULL << 30)) { ABSL_RAW_LOG(WARNING, "Measurement failed: need 64-bit timer for input=%zu\n", static_cast<size_t>(input)); return 0; } double rel_mad; const Ticks total = SampleUntilStable( p.target_rel_mad, &rel_mad, p, [func, arg, input]() { PreventElision(func(arg, input)); }); min_duration = (std::min)(min_duration, total - timer_resolution); } const size_t max_skip = p.precision_divisor; const size_t num_skip = min_duration == 0 ? 0 : (max_skip + min_duration - 1) / min_duration; if (p.verbose) { ABSL_RAW_LOG(INFO, "res=%u max_skip=%zu min_dur=%u num_skip=%zu\n", timer_resolution, max_skip, min_duration, num_skip); } return num_skip; } InputVec ReplicateInputs(const FuncInput* inputs, const size_t num_inputs, const size_t num_unique, const size_t num_skip, const Params& p) { InputVec full; if (num_unique == 1) { full.assign(p.subset_ratio * num_skip, inputs[0]); return full; } full.reserve(p.subset_ratio * num_skip * num_inputs); for (size_t i = 0; i < p.subset_ratio * num_skip; ++i) { full.insert(full.end(), inputs, inputs + num_inputs); } absl::random_internal::randen_engine<uint32_t> rng; std::shuffle(full.begin(), full.end(), rng); return full; } void FillSubset(const InputVec& full, const FuncInput input_to_skip, const size_t num_skip, InputVec* subset) { const size_t count = std::count(full.begin(), full.end(), input_to_skip); std::vector<uint32_t> omit; omit.reserve(count); for (size_t i = 0; i < count; ++i) { omit.push_back(i); } absl::random_internal::randen_engine<uint32_t> rng; std::shuffle(omit.begin(), omit.end(), rng); omit.resize(num_skip); std::sort(omit.begin(), omit.end()); uint32_t occurrence = ~0u; size_t idx_omit = 0; size_t idx_subset = 0; for (const FuncInput next : full) { if (next == input_to_skip) { ++occurrence; if (idx_omit < num_skip) { if (occurrence == omit[idx_omit]) { ++idx_omit; continue; } } } if (idx_subset < subset->size()) { (*subset)[idx_subset++] = next; } } ABSL_RAW_CHECK(idx_subset == subset->size(), "idx_subset not at end"); ABSL_RAW_CHECK(idx_omit == omit.size(), "idx_omit not at end"); ABSL_RAW_CHECK(occurrence == count - 1, "occurrence not at end"); } Ticks TotalDuration(const Func func, const void* arg, const InputVec* inputs, const Params& p, double* max_rel_mad) { double rel_mad; const Ticks duration = SampleUntilStable(p.target_rel_mad, &rel_mad, p, [func, arg, inputs]() { for (const FuncInput input : *inputs) { PreventElision(func(arg, input)); } }); *max_rel_mad = (std::max)(*max_rel_mad, rel_mad); return duration; } ABSL_RANDOM_INTERNAL_ATTRIBUTE_NEVER_INLINE FuncOutput EmptyFunc(const void* arg, const FuncInput input) { return input; } Ticks Overhead(const void* arg, const InputVec* inputs, const Params& p) { double rel_mad; return SampleUntilStable(0.0, &rel_mad, p, [arg, inputs]() { for (const FuncInput input : *inputs) { PreventElision(EmptyFunc(arg, input)); } }); } } void PinThreadToCPU(int cpu) { #if defined(ABSL_OS_WIN) if (cpu < 0) { cpu = static_cast<int>(GetCurrentProcessorNumber()); ABSL_RAW_CHECK(cpu >= 0, "PinThreadToCPU detect failed"); if (cpu >= 64) { ABSL_RAW_LOG(ERROR, "Invalid CPU number: %d", cpu); return; } } else if (cpu >= 64) { ABSL_RAW_LOG(FATAL, "Invalid CPU number: %d", cpu); } const DWORD_PTR prev = SetThreadAffinityMask(GetCurrentThread(), 1ULL << cpu); ABSL_RAW_CHECK(prev != 0, "SetAffinity failed"); #elif defined(ABSL_OS_LINUX) && !defined(ABSL_OS_ANDROID) if (cpu < 0) { cpu = sched_getcpu(); ABSL_RAW_CHECK(cpu >= 0, "PinThreadToCPU detect failed"); } const pid_t pid = 0; cpu_set_t set; CPU_ZERO(&set); CPU_SET(cpu, &set); const int err = sched_setaffinity(pid, sizeof(set), &set); ABSL_RAW_CHECK(err == 0, "SetAffinity failed"); #endif } double InvariantTicksPerSecond() { #if defined(ABSL_ARCH_PPC) return __ppc_get_timebase_freq(); #elif defined(ABSL_ARCH_X86_64) return platform::NominalClockRate(); #else return 1E9; #endif } size_t MeasureImpl(const Func func, const void* arg, const size_t num_skip, const InputVec& unique, const InputVec& full, const Params& p, Result* results) { const float mul = 1.0f / static_cast<int>(num_skip); InputVec subset(full.size() - num_skip); const Ticks overhead = Overhead(arg, &full, p); const Ticks overhead_skip = Overhead(arg, &subset, p); if (overhead < overhead_skip) { ABSL_RAW_LOG(WARNING, "Measurement failed: overhead %u < %u\n", overhead, overhead_skip); return 0; } if (p.verbose) { ABSL_RAW_LOG(INFO, "#inputs=%5zu,%5zu overhead=%5u,%5u\n", full.size(), subset.size(), overhead, overhead_skip); } double max_rel_mad = 0.0; const Ticks total = TotalDuration(func, arg, &full, p, &max_rel_mad); for (size_t i = 0; i < unique.size(); ++i) { FillSubset(full, unique[i], num_skip, &subset); const Ticks total_skip = TotalDuration(func, arg, &subset, p, &max_rel_mad); if (total < total_skip) { ABSL_RAW_LOG(WARNING, "Measurement failed: total %u < %u\n", total, total_skip); return 0; } const Ticks duration = (total - overhead) - (total_skip - overhead_skip); results[i].input = unique[i]; results[i].ticks = duration * mul; results[i].variability = max_rel_mad; } return unique.size(); } size_t Measure(const Func func, const void* arg, const FuncInput* inputs, const size_t num_inputs, Result* results, const Params& p) { ABSL_RAW_CHECK(num_inputs != 0, "No inputs"); const InputVec unique = UniqueInputs(inputs, num_inputs); const size_t num_skip = NumSkip(func, arg, unique, p); if (num_skip == 0) return 0; const InputVec full = ReplicateInputs(inputs, num_inputs, unique.size(), num_skip, p); for (size_t i = 0; i < p.max_measure_retries; i++) { auto result = MeasureImpl(func, arg, num_skip, unique, full, p, results); if (result != 0) { return result; } } return 0; } } ABSL_NAMESPACE_END }
#include "absl/random/internal/nanobenchmark.h" #include "absl/log/check.h" #include "absl/log/log.h" #include "absl/strings/numbers.h" #include "absl/strings/str_format.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal_nanobenchmark { namespace { uint64_t Div(const void*, FuncInput in) { const int64_t d1 = 0xFFFFFFFFFFll / int64_t(in); return d1; } template <size_t N> void MeasureDiv(const FuncInput (&inputs)[N]) { Result results[N]; Params params; params.max_evals = 6; const size_t num_results = Measure(&Div, nullptr, inputs, N, results, params); if (num_results == 0) { LOG(WARNING) << "WARNING: Measurement failed, should not happen when using " "PinThreadToCPU unless the region to measure takes > 1 second."; return; } for (size_t i = 0; i < num_results; ++i) { LOG(INFO) << absl::StreamFormat("%5u: %6.2f ticks; MAD=%4.2f%%\n", results[i].input, results[i].ticks, results[i].variability * 100.0); CHECK_NE(results[i].ticks, 0.0f) << "Zero duration"; } } void RunAll(const int argc, char* argv[]) { int cpu = -1; if (argc == 2) { if (!absl::SimpleAtoi(argv[1], &cpu)) { LOG(FATAL) << "The optional argument must be a CPU number >= 0."; } } PinThreadToCPU(cpu); const FuncInput unpredictable = argc != 999; static const FuncInput inputs[] = {unpredictable * 10, unpredictable * 100}; MeasureDiv(inputs); } } } ABSL_NAMESPACE_END } int main(int argc, char* argv[]) { absl::random_internal_nanobenchmark::RunAll(argc, argv); return 0; }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/nanobenchmark.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/nanobenchmark_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
d5ea14ca-6249-4bf8-aada-5d9dd4f90b4f
cpp
abseil/abseil-cpp
seed_material
absl/random/internal/seed_material.cc
absl/random/internal/seed_material_test.cc
#include "absl/random/internal/seed_material.h" #include <fcntl.h> #ifndef _WIN32 #include <unistd.h> #else #include <io.h> #endif #include <algorithm> #include <cerrno> #include <cstdint> #include <cstdlib> #include <cstring> #include "absl/base/dynamic_annotations.h" #include "absl/base/internal/raw_logging.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #if defined(__native_client__) #include <nacl/nacl_random.h> #define ABSL_RANDOM_USE_NACL_SECURE_RANDOM 1 #elif defined(_WIN32) #include <windows.h> #define ABSL_RANDOM_USE_BCRYPT 1 #pragma comment(lib, "bcrypt.lib") #elif defined(__Fuchsia__) #include <zircon/syscalls.h> #endif #if defined(__GLIBC__) && \ (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 25)) #define ABSL_RANDOM_USE_GET_ENTROPY 1 #endif #if defined(__EMSCRIPTEN__) #include <sys/random.h> #define ABSL_RANDOM_USE_GET_ENTROPY 1 #endif #if defined(ABSL_RANDOM_USE_BCRYPT) #include <bcrypt.h> #ifndef BCRYPT_SUCCESS #define BCRYPT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0) #endif #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { namespace { #if defined(ABSL_RANDOM_USE_BCRYPT) bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) { BCRYPT_ALG_HANDLE hProvider; NTSTATUS ret; ret = BCryptOpenAlgorithmProvider(&hProvider, BCRYPT_RNG_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0); if (!(BCRYPT_SUCCESS(ret))) { ABSL_RAW_LOG(ERROR, "Failed to open crypto provider."); return false; } ret = BCryptGenRandom( hProvider, reinterpret_cast<UCHAR*>(values.data()), static_cast<ULONG>(sizeof(uint32_t) * values.size()), 0); BCryptCloseAlgorithmProvider(hProvider, 0); return BCRYPT_SUCCESS(ret); } #elif defined(ABSL_RANDOM_USE_NACL_SECURE_RANDOM) bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) { auto buffer = reinterpret_cast<uint8_t*>(values.data()); size_t buffer_size = sizeof(uint32_t) * values.size(); uint8_t* output_ptr = buffer; while (buffer_size > 0) { size_t nread = 0; const int error = nacl_secure_random(output_ptr, buffer_size, &nread); if (error != 0 || nread > buffer_size) { ABSL_RAW_LOG(ERROR, "Failed to read secure_random seed data: %d", error); return false; } output_ptr += nread; buffer_size -= nread; } return true; } #elif defined(__Fuchsia__) bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) { auto buffer = reinterpret_cast<uint8_t*>(values.data()); size_t buffer_size = sizeof(uint32_t) * values.size(); zx_cprng_draw(buffer, buffer_size); return true; } #else #if defined(ABSL_RANDOM_USE_GET_ENTROPY) bool ReadSeedMaterialFromGetEntropy(absl::Span<uint32_t> values) { auto buffer = reinterpret_cast<uint8_t*>(values.data()); size_t buffer_size = sizeof(uint32_t) * values.size(); while (buffer_size > 0) { size_t to_read = std::min<size_t>(buffer_size, 256); int result = getentropy(buffer, to_read); if (result < 0) { return false; } ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(buffer, to_read); buffer += to_read; buffer_size -= to_read; } return true; } #endif bool ReadSeedMaterialFromDevURandom(absl::Span<uint32_t> values) { const char kEntropyFile[] = "/dev/urandom"; auto buffer = reinterpret_cast<uint8_t*>(values.data()); size_t buffer_size = sizeof(uint32_t) * values.size(); int dev_urandom = open(kEntropyFile, O_RDONLY); bool success = (-1 != dev_urandom); if (!success) { return false; } while (success && buffer_size > 0) { ssize_t bytes_read = read(dev_urandom, buffer, buffer_size); int read_error = errno; success = (bytes_read > 0); if (success) { buffer += bytes_read; buffer_size -= static_cast<size_t>(bytes_read); } else if (bytes_read == -1 && read_error == EINTR) { success = true; } } close(dev_urandom); return success; } bool ReadSeedMaterialFromOSEntropyImpl(absl::Span<uint32_t> values) { #if defined(ABSL_RANDOM_USE_GET_ENTROPY) if (ReadSeedMaterialFromGetEntropy(values)) { return true; } #endif return ReadSeedMaterialFromDevURandom(values); } #endif } bool ReadSeedMaterialFromOSEntropy(absl::Span<uint32_t> values) { assert(values.data() != nullptr); if (values.data() == nullptr) { return false; } if (values.empty()) { return true; } return ReadSeedMaterialFromOSEntropyImpl(values); } void MixIntoSeedMaterial(absl::Span<const uint32_t> sequence, absl::Span<uint32_t> seed_material) { constexpr uint32_t kInitVal = 0x43b0d7e5; constexpr uint32_t kHashMul = 0x931e8875; constexpr uint32_t kMixMulL = 0xca01f9dd; constexpr uint32_t kMixMulR = 0x4973f715; constexpr uint32_t kShiftSize = sizeof(uint32_t) * 8 / 2; uint32_t hash_const = kInitVal; auto hash = [&](uint32_t value) { value ^= hash_const; hash_const *= kHashMul; value *= hash_const; value ^= value >> kShiftSize; return value; }; auto mix = [&](uint32_t x, uint32_t y) { uint32_t result = kMixMulL * x - kMixMulR * y; result ^= result >> kShiftSize; return result; }; for (const auto& seq_val : sequence) { for (auto& elem : seed_material) { elem = mix(elem, hash(seq_val)); } } } absl::optional<uint32_t> GetSaltMaterial() { static const auto salt_material = []() -> absl::optional<uint32_t> { uint32_t salt_value = 0; if (random_internal::ReadSeedMaterialFromOSEntropy( MakeSpan(&salt_value, 1))) { return salt_value; } return absl::nullopt; }(); return salt_material; } } ABSL_NAMESPACE_END }
#include "absl/random/internal/seed_material.h" #include <bitset> #include <cstdlib> #include <cstring> #include <random> #include "gmock/gmock.h" #include "gtest/gtest.h" #ifdef __ANDROID__ #define ABSL_EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ EXPECT_DEATH_IF_SUPPORTED(statement, ".*") #else #define ABSL_EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ EXPECT_DEATH_IF_SUPPORTED(statement, regex) #endif namespace { using testing::Each; using testing::ElementsAre; using testing::Eq; using testing::Ne; using testing::Pointwise; TEST(SeedBitsToBlocks, VerifyCases) { EXPECT_EQ(0, absl::random_internal::SeedBitsToBlocks(0)); EXPECT_EQ(1, absl::random_internal::SeedBitsToBlocks(1)); EXPECT_EQ(1, absl::random_internal::SeedBitsToBlocks(31)); EXPECT_EQ(1, absl::random_internal::SeedBitsToBlocks(32)); EXPECT_EQ(2, absl::random_internal::SeedBitsToBlocks(33)); EXPECT_EQ(4, absl::random_internal::SeedBitsToBlocks(127)); EXPECT_EQ(4, absl::random_internal::SeedBitsToBlocks(128)); EXPECT_EQ(5, absl::random_internal::SeedBitsToBlocks(129)); } TEST(ReadSeedMaterialFromOSEntropy, SuccessiveReadsAreDistinct) { constexpr size_t kSeedMaterialSize = 64; uint32_t seed_material_1[kSeedMaterialSize] = {}; uint32_t seed_material_2[kSeedMaterialSize] = {}; EXPECT_TRUE(absl::random_internal::ReadSeedMaterialFromOSEntropy( absl::Span<uint32_t>(seed_material_1, kSeedMaterialSize))); EXPECT_TRUE(absl::random_internal::ReadSeedMaterialFromOSEntropy( absl::Span<uint32_t>(seed_material_2, kSeedMaterialSize))); EXPECT_THAT(seed_material_1, Pointwise(Ne(), seed_material_2)); } TEST(ReadSeedMaterialFromOSEntropy, ReadZeroBytesIsNoOp) { uint32_t seed_material[32] = {}; std::memset(seed_material, 0xAA, sizeof(seed_material)); EXPECT_TRUE(absl::random_internal::ReadSeedMaterialFromOSEntropy( absl::Span<uint32_t>(seed_material, 0))); EXPECT_THAT(seed_material, Each(Eq(0xAAAAAAAA))); } TEST(ReadSeedMaterialFromOSEntropy, NullPtrVectorArgument) { #ifdef NDEBUG EXPECT_FALSE(absl::random_internal::ReadSeedMaterialFromOSEntropy( absl::Span<uint32_t>(nullptr, 32))); #else bool result; ABSL_EXPECT_DEATH_IF_SUPPORTED( result = absl::random_internal::ReadSeedMaterialFromOSEntropy( absl::Span<uint32_t>(nullptr, 32)), "!= nullptr"); (void)result; #endif } TEST(ReadSeedMaterialFromURBG, SeedMaterialEqualsVariateSequence) { std::mt19937 urbg_1; std::mt19937 urbg_2; constexpr size_t kSeedMaterialSize = 1024; uint32_t seed_material[kSeedMaterialSize] = {}; EXPECT_TRUE(absl::random_internal::ReadSeedMaterialFromURBG( &urbg_1, absl::Span<uint32_t>(seed_material, kSeedMaterialSize))); for (uint32_t seed : seed_material) { EXPECT_EQ(seed, urbg_2()); } } TEST(ReadSeedMaterialFromURBG, ReadZeroBytesIsNoOp) { std::mt19937_64 urbg; uint32_t seed_material[32]; std::memset(seed_material, 0xAA, sizeof(seed_material)); EXPECT_TRUE(absl::random_internal::ReadSeedMaterialFromURBG( &urbg, absl::Span<uint32_t>(seed_material, 0))); EXPECT_THAT(seed_material, Each(Eq(0xAAAAAAAA))); } TEST(ReadSeedMaterialFromURBG, NullUrbgArgument) { constexpr size_t kSeedMaterialSize = 32; uint32_t seed_material[kSeedMaterialSize]; #ifdef NDEBUG EXPECT_FALSE(absl::random_internal::ReadSeedMaterialFromURBG<std::mt19937_64>( nullptr, absl::Span<uint32_t>(seed_material, kSeedMaterialSize))); #else bool result; ABSL_EXPECT_DEATH_IF_SUPPORTED( result = absl::random_internal::ReadSeedMaterialFromURBG<std::mt19937_64>( nullptr, absl::Span<uint32_t>(seed_material, kSeedMaterialSize)), "!= nullptr"); (void)result; #endif } TEST(ReadSeedMaterialFromURBG, NullPtrVectorArgument) { std::mt19937_64 urbg; #ifdef NDEBUG EXPECT_FALSE(absl::random_internal::ReadSeedMaterialFromURBG( &urbg, absl::Span<uint32_t>(nullptr, 32))); #else bool result; ABSL_EXPECT_DEATH_IF_SUPPORTED( result = absl::random_internal::ReadSeedMaterialFromURBG( &urbg, absl::Span<uint32_t>(nullptr, 32)), "!= nullptr"); (void)result; #endif } TEST(MixSequenceIntoSeedMaterial, AvalancheEffectTestOneBitLong) { std::vector<uint32_t> seed_material = {1, 2, 3, 4, 5, 6, 7, 8}; for (uint32_t v = 1; v != 0; v <<= 1) { std::vector<uint32_t> seed_material_copy = seed_material; absl::random_internal::MixIntoSeedMaterial( absl::Span<uint32_t>(&v, 1), absl::Span<uint32_t>(seed_material_copy.data(), seed_material_copy.size())); uint32_t changed_bits = 0; for (size_t i = 0; i < seed_material.size(); i++) { std::bitset<sizeof(uint32_t) * 8> bitset(seed_material[i] ^ seed_material_copy[i]); changed_bits += bitset.count(); } EXPECT_LE(changed_bits, 0.7 * sizeof(uint32_t) * 8 * seed_material.size()); EXPECT_GE(changed_bits, 0.3 * sizeof(uint32_t) * 8 * seed_material.size()); } } TEST(MixSequenceIntoSeedMaterial, AvalancheEffectTestOneBitShort) { std::vector<uint32_t> seed_material = {1}; for (uint32_t v = 1; v != 0; v <<= 1) { std::vector<uint32_t> seed_material_copy = seed_material; absl::random_internal::MixIntoSeedMaterial( absl::Span<uint32_t>(&v, 1), absl::Span<uint32_t>(seed_material_copy.data(), seed_material_copy.size())); uint32_t changed_bits = 0; for (size_t i = 0; i < seed_material.size(); i++) { std::bitset<sizeof(uint32_t) * 8> bitset(seed_material[i] ^ seed_material_copy[i]); changed_bits += bitset.count(); } EXPECT_LE(changed_bits, 0.7 * sizeof(uint32_t) * 8 * seed_material.size()); EXPECT_GE(changed_bits, 0.3 * sizeof(uint32_t) * 8 * seed_material.size()); } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/seed_material.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/seed_material_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
cc95e60a-c618-432e-bfb2-9f6a83d7af84
cpp
abseil/abseil-cpp
distribution_test_util
absl/random/internal/distribution_test_util.cc
absl/random/internal/distribution_test_util_test.cc
#include "absl/random/internal/distribution_test_util.h" #include <cassert> #include <cmath> #include <string> #include <vector> #include "absl/base/internal/raw_logging.h" #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { namespace { #if defined(__EMSCRIPTEN__) inline double fma(double x, double y, double z) { return (x * y) + z; } #endif } DistributionMoments ComputeDistributionMoments( absl::Span<const double> data_points) { DistributionMoments result; for (double x : data_points) { result.n++; result.mean += x; } result.mean /= static_cast<double>(result.n); for (double x : data_points) { double v = x - result.mean; result.variance += v * v; result.skewness += v * v * v; result.kurtosis += v * v * v * v; } result.variance /= static_cast<double>(result.n - 1); result.skewness /= static_cast<double>(result.n); result.skewness /= std::pow(result.variance, 1.5); result.kurtosis /= static_cast<double>(result.n); result.kurtosis /= std::pow(result.variance, 2.0); return result; } std::ostream& operator<<(std::ostream& os, const DistributionMoments& moments) { return os << absl::StrFormat("mean=%f, stddev=%f, skewness=%f, kurtosis=%f", moments.mean, std::sqrt(moments.variance), moments.skewness, moments.kurtosis); } double InverseNormalSurvival(double x) { static constexpr double kSqrt2 = 1.4142135623730950488; return -kSqrt2 * absl::random_internal::erfinv(2 * x - 1.0); } bool Near(absl::string_view msg, double actual, double expected, double bound) { assert(bound > 0.0); double delta = fabs(expected - actual); if (delta < bound) { return true; } std::string formatted = absl::StrCat( msg, " actual=", actual, " expected=", expected, " err=", delta / bound); ABSL_RAW_LOG(INFO, "%s", formatted.c_str()); return false; } double beta(double p, double q) { double lbeta = std::lgamma(p) + std::lgamma(q) - std::lgamma(p + q); return std::exp(lbeta); } double erfinv(double x) { #if !defined(__EMSCRIPTEN__) using std::fma; #endif double w = 0.0; double p = 0.0; w = -std::log((1.0 - x) * (1.0 + x)); if (w < 6.250000) { w = w - 3.125000; p = -3.6444120640178196996e-21; p = fma(p, w, -1.685059138182016589e-19); p = fma(p, w, 1.2858480715256400167e-18); p = fma(p, w, 1.115787767802518096e-17); p = fma(p, w, -1.333171662854620906e-16); p = fma(p, w, 2.0972767875968561637e-17); p = fma(p, w, 6.6376381343583238325e-15); p = fma(p, w, -4.0545662729752068639e-14); p = fma(p, w, -8.1519341976054721522e-14); p = fma(p, w, 2.6335093153082322977e-12); p = fma(p, w, -1.2975133253453532498e-11); p = fma(p, w, -5.4154120542946279317e-11); p = fma(p, w, 1.051212273321532285e-09); p = fma(p, w, -4.1126339803469836976e-09); p = fma(p, w, -2.9070369957882005086e-08); p = fma(p, w, 4.2347877827932403518e-07); p = fma(p, w, -1.3654692000834678645e-06); p = fma(p, w, -1.3882523362786468719e-05); p = fma(p, w, 0.0001867342080340571352); p = fma(p, w, -0.00074070253416626697512); p = fma(p, w, -0.0060336708714301490533); p = fma(p, w, 0.24015818242558961693); p = fma(p, w, 1.6536545626831027356); } else if (w < 16.000000) { w = std::sqrt(w) - 3.250000; p = 2.2137376921775787049e-09; p = fma(p, w, 9.0756561938885390979e-08); p = fma(p, w, -2.7517406297064545428e-07); p = fma(p, w, 1.8239629214389227755e-08); p = fma(p, w, 1.5027403968909827627e-06); p = fma(p, w, -4.013867526981545969e-06); p = fma(p, w, 2.9234449089955446044e-06); p = fma(p, w, 1.2475304481671778723e-05); p = fma(p, w, -4.7318229009055733981e-05); p = fma(p, w, 6.8284851459573175448e-05); p = fma(p, w, 2.4031110387097893999e-05); p = fma(p, w, -0.0003550375203628474796); p = fma(p, w, 0.00095328937973738049703); p = fma(p, w, -0.0016882755560235047313); p = fma(p, w, 0.0024914420961078508066); p = fma(p, w, -0.0037512085075692412107); p = fma(p, w, 0.005370914553590063617); p = fma(p, w, 1.0052589676941592334); p = fma(p, w, 3.0838856104922207635); } else { w = std::sqrt(w) - 5.000000; p = -2.7109920616438573243e-11; p = fma(p, w, -2.5556418169965252055e-10); p = fma(p, w, 1.5076572693500548083e-09); p = fma(p, w, -3.7894654401267369937e-09); p = fma(p, w, 7.6157012080783393804e-09); p = fma(p, w, -1.4960026627149240478e-08); p = fma(p, w, 2.9147953450901080826e-08); p = fma(p, w, -6.7711997758452339498e-08); p = fma(p, w, 2.2900482228026654717e-07); p = fma(p, w, -9.9298272942317002539e-07); p = fma(p, w, 4.5260625972231537039e-06); p = fma(p, w, -1.9681778105531670567e-05); p = fma(p, w, 7.5995277030017761139e-05); p = fma(p, w, -0.00021503011930044477347); p = fma(p, w, -0.00013871931833623122026); p = fma(p, w, 1.0103004648645343977); p = fma(p, w, 4.8499064014085844221); } return p * x; } namespace { double BetaIncompleteImpl(const double x, const double p, const double q, const double beta) { if (p < (p + q) * x) { return 1. - BetaIncompleteImpl(1.0 - x, q, p, beta); } double psq = p + q; const double kErr = 1e-14; const double xc = 1. - x; const double pre = std::exp(p * std::log(x) + (q - 1.) * std::log(xc) - beta) / p; double term = 1.; double ai = 1.; double result = 1.; int ns = static_cast<int>(q + xc * psq); double rx = (ns == 0) ? x : x / xc; double temp = q - ai; for (;;) { term = term * temp * rx / (p + ai); result = result + term; temp = std::fabs(term); if (temp < kErr && temp < kErr * result) { return result * pre; } ai = ai + 1.; --ns; if (ns >= 0) { temp = q - ai; if (ns == 0) { rx = x; } } else { temp = psq; psq = psq + 1.; } } } double BetaIncompleteInvImpl(const double p, const double q, const double beta, const double alpha) { if (alpha < 0.5) { return 1. - BetaIncompleteInvImpl(q, p, beta, 1. - alpha); } const double kErr = 1e-14; double value = kErr; { double r = std::sqrt(-std::log(alpha * alpha)); double y = r - fma(r, 0.27061, 2.30753) / fma(r, fma(r, 0.04481, 0.99229), 1.0); if (p > 1. && q > 1.) { r = (y * y - 3.) / 6.; double s = 1. / (p + p - 1.); double t = 1. / (q + q - 1.); double h = 2. / s + t; double w = y * std::sqrt(h + r) / h - (t - s) * (r + 5. / 6. - t / (3. * h)); value = p / (p + q * std::exp(w + w)); } else { r = q + q; double t = 1.0 / (9. * q); double u = 1.0 - t + y * std::sqrt(t); t = r * (u * u * u); if (t <= 0) { value = 1.0 - std::exp((std::log((1.0 - alpha) * q) + beta) / q); } else { t = (4.0 * p + r - 2.0) / t; if (t <= 1) { value = std::exp((std::log(alpha * p) + beta) / p); } else { value = 1.0 - 2.0 / (t + 1.0); } } } } { value = std::max(value, kErr); value = std::min(value, 1.0 - kErr); const double r = 1.0 - p; const double t = 1.0 - q; double y; double yprev = 0; double sq = 1; double prev = 1; for (;;) { if (value < 0 || value > 1.0) { return std::numeric_limits<double>::infinity(); } else if (value == 0 || value == 1) { y = value; } else { y = BetaIncompleteImpl(value, p, q, beta); if (!std::isfinite(y)) { return y; } } y = (y - alpha) * std::exp(beta + r * std::log(value) + t * std::log(1.0 - value)); if (y * yprev <= 0) { prev = std::max(sq, std::numeric_limits<double>::min()); } double g = 1.0; for (;;) { const double adj = g * y; const double adj_sq = adj * adj; if (adj_sq >= prev) { g = g / 3.0; continue; } const double tx = value - adj; if (tx < 0 || tx > 1) { g = g / 3.0; continue; } if (prev < kErr) { return value; } if (y * y < kErr) { return value; } if (tx == value) { return value; } if (tx == 0 || tx == 1) { g = g / 3.0; continue; } value = tx; yprev = y; break; } } } } } double BetaIncomplete(const double x, const double p, const double q) { if (p < 0 || q < 0 || x < 0 || x > 1.0) { return std::numeric_limits<double>::infinity(); } if (x == 0 || x == 1) { return x; } double beta = std::lgamma(p) + std::lgamma(q) - std::lgamma(p + q); return BetaIncompleteImpl(x, p, q, beta); } double BetaIncompleteInv(const double p, const double q, const double alpha) { if (p < 0 || q < 0 || alpha < 0 || alpha > 1.0) { return std::numeric_limits<double>::infinity(); } if (alpha == 0 || alpha == 1) { return alpha; } double beta = std::lgamma(p) + std::lgamma(q) - std::lgamma(p + q); return BetaIncompleteInvImpl(p, q, beta, alpha); } double RequiredSuccessProbability(const double p_fail, const int num_trials) { double p = std::exp(std::log(1.0 - p_fail) / static_cast<double>(num_trials)); ABSL_ASSERT(p > 0); return p; } double ZScore(double expected_mean, const DistributionMoments& moments) { return (moments.mean - expected_mean) / (std::sqrt(moments.variance) / std::sqrt(static_cast<double>(moments.n))); } double MaxErrorTolerance(double acceptance_probability) { double one_sided_pvalue = 0.5 * (1.0 - acceptance_probability); const double max_err = InverseNormalSurvival(one_sided_pvalue); ABSL_ASSERT(max_err > 0); return max_err; } } ABSL_NAMESPACE_END }
#include "absl/random/internal/distribution_test_util.h" #include "gtest/gtest.h" namespace { TEST(TestUtil, InverseErf) { const struct { const double z; const double value; } kErfInvTable[] = { {0.0000001, 8.86227e-8}, {0.00001, 8.86227e-6}, {0.5, 0.4769362762044}, {0.6, 0.5951160814499}, {0.99999, 3.1234132743}, {0.9999999, 3.7665625816}, {0.999999944, 3.8403850690566985}, {0.999999999, 4.3200053849134452}, }; for (const auto& data : kErfInvTable) { auto value = absl::random_internal::erfinv(data.z); EXPECT_NEAR(value, data.value, 1e-8) << " InverseErf[" << data.z << "] (expected=" << data.value << ") -> " << value; } } const struct { const double p; const double q; const double x; const double alpha; } kBetaTable[] = { {0.5, 0.5, 0.01, 0.06376856085851985}, {0.5, 0.5, 0.1, 0.2048327646991335}, {0.5, 0.5, 1, 1}, {1, 0.5, 0, 0}, {1, 0.5, 0.01, 0.005012562893380045}, {1, 0.5, 0.1, 0.0513167019494862}, {1, 0.5, 0.5, 0.2928932188134525}, {1, 1, 0.5, 0.5}, {2, 2, 0.1, 0.028}, {2, 2, 0.2, 0.104}, {2, 2, 0.3, 0.216}, {2, 2, 0.4, 0.352}, {2, 2, 0.5, 0.5}, {2, 2, 0.6, 0.648}, {2, 2, 0.7, 0.784}, {2, 2, 0.8, 0.896}, {2, 2, 0.9, 0.972}, {5.5, 5, 0.5, 0.4361908850559777}, {10, 0.5, 0.9, 0.1516409096346979}, {10, 5, 0.5, 0.08978271484375}, {10, 5, 1, 1}, {10, 10, 0.5, 0.5}, {20, 5, 0.8, 0.4598773297575791}, {20, 10, 0.6, 0.2146816102371739}, {20, 10, 0.8, 0.9507364826957875}, {20, 20, 0.5, 0.5}, {20, 20, 0.6, 0.8979413687105918}, {30, 10, 0.7, 0.2241297491808366}, {30, 10, 0.8, 0.7586405487192086}, {40, 20, 0.7, 0.7001783247477069}, {1, 0.5, 0.1, 0.0513167019494862}, {1, 0.5, 0.2, 0.1055728090000841}, {1, 0.5, 0.3, 0.1633399734659245}, {1, 0.5, 0.4, 0.2254033307585166}, {1, 2, 0.2, 0.36}, {1, 3, 0.2, 0.488}, {1, 4, 0.2, 0.5904}, {1, 5, 0.2, 0.67232}, {2, 2, 0.3, 0.216}, {3, 2, 0.3, 0.0837}, {4, 2, 0.3, 0.03078}, {5, 2, 0.3, 0.010935}, {1e-5, 1e-5, 1e-5, 0.4999424388184638311}, {1e-5, 1e-5, (1.0 - 1e-8), 0.5000920948389232964}, {1e-5, 1e5, 1e-6, 0.9999817708130066936}, {1e-5, 1e5, (1.0 - 1e-7), 1.0}, {1e5, 1e-5, 1e-6, 0}, {1e5, 1e-5, (1.0 - 1e-6), 1.8229186993306369e-5}, }; TEST(BetaTest, BetaIncomplete) { for (const auto& data : kBetaTable) { auto value = absl::random_internal::BetaIncomplete(data.x, data.p, data.q); EXPECT_NEAR(value, data.alpha, 1e-12) << " BetaRegularized[" << data.x << ", " << data.p << ", " << data.q << "] (expected=" << data.alpha << ") -> " << value; } } TEST(BetaTest, BetaIncompleteInv) { for (const auto& data : kBetaTable) { auto value = absl::random_internal::BetaIncompleteInv(data.p, data.q, data.alpha); EXPECT_NEAR(value, data.x, 1e-6) << " InverseBetaRegularized[" << data.alpha << ", " << data.p << ", " << data.q << "] (expected=" << data.x << ") -> " << value; } } TEST(MaxErrorTolerance, MaxErrorTolerance) { std::vector<std::pair<double, double>> cases = { {0.0000001, 8.86227e-8 * 1.41421356237}, {0.00001, 8.86227e-6 * 1.41421356237}, {0.5, 0.4769362762044 * 1.41421356237}, {0.6, 0.5951160814499 * 1.41421356237}, {0.99999, 3.1234132743 * 1.41421356237}, {0.9999999, 3.7665625816 * 1.41421356237}, {0.999999944, 3.8403850690566985 * 1.41421356237}, {0.999999999, 4.3200053849134452 * 1.41421356237}}; for (auto entry : cases) { EXPECT_NEAR(absl::random_internal::MaxErrorTolerance(entry.first), entry.second, 1e-8); } } TEST(ZScore, WithSameMean) { absl::random_internal::DistributionMoments m; m.n = 100; m.mean = 5; m.variance = 1; EXPECT_NEAR(absl::random_internal::ZScore(5, m), 0, 1e-12); m.n = 1; m.mean = 0; m.variance = 1; EXPECT_NEAR(absl::random_internal::ZScore(0, m), 0, 1e-12); m.n = 10000; m.mean = -5; m.variance = 100; EXPECT_NEAR(absl::random_internal::ZScore(-5, m), 0, 1e-12); } TEST(ZScore, DifferentMean) { absl::random_internal::DistributionMoments m; m.n = 100; m.mean = 5; m.variance = 1; EXPECT_NEAR(absl::random_internal::ZScore(4, m), 10, 1e-12); m.n = 1; m.mean = 0; m.variance = 1; EXPECT_NEAR(absl::random_internal::ZScore(-1, m), 1, 1e-12); m.n = 10000; m.mean = -5; m.variance = 100; EXPECT_NEAR(absl::random_internal::ZScore(-4, m), -10, 1e-12); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/distribution_test_util.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/distribution_test_util_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
75dce5ff-5b75-4027-b504-c171a5ad68f2
cpp
abseil/abseil-cpp
randen_slow
absl/random/internal/randen_slow.cc
absl/random/internal/randen_slow_test.cc
#include "absl/random/internal/randen_slow.h" #include <cstddef> #include <cstdint> #include <cstring> #include "absl/base/attributes.h" #include "absl/base/internal/endian.h" #include "absl/numeric/int128.h" #include "absl/random/internal/platform.h" #include "absl/random/internal/randen_traits.h" #if ABSL_HAVE_ATTRIBUTE(always_inline) || \ (defined(__GNUC__) && !defined(__clang__)) #define ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE \ __attribute__((always_inline)) #elif defined(_MSC_VER) #define ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE __forceinline #else #define ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE #endif namespace { constexpr uint32_t te0[256] = { 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c, }; constexpr uint32_t te1[256] = { 0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x0404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f, 0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76, 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db, 0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x08081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701, 0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, 0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a, }; constexpr uint32_t te2[256] = { 0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x04080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05, 0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, 0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db, 0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49, 0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x08101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6, 0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, 0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16, }; constexpr uint32_t te3[256] = { 0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x080c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505, 0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, 0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6, 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, 0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616, }; struct alignas(16) Vector128 { uint32_t s[4]; }; inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE Vector128 Vector128Load(const void* from) { Vector128 result; std::memcpy(result.s, from, sizeof(Vector128)); return result; } inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE void Vector128Store( const Vector128& v, void* to) { std::memcpy(to, v.s, sizeof(Vector128)); } inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE Vector128 AesRound(const Vector128& state, const Vector128& round_key) { Vector128 result; #ifdef ABSL_IS_LITTLE_ENDIAN result.s[0] = round_key.s[0] ^ te0[uint8_t(state.s[0])] ^ te1[uint8_t(state.s[1] >> 8)] ^ te2[uint8_t(state.s[2] >> 16)] ^ te3[uint8_t(state.s[3] >> 24)]; result.s[1] = round_key.s[1] ^ te0[uint8_t(state.s[1])] ^ te1[uint8_t(state.s[2] >> 8)] ^ te2[uint8_t(state.s[3] >> 16)] ^ te3[uint8_t(state.s[0] >> 24)]; result.s[2] = round_key.s[2] ^ te0[uint8_t(state.s[2])] ^ te1[uint8_t(state.s[3] >> 8)] ^ te2[uint8_t(state.s[0] >> 16)] ^ te3[uint8_t(state.s[1] >> 24)]; result.s[3] = round_key.s[3] ^ te0[uint8_t(state.s[3])] ^ te1[uint8_t(state.s[0] >> 8)] ^ te2[uint8_t(state.s[1] >> 16)] ^ te3[uint8_t(state.s[2] >> 24)]; #else result.s[0] = round_key.s[0] ^ te0[uint8_t(state.s[0])] ^ te1[uint8_t(state.s[3] >> 8)] ^ te2[uint8_t(state.s[2] >> 16)] ^ te3[uint8_t(state.s[1] >> 24)]; result.s[1] = round_key.s[1] ^ te0[uint8_t(state.s[1])] ^ te1[uint8_t(state.s[0] >> 8)] ^ te2[uint8_t(state.s[3] >> 16)] ^ te3[uint8_t(state.s[2] >> 24)]; result.s[2] = round_key.s[2] ^ te0[uint8_t(state.s[2])] ^ te1[uint8_t(state.s[1] >> 8)] ^ te2[uint8_t(state.s[0] >> 16)] ^ te3[uint8_t(state.s[3] >> 24)]; result.s[3] = round_key.s[3] ^ te0[uint8_t(state.s[3])] ^ te1[uint8_t(state.s[2] >> 8)] ^ te2[uint8_t(state.s[1] >> 16)] ^ te3[uint8_t(state.s[0] >> 24)]; #endif return result; } using ::absl::random_internal::RandenTraits; inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE void BlockShuffle( absl::uint128* state) { static_assert(RandenTraits::kFeistelBlocks == 16, "Feistel block shuffle only works for 16 blocks."); constexpr size_t shuffle[RandenTraits::kFeistelBlocks] = { 7, 2, 13, 4, 11, 8, 3, 6, 15, 0, 9, 10, 1, 14, 5, 12}; #if 0 absl::uint128 source[RandenTraits::kFeistelBlocks]; std::memcpy(source, state, sizeof(source)); for (size_t i = 0; i < RandenTraits::kFeistelBlocks; i++) { const absl::uint128 v0 = source[shuffle[i]]; state[i] = v0; } return; #endif const absl::uint128 v0 = state[shuffle[0]]; const absl::uint128 v1 = state[shuffle[1]]; const absl::uint128 v2 = state[shuffle[2]]; const absl::uint128 v3 = state[shuffle[3]]; const absl::uint128 v4 = state[shuffle[4]]; const absl::uint128 v5 = state[shuffle[5]]; const absl::uint128 v6 = state[shuffle[6]]; const absl::uint128 v7 = state[shuffle[7]]; const absl::uint128 w0 = state[shuffle[8]]; const absl::uint128 w1 = state[shuffle[9]]; const absl::uint128 w2 = state[shuffle[10]]; const absl::uint128 w3 = state[shuffle[11]]; const absl::uint128 w4 = state[shuffle[12]]; const absl::uint128 w5 = state[shuffle[13]]; const absl::uint128 w6 = state[shuffle[14]]; const absl::uint128 w7 = state[shuffle[15]]; state[0] = v0; state[1] = v1; state[2] = v2; state[3] = v3; state[4] = v4; state[5] = v5; state[6] = v6; state[7] = v7; state[8] = w0; state[9] = w1; state[10] = w2; state[11] = w3; state[12] = w4; state[13] = w5; state[14] = w6; state[15] = w7; } inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE const absl::uint128* FeistelRound(absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT state, const absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT keys) { for (size_t branch = 0; branch < RandenTraits::kFeistelBlocks; branch += 4) { const Vector128 s0 = Vector128Load(state + branch); const Vector128 s1 = Vector128Load(state + branch + 1); const Vector128 f0 = AesRound(s0, Vector128Load(keys)); keys++; const Vector128 o1 = AesRound(f0, s1); Vector128Store(o1, state + branch + 1); const Vector128 s2 = Vector128Load(state + branch + 2); const Vector128 s3 = Vector128Load(state + branch + 3); const Vector128 f2 = AesRound(s2, Vector128Load(keys)); keys++; const Vector128 o3 = AesRound(f2, s3); Vector128Store(o3, state + branch + 3); } return keys; } inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE void Permute( absl::uint128* state, const absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT keys) { for (size_t round = 0; round < RandenTraits::kFeistelRounds; ++round) { keys = FeistelRound(state, keys); BlockShuffle(state); } } inline ABSL_RANDOM_INTERNAL_ATTRIBUTE_ALWAYS_INLINE void SwapEndian( absl::uint128* state) { #ifdef ABSL_IS_BIG_ENDIAN for (uint32_t block = 0; block < RandenTraits::kFeistelBlocks; ++block) { uint64_t new_lo = absl::little_endian::ToHost64( static_cast<uint64_t>(state[block] >> 64)); uint64_t new_hi = absl::little_endian::ToHost64( static_cast<uint64_t>((state[block] << 64) >> 64)); state[block] = (static_cast<absl::uint128>(new_hi) << 64) | new_lo; } #else (void)state; #endif } } namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { const void* RandenSlow::GetKeys() { #ifdef ABSL_IS_LITTLE_ENDIAN return kRandenRoundKeys; #else return kRandenRoundKeysBE; #endif } void RandenSlow::Absorb(const void* seed_void, void* state_void) { auto* state = reinterpret_cast<uint64_t * ABSL_RANDOM_INTERNAL_RESTRICT>(state_void); const auto* seed = reinterpret_cast<const uint64_t * ABSL_RANDOM_INTERNAL_RESTRICT>( seed_void); constexpr size_t kCapacityBlocks = RandenTraits::kCapacityBytes / sizeof(uint64_t); static_assert( kCapacityBlocks * sizeof(uint64_t) == RandenTraits::kCapacityBytes, "Not i*V"); for (size_t i = kCapacityBlocks; i < RandenTraits::kStateBytes / sizeof(uint64_t); ++i) { state[i] ^= seed[i - kCapacityBlocks]; } } void RandenSlow::Generate(const void* keys_void, void* state_void) { static_assert(RandenTraits::kCapacityBytes == sizeof(absl::uint128), "Capacity mismatch"); auto* state = reinterpret_cast<absl::uint128*>(state_void); const auto* keys = reinterpret_cast<const absl::uint128*>(keys_void); const absl::uint128 prev_inner = state[0]; SwapEndian(state); Permute(state, keys); SwapEndian(state); *state ^= prev_inner; } } ABSL_NAMESPACE_END }
#include "absl/random/internal/randen_slow.h" #include <cstring> #include "gtest/gtest.h" #include "absl/base/internal/endian.h" #include "absl/random/internal/randen_traits.h" namespace { using absl::random_internal::RandenSlow; using absl::random_internal::RandenTraits; TEST(RandenSlowTest, Default) { constexpr uint8_t kGolden[] = { 0xee, 0xd3, 0xe6, 0x0e, 0x09, 0x34, 0x65, 0x6c, 0xc6, 0x33, 0x53, 0x9d, 0x9b, 0x2b, 0x4e, 0x04, 0x77, 0x39, 0x43, 0x4e, 0x13, 0x4f, 0xc1, 0xc3, 0xee, 0x10, 0x04, 0xd9, 0x7c, 0xf4, 0xa9, 0xdd, 0x10, 0xca, 0xd8, 0x7f, 0x08, 0xf3, 0x7b, 0x88, 0x12, 0x29, 0xc7, 0x45, 0xf5, 0x80, 0xb7, 0xf0, 0x9f, 0x59, 0x96, 0x76, 0xd3, 0xb1, 0xdb, 0x15, 0x59, 0x6d, 0x3c, 0xff, 0xba, 0x63, 0xec, 0x30, 0xa6, 0x20, 0x7f, 0x6f, 0x60, 0x73, 0x9f, 0xb2, 0x4c, 0xa5, 0x49, 0x6f, 0x31, 0x8a, 0x80, 0x02, 0x0e, 0xe5, 0xc8, 0xd5, 0xf9, 0xea, 0x8f, 0x3b, 0x8a, 0xde, 0xd9, 0x3f, 0x5e, 0x60, 0xbf, 0x9c, 0xbb, 0x3b, 0x18, 0x78, 0x1a, 0xae, 0x70, 0xc9, 0xd5, 0x1e, 0x30, 0x56, 0xd3, 0xff, 0xb2, 0xd8, 0x37, 0x3c, 0xc7, 0x0f, 0xfe, 0x27, 0xb3, 0xf4, 0x19, 0x9a, 0x8f, 0xeb, 0x76, 0x8d, 0xfd, 0xcd, 0x9d, 0x0c, 0x42, 0x91, 0xeb, 0x06, 0xa5, 0xc3, 0x56, 0x95, 0xff, 0x3e, 0xdd, 0x05, 0xaf, 0xd5, 0xa1, 0xc4, 0x83, 0x8f, 0xb7, 0x1b, 0xdb, 0x48, 0x8c, 0xfe, 0x6b, 0x0d, 0x0e, 0x92, 0x23, 0x70, 0x42, 0x6d, 0x95, 0x34, 0x58, 0x57, 0xd3, 0x58, 0x40, 0xb8, 0x87, 0x6b, 0xc2, 0xf4, 0x1e, 0xed, 0xf3, 0x2d, 0x0b, 0x3e, 0xa2, 0x32, 0xef, 0x8e, 0xfc, 0x54, 0x11, 0x43, 0xf3, 0xab, 0x7c, 0x49, 0x8b, 0x9a, 0x02, 0x70, 0x05, 0x37, 0x24, 0x4e, 0xea, 0xe5, 0x90, 0xf0, 0x49, 0x57, 0x8b, 0xd8, 0x2f, 0x69, 0x70, 0xa9, 0x82, 0xa5, 0x51, 0xc6, 0xf5, 0x42, 0x63, 0xbb, 0x2c, 0xec, 0xfc, 0x78, 0xdb, 0x55, 0x2f, 0x61, 0x45, 0xb7, 0x3c, 0x46, 0xe3, 0xaf, 0x16, 0x18, 0xad, 0xe4, 0x2e, 0x35, 0x7e, 0xda, 0x01, 0xc1, 0x74, 0xf3, 0x6f, 0x02, 0x51, 0xe8, 0x3d, 0x1c, 0x82, 0xf0, 0x1e, 0x81, }; alignas(16) uint8_t state[RandenTraits::kStateBytes]; std::memset(state, 0, sizeof(state)); RandenSlow::Generate(RandenSlow::GetKeys(), state); EXPECT_EQ(0, std::memcmp(state, kGolden, sizeof(state))); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/randen_slow.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/randen_slow_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
21b3e2ff-cbf9-4303-875a-b4942003e6eb
cpp
abseil/abseil-cpp
chi_square
absl/random/internal/chi_square.cc
absl/random/internal/chi_square_test.cc
#include "absl/random/internal/chi_square.h" #include <cmath> #include "absl/random/internal/distribution_test_util.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { namespace { #if defined(__EMSCRIPTEN__) inline double fma(double x, double y, double z) { return (x * y) + z; } #endif template <typename T, unsigned N> inline T EvaluatePolynomial(T x, const T (&poly)[N]) { #if !defined(__EMSCRIPTEN__) using std::fma; #endif T p = poly[N - 1]; for (unsigned i = 2; i <= N; i++) { p = fma(p, x, poly[N - i]); } return p; } static constexpr int kLargeDOF = 150; double POZ(double z) { static constexpr double kP1[] = { 0.797884560593, -0.531923007300, 0.319152932694, -0.151968751364, 0.059054035642, -0.019198292004, 0.005198775019, -0.001075204047, 0.000124818987, }; static constexpr double kP2[] = { 0.999936657524, 0.000535310849, -0.002141268741, 0.005353579108, -0.009279453341, 0.011630447319, -0.010557625006, 0.006549791214, -0.002034254874, -0.000794620820, 0.001390604284, -0.000676904986, -0.000019538132, 0.000152529290, -0.000045255659, }; const double kZMax = 6.0; if (z == 0.0) { return 0.5; } double x; double y = 0.5 * std::fabs(z); if (y >= (kZMax * 0.5)) { x = 1.0; } else if (y < 1.0) { double w = y * y; x = EvaluatePolynomial(w, kP1) * y * 2.0; } else { y -= 2.0; x = EvaluatePolynomial(y, kP2); } return z > 0.0 ? ((x + 1.0) * 0.5) : ((1.0 - x) * 0.5); } double normal_survival(double z) { static constexpr double kR[] = { 1.0, 0.196854, 0.115194, 0.000344, 0.019527, }; double r = EvaluatePolynomial(z, kR); r *= r; return 0.5 / (r * r); } } double ChiSquareValue(int dof, double p) { static constexpr double kChiEpsilon = 0.000001; static constexpr double kChiMax = 99999.0; const double p_value = 1.0 - p; if (dof < 1 || p_value > 1.0) { return 0.0; } if (dof > kLargeDOF) { const double z = InverseNormalSurvival(p_value); const double mean = 1 - 2.0 / (9 * dof); const double variance = 2.0 / (9 * dof); if (variance != 0) { double term = z * std::sqrt(variance) + mean; return dof * (term * term * term); } } if (p_value <= 0.0) return kChiMax; double min_chisq = 0.0; double max_chisq = kChiMax; double current = dof / std::sqrt(p_value); while ((max_chisq - min_chisq) > kChiEpsilon) { if (ChiSquarePValue(current, dof) < p_value) { max_chisq = current; } else { min_chisq = current; } current = (max_chisq + min_chisq) * 0.5; } return current; } double ChiSquarePValue(double chi_square, int dof) { static constexpr double kLogSqrtPi = 0.5723649429247000870717135; static constexpr double kInverseSqrtPi = 0.5641895835477562869480795; if (dof > kLargeDOF) { const double chi_square_scaled = std::pow(chi_square / dof, 1.0 / 3); const double mean = 1 - 2.0 / (9 * dof); const double variance = 2.0 / (9 * dof); if (variance != 0) { const double z = (chi_square_scaled - mean) / std::sqrt(variance); if (z > 0) { return normal_survival(z); } else if (z < 0) { return 1.0 - normal_survival(-z); } else { return 0.5; } } } if (chi_square <= 0.0) return 1.0; if (dof < 1) return 0; auto capped_exp = [](double x) { return x < -20 ? 0.0 : std::exp(x); }; static constexpr double kBigX = 20; double a = 0.5 * chi_square; const bool even = !(dof & 1); const double y = capped_exp(-a); double s = even ? y : (2.0 * POZ(-std::sqrt(chi_square))); if (dof <= 2) { return s; } chi_square = 0.5 * (dof - 1.0); double z = (even ? 1.0 : 0.5); if (a > kBigX) { double e = (even ? 0.0 : kLogSqrtPi); double c = std::log(a); while (z <= chi_square) { e = std::log(z) + e; s += capped_exp(c * z - a - e); z += 1.0; } return s; } double e = (even ? 1.0 : (kInverseSqrtPi / std::sqrt(a))); double c = 0.0; while (z <= chi_square) { e = e * (a / z); c = c + e; z += 1.0; } return c * y + s; } } ABSL_NAMESPACE_END }
#include "absl/random/internal/chi_square.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <iterator> #include <numeric> #include <vector> #include "gtest/gtest.h" #include "absl/base/macros.h" using absl::random_internal::ChiSquare; using absl::random_internal::ChiSquarePValue; using absl::random_internal::ChiSquareValue; using absl::random_internal::ChiSquareWithExpected; namespace { TEST(ChiSquare, Value) { struct { int line; double chi_square; int df; double confidence; } const specs[] = { {__LINE__, 0, 0, 0.01}, {__LINE__, 0.00016, 1, 0.01}, {__LINE__, 1.64650, 8, 0.01}, {__LINE__, 5.81221, 16, 0.01}, {__LINE__, 156.4319, 200, 0.01}, {__LINE__, 1121.3784, 1234, 0.01}, {__LINE__, 53557.1629, 54321, 0.01}, {__LINE__, 651662.6647, 654321, 0.01}, {__LINE__, 0, 0, 0.99}, {__LINE__, 6.635, 1, 0.99}, {__LINE__, 20.090, 8, 0.99}, {__LINE__, 32.000, 16, 0.99}, {__LINE__, 249.4456, 200, 0.99}, {__LINE__, 1131.1573, 1023, 0.99}, {__LINE__, 1352.5038, 1234, 0.99}, {__LINE__, 55090.7356, 54321, 0.99}, {__LINE__, 656985.1514, 654321, 0.99}, {__LINE__, 16.2659, 3, 0.999}, {__LINE__, 22.4580, 6, 0.999}, {__LINE__, 267.5409, 200, 0.999}, {__LINE__, 1168.5033, 1023, 0.999}, {__LINE__, 55345.1741, 54321, 0.999}, {__LINE__, 657861.7284, 654321, 0.999}, {__LINE__, 51.1772, 24, 0.999}, {__LINE__, 59.7003, 30, 0.999}, {__LINE__, 37.6984, 15, 0.999}, {__LINE__, 29.5898, 10, 0.999}, {__LINE__, 27.8776, 9, 0.999}, {__LINE__, 0.000157088, 1, 0.01}, {__LINE__, 5.31852, 2, 0.93}, {__LINE__, 1.92256, 4, 0.25}, {__LINE__, 10.7709, 13, 0.37}, {__LINE__, 26.2514, 17, 0.93}, {__LINE__, 36.4799, 29, 0.84}, {__LINE__, 25.818, 31, 0.27}, {__LINE__, 63.3346, 64, 0.50}, {__LINE__, 196.211, 128, 0.9999}, {__LINE__, 215.21, 243, 0.10}, {__LINE__, 285.393, 256, 0.90}, {__LINE__, 984.504, 1024, 0.1923}, {__LINE__, 2043.85, 2048, 0.4783}, {__LINE__, 48004.6, 48273, 0.194}, }; for (const auto& spec : specs) { SCOPED_TRACE(spec.line); const double val = ChiSquareValue(spec.df, spec.confidence); const double err = std::max(5e-6, spec.chi_square / 5e3); EXPECT_NEAR(spec.chi_square, val, err) << spec.line; } EXPECT_NEAR(49.2680, ChiSquareValue(100, 1e-6), 5); EXPECT_NEAR(123.499, ChiSquareValue(200, 1e-6), 5); EXPECT_NEAR(149.449, ChiSquareValue(100, 0.999), 0.01); EXPECT_NEAR(161.318, ChiSquareValue(100, 0.9999), 0.01); EXPECT_NEAR(172.098, ChiSquareValue(100, 0.99999), 0.01); EXPECT_NEAR(381.426, ChiSquareValue(300, 0.999), 0.05); EXPECT_NEAR(399.756, ChiSquareValue(300, 0.9999), 0.1); EXPECT_NEAR(416.126, ChiSquareValue(300, 0.99999), 0.2); } TEST(ChiSquareTest, PValue) { struct { int line; double pval; double chi_square; int df; } static const specs[] = { {__LINE__, 1, 0, 0}, {__LINE__, 0, 0.001, 0}, {__LINE__, 1.000, 0, 453}, {__LINE__, 0.134471, 7972.52, 7834}, {__LINE__, 0.203922, 28.32, 23}, {__LINE__, 0.737171, 48274, 48472}, {__LINE__, 0.444146, 583.1234, 579}, {__LINE__, 0.294814, 138.2, 130}, {__LINE__, 0.0816532, 12.63, 7}, {__LINE__, 0, 682.32, 67}, {__LINE__, 0.49405, 999, 999}, {__LINE__, 1.000, 0, 9999}, {__LINE__, 0.997477, 0.00001, 1}, {__LINE__, 0, 5823.21, 5040}, }; for (const auto& spec : specs) { SCOPED_TRACE(spec.line); const double pval = ChiSquarePValue(spec.chi_square, spec.df); EXPECT_NEAR(spec.pval, pval, 1e-3); } } TEST(ChiSquareTest, CalcChiSquare) { struct { int line; std::vector<int> expected; std::vector<int> actual; } const specs[] = { {__LINE__, {56, 234, 76, 1, 546, 1, 87, 345, 1, 234}, {2, 132, 4, 43, 234, 8, 345, 8, 236, 56}}, {__LINE__, {123, 36, 234, 367, 345, 2, 456, 567, 234, 567}, {123, 56, 2345, 8, 345, 8, 2345, 23, 48, 267}}, {__LINE__, {123, 234, 345, 456, 567, 678, 789, 890, 98, 76}, {123, 234, 345, 456, 567, 678, 789, 890, 98, 76}}, {__LINE__, {3, 675, 23, 86, 2, 8, 2}, {456, 675, 23, 86, 23, 65, 2}}, {__LINE__, {1}, {23}}, }; for (const auto& spec : specs) { SCOPED_TRACE(spec.line); double chi_square = 0; for (int i = 0; i < spec.expected.size(); ++i) { const double diff = spec.actual[i] - spec.expected[i]; chi_square += (diff * diff) / spec.expected[i]; } EXPECT_NEAR(chi_square, ChiSquare(std::begin(spec.actual), std::end(spec.actual), std::begin(spec.expected), std::end(spec.expected)), 1e-5); } } TEST(ChiSquareTest, CalcChiSquareInt64) { const int64_t data[3] = {910293487, 910292491, 910216780}; double sum = std::accumulate(std::begin(data), std::end(data), double{0}); size_t n = std::distance(std::begin(data), std::end(data)); double a = ChiSquareWithExpected(std::begin(data), std::end(data), sum / n); EXPECT_NEAR(4.254101, a, 1e-6); double b = ChiSquareWithExpected(std::begin(data), std::end(data), 910267586.0); EXPECT_NEAR(4.254101, b, 1e-6); } TEST(ChiSquareTest, TableData) { const double data[100][5] = { {2.706, 3.841, 5.024, 6.635, 10.828}, {4.605, 5.991, 7.378, 9.210, 13.816}, {6.251, 7.815, 9.348, 11.345, 16.266}, {7.779, 9.488, 11.143, 13.277, 18.467}, {9.236, 11.070, 12.833, 15.086, 20.515}, {10.645, 12.592, 14.449, 16.812, 22.458}, {12.017, 14.067, 16.013, 18.475, 24.322}, {13.362, 15.507, 17.535, 20.090, 26.125}, {14.684, 16.919, 19.023, 21.666, 27.877}, {15.987, 18.307, 20.483, 23.209, 29.588}, {17.275, 19.675, 21.920, 24.725, 31.264}, {18.549, 21.026, 23.337, 26.217, 32.910}, {19.812, 22.362, 24.736, 27.688, 34.528}, {21.064, 23.685, 26.119, 29.141, 36.123}, {22.307, 24.996, 27.488, 30.578, 37.697}, {23.542, 26.296, 28.845, 32.000, 39.252}, {24.769, 27.587, 30.191, 33.409, 40.790}, {25.989, 28.869, 31.526, 34.805, 42.312}, {27.204, 30.144, 32.852, 36.191, 43.820}, {28.412, 31.410, 34.170, 37.566, 45.315}, {29.615, 32.671, 35.479, 38.932, 46.797}, {30.813, 33.924, 36.781, 40.289, 48.268}, {32.007, 35.172, 38.076, 41.638, 49.728}, {33.196, 36.415, 39.364, 42.980, 51.179}, {34.382, 37.652, 40.646, 44.314, 52.620}, {35.563, 38.885, 41.923, 45.642, 54.052}, {36.741, 40.113, 43.195, 46.963, 55.476}, {37.916, 41.337, 44.461, 48.278, 56.892}, {39.087, 42.557, 45.722, 49.588, 58.301}, {40.256, 43.773, 46.979, 50.892, 59.703}, {41.422, 44.985, 48.232, 52.191, 61.098}, {42.585, 46.194, 49.480, 53.486, 62.487}, {43.745, 47.400, 50.725, 54.776, 63.870}, {44.903, 48.602, 51.966, 56.061, 65.247}, {46.059, 49.802, 53.203, 57.342, 66.619}, {47.212, 50.998, 54.437, 58.619, 67.985}, {48.363, 52.192, 55.668, 59.893, 69.347}, {49.513, 53.384, 56.896, 61.162, 70.703}, {50.660, 54.572, 58.120, 62.428, 72.055}, {51.805, 55.758, 59.342, 63.691, 73.402}, {52.949, 56.942, 60.561, 64.950, 74.745}, {54.090, 58.124, 61.777, 66.206, 76.084}, {55.230, 59.304, 62.990, 67.459, 77.419}, {56.369, 60.481, 64.201, 68.710, 78.750}, {57.505, 61.656, 65.410, 69.957, 80.077}, {58.641, 62.830, 66.617, 71.201, 81.400}, {59.774, 64.001, 67.821, 72.443, 82.720}, {60.907, 65.171, 69.023, 73.683, 84.037}, {62.038, 66.339, 70.222, 74.919, 85.351}, {63.167, 67.505, 71.420, 76.154, 86.661}, {64.295, 68.669, 72.616, 77.386, 87.968}, {65.422, 69.832, 73.810, 78.616, 89.272}, {66.548, 70.993, 75.002, 79.843, 90.573}, {67.673, 72.153, 76.192, 81.069, 91.872}, {68.796, 73.311, 77.380, 82.292, 93.168}, {69.919, 74.468, 78.567, 83.513, 94.461}, {71.040, 75.624, 79.752, 84.733, 95.751}, {72.160, 76.778, 80.936, 85.950, 97.039}, {73.279, 77.931, 82.117, 87.166, 98.324}, {74.397, 79.082, 83.298, 88.379, 99.607}, {75.514, 80.232, 84.476, 89.591, 100.888}, {76.630, 81.381, 85.654, 90.802, 102.166}, {77.745, 82.529, 86.830, 92.010, 103.442}, {78.860, 83.675, 88.004, 93.217, 104.716}, {79.973, 84.821, 89.177, 94.422, 105.988}, {81.085, 85.965, 90.349, 95.626, 107.258}, {82.197, 87.108, 91.519, 96.828, 108.526}, {83.308, 88.250, 92.689, 98.028, 109.791}, {84.418, 89.391, 93.856, 99.228, 111.055}, {85.527, 90.531, 95.023, 100.425, 112.317}, {86.635, 91.670, 96.189, 101.621, 113.577}, {87.743, 92.808, 97.353, 102.816, 114.835}, {88.850, 93.945, 98.516, 104.010, 116.092}, {89.956, 95.081, 99.678, 105.202, 117.346}, {91.061, 96.217, 100.839, 106.393, 118.599}, {92.166, 97.351, 101.999, 107.583, 119.850}, {93.270, 98.484, 103.158, 108.771, 121.100}, {94.374, 99.617, 104.316, 109.958, 122.348}, {95.476, 100.749, 105.473, 111.144, 123.594}, {96.578, 101.879, 106.629, 112.329, 124.839}, {97.680, 103.010, 107.783, 113.512, 126.083}, {98.780, 104.139, 108.937, 114.695, 127.324}, {99.880, 105.267, 110.090, 115.876, 128.565}, {100.980, 106.395, 111.242, 117.057, 129.804}, {102.079, 107.522, 112.393, 118.236, 131.041}, {103.177, 108.648, 113.544, 119.414, 132.277}, {104.275, 109.773, 114.693, 120.591, 133.512}, {105.372, 110.898, 115.841, 121.767, 134.746}, {106.469, 112.022, 116.989, 122.942, 135.978}, {107.565, 113.145, 118.136, 124.116, 137.208}, {108.661, 114.268, 119.282, 125.289, 138.438}, {109.756, 115.390, 120.427, 126.462, 139.666}, {110.850, 116.511, 121.571, 127.633, 140.893}, {111.944, 117.632, 122.715, 128.803, 142.119}, {113.038, 118.752, 123.858, 129.973, 143.344}, {114.131, 119.871, 125.000, 131.141, 144.567}, {115.223, 120.990, 126.141, 132.309, 145.789}, {116.315, 122.108, 127.282, 133.476, 147.010}, {117.407, 123.225, 128.422, 134.642, 148.230}, {118.498, 124.342, 129.561, 135.807, 149.449} }; for (int i = 0; i < ABSL_ARRAYSIZE(data); i++) { const double E = 0.0001; EXPECT_NEAR(ChiSquarePValue(data[i][0], i + 1), 0.10, E) << i << " " << data[i][0]; EXPECT_NEAR(ChiSquarePValue(data[i][1], i + 1), 0.05, E) << i << " " << data[i][1]; EXPECT_NEAR(ChiSquarePValue(data[i][2], i + 1), 0.025, E) << i << " " << data[i][2]; EXPECT_NEAR(ChiSquarePValue(data[i][3], i + 1), 0.01, E) << i << " " << data[i][3]; EXPECT_NEAR(ChiSquarePValue(data[i][4], i + 1), 0.001, E) << i << " " << data[i][4]; const double F = 0.1; EXPECT_NEAR(ChiSquareValue(i + 1, 0.90), data[i][0], F) << i; EXPECT_NEAR(ChiSquareValue(i + 1, 0.95), data[i][1], F) << i; EXPECT_NEAR(ChiSquareValue(i + 1, 0.975), data[i][2], F) << i; EXPECT_NEAR(ChiSquareValue(i + 1, 0.99), data[i][3], F) << i; EXPECT_NEAR(ChiSquareValue(i + 1, 0.999), data[i][4], F) << i; } } TEST(ChiSquareTest, ChiSquareTwoIterator) { const int counts[10] = {6, 6, 18, 33, 38, 38, 28, 21, 9, 3}; const double expected[10] = {4.6, 8.8, 18.4, 30.0, 38.2, 38.2, 30.0, 18.4, 8.8, 4.6}; double chi_square = ChiSquare(std::begin(counts), std::end(counts), std::begin(expected), std::end(expected)); EXPECT_NEAR(chi_square, 2.69, 0.001); const int dof = 7; double p_value_05 = ChiSquarePValue(14.067, dof); EXPECT_NEAR(p_value_05, 0.05, 0.001); double p_actual = ChiSquarePValue(chi_square, dof); EXPECT_GT(p_actual, 0.05); } TEST(ChiSquareTest, DiceRolls) { const int rolls[6] = {22, 11, 17, 14, 20, 18}; double sum = std::accumulate(std::begin(rolls), std::end(rolls), double{0}); size_t n = std::distance(std::begin(rolls), std::end(rolls)); double a = ChiSquareWithExpected(std::begin(rolls), std::end(rolls), sum / n); EXPECT_NEAR(a, 4.70588, 1e-5); EXPECT_LT(a, ChiSquareValue(4, 0.95)); double p_a = ChiSquarePValue(a, 4); EXPECT_NEAR(p_a, 0.318828, 1e-5); double b = ChiSquareWithExpected(std::begin(rolls), std::end(rolls), 17.0); EXPECT_NEAR(b, 4.70588, 1e-5); EXPECT_LT(b, ChiSquareValue(5, 0.95)); double p_b = ChiSquarePValue(b, 5); EXPECT_NEAR(p_b, 0.4528180, 1e-5); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/chi_square.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/chi_square_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
14b90607-2c26-427d-a00b-7fb9d69a4c4b
cpp
abseil/abseil-cpp
randen
absl/random/internal/randen.cc
absl/random/internal/randen_test.cc
#include "absl/random/internal/randen.h" #include "absl/base/internal/raw_logging.h" #include "absl/random/internal/randen_detect.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { namespace { struct RandenState { const void* keys; bool has_crypto; }; RandenState GetRandenState() { static const RandenState state = []() { RandenState tmp; #if ABSL_RANDOM_INTERNAL_AES_DISPATCH if (HasRandenHwAesImplementation() && CPUSupportsRandenHwAes()) { tmp.has_crypto = true; tmp.keys = RandenHwAes::GetKeys(); } else { tmp.has_crypto = false; tmp.keys = RandenSlow::GetKeys(); } #elif ABSL_HAVE_ACCELERATED_AES tmp.has_crypto = true; tmp.keys = RandenHwAes::GetKeys(); #else tmp.has_crypto = false; tmp.keys = RandenSlow::GetKeys(); #endif return tmp; }(); return state; } } Randen::Randen() { auto tmp = GetRandenState(); keys_ = tmp.keys; #if ABSL_RANDOM_INTERNAL_AES_DISPATCH has_crypto_ = tmp.has_crypto; #endif } } ABSL_NAMESPACE_END }
#include "absl/random/internal/randen.h" #include <cstring> #include "gtest/gtest.h" #include "absl/meta/type_traits.h" namespace { using absl::random_internal::Randen; TEST(RandenTest, CopyAndMove) { static_assert(std::is_copy_constructible<Randen>::value, "Randen must be copy constructible"); static_assert(absl::is_copy_assignable<Randen>::value, "Randen must be copy assignable"); static_assert(std::is_move_constructible<Randen>::value, "Randen must be move constructible"); static_assert(absl::is_move_assignable<Randen>::value, "Randen must be move assignable"); } TEST(RandenTest, Default) { constexpr uint8_t kGolden[] = { 0xee, 0xd3, 0xe6, 0x0e, 0x09, 0x34, 0x65, 0x6c, 0xc6, 0x33, 0x53, 0x9d, 0x9b, 0x2b, 0x4e, 0x04, 0x77, 0x39, 0x43, 0x4e, 0x13, 0x4f, 0xc1, 0xc3, 0xee, 0x10, 0x04, 0xd9, 0x7c, 0xf4, 0xa9, 0xdd, 0x10, 0xca, 0xd8, 0x7f, 0x08, 0xf3, 0x7b, 0x88, 0x12, 0x29, 0xc7, 0x45, 0xf5, 0x80, 0xb7, 0xf0, 0x9f, 0x59, 0x96, 0x76, 0xd3, 0xb1, 0xdb, 0x15, 0x59, 0x6d, 0x3c, 0xff, 0xba, 0x63, 0xec, 0x30, 0xa6, 0x20, 0x7f, 0x6f, 0x60, 0x73, 0x9f, 0xb2, 0x4c, 0xa5, 0x49, 0x6f, 0x31, 0x8a, 0x80, 0x02, 0x0e, 0xe5, 0xc8, 0xd5, 0xf9, 0xea, 0x8f, 0x3b, 0x8a, 0xde, 0xd9, 0x3f, 0x5e, 0x60, 0xbf, 0x9c, 0xbb, 0x3b, 0x18, 0x78, 0x1a, 0xae, 0x70, 0xc9, 0xd5, 0x1e, 0x30, 0x56, 0xd3, 0xff, 0xb2, 0xd8, 0x37, 0x3c, 0xc7, 0x0f, 0xfe, 0x27, 0xb3, 0xf4, 0x19, 0x9a, 0x8f, 0xeb, 0x76, 0x8d, 0xfd, 0xcd, 0x9d, 0x0c, 0x42, 0x91, 0xeb, 0x06, 0xa5, 0xc3, 0x56, 0x95, 0xff, 0x3e, 0xdd, 0x05, 0xaf, 0xd5, 0xa1, 0xc4, 0x83, 0x8f, 0xb7, 0x1b, 0xdb, 0x48, 0x8c, 0xfe, 0x6b, 0x0d, 0x0e, 0x92, 0x23, 0x70, 0x42, 0x6d, 0x95, 0x34, 0x58, 0x57, 0xd3, 0x58, 0x40, 0xb8, 0x87, 0x6b, 0xc2, 0xf4, 0x1e, 0xed, 0xf3, 0x2d, 0x0b, 0x3e, 0xa2, 0x32, 0xef, 0x8e, 0xfc, 0x54, 0x11, 0x43, 0xf3, 0xab, 0x7c, 0x49, 0x8b, 0x9a, 0x02, 0x70, 0x05, 0x37, 0x24, 0x4e, 0xea, 0xe5, 0x90, 0xf0, 0x49, 0x57, 0x8b, 0xd8, 0x2f, 0x69, 0x70, 0xa9, 0x82, 0xa5, 0x51, 0xc6, 0xf5, 0x42, 0x63, 0xbb, 0x2c, 0xec, 0xfc, 0x78, 0xdb, 0x55, 0x2f, 0x61, 0x45, 0xb7, 0x3c, 0x46, 0xe3, 0xaf, 0x16, 0x18, 0xad, 0xe4, 0x2e, 0x35, 0x7e, 0xda, 0x01, 0xc1, 0x74, 0xf3, 0x6f, 0x02, 0x51, 0xe8, 0x3d, 0x1c, 0x82, 0xf0, 0x1e, 0x81, }; alignas(16) uint8_t state[Randen::kStateBytes]; std::memset(state, 0, sizeof(state)); Randen r; r.Generate(state); EXPECT_EQ(0, std::memcmp(state, kGolden, sizeof(state))); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/randen.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/randen_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
d27c1299-07dc-48ba-9a98-b5439509c8ea
cpp
abseil/abseil-cpp
randen_hwaes
absl/random/internal/randen_hwaes.cc
absl/random/internal/randen_hwaes_test.cc
#include "absl/random/internal/randen_hwaes.h" #include <cstdint> #include <cstring> #include "absl/base/attributes.h" #include "absl/numeric/int128.h" #include "absl/random/internal/platform.h" #include "absl/random/internal/randen_traits.h" #if ABSL_HAVE_ACCELERATED_AES #if defined(ABSL_ARCH_X86_64) || defined(ABSL_ARCH_X86_32) || \ defined(ABSL_ARCH_PPC) || defined(ABSL_ARCH_ARM) || \ defined(ABSL_ARCH_AARCH64) #define ABSL_RANDEN_HWAES_IMPL 1 #endif #endif #if !defined(ABSL_RANDEN_HWAES_IMPL) #include <cstdio> #include <cstdlib> namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { bool HasRandenHwAesImplementation() { return false; } const void* RandenHwAes::GetKeys() { const int d = ABSL_RANDOM_INTERNAL_AES_DISPATCH; fprintf(stderr, "AES Hardware detection failed (%d).\n", d); exit(1); return nullptr; } void RandenHwAes::Absorb(const void*, void*) { const int d = ABSL_RANDOM_INTERNAL_AES_DISPATCH; fprintf(stderr, "AES Hardware detection failed (%d).\n", d); exit(1); } void RandenHwAes::Generate(const void*, void*) { const int d = ABSL_RANDOM_INTERNAL_AES_DISPATCH; fprintf(stderr, "AES Hardware detection failed (%d).\n", d); exit(1); } } ABSL_NAMESPACE_END } #else namespace { using absl::random_internal::RandenTraits; } #if (defined(__clang__) || defined(__GNUC__)) #if defined(ABSL_ARCH_X86_64) || defined(ABSL_ARCH_X86_32) #define ABSL_TARGET_CRYPTO __attribute__((target("aes"))) #elif defined(ABSL_ARCH_PPC) #define ABSL_TARGET_CRYPTO __attribute__((target("crypto"))) #else #define ABSL_TARGET_CRYPTO #endif #else #define ABSL_TARGET_CRYPTO #endif #if defined(ABSL_ARCH_PPC) #include <altivec.h> #undef vector #undef bool using Vector128 = __vector unsigned long long; namespace { inline ABSL_TARGET_CRYPTO Vector128 ReverseBytes(const Vector128& v) { const __vector unsigned char perm = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; return vec_perm(v, v, perm); } inline ABSL_TARGET_CRYPTO Vector128 Vector128Load(const void* from) { return vec_vsx_ld(0, reinterpret_cast<const Vector128*>(from)); } inline ABSL_TARGET_CRYPTO void Vector128Store(const Vector128& v, void* to) { vec_vsx_st(v, 0, reinterpret_cast<Vector128*>(to)); } inline ABSL_TARGET_CRYPTO Vector128 AesRound(const Vector128& state, const Vector128& round_key) { return Vector128(__builtin_crypto_vcipher(state, round_key)); } inline ABSL_TARGET_CRYPTO void SwapEndian(absl::uint128* state) { for (uint32_t block = 0; block < RandenTraits::kFeistelBlocks; ++block) { Vector128Store(ReverseBytes(Vector128Load(state + block)), state + block); } } } #elif defined(ABSL_ARCH_ARM) || defined(ABSL_ARCH_AARCH64) #include <arm_neon.h> using Vector128 = uint8x16_t; namespace { inline ABSL_TARGET_CRYPTO Vector128 Vector128Load(const void* from) { return vld1q_u8(reinterpret_cast<const uint8_t*>(from)); } inline ABSL_TARGET_CRYPTO void Vector128Store(const Vector128& v, void* to) { vst1q_u8(reinterpret_cast<uint8_t*>(to), v); } inline ABSL_TARGET_CRYPTO Vector128 AesRound(const Vector128& state, const Vector128& round_key) { return vaesmcq_u8(vaeseq_u8(state, uint8x16_t{})) ^ round_key; } inline ABSL_TARGET_CRYPTO void SwapEndian(void*) {} } #elif defined(ABSL_ARCH_X86_64) || defined(ABSL_ARCH_X86_32) #include <immintrin.h> namespace { class Vector128 { public: inline explicit Vector128(const __m128i& v) : data_(v) {} inline __m128i data() const { return data_; } inline Vector128& operator^=(const Vector128& other) { data_ = _mm_xor_si128(data_, other.data()); return *this; } private: __m128i data_; }; inline ABSL_TARGET_CRYPTO Vector128 Vector128Load(const void* from) { return Vector128(_mm_load_si128(reinterpret_cast<const __m128i*>(from))); } inline ABSL_TARGET_CRYPTO void Vector128Store(const Vector128& v, void* to) { _mm_store_si128(reinterpret_cast<__m128i*>(to), v.data()); } inline ABSL_TARGET_CRYPTO Vector128 AesRound(const Vector128& state, const Vector128& round_key) { return Vector128(_mm_aesenc_si128(state.data(), round_key.data())); } inline ABSL_TARGET_CRYPTO void SwapEndian(void*) {} } #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunknown-pragmas" #endif namespace { inline ABSL_TARGET_CRYPTO void BlockShuffle(absl::uint128* state) { static_assert(RandenTraits::kFeistelBlocks == 16, "Expecting 16 FeistelBlocks."); constexpr size_t shuffle[RandenTraits::kFeistelBlocks] = { 7, 2, 13, 4, 11, 8, 3, 6, 15, 0, 9, 10, 1, 14, 5, 12}; const Vector128 v0 = Vector128Load(state + shuffle[0]); const Vector128 v1 = Vector128Load(state + shuffle[1]); const Vector128 v2 = Vector128Load(state + shuffle[2]); const Vector128 v3 = Vector128Load(state + shuffle[3]); const Vector128 v4 = Vector128Load(state + shuffle[4]); const Vector128 v5 = Vector128Load(state + shuffle[5]); const Vector128 v6 = Vector128Load(state + shuffle[6]); const Vector128 v7 = Vector128Load(state + shuffle[7]); const Vector128 w0 = Vector128Load(state + shuffle[8]); const Vector128 w1 = Vector128Load(state + shuffle[9]); const Vector128 w2 = Vector128Load(state + shuffle[10]); const Vector128 w3 = Vector128Load(state + shuffle[11]); const Vector128 w4 = Vector128Load(state + shuffle[12]); const Vector128 w5 = Vector128Load(state + shuffle[13]); const Vector128 w6 = Vector128Load(state + shuffle[14]); const Vector128 w7 = Vector128Load(state + shuffle[15]); Vector128Store(v0, state + 0); Vector128Store(v1, state + 1); Vector128Store(v2, state + 2); Vector128Store(v3, state + 3); Vector128Store(v4, state + 4); Vector128Store(v5, state + 5); Vector128Store(v6, state + 6); Vector128Store(v7, state + 7); Vector128Store(w0, state + 8); Vector128Store(w1, state + 9); Vector128Store(w2, state + 10); Vector128Store(w3, state + 11); Vector128Store(w4, state + 12); Vector128Store(w5, state + 13); Vector128Store(w6, state + 14); Vector128Store(w7, state + 15); } inline ABSL_TARGET_CRYPTO const absl::uint128* FeistelRound( absl::uint128* state, const absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT keys) { static_assert(RandenTraits::kFeistelBlocks == 16, "Expecting 16 FeistelBlocks."); const Vector128 s0 = Vector128Load(state + 0); const Vector128 s1 = Vector128Load(state + 1); const Vector128 s2 = Vector128Load(state + 2); const Vector128 s3 = Vector128Load(state + 3); const Vector128 s4 = Vector128Load(state + 4); const Vector128 s5 = Vector128Load(state + 5); const Vector128 s6 = Vector128Load(state + 6); const Vector128 s7 = Vector128Load(state + 7); const Vector128 s8 = Vector128Load(state + 8); const Vector128 s9 = Vector128Load(state + 9); const Vector128 s10 = Vector128Load(state + 10); const Vector128 s11 = Vector128Load(state + 11); const Vector128 s12 = Vector128Load(state + 12); const Vector128 s13 = Vector128Load(state + 13); const Vector128 s14 = Vector128Load(state + 14); const Vector128 s15 = Vector128Load(state + 15); const Vector128 e0 = AesRound(s0, Vector128Load(keys + 0)); const Vector128 e2 = AesRound(s2, Vector128Load(keys + 1)); const Vector128 e4 = AesRound(s4, Vector128Load(keys + 2)); const Vector128 e6 = AesRound(s6, Vector128Load(keys + 3)); const Vector128 e8 = AesRound(s8, Vector128Load(keys + 4)); const Vector128 e10 = AesRound(s10, Vector128Load(keys + 5)); const Vector128 e12 = AesRound(s12, Vector128Load(keys + 6)); const Vector128 e14 = AesRound(s14, Vector128Load(keys + 7)); const Vector128 o1 = AesRound(e0, s1); const Vector128 o3 = AesRound(e2, s3); const Vector128 o5 = AesRound(e4, s5); const Vector128 o7 = AesRound(e6, s7); const Vector128 o9 = AesRound(e8, s9); const Vector128 o11 = AesRound(e10, s11); const Vector128 o13 = AesRound(e12, s13); const Vector128 o15 = AesRound(e14, s15); Vector128Store(o1, state + 1); Vector128Store(o3, state + 3); Vector128Store(o5, state + 5); Vector128Store(o7, state + 7); Vector128Store(o9, state + 9); Vector128Store(o11, state + 11); Vector128Store(o13, state + 13); Vector128Store(o15, state + 15); return keys + 8; } inline ABSL_TARGET_CRYPTO void Permute( absl::uint128* state, const absl::uint128* ABSL_RANDOM_INTERNAL_RESTRICT keys) { #ifdef __clang__ #pragma clang loop unroll_count(2) #endif for (size_t round = 0; round < RandenTraits::kFeistelRounds; ++round) { keys = FeistelRound(state, keys); BlockShuffle(state); } } } namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { bool HasRandenHwAesImplementation() { return true; } const void* ABSL_TARGET_CRYPTO RandenHwAes::GetKeys() { #if defined(ABSL_ARCH_PPC) return kRandenRoundKeysBE; #else return kRandenRoundKeys; #endif } void ABSL_TARGET_CRYPTO RandenHwAes::Absorb(const void* seed_void, void* state_void) { static_assert(RandenTraits::kCapacityBytes / sizeof(Vector128) == 1, "Unexpected Randen kCapacityBlocks"); static_assert(RandenTraits::kStateBytes / sizeof(Vector128) == 16, "Unexpected Randen kStateBlocks"); auto* state = reinterpret_cast<absl::uint128 * ABSL_RANDOM_INTERNAL_RESTRICT>( state_void); const auto* seed = reinterpret_cast<const absl::uint128 * ABSL_RANDOM_INTERNAL_RESTRICT>( seed_void); Vector128 b1 = Vector128Load(state + 1); b1 ^= Vector128Load(seed + 0); Vector128Store(b1, state + 1); Vector128 b2 = Vector128Load(state + 2); b2 ^= Vector128Load(seed + 1); Vector128Store(b2, state + 2); Vector128 b3 = Vector128Load(state + 3); b3 ^= Vector128Load(seed + 2); Vector128Store(b3, state + 3); Vector128 b4 = Vector128Load(state + 4); b4 ^= Vector128Load(seed + 3); Vector128Store(b4, state + 4); Vector128 b5 = Vector128Load(state + 5); b5 ^= Vector128Load(seed + 4); Vector128Store(b5, state + 5); Vector128 b6 = Vector128Load(state + 6); b6 ^= Vector128Load(seed + 5); Vector128Store(b6, state + 6); Vector128 b7 = Vector128Load(state + 7); b7 ^= Vector128Load(seed + 6); Vector128Store(b7, state + 7); Vector128 b8 = Vector128Load(state + 8); b8 ^= Vector128Load(seed + 7); Vector128Store(b8, state + 8); Vector128 b9 = Vector128Load(state + 9); b9 ^= Vector128Load(seed + 8); Vector128Store(b9, state + 9); Vector128 b10 = Vector128Load(state + 10); b10 ^= Vector128Load(seed + 9); Vector128Store(b10, state + 10); Vector128 b11 = Vector128Load(state + 11); b11 ^= Vector128Load(seed + 10); Vector128Store(b11, state + 11); Vector128 b12 = Vector128Load(state + 12); b12 ^= Vector128Load(seed + 11); Vector128Store(b12, state + 12); Vector128 b13 = Vector128Load(state + 13); b13 ^= Vector128Load(seed + 12); Vector128Store(b13, state + 13); Vector128 b14 = Vector128Load(state + 14); b14 ^= Vector128Load(seed + 13); Vector128Store(b14, state + 14); Vector128 b15 = Vector128Load(state + 15); b15 ^= Vector128Load(seed + 14); Vector128Store(b15, state + 15); } void ABSL_TARGET_CRYPTO RandenHwAes::Generate(const void* keys_void, void* state_void) { static_assert(RandenTraits::kCapacityBytes == sizeof(Vector128), "Capacity mismatch"); auto* state = reinterpret_cast<absl::uint128*>(state_void); const auto* keys = reinterpret_cast<const absl::uint128*>(keys_void); const Vector128 prev_inner = Vector128Load(state); SwapEndian(state); Permute(state, keys); SwapEndian(state); Vector128 inner = Vector128Load(state); inner ^= prev_inner; Vector128Store(inner, state); } #ifdef __clang__ #pragma clang diagnostic pop #endif } ABSL_NAMESPACE_END } #endif
#include "absl/random/internal/randen_hwaes.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/log/log.h" #include "absl/random/internal/platform.h" #include "absl/random/internal/randen_detect.h" #include "absl/random/internal/randen_traits.h" #include "absl/strings/str_format.h" namespace { using absl::random_internal::RandenHwAes; using absl::random_internal::RandenTraits; TEST(RandenHwAesTest, Default) { EXPECT_TRUE(absl::random_internal::CPUSupportsRandenHwAes()); constexpr uint8_t kGolden[] = { 0xee, 0xd3, 0xe6, 0x0e, 0x09, 0x34, 0x65, 0x6c, 0xc6, 0x33, 0x53, 0x9d, 0x9b, 0x2b, 0x4e, 0x04, 0x77, 0x39, 0x43, 0x4e, 0x13, 0x4f, 0xc1, 0xc3, 0xee, 0x10, 0x04, 0xd9, 0x7c, 0xf4, 0xa9, 0xdd, 0x10, 0xca, 0xd8, 0x7f, 0x08, 0xf3, 0x7b, 0x88, 0x12, 0x29, 0xc7, 0x45, 0xf5, 0x80, 0xb7, 0xf0, 0x9f, 0x59, 0x96, 0x76, 0xd3, 0xb1, 0xdb, 0x15, 0x59, 0x6d, 0x3c, 0xff, 0xba, 0x63, 0xec, 0x30, 0xa6, 0x20, 0x7f, 0x6f, 0x60, 0x73, 0x9f, 0xb2, 0x4c, 0xa5, 0x49, 0x6f, 0x31, 0x8a, 0x80, 0x02, 0x0e, 0xe5, 0xc8, 0xd5, 0xf9, 0xea, 0x8f, 0x3b, 0x8a, 0xde, 0xd9, 0x3f, 0x5e, 0x60, 0xbf, 0x9c, 0xbb, 0x3b, 0x18, 0x78, 0x1a, 0xae, 0x70, 0xc9, 0xd5, 0x1e, 0x30, 0x56, 0xd3, 0xff, 0xb2, 0xd8, 0x37, 0x3c, 0xc7, 0x0f, 0xfe, 0x27, 0xb3, 0xf4, 0x19, 0x9a, 0x8f, 0xeb, 0x76, 0x8d, 0xfd, 0xcd, 0x9d, 0x0c, 0x42, 0x91, 0xeb, 0x06, 0xa5, 0xc3, 0x56, 0x95, 0xff, 0x3e, 0xdd, 0x05, 0xaf, 0xd5, 0xa1, 0xc4, 0x83, 0x8f, 0xb7, 0x1b, 0xdb, 0x48, 0x8c, 0xfe, 0x6b, 0x0d, 0x0e, 0x92, 0x23, 0x70, 0x42, 0x6d, 0x95, 0x34, 0x58, 0x57, 0xd3, 0x58, 0x40, 0xb8, 0x87, 0x6b, 0xc2, 0xf4, 0x1e, 0xed, 0xf3, 0x2d, 0x0b, 0x3e, 0xa2, 0x32, 0xef, 0x8e, 0xfc, 0x54, 0x11, 0x43, 0xf3, 0xab, 0x7c, 0x49, 0x8b, 0x9a, 0x02, 0x70, 0x05, 0x37, 0x24, 0x4e, 0xea, 0xe5, 0x90, 0xf0, 0x49, 0x57, 0x8b, 0xd8, 0x2f, 0x69, 0x70, 0xa9, 0x82, 0xa5, 0x51, 0xc6, 0xf5, 0x42, 0x63, 0xbb, 0x2c, 0xec, 0xfc, 0x78, 0xdb, 0x55, 0x2f, 0x61, 0x45, 0xb7, 0x3c, 0x46, 0xe3, 0xaf, 0x16, 0x18, 0xad, 0xe4, 0x2e, 0x35, 0x7e, 0xda, 0x01, 0xc1, 0x74, 0xf3, 0x6f, 0x02, 0x51, 0xe8, 0x3d, 0x1c, 0x82, 0xf0, 0x1e, 0x81, }; alignas(16) uint8_t state[RandenTraits::kStateBytes]; std::memset(state, 0, sizeof(state)); RandenHwAes::Generate(RandenHwAes::GetKeys(), state); EXPECT_EQ(0, std::memcmp(state, kGolden, sizeof(state))); } } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); LOG(INFO) << "ABSL_HAVE_ACCELERATED_AES=" << ABSL_HAVE_ACCELERATED_AES; LOG(INFO) << "ABSL_RANDOM_INTERNAL_AES_DISPATCH=" << ABSL_RANDOM_INTERNAL_AES_DISPATCH; #if defined(ABSL_ARCH_X86_64) LOG(INFO) << "ABSL_ARCH_X86_64"; #elif defined(ABSL_ARCH_X86_32) LOG(INFO) << "ABSL_ARCH_X86_32"; #elif defined(ABSL_ARCH_AARCH64) LOG(INFO) << "ABSL_ARCH_AARCH64"; #elif defined(ABSL_ARCH_ARM) LOG(INFO) << "ABSL_ARCH_ARM"; #elif defined(ABSL_ARCH_PPC) LOG(INFO) << "ABSL_ARCH_PPC"; #else LOG(INFO) << "ARCH Unknown"; #endif int x = absl::random_internal::HasRandenHwAesImplementation(); LOG(INFO) << "HasRandenHwAesImplementation = " << x; int y = absl::random_internal::CPUSupportsRandenHwAes(); LOG(INFO) << "CPUSupportsRandenHwAes = " << x; if (!x || !y) { LOG(INFO) << "Skipping Randen HWAES tests."; return 0; } return RUN_ALL_TESTS(); }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/randen_hwaes.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/randen_hwaes_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
b72f667a-24cd-4daf-9d39-213b23b9b095
cpp
abseil/abseil-cpp
pool_urbg
absl/random/internal/pool_urbg.cc
absl/random/internal/pool_urbg_test.cc
#include "absl/random/internal/pool_urbg.h" #include <algorithm> #include <atomic> #include <cstdint> #include <cstring> #include <iterator> #include "absl/base/attributes.h" #include "absl/base/call_once.h" #include "absl/base/config.h" #include "absl/base/internal/endian.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/spinlock.h" #include "absl/base/internal/sysinfo.h" #include "absl/base/internal/unaligned_access.h" #include "absl/base/optimization.h" #include "absl/random/internal/randen.h" #include "absl/random/internal/seed_material.h" #include "absl/random/seed_gen_exception.h" using absl::base_internal::SpinLock; using absl::base_internal::SpinLockHolder; namespace absl { ABSL_NAMESPACE_BEGIN namespace random_internal { namespace { class RandenPoolEntry { public: static constexpr size_t kState = RandenTraits::kStateBytes / sizeof(uint32_t); static constexpr size_t kCapacity = RandenTraits::kCapacityBytes / sizeof(uint32_t); void Init(absl::Span<const uint32_t> data) { SpinLockHolder l(&mu_); std::copy(data.begin(), data.end(), std::begin(state_)); next_ = kState; } void Fill(uint8_t* out, size_t bytes) ABSL_LOCKS_EXCLUDED(mu_); template <typename T> inline T Generate() ABSL_LOCKS_EXCLUDED(mu_); inline void MaybeRefill() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) { if (next_ >= kState) { next_ = kCapacity; impl_.Generate(state_); } } private: uint32_t state_[kState] ABSL_GUARDED_BY(mu_); SpinLock mu_; const Randen impl_; size_t next_ ABSL_GUARDED_BY(mu_); }; template <> inline uint8_t RandenPoolEntry::Generate<uint8_t>() { SpinLockHolder l(&mu_); MaybeRefill(); return static_cast<uint8_t>(state_[next_++]); } template <> inline uint16_t RandenPoolEntry::Generate<uint16_t>() { SpinLockHolder l(&mu_); MaybeRefill(); return static_cast<uint16_t>(state_[next_++]); } template <> inline uint32_t RandenPoolEntry::Generate<uint32_t>() { SpinLockHolder l(&mu_); MaybeRefill(); return state_[next_++]; } template <> inline uint64_t RandenPoolEntry::Generate<uint64_t>() { SpinLockHolder l(&mu_); if (next_ >= kState - 1) { next_ = kCapacity; impl_.Generate(state_); } auto p = state_ + next_; next_ += 2; uint64_t result; std::memcpy(&result, p, sizeof(result)); return result; } void RandenPoolEntry::Fill(uint8_t* out, size_t bytes) { SpinLockHolder l(&mu_); while (bytes > 0) { MaybeRefill(); size_t remaining = (kState - next_) * sizeof(state_[0]); size_t to_copy = std::min(bytes, remaining); std::memcpy(out, &state_[next_], to_copy); out += to_copy; bytes -= to_copy; next_ += (to_copy + sizeof(state_[0]) - 1) / sizeof(state_[0]); } } static constexpr size_t kPoolSize = 8; static absl::once_flag pool_once; ABSL_CACHELINE_ALIGNED static RandenPoolEntry* shared_pools[kPoolSize]; size_t GetPoolID() { static_assert(kPoolSize >= 1, "At least one urbg instance is required for PoolURBG"); ABSL_CONST_INIT static std::atomic<uint64_t> sequence{0}; #ifdef ABSL_HAVE_THREAD_LOCAL static thread_local size_t my_pool_id = kPoolSize; if (ABSL_PREDICT_FALSE(my_pool_id == kPoolSize)) { my_pool_id = (sequence++ % kPoolSize); } return my_pool_id; #else static pthread_key_t tid_key = [] { pthread_key_t tmp_key; int err = pthread_key_create(&tmp_key, nullptr); if (err) { ABSL_RAW_LOG(FATAL, "pthread_key_create failed with %d", err); } return tmp_key; }(); uintptr_t my_pool_id = reinterpret_cast<uintptr_t>(pthread_getspecific(tid_key)); if (ABSL_PREDICT_FALSE(my_pool_id == 0)) { my_pool_id = (sequence++ % kPoolSize) + 1; int err = pthread_setspecific(tid_key, reinterpret_cast<void*>(my_pool_id)); if (err) { ABSL_RAW_LOG(FATAL, "pthread_setspecific failed with %d", err); } } return my_pool_id - 1; #endif } RandenPoolEntry* PoolAlignedAlloc() { constexpr size_t kAlignment = ABSL_CACHELINE_SIZE > 32 ? ABSL_CACHELINE_SIZE : 32; uintptr_t x = reinterpret_cast<uintptr_t>( new char[sizeof(RandenPoolEntry) + kAlignment]); auto y = x % kAlignment; void* aligned = reinterpret_cast<void*>(y == 0 ? x : (x + kAlignment - y)); return new (aligned) RandenPoolEntry(); } void InitPoolURBG() { static constexpr size_t kSeedSize = RandenTraits::kStateBytes / sizeof(uint32_t); uint32_t seed_material[kPoolSize * kSeedSize]; if (!random_internal::ReadSeedMaterialFromOSEntropy( absl::MakeSpan(seed_material))) { random_internal::ThrowSeedGenException(); } for (size_t i = 0; i < kPoolSize; i++) { shared_pools[i] = PoolAlignedAlloc(); shared_pools[i]->Init( absl::MakeSpan(&seed_material[i * kSeedSize], kSeedSize)); } } RandenPoolEntry* GetPoolForCurrentThread() { absl::call_once(pool_once, InitPoolURBG); return shared_pools[GetPoolID()]; } } template <typename T> typename RandenPool<T>::result_type RandenPool<T>::Generate() { auto* pool = GetPoolForCurrentThread(); return pool->Generate<T>(); } template <typename T> void RandenPool<T>::Fill(absl::Span<result_type> data) { auto* pool = GetPoolForCurrentThread(); pool->Fill(reinterpret_cast<uint8_t*>(data.data()), data.size() * sizeof(result_type)); } template class RandenPool<uint8_t>; template class RandenPool<uint16_t>; template class RandenPool<uint32_t>; template class RandenPool<uint64_t>; } ABSL_NAMESPACE_END }
#include "absl/random/internal/pool_urbg.h" #include <algorithm> #include <bitset> #include <cmath> #include <cstdint> #include <iterator> #include "gtest/gtest.h" #include "absl/meta/type_traits.h" #include "absl/types/span.h" using absl::random_internal::PoolURBG; using absl::random_internal::RandenPool; namespace { template <typename T> using is_randen_pool = typename absl::disjunction< std::is_same<T, RandenPool<uint8_t>>, std::is_same<T, RandenPool<uint16_t>>, std::is_same<T, RandenPool<uint32_t>>, std::is_same<T, RandenPool<uint64_t>>>; template <typename T, typename V> typename absl::enable_if_t<absl::negation<is_randen_pool<T>>::value, void> MyFill(T& rng, absl::Span<V> data) { std::generate(std::begin(data), std::end(data), rng); } template <typename T, typename V> typename absl::enable_if_t<is_randen_pool<T>::value, void> MyFill(T& rng, absl::Span<V> data) { rng.Fill(data); } template <typename EngineType> class PoolURBGTypedTest : public ::testing::Test {}; using EngineTypes = ::testing::Types< RandenPool<uint8_t>, RandenPool<uint16_t>, RandenPool<uint32_t>, RandenPool<uint64_t>, PoolURBG<uint8_t, 2>, PoolURBG<uint16_t, 2>, PoolURBG<uint32_t, 2>, PoolURBG<uint64_t, 2>, PoolURBG<unsigned int, 8>, PoolURBG<unsigned long, 8>, PoolURBG<unsigned long int, 4>, PoolURBG<unsigned long long, 4>>; TYPED_TEST_SUITE(PoolURBGTypedTest, EngineTypes); TYPED_TEST(PoolURBGTypedTest, URBGInterface) { using E = TypeParam; using T = typename E::result_type; static_assert(std::is_copy_constructible<E>::value, "engine must be copy constructible"); static_assert(absl::is_copy_assignable<E>::value, "engine must be copy assignable"); E e; const E x; e(); static_assert(std::is_same<decltype(e()), T>::value, "return type of operator() must be result_type"); E u0(x); u0(); E u1 = e; u1(); } TYPED_TEST(PoolURBGTypedTest, VerifySequences) { using E = TypeParam; using result_type = typename E::result_type; E rng; (void)rng(); constexpr int kNumOutputs = 64; result_type a[kNumOutputs]; result_type b[kNumOutputs]; std::fill(std::begin(b), std::end(b), 0); { E x = rng; MyFill(x, absl::MakeSpan(a)); } { E x = rng; std::generate(std::begin(b), std::end(b), x); } size_t changed_bits = 0; size_t unchanged_bits = 0; size_t total_set = 0; size_t total_bits = 0; size_t equal_count = 0; for (size_t i = 0; i < kNumOutputs; ++i) { equal_count += (a[i] == b[i]) ? 1 : 0; std::bitset<sizeof(result_type) * 8> bitset(a[i] ^ b[i]); changed_bits += bitset.count(); unchanged_bits += bitset.size() - bitset.count(); std::bitset<sizeof(result_type) * 8> a_set(a[i]); std::bitset<sizeof(result_type) * 8> b_set(b[i]); total_set += a_set.count() + b_set.count(); total_bits += 2 * 8 * sizeof(result_type); } EXPECT_LE(changed_bits, 0.60 * (changed_bits + unchanged_bits)); EXPECT_GE(changed_bits, 0.40 * (changed_bits + unchanged_bits)); EXPECT_NEAR(total_set, total_bits * 0.5, 4 * std::sqrt(total_bits)) << "@" << total_set / static_cast<double>(total_bits); const double kExpected = kNumOutputs / (1.0 * sizeof(result_type) * 8); EXPECT_LE(equal_count, 1.0 + kExpected); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/pool_urbg.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/random/internal/pool_urbg_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
d20b59d0-6eb9-4929-88d1-5a612e569453
cpp
abseil/abseil-cpp
log_severity
absl/base/log_severity.cc
absl/base/log_severity_test.cc
#include "absl/base/log_severity.h" #include <ostream> #include "absl/base/attributes.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN std::ostream& operator<<(std::ostream& os, absl::LogSeverity s) { if (s == absl::NormalizeLogSeverity(s)) return os << absl::LogSeverityName(s); return os << "absl::LogSeverity(" << static_cast<int>(s) << ")"; } std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtLeast s) { switch (s) { case absl::LogSeverityAtLeast::kInfo: case absl::LogSeverityAtLeast::kWarning: case absl::LogSeverityAtLeast::kError: case absl::LogSeverityAtLeast::kFatal: return os << ">=" << static_cast<absl::LogSeverity>(s); case absl::LogSeverityAtLeast::kInfinity: return os << "INFINITY"; } return os; } std::ostream& operator<<(std::ostream& os, absl::LogSeverityAtMost s) { switch (s) { case absl::LogSeverityAtMost::kInfo: case absl::LogSeverityAtMost::kWarning: case absl::LogSeverityAtMost::kError: case absl::LogSeverityAtMost::kFatal: return os << "<=" << static_cast<absl::LogSeverity>(s); case absl::LogSeverityAtMost::kNegativeInfinity: return os << "NEGATIVE_INFINITY"; } return os; } ABSL_NAMESPACE_END }
#include "absl/base/log_severity.h" #include <cstdint> #include <ios> #include <limits> #include <ostream> #include <sstream> #include <string> #include <tuple> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/flags/internal/flag.h" #include "absl/flags/marshalling.h" #include "absl/strings/str_cat.h" namespace { using ::testing::Eq; using ::testing::IsFalse; using ::testing::IsTrue; using ::testing::TestWithParam; using ::testing::Values; template <typename T> std::string StreamHelper(T value) { std::ostringstream stream; stream << value; return stream.str(); } TEST(StreamTest, Works) { EXPECT_THAT(StreamHelper(static_cast<absl::LogSeverity>(-100)), Eq("absl::LogSeverity(-100)")); EXPECT_THAT(StreamHelper(absl::LogSeverity::kInfo), Eq("INFO")); EXPECT_THAT(StreamHelper(absl::LogSeverity::kWarning), Eq("WARNING")); EXPECT_THAT(StreamHelper(absl::LogSeverity::kError), Eq("ERROR")); EXPECT_THAT(StreamHelper(absl::LogSeverity::kFatal), Eq("FATAL")); EXPECT_THAT(StreamHelper(static_cast<absl::LogSeverity>(4)), Eq("absl::LogSeverity(4)")); } static_assert(absl::flags_internal::FlagUseValueAndInitBitStorage< absl::LogSeverity>::value, "Flags of type absl::LogSeverity ought to be lock-free."); using ParseFlagFromOutOfRangeIntegerTest = TestWithParam<int64_t>; INSTANTIATE_TEST_SUITE_P( Instantiation, ParseFlagFromOutOfRangeIntegerTest, Values(static_cast<int64_t>(std::numeric_limits<int>::min()) - 1, static_cast<int64_t>(std::numeric_limits<int>::max()) + 1)); TEST_P(ParseFlagFromOutOfRangeIntegerTest, ReturnsError) { const std::string to_parse = absl::StrCat(GetParam()); absl::LogSeverity value; std::string error; EXPECT_THAT(absl::ParseFlag(to_parse, &value, &error), IsFalse()) << value; } using ParseFlagFromAlmostOutOfRangeIntegerTest = TestWithParam<int>; INSTANTIATE_TEST_SUITE_P(Instantiation, ParseFlagFromAlmostOutOfRangeIntegerTest, Values(std::numeric_limits<int>::min(), std::numeric_limits<int>::max())); TEST_P(ParseFlagFromAlmostOutOfRangeIntegerTest, YieldsExpectedValue) { const auto expected = static_cast<absl::LogSeverity>(GetParam()); const std::string to_parse = absl::StrCat(GetParam()); absl::LogSeverity value; std::string error; ASSERT_THAT(absl::ParseFlag(to_parse, &value, &error), IsTrue()) << error; EXPECT_THAT(value, Eq(expected)); } using ParseFlagFromIntegerMatchingEnumeratorTest = TestWithParam<std::tuple<absl::string_view, absl::LogSeverity>>; INSTANTIATE_TEST_SUITE_P( Instantiation, ParseFlagFromIntegerMatchingEnumeratorTest, Values(std::make_tuple("0", absl::LogSeverity::kInfo), std::make_tuple(" 0", absl::LogSeverity::kInfo), std::make_tuple("-0", absl::LogSeverity::kInfo), std::make_tuple("+0", absl::LogSeverity::kInfo), std::make_tuple("00", absl::LogSeverity::kInfo), std::make_tuple("0 ", absl::LogSeverity::kInfo), std::make_tuple("0x0", absl::LogSeverity::kInfo), std::make_tuple("1", absl::LogSeverity::kWarning), std::make_tuple("+1", absl::LogSeverity::kWarning), std::make_tuple("2", absl::LogSeverity::kError), std::make_tuple("3", absl::LogSeverity::kFatal))); TEST_P(ParseFlagFromIntegerMatchingEnumeratorTest, YieldsExpectedValue) { const absl::string_view to_parse = std::get<0>(GetParam()); const absl::LogSeverity expected = std::get<1>(GetParam()); absl::LogSeverity value; std::string error; ASSERT_THAT(absl::ParseFlag(to_parse, &value, &error), IsTrue()) << error; EXPECT_THAT(value, Eq(expected)); } using ParseFlagFromOtherIntegerTest = TestWithParam<std::tuple<absl::string_view, int>>; INSTANTIATE_TEST_SUITE_P(Instantiation, ParseFlagFromOtherIntegerTest, Values(std::make_tuple("-1", -1), std::make_tuple("4", 4), std::make_tuple("010", 10), std::make_tuple("0x10", 16))); TEST_P(ParseFlagFromOtherIntegerTest, YieldsExpectedValue) { const absl::string_view to_parse = std::get<0>(GetParam()); const auto expected = static_cast<absl::LogSeverity>(std::get<1>(GetParam())); absl::LogSeverity value; std::string error; ASSERT_THAT(absl::ParseFlag(to_parse, &value, &error), IsTrue()) << error; EXPECT_THAT(value, Eq(expected)); } using ParseFlagFromEnumeratorTest = TestWithParam<std::tuple<absl::string_view, absl::LogSeverity>>; INSTANTIATE_TEST_SUITE_P( Instantiation, ParseFlagFromEnumeratorTest, Values(std::make_tuple("INFO", absl::LogSeverity::kInfo), std::make_tuple("info", absl::LogSeverity::kInfo), std::make_tuple("kInfo", absl::LogSeverity::kInfo), std::make_tuple("iNfO", absl::LogSeverity::kInfo), std::make_tuple("kInFo", absl::LogSeverity::kInfo), std::make_tuple("WARNING", absl::LogSeverity::kWarning), std::make_tuple("warning", absl::LogSeverity::kWarning), std::make_tuple("kWarning", absl::LogSeverity::kWarning), std::make_tuple("WaRnInG", absl::LogSeverity::kWarning), std::make_tuple("KwArNiNg", absl::LogSeverity::kWarning), std::make_tuple("ERROR", absl::LogSeverity::kError), std::make_tuple("error", absl::LogSeverity::kError), std::make_tuple("kError", absl::LogSeverity::kError), std::make_tuple("eRrOr", absl::LogSeverity::kError), std::make_tuple("kErRoR", absl::LogSeverity::kError), std::make_tuple("FATAL", absl::LogSeverity::kFatal), std::make_tuple("fatal", absl::LogSeverity::kFatal), std::make_tuple("kFatal", absl::LogSeverity::kFatal), std::make_tuple("FaTaL", absl::LogSeverity::kFatal), std::make_tuple("KfAtAl", absl::LogSeverity::kFatal), std::make_tuple("DFATAL", absl::kLogDebugFatal), std::make_tuple("dfatal", absl::kLogDebugFatal), std::make_tuple("kLogDebugFatal", absl::kLogDebugFatal), std::make_tuple("dFaTaL", absl::kLogDebugFatal), std::make_tuple("kLoGdEbUgFaTaL", absl::kLogDebugFatal))); TEST_P(ParseFlagFromEnumeratorTest, YieldsExpectedValue) { const absl::string_view to_parse = std::get<0>(GetParam()); const absl::LogSeverity expected = std::get<1>(GetParam()); absl::LogSeverity value; std::string error; ASSERT_THAT(absl::ParseFlag(to_parse, &value, &error), IsTrue()) << error; EXPECT_THAT(value, Eq(expected)); } using ParseFlagFromGarbageTest = TestWithParam<absl::string_view>; INSTANTIATE_TEST_SUITE_P(Instantiation, ParseFlagFromGarbageTest, Values("", "\0", " ", "garbage", "kkinfo", "I", "kDFATAL", "LogDebugFatal", "lOgDeBuGfAtAl")); TEST_P(ParseFlagFromGarbageTest, ReturnsError) { const absl::string_view to_parse = GetParam(); absl::LogSeverity value; std::string error; EXPECT_THAT(absl::ParseFlag(to_parse, &value, &error), IsFalse()) << value; } using UnparseFlagToEnumeratorTest = TestWithParam<std::tuple<absl::LogSeverity, absl::string_view>>; INSTANTIATE_TEST_SUITE_P( Instantiation, UnparseFlagToEnumeratorTest, Values(std::make_tuple(absl::LogSeverity::kInfo, "INFO"), std::make_tuple(absl::LogSeverity::kWarning, "WARNING"), std::make_tuple(absl::LogSeverity::kError, "ERROR"), std::make_tuple(absl::LogSeverity::kFatal, "FATAL"))); TEST_P(UnparseFlagToEnumeratorTest, ReturnsExpectedValueAndRoundTrips) { const absl::LogSeverity to_unparse = std::get<0>(GetParam()); const absl::string_view expected = std::get<1>(GetParam()); const std::string stringified_value = absl::UnparseFlag(to_unparse); EXPECT_THAT(stringified_value, Eq(expected)); absl::LogSeverity reparsed_value; std::string error; EXPECT_THAT(absl::ParseFlag(stringified_value, &reparsed_value, &error), IsTrue()); EXPECT_THAT(reparsed_value, Eq(to_unparse)); } using UnparseFlagToOtherIntegerTest = TestWithParam<int>; INSTANTIATE_TEST_SUITE_P(Instantiation, UnparseFlagToOtherIntegerTest, Values(std::numeric_limits<int>::min(), -1, 4, std::numeric_limits<int>::max())); TEST_P(UnparseFlagToOtherIntegerTest, ReturnsExpectedValueAndRoundTrips) { const absl::LogSeverity to_unparse = static_cast<absl::LogSeverity>(GetParam()); const std::string expected = absl::StrCat(GetParam()); const std::string stringified_value = absl::UnparseFlag(to_unparse); EXPECT_THAT(stringified_value, Eq(expected)); absl::LogSeverity reparsed_value; std::string error; EXPECT_THAT(absl::ParseFlag(stringified_value, &reparsed_value, &error), IsTrue()); EXPECT_THAT(reparsed_value, Eq(to_unparse)); } TEST(LogThresholdTest, LogSeverityAtLeastTest) { EXPECT_LT(absl::LogSeverity::kError, absl::LogSeverityAtLeast::kFatal); EXPECT_GT(absl::LogSeverityAtLeast::kError, absl::LogSeverity::kInfo); EXPECT_LE(absl::LogSeverityAtLeast::kInfo, absl::LogSeverity::kError); EXPECT_GE(absl::LogSeverity::kError, absl::LogSeverityAtLeast::kInfo); } TEST(LogThresholdTest, LogSeverityAtMostTest) { EXPECT_GT(absl::LogSeverity::kError, absl::LogSeverityAtMost::kWarning); EXPECT_LT(absl::LogSeverityAtMost::kError, absl::LogSeverity::kFatal); EXPECT_GE(absl::LogSeverityAtMost::kFatal, absl::LogSeverity::kError); EXPECT_LE(absl::LogSeverity::kWarning, absl::LogSeverityAtMost::kError); } TEST(LogThresholdTest, Extremes) { EXPECT_LT(absl::LogSeverity::kFatal, absl::LogSeverityAtLeast::kInfinity); EXPECT_GT(absl::LogSeverity::kInfo, absl::LogSeverityAtMost::kNegativeInfinity); } TEST(LogThresholdTest, Output) { EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kInfo), Eq(">=INFO")); EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kWarning), Eq(">=WARNING")); EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kError), Eq(">=ERROR")); EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kFatal), Eq(">=FATAL")); EXPECT_THAT(StreamHelper(absl::LogSeverityAtLeast::kInfinity), Eq("INFINITY")); EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kInfo), Eq("<=INFO")); EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kWarning), Eq("<=WARNING")); EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kError), Eq("<=ERROR")); EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kFatal), Eq("<=FATAL")); EXPECT_THAT(StreamHelper(absl::LogSeverityAtMost::kNegativeInfinity), Eq("NEGATIVE_INFINITY")); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/log_severity.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/log_severity_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
e819cfb7-a025-47d3-82e8-885348ab9d1c
cpp
abseil/abseil-cpp
scoped_set_env
absl/base/internal/scoped_set_env.cc
absl/base/internal/scoped_set_env_test.cc
#include "absl/base/internal/scoped_set_env.h" #ifdef _WIN32 #include <windows.h> #endif #include <cstdlib> #include "absl/base/internal/raw_logging.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { namespace { #ifdef _WIN32 const int kMaxEnvVarValueSize = 1024; #endif void SetEnvVar(const char* name, const char* value) { #ifdef _WIN32 SetEnvironmentVariableA(name, value); #else if (value == nullptr) { ::unsetenv(name); } else { ::setenv(name, value, 1); } #endif } } ScopedSetEnv::ScopedSetEnv(const char* var_name, const char* new_value) : var_name_(var_name), was_unset_(false) { #ifdef _WIN32 char buf[kMaxEnvVarValueSize]; auto get_res = GetEnvironmentVariableA(var_name_.c_str(), buf, sizeof(buf)); ABSL_INTERNAL_CHECK(get_res < sizeof(buf), "value exceeds buffer size"); if (get_res == 0) { was_unset_ = (GetLastError() == ERROR_ENVVAR_NOT_FOUND); } else { old_value_.assign(buf, get_res); } SetEnvironmentVariableA(var_name_.c_str(), new_value); #else const char* val = ::getenv(var_name_.c_str()); if (val == nullptr) { was_unset_ = true; } else { old_value_ = val; } #endif SetEnvVar(var_name_.c_str(), new_value); } ScopedSetEnv::~ScopedSetEnv() { SetEnvVar(var_name_.c_str(), was_unset_ ? nullptr : old_value_.c_str()); } } ABSL_NAMESPACE_END }
#ifdef _WIN32 #include <windows.h> #endif #include "gtest/gtest.h" #include "absl/base/internal/scoped_set_env.h" namespace { using absl::base_internal::ScopedSetEnv; std::string GetEnvVar(const char* name) { #ifdef _WIN32 char buf[1024]; auto get_res = GetEnvironmentVariableA(name, buf, sizeof(buf)); if (get_res >= sizeof(buf)) { return "TOO_BIG"; } if (get_res == 0) { return "UNSET"; } return std::string(buf, get_res); #else const char* val = ::getenv(name); if (val == nullptr) { return "UNSET"; } return val; #endif } TEST(ScopedSetEnvTest, SetNonExistingVarToString) { EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET"); { ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "value"); EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value"); } EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET"); } TEST(ScopedSetEnvTest, SetNonExistingVarToNull) { EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET"); { ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", nullptr); EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET"); } EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET"); } TEST(ScopedSetEnvTest, SetExistingVarToString) { ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "value"); EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value"); { ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "new_value"); EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "new_value"); } EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value"); } TEST(ScopedSetEnvTest, SetExistingVarToNull) { ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", "value"); EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value"); { ScopedSetEnv scoped_set("SCOPED_SET_ENV_TEST_VAR", nullptr); EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "UNSET"); } EXPECT_EQ(GetEnvVar("SCOPED_SET_ENV_TEST_VAR"), "value"); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/scoped_set_env.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/scoped_set_env_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
ca36bd5b-bb69-404b-a7e1-93b19435d268
cpp
abseil/abseil-cpp
sysinfo
absl/base/internal/sysinfo.cc
absl/base/internal/sysinfo_test.cc
#include "absl/base/internal/sysinfo.h" #include "absl/base/attributes.h" #ifdef _WIN32 #include <windows.h> #else #include <fcntl.h> #include <pthread.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #endif #ifdef __linux__ #include <sys/syscall.h> #endif #if defined(__APPLE__) || defined(__FreeBSD__) #include <sys/sysctl.h> #endif #ifdef __FreeBSD__ #include <pthread_np.h> #endif #ifdef __NetBSD__ #include <lwp.h> #endif #if defined(__myriad2__) #include <rtems.h> #endif #if defined(__Fuchsia__) #include <zircon/process.h> #endif #include <string.h> #include <cassert> #include <cerrno> #include <cstdint> #include <cstdio> #include <cstdlib> #include <ctime> #include <limits> #include <thread> #include <utility> #include <vector> #include "absl/base/call_once.h" #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/spinlock.h" #include "absl/base/internal/unscaledcycleclock.h" #include "absl/base/thread_annotations.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { namespace { #if defined(_WIN32) DWORD Win32CountSetBits(ULONG_PTR bitMask) { for (DWORD bitSetCount = 0; ; ++bitSetCount) { if (bitMask == 0) return bitSetCount; bitMask &= bitMask - 1; } } int Win32NumCPUs() { #pragma comment(lib, "kernel32.lib") using Info = SYSTEM_LOGICAL_PROCESSOR_INFORMATION; DWORD info_size = sizeof(Info); Info* info(static_cast<Info*>(malloc(info_size))); if (info == nullptr) return 0; bool success = GetLogicalProcessorInformation(info, &info_size); if (!success && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { free(info); info = static_cast<Info*>(malloc(info_size)); if (info == nullptr) return 0; success = GetLogicalProcessorInformation(info, &info_size); } DWORD logicalProcessorCount = 0; if (success) { Info* ptr = info; DWORD byteOffset = 0; while (byteOffset + sizeof(Info) <= info_size) { switch (ptr->Relationship) { case RelationProcessorCore: logicalProcessorCount += Win32CountSetBits(ptr->ProcessorMask); break; case RelationNumaNode: case RelationCache: case RelationProcessorPackage: break; default: break; } byteOffset += sizeof(Info); ptr++; } } free(info); return static_cast<int>(logicalProcessorCount); } #endif } static int GetNumCPUs() { #if defined(__myriad2__) return 1; #elif defined(_WIN32) const int hardware_concurrency = Win32NumCPUs(); return hardware_concurrency ? hardware_concurrency : 1; #elif defined(_AIX) return sysconf(_SC_NPROCESSORS_ONLN); #else return static_cast<int>(std::thread::hardware_concurrency()); #endif } #if defined(_WIN32) static double GetNominalCPUFrequency() { #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \ !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) return 1.0; #else #pragma comment(lib, "advapi32.lib") HKEY key; if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &key) == ERROR_SUCCESS) { DWORD type = 0; DWORD data = 0; DWORD data_size = sizeof(data); auto result = RegQueryValueExA(key, "~MHz", nullptr, &type, reinterpret_cast<LPBYTE>(&data), &data_size); RegCloseKey(key); if (result == ERROR_SUCCESS && type == REG_DWORD && data_size == sizeof(data)) { return data * 1e6; } } return 1.0; #endif } #elif defined(CTL_HW) && defined(HW_CPU_FREQ) static double GetNominalCPUFrequency() { unsigned freq; size_t size = sizeof(freq); int mib[2] = {CTL_HW, HW_CPU_FREQ}; if (sysctl(mib, 2, &freq, &size, nullptr, 0) == 0) { return static_cast<double>(freq); } return 1.0; } #else static bool ReadLongFromFile(const char *file, long *value) { bool ret = false; #if defined(_POSIX_C_SOURCE) const int file_mode = (O_RDONLY | O_CLOEXEC); #else const int file_mode = O_RDONLY; #endif int fd = open(file, file_mode); if (fd != -1) { char line[1024]; char *err; memset(line, '\0', sizeof(line)); ssize_t len; do { len = read(fd, line, sizeof(line) - 1); } while (len < 0 && errno == EINTR); if (len <= 0) { ret = false; } else { const long temp_value = strtol(line, &err, 10); if (line[0] != '\0' && (*err == '\n' || *err == '\0')) { *value = temp_value; ret = true; } } close(fd); } return ret; } #if defined(ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY) static int64_t ReadMonotonicClockNanos() { struct timespec t; #ifdef CLOCK_MONOTONIC_RAW int rc = clock_gettime(CLOCK_MONOTONIC_RAW, &t); #else int rc = clock_gettime(CLOCK_MONOTONIC, &t); #endif if (rc != 0) { ABSL_INTERNAL_LOG( FATAL, "clock_gettime() failed: (" + std::to_string(errno) + ")"); } return int64_t{t.tv_sec} * 1000000000 + t.tv_nsec; } class UnscaledCycleClockWrapperForInitializeFrequency { public: static int64_t Now() { return base_internal::UnscaledCycleClock::Now(); } }; struct TimeTscPair { int64_t time; int64_t tsc; }; static TimeTscPair GetTimeTscPair() { int64_t best_latency = std::numeric_limits<int64_t>::max(); TimeTscPair best; for (int i = 0; i < 10; ++i) { int64_t t0 = ReadMonotonicClockNanos(); int64_t tsc = UnscaledCycleClockWrapperForInitializeFrequency::Now(); int64_t t1 = ReadMonotonicClockNanos(); int64_t latency = t1 - t0; if (latency < best_latency) { best_latency = latency; best.time = t0; best.tsc = tsc; } } return best; } static double MeasureTscFrequencyWithSleep(int sleep_nanoseconds) { auto t0 = GetTimeTscPair(); struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = sleep_nanoseconds; while (nanosleep(&ts, &ts) != 0 && errno == EINTR) {} auto t1 = GetTimeTscPair(); double elapsed_ticks = t1.tsc - t0.tsc; double elapsed_time = (t1.time - t0.time) * 1e-9; return elapsed_ticks / elapsed_time; } static double MeasureTscFrequency() { double last_measurement = -1.0; int sleep_nanoseconds = 1000000; for (int i = 0; i < 8; ++i) { double measurement = MeasureTscFrequencyWithSleep(sleep_nanoseconds); if (measurement * 0.99 < last_measurement && last_measurement < measurement * 1.01) { return measurement; } last_measurement = measurement; sleep_nanoseconds *= 2; } return last_measurement; } #endif static double GetNominalCPUFrequency() { long freq = 0; if (ReadLongFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq)) { return freq * 1e3; } #if defined(ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY) return MeasureTscFrequency(); #else if (ReadLongFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", &freq)) { return freq * 1e3; } return 1.0; #endif } #endif ABSL_CONST_INIT static once_flag init_num_cpus_once; ABSL_CONST_INIT static int num_cpus = 0; int NumCPUs() { base_internal::LowLevelCallOnce( &init_num_cpus_once, []() { num_cpus = GetNumCPUs(); }); return num_cpus; } ABSL_CONST_INIT static once_flag init_nominal_cpu_frequency_once; ABSL_CONST_INIT static double nominal_cpu_frequency = 1.0; double NominalCPUFrequency() { base_internal::LowLevelCallOnce( &init_nominal_cpu_frequency_once, []() { nominal_cpu_frequency = GetNominalCPUFrequency(); }); return nominal_cpu_frequency; } #if defined(_WIN32) pid_t GetTID() { return pid_t{GetCurrentThreadId()}; } #elif defined(__linux__) #ifndef SYS_gettid #define SYS_gettid __NR_gettid #endif pid_t GetTID() { return static_cast<pid_t>(syscall(SYS_gettid)); } #elif defined(__akaros__) pid_t GetTID() { if (in_vcore_context()) return 0; return reinterpret_cast<struct pthread_tcb *>(current_uthread)->id; } #elif defined(__myriad2__) pid_t GetTID() { uint32_t tid; rtems_task_ident(RTEMS_SELF, 0, &tid); return tid; } #elif defined(__APPLE__) pid_t GetTID() { uint64_t tid; pthread_threadid_np(nullptr, &tid); return static_cast<pid_t>(tid); } #elif defined(__FreeBSD__) pid_t GetTID() { return static_cast<pid_t>(pthread_getthreadid_np()); } #elif defined(__OpenBSD__) pid_t GetTID() { return getthrid(); } #elif defined(__NetBSD__) pid_t GetTID() { return static_cast<pid_t>(_lwp_self()); } #elif defined(__native_client__) pid_t GetTID() { auto* thread = pthread_self(); static_assert(sizeof(pid_t) == sizeof(thread), "In NaCL int expected to be the same size as a pointer"); return reinterpret_cast<pid_t>(thread); } #elif defined(__Fuchsia__) pid_t GetTID() { return static_cast<pid_t>(zx_thread_self()); } #else pid_t GetTID() { return static_cast<pid_t>(pthread_self()); } #endif pid_t GetCachedTID() { #ifdef ABSL_HAVE_THREAD_LOCAL static thread_local pid_t thread_id = GetTID(); return thread_id; #else return GetTID(); #endif } } ABSL_NAMESPACE_END }
#include "absl/base/internal/sysinfo.h" #ifndef _WIN32 #include <sys/types.h> #include <unistd.h> #endif #include <thread> #include <unordered_set> #include <vector> #include "gtest/gtest.h" #include "absl/synchronization/barrier.h" #include "absl/synchronization/mutex.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { namespace { TEST(SysinfoTest, NumCPUs) { EXPECT_NE(NumCPUs(), 0) << "NumCPUs() should not have the default value of 0"; } TEST(SysinfoTest, GetTID) { EXPECT_EQ(GetTID(), GetTID()); #ifdef __native_client__ return; #endif for (int i = 0; i < 10; ++i) { constexpr int kNumThreads = 10; Barrier all_threads_done(kNumThreads); std::vector<std::thread> threads; Mutex mutex; std::unordered_set<pid_t> tids; for (int j = 0; j < kNumThreads; ++j) { threads.push_back(std::thread([&]() { pid_t id = GetTID(); { MutexLock lock(&mutex); ASSERT_TRUE(tids.find(id) == tids.end()); tids.insert(id); } all_threads_done.Block(); })); } for (auto& thread : threads) { thread.join(); } } } #ifdef __linux__ TEST(SysinfoTest, LinuxGetTID) { EXPECT_EQ(GetTID(), getpid()); } #endif } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/sysinfo.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/sysinfo_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
e580d97c-eae2-4a33-ad5b-e764f270b769
cpp
abseil/abseil-cpp
raw_logging
absl/base/internal/raw_logging.cc
absl/base/raw_logging_test.cc
#include "absl/base/internal/raw_logging.h" #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #ifdef __EMSCRIPTEN__ #include <emscripten/console.h> #endif #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/atomic_hook.h" #include "absl/base/internal/errno_saver.h" #include "absl/base/log_severity.h" #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \ defined(__hexagon__) || defined(__Fuchsia__) || \ defined(__native_client__) || defined(__OpenBSD__) || \ defined(__EMSCRIPTEN__) || defined(__ASYLO__) #include <unistd.h> #define ABSL_HAVE_POSIX_WRITE 1 #define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1 #else #undef ABSL_HAVE_POSIX_WRITE #endif #if (defined(__linux__) || defined(__FreeBSD__)) && !defined(__ANDROID__) #include <sys/syscall.h> #define ABSL_HAVE_SYSCALL_WRITE 1 #define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1 #else #undef ABSL_HAVE_SYSCALL_WRITE #endif #ifdef _WIN32 #include <io.h> #define ABSL_HAVE_RAW_IO 1 #define ABSL_LOW_LEVEL_WRITE_SUPPORTED 1 #else #undef ABSL_HAVE_RAW_IO #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace raw_log_internal { namespace { #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED constexpr char kTruncated[] = " ... (message truncated)\n"; bool VADoRawLog(char** buf, int* size, const char* format, va_list ap) ABSL_PRINTF_ATTRIBUTE(3, 0); bool VADoRawLog(char** buf, int* size, const char* format, va_list ap) { if (*size < 0) return false; int n = vsnprintf(*buf, static_cast<size_t>(*size), format, ap); bool result = true; if (n < 0 || n > *size) { result = false; if (static_cast<size_t>(*size) > sizeof(kTruncated)) { n = *size - static_cast<int>(sizeof(kTruncated)); } else { n = 0; } } *size -= n; *buf += n; return result; } #endif constexpr int kLogBufSize = 3000; bool DoRawLog(char** buf, int* size, const char* format, ...) ABSL_PRINTF_ATTRIBUTE(3, 4); bool DoRawLog(char** buf, int* size, const char* format, ...) { if (*size < 0) return false; va_list ap; va_start(ap, format); int n = vsnprintf(*buf, static_cast<size_t>(*size), format, ap); va_end(ap); if (n < 0 || n > *size) return false; *size -= n; *buf += n; return true; } bool DefaultLogFilterAndPrefix(absl::LogSeverity, const char* file, int line, char** buf, int* buf_size) { DoRawLog(buf, buf_size, "[%s : %d] RAW: ", file, line); return true; } ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES absl::base_internal::AtomicHook<LogFilterAndPrefixHook> log_filter_and_prefix_hook(DefaultLogFilterAndPrefix); ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES absl::base_internal::AtomicHook<AbortHook> abort_hook; void RawLogVA(absl::LogSeverity severity, const char* file, int line, const char* format, va_list ap) ABSL_PRINTF_ATTRIBUTE(4, 0); void RawLogVA(absl::LogSeverity severity, const char* file, int line, const char* format, va_list ap) { char buffer[kLogBufSize]; char* buf = buffer; int size = sizeof(buffer); #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED bool enabled = true; #else bool enabled = false; #endif #ifdef ABSL_MIN_LOG_LEVEL if (severity < static_cast<absl::LogSeverity>(ABSL_MIN_LOG_LEVEL) && severity < absl::LogSeverity::kFatal) { enabled = false; } #endif enabled = log_filter_and_prefix_hook(severity, file, line, &buf, &size); const char* const prefix_end = buf; #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED if (enabled) { bool no_chop = VADoRawLog(&buf, &size, format, ap); if (no_chop) { DoRawLog(&buf, &size, "\n"); } else { DoRawLog(&buf, &size, "%s", kTruncated); } AsyncSignalSafeWriteError(buffer, static_cast<size_t>(buf - buffer)); } #else static_cast<void>(format); static_cast<void>(ap); static_cast<void>(enabled); #endif if (severity == absl::LogSeverity::kFatal) { abort_hook(file, line, buffer, prefix_end, buffer + kLogBufSize); abort(); } } void DefaultInternalLog(absl::LogSeverity severity, const char* file, int line, const std::string& message) { RawLog(severity, file, line, "%.*s", static_cast<int>(message.size()), message.data()); } } void AsyncSignalSafeWriteError(const char* s, size_t len) { if (!len) return; absl::base_internal::ErrnoSaver errno_saver; #if defined(__EMSCRIPTEN__) if (s[len - 1] == '\n') { len--; } #if ABSL_INTERNAL_EMSCRIPTEN_VERSION >= 3001043 emscripten_errn(s, len); #else char buf[kLogBufSize]; if (len >= kLogBufSize) { len = kLogBufSize - 1; constexpr size_t trunc_len = sizeof(kTruncated) - 2; memcpy(buf + len - trunc_len, kTruncated, trunc_len); buf[len] = '\0'; len -= trunc_len; } else { buf[len] = '\0'; } memcpy(buf, s, len); _emscripten_err(buf); #endif #elif defined(ABSL_HAVE_SYSCALL_WRITE) syscall(SYS_write, STDERR_FILENO, s, len); #elif defined(ABSL_HAVE_POSIX_WRITE) write(STDERR_FILENO, s, len); #elif defined(ABSL_HAVE_RAW_IO) _write( 2, s, static_cast<unsigned>(len)); #else (void)s; (void)len; #endif } void RawLog(absl::LogSeverity severity, const char* file, int line, const char* format, ...) { va_list ap; va_start(ap, format); RawLogVA(severity, file, line, format, ap); va_end(ap); } bool RawLoggingFullySupported() { #ifdef ABSL_LOW_LEVEL_WRITE_SUPPORTED return true; #else return false; #endif } ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES ABSL_DLL absl::base_internal::AtomicHook<InternalLogFunction> internal_log_function(DefaultInternalLog); void RegisterLogFilterAndPrefixHook(LogFilterAndPrefixHook func) { log_filter_and_prefix_hook.Store(func); } void RegisterAbortHook(AbortHook func) { abort_hook.Store(func); } void RegisterInternalLogFunction(InternalLogFunction func) { internal_log_function.Store(func); } } ABSL_NAMESPACE_END }
#include "absl/base/internal/raw_logging.h" #include <tuple> #include "gtest/gtest.h" #include "absl/strings/str_cat.h" namespace { TEST(RawLoggingCompilationTest, Log) { ABSL_RAW_LOG(INFO, "RAW INFO: %d", 1); ABSL_RAW_LOG(INFO, "RAW INFO: %d %d", 1, 2); ABSL_RAW_LOG(INFO, "RAW INFO: %d %d %d", 1, 2, 3); ABSL_RAW_LOG(INFO, "RAW INFO: %d %d %d %d", 1, 2, 3, 4); ABSL_RAW_LOG(INFO, "RAW INFO: %d %d %d %d %d", 1, 2, 3, 4, 5); ABSL_RAW_LOG(WARNING, "RAW WARNING: %d", 1); ABSL_RAW_LOG(ERROR, "RAW ERROR: %d", 1); } TEST(RawLoggingCompilationTest, LogWithNulls) { ABSL_RAW_LOG(INFO, "RAW INFO: %s%c%s", "Hello", 0, "World"); } TEST(RawLoggingCompilationTest, PassingCheck) { ABSL_RAW_CHECK(true, "RAW CHECK"); } const char kExpectedDeathOutput[] = ""; TEST(RawLoggingDeathTest, FailingCheck) { EXPECT_DEATH_IF_SUPPORTED(ABSL_RAW_CHECK(1 == 0, "explanation"), kExpectedDeathOutput); } TEST(RawLoggingDeathTest, LogFatal) { EXPECT_DEATH_IF_SUPPORTED(ABSL_RAW_LOG(FATAL, "my dog has fleas"), kExpectedDeathOutput); } TEST(InternalLog, CompilationTest) { ABSL_INTERNAL_LOG(INFO, "Internal Log"); std::string log_msg = "Internal Log"; ABSL_INTERNAL_LOG(INFO, log_msg); ABSL_INTERNAL_LOG(INFO, log_msg + " 2"); float d = 1.1f; ABSL_INTERNAL_LOG(INFO, absl::StrCat("Internal log ", 3, " + ", d)); } TEST(InternalLogDeathTest, FailingCheck) { EXPECT_DEATH_IF_SUPPORTED(ABSL_INTERNAL_CHECK(1 == 0, "explanation"), kExpectedDeathOutput); } TEST(InternalLogDeathTest, LogFatal) { EXPECT_DEATH_IF_SUPPORTED(ABSL_INTERNAL_LOG(FATAL, "my dog has fleas"), kExpectedDeathOutput); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/raw_logging.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/raw_logging_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
47fa5fb3-f86c-435e-9a76-367e9e180235
cpp
abseil/abseil-cpp
throw_delegate
absl/base/internal/throw_delegate.cc
absl/base/throw_delegate_test.cc
#include "absl/base/internal/throw_delegate.h" #include <cstdlib> #include <functional> #include <new> #include <stdexcept> #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { void ThrowStdLogicError(const std::string& what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::logic_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str()); std::abort(); #endif } void ThrowStdLogicError(const char* what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::logic_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg); std::abort(); #endif } void ThrowStdInvalidArgument(const std::string& what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::invalid_argument(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str()); std::abort(); #endif } void ThrowStdInvalidArgument(const char* what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::invalid_argument(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg); std::abort(); #endif } void ThrowStdDomainError(const std::string& what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::domain_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str()); std::abort(); #endif } void ThrowStdDomainError(const char* what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::domain_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg); std::abort(); #endif } void ThrowStdLengthError(const std::string& what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::length_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str()); std::abort(); #endif } void ThrowStdLengthError(const char* what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::length_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg); std::abort(); #endif } void ThrowStdOutOfRange(const std::string& what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::out_of_range(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str()); std::abort(); #endif } void ThrowStdOutOfRange(const char* what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::out_of_range(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg); std::abort(); #endif } void ThrowStdRuntimeError(const std::string& what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::runtime_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str()); std::abort(); #endif } void ThrowStdRuntimeError(const char* what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::runtime_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg); std::abort(); #endif } void ThrowStdRangeError(const std::string& what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::range_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str()); std::abort(); #endif } void ThrowStdRangeError(const char* what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::range_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg); std::abort(); #endif } void ThrowStdOverflowError(const std::string& what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::overflow_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str()); std::abort(); #endif } void ThrowStdOverflowError(const char* what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::overflow_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg); std::abort(); #endif } void ThrowStdUnderflowError(const std::string& what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::underflow_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg.c_str()); std::abort(); #endif } void ThrowStdUnderflowError(const char* what_arg) { #ifdef ABSL_HAVE_EXCEPTIONS throw std::underflow_error(what_arg); #else ABSL_RAW_LOG(FATAL, "%s", what_arg); std::abort(); #endif } void ThrowStdBadFunctionCall() { #ifdef ABSL_HAVE_EXCEPTIONS throw std::bad_function_call(); #else std::abort(); #endif } void ThrowStdBadAlloc() { #ifdef ABSL_HAVE_EXCEPTIONS throw std::bad_alloc(); #else std::abort(); #endif } } ABSL_NAMESPACE_END }
#include "absl/base/internal/throw_delegate.h" #include <functional> #include <new> #include <stdexcept> #include "absl/base/config.h" #include "gtest/gtest.h" namespace { using absl::base_internal::ThrowStdLogicError; using absl::base_internal::ThrowStdInvalidArgument; using absl::base_internal::ThrowStdDomainError; using absl::base_internal::ThrowStdLengthError; using absl::base_internal::ThrowStdOutOfRange; using absl::base_internal::ThrowStdRuntimeError; using absl::base_internal::ThrowStdRangeError; using absl::base_internal::ThrowStdOverflowError; using absl::base_internal::ThrowStdUnderflowError; using absl::base_internal::ThrowStdBadFunctionCall; using absl::base_internal::ThrowStdBadAlloc; constexpr const char* what_arg = "The quick brown fox jumps over the lazy dog"; template <typename E> void ExpectThrowChar(void (*f)(const char*)) { #ifdef ABSL_HAVE_EXCEPTIONS try { f(what_arg); FAIL() << "Didn't throw"; } catch (const E& e) { EXPECT_STREQ(e.what(), what_arg); } #else EXPECT_DEATH_IF_SUPPORTED(f(what_arg), what_arg); #endif } template <typename E> void ExpectThrowString(void (*f)(const std::string&)) { #ifdef ABSL_HAVE_EXCEPTIONS try { f(what_arg); FAIL() << "Didn't throw"; } catch (const E& e) { EXPECT_STREQ(e.what(), what_arg); } #else EXPECT_DEATH_IF_SUPPORTED(f(what_arg), what_arg); #endif } template <typename E> void ExpectThrowNoWhat(void (*f)()) { #ifdef ABSL_HAVE_EXCEPTIONS try { f(); FAIL() << "Didn't throw"; } catch (const E& e) { } #else EXPECT_DEATH_IF_SUPPORTED(f(), ""); #endif } TEST(ThrowDelegate, ThrowStdLogicErrorChar) { ExpectThrowChar<std::logic_error>(ThrowStdLogicError); } TEST(ThrowDelegate, ThrowStdInvalidArgumentChar) { ExpectThrowChar<std::invalid_argument>(ThrowStdInvalidArgument); } TEST(ThrowDelegate, ThrowStdDomainErrorChar) { ExpectThrowChar<std::domain_error>(ThrowStdDomainError); } TEST(ThrowDelegate, ThrowStdLengthErrorChar) { ExpectThrowChar<std::length_error>(ThrowStdLengthError); } TEST(ThrowDelegate, ThrowStdOutOfRangeChar) { ExpectThrowChar<std::out_of_range>(ThrowStdOutOfRange); } TEST(ThrowDelegate, ThrowStdRuntimeErrorChar) { ExpectThrowChar<std::runtime_error>(ThrowStdRuntimeError); } TEST(ThrowDelegate, ThrowStdRangeErrorChar) { ExpectThrowChar<std::range_error>(ThrowStdRangeError); } TEST(ThrowDelegate, ThrowStdOverflowErrorChar) { ExpectThrowChar<std::overflow_error>(ThrowStdOverflowError); } TEST(ThrowDelegate, ThrowStdUnderflowErrorChar) { ExpectThrowChar<std::underflow_error>(ThrowStdUnderflowError); } TEST(ThrowDelegate, ThrowStdLogicErrorString) { ExpectThrowString<std::logic_error>(ThrowStdLogicError); } TEST(ThrowDelegate, ThrowStdInvalidArgumentString) { ExpectThrowString<std::invalid_argument>(ThrowStdInvalidArgument); } TEST(ThrowDelegate, ThrowStdDomainErrorString) { ExpectThrowString<std::domain_error>(ThrowStdDomainError); } TEST(ThrowDelegate, ThrowStdLengthErrorString) { ExpectThrowString<std::length_error>(ThrowStdLengthError); } TEST(ThrowDelegate, ThrowStdOutOfRangeString) { ExpectThrowString<std::out_of_range>(ThrowStdOutOfRange); } TEST(ThrowDelegate, ThrowStdRuntimeErrorString) { ExpectThrowString<std::runtime_error>(ThrowStdRuntimeError); } TEST(ThrowDelegate, ThrowStdRangeErrorString) { ExpectThrowString<std::range_error>(ThrowStdRangeError); } TEST(ThrowDelegate, ThrowStdOverflowErrorString) { ExpectThrowString<std::overflow_error>(ThrowStdOverflowError); } TEST(ThrowDelegate, ThrowStdUnderflowErrorString) { ExpectThrowString<std::underflow_error>(ThrowStdUnderflowError); } TEST(ThrowDelegate, ThrowStdBadFunctionCallNoWhat) { #ifdef ABSL_HAVE_EXCEPTIONS try { ThrowStdBadFunctionCall(); FAIL() << "Didn't throw"; } catch (const std::bad_function_call&) { } #ifdef _LIBCPP_VERSION catch (const std::exception&) { } #endif #else EXPECT_DEATH_IF_SUPPORTED(ThrowStdBadFunctionCall(), ""); #endif } TEST(ThrowDelegate, ThrowStdBadAllocNoWhat) { ExpectThrowNoWhat<std::bad_alloc>(ThrowStdBadAlloc); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/throw_delegate.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/throw_delegate_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
cf56abb7-7215-4d48-bfa7-541690f4acc7
cpp
abseil/abseil-cpp
exception_safety_testing
absl/base/internal/exception_safety_testing.cc
absl/base/exception_safety_testing_test.cc
#include "absl/base/internal/exception_safety_testing.h" #ifdef ABSL_HAVE_EXCEPTIONS #include "gtest/gtest.h" #include "absl/meta/type_traits.h" namespace testing { exceptions_internal::NoThrowTag nothrow_ctor; exceptions_internal::StrongGuaranteeTagType strong_guarantee; exceptions_internal::ExceptionSafetyTestBuilder<> MakeExceptionSafetyTester() { return {}; } namespace exceptions_internal { int countdown = -1; ConstructorTracker* ConstructorTracker::current_tracker_instance_ = nullptr; void MaybeThrow(absl::string_view msg, bool throw_bad_alloc) { if (countdown-- == 0) { if (throw_bad_alloc) throw TestBadAllocException(msg); throw TestException(msg); } } testing::AssertionResult FailureMessage(const TestException& e, int countdown) noexcept { return testing::AssertionFailure() << "Exception thrown from " << e.what(); } std::string GetSpecString(TypeSpec spec) { std::string out; absl::string_view sep; const auto append = [&](absl::string_view s) { absl::StrAppend(&out, sep, s); sep = " | "; }; if (static_cast<bool>(TypeSpec::kNoThrowCopy & spec)) { append("kNoThrowCopy"); } if (static_cast<bool>(TypeSpec::kNoThrowMove & spec)) { append("kNoThrowMove"); } if (static_cast<bool>(TypeSpec::kNoThrowNew & spec)) { append("kNoThrowNew"); } return out; } std::string GetSpecString(AllocSpec spec) { return static_cast<bool>(AllocSpec::kNoThrowAllocate & spec) ? "kNoThrowAllocate" : ""; } } } #endif
#include "absl/base/internal/exception_safety_testing.h" #ifdef ABSL_HAVE_EXCEPTIONS #include <cstddef> #include <exception> #include <iostream> #include <list> #include <type_traits> #include <vector> #include "gtest/gtest-spi.h" #include "gtest/gtest.h" #include "absl/memory/memory.h" namespace testing { namespace { using ::testing::exceptions_internal::SetCountdown; using ::testing::exceptions_internal::TestException; using ::testing::exceptions_internal::UnsetCountdown; template <typename F> void ExpectNoThrow(const F& f) { try { f(); } catch (const TestException& e) { ADD_FAILURE() << "Unexpected exception thrown from " << e.what(); } } TEST(ThrowingValueTest, Throws) { SetCountdown(); EXPECT_THROW(ThrowingValue<> bomb, TestException); SetCountdown(2); ExpectNoThrow([]() { ThrowingValue<> bomb; }); ExpectNoThrow([]() { ThrowingValue<> bomb; }); EXPECT_THROW(ThrowingValue<> bomb, TestException); UnsetCountdown(); } template <typename F> void TestOp(const F& f) { ExpectNoThrow(f); SetCountdown(); EXPECT_THROW(f(), TestException); UnsetCountdown(); } TEST(ThrowingValueTest, ThrowingCtors) { ThrowingValue<> bomb; TestOp([]() { ThrowingValue<> bomb(1); }); TestOp([&]() { ThrowingValue<> bomb1 = bomb; }); TestOp([&]() { ThrowingValue<> bomb1 = std::move(bomb); }); } TEST(ThrowingValueTest, ThrowingAssignment) { ThrowingValue<> bomb, bomb1; TestOp([&]() { bomb = bomb1; }); TestOp([&]() { bomb = std::move(bomb1); }); { ThrowingValue<> lhs(39), rhs(42); ThrowingValue<> lhs_copy(lhs); SetCountdown(); EXPECT_THROW(lhs = rhs, TestException); UnsetCountdown(); EXPECT_NE(lhs, rhs); EXPECT_NE(lhs_copy, lhs); } { ThrowingValue<> lhs(39), rhs(42); ThrowingValue<> lhs_copy(lhs), rhs_copy(rhs); SetCountdown(); EXPECT_THROW(lhs = std::move(rhs), TestException); UnsetCountdown(); EXPECT_NE(lhs, rhs_copy); EXPECT_NE(lhs_copy, lhs); } } TEST(ThrowingValueTest, ThrowingComparisons) { ThrowingValue<> bomb1, bomb2; TestOp([&]() { return bomb1 == bomb2; }); TestOp([&]() { return bomb1 != bomb2; }); TestOp([&]() { return bomb1 < bomb2; }); TestOp([&]() { return bomb1 <= bomb2; }); TestOp([&]() { return bomb1 > bomb2; }); TestOp([&]() { return bomb1 >= bomb2; }); } TEST(ThrowingValueTest, ThrowingArithmeticOps) { ThrowingValue<> bomb1(1), bomb2(2); TestOp([&bomb1]() { +bomb1; }); TestOp([&bomb1]() { -bomb1; }); TestOp([&bomb1]() { ++bomb1; }); TestOp([&bomb1]() { bomb1++; }); TestOp([&bomb1]() { --bomb1; }); TestOp([&bomb1]() { bomb1--; }); TestOp([&]() { bomb1 + bomb2; }); TestOp([&]() { bomb1 - bomb2; }); TestOp([&]() { bomb1* bomb2; }); TestOp([&]() { bomb1 / bomb2; }); TestOp([&]() { bomb1 << 1; }); TestOp([&]() { bomb1 >> 1; }); } TEST(ThrowingValueTest, ThrowingLogicalOps) { ThrowingValue<> bomb1, bomb2; TestOp([&bomb1]() { !bomb1; }); TestOp([&]() { bomb1&& bomb2; }); TestOp([&]() { bomb1 || bomb2; }); } TEST(ThrowingValueTest, ThrowingBitwiseOps) { ThrowingValue<> bomb1, bomb2; TestOp([&bomb1]() { ~bomb1; }); TestOp([&]() { bomb1 & bomb2; }); TestOp([&]() { bomb1 | bomb2; }); TestOp([&]() { bomb1 ^ bomb2; }); } TEST(ThrowingValueTest, ThrowingCompoundAssignmentOps) { ThrowingValue<> bomb1(1), bomb2(2); TestOp([&]() { bomb1 += bomb2; }); TestOp([&]() { bomb1 -= bomb2; }); TestOp([&]() { bomb1 *= bomb2; }); TestOp([&]() { bomb1 /= bomb2; }); TestOp([&]() { bomb1 %= bomb2; }); TestOp([&]() { bomb1 &= bomb2; }); TestOp([&]() { bomb1 |= bomb2; }); TestOp([&]() { bomb1 ^= bomb2; }); TestOp([&]() { bomb1 *= bomb2; }); } TEST(ThrowingValueTest, ThrowingStreamOps) { ThrowingValue<> bomb; TestOp([&]() { std::istringstream stream; stream >> bomb; }); TestOp([&]() { std::stringstream stream; stream << bomb; }); } TEST(ThrowingValueTest, StreamOpsOutput) { using ::testing::TypeSpec; exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown); EXPECT_NONFATAL_FAILURE( { using Thrower = ThrowingValue<TypeSpec{}>; auto thrower = Thrower(123); thrower.~Thrower(); }, "ThrowingValue<>(123)"); EXPECT_NONFATAL_FAILURE( { using Thrower = ThrowingValue<TypeSpec::kNoThrowCopy>; auto thrower = Thrower(234); thrower.~Thrower(); }, "ThrowingValue<kNoThrowCopy>(234)"); EXPECT_NONFATAL_FAILURE( { using Thrower = ThrowingValue<TypeSpec::kNoThrowMove | TypeSpec::kNoThrowNew>; auto thrower = Thrower(345); thrower.~Thrower(); }, "ThrowingValue<kNoThrowMove | kNoThrowNew>(345)"); EXPECT_NONFATAL_FAILURE( { using Thrower = ThrowingValue<static_cast<TypeSpec>(-1)>; auto thrower = Thrower(456); thrower.~Thrower(); }, "ThrowingValue<kNoThrowCopy | kNoThrowMove | kNoThrowNew>(456)"); } template <typename F> void TestAllocatingOp(const F& f) { ExpectNoThrow(f); SetCountdown(); EXPECT_THROW(f(), exceptions_internal::TestBadAllocException); UnsetCountdown(); } TEST(ThrowingValueTest, ThrowingAllocatingOps) { TestAllocatingOp([]() { return absl::make_unique<ThrowingValue<>>(1); }); TestAllocatingOp([]() { return absl::make_unique<ThrowingValue<>[]>(2); }); } TEST(ThrowingValueTest, NonThrowingMoveCtor) { ThrowingValue<TypeSpec::kNoThrowMove> nothrow_ctor; SetCountdown(); ExpectNoThrow([&nothrow_ctor]() { ThrowingValue<TypeSpec::kNoThrowMove> nothrow1 = std::move(nothrow_ctor); }); UnsetCountdown(); } TEST(ThrowingValueTest, NonThrowingMoveAssign) { ThrowingValue<TypeSpec::kNoThrowMove> nothrow_assign1, nothrow_assign2; SetCountdown(); ExpectNoThrow([&nothrow_assign1, &nothrow_assign2]() { nothrow_assign1 = std::move(nothrow_assign2); }); UnsetCountdown(); } TEST(ThrowingValueTest, ThrowingCopyCtor) { ThrowingValue<> tv; TestOp([&]() { ThrowingValue<> tv_copy(tv); }); } TEST(ThrowingValueTest, ThrowingCopyAssign) { ThrowingValue<> tv1, tv2; TestOp([&]() { tv1 = tv2; }); } TEST(ThrowingValueTest, NonThrowingCopyCtor) { ThrowingValue<TypeSpec::kNoThrowCopy> nothrow_ctor; SetCountdown(); ExpectNoThrow([&nothrow_ctor]() { ThrowingValue<TypeSpec::kNoThrowCopy> nothrow1(nothrow_ctor); }); UnsetCountdown(); } TEST(ThrowingValueTest, NonThrowingCopyAssign) { ThrowingValue<TypeSpec::kNoThrowCopy> nothrow_assign1, nothrow_assign2; SetCountdown(); ExpectNoThrow([&nothrow_assign1, &nothrow_assign2]() { nothrow_assign1 = nothrow_assign2; }); UnsetCountdown(); } TEST(ThrowingValueTest, ThrowingSwap) { ThrowingValue<> bomb1, bomb2; TestOp([&]() { std::swap(bomb1, bomb2); }); } TEST(ThrowingValueTest, NonThrowingSwap) { ThrowingValue<TypeSpec::kNoThrowMove> bomb1, bomb2; ExpectNoThrow([&]() { std::swap(bomb1, bomb2); }); } TEST(ThrowingValueTest, NonThrowingAllocation) { ThrowingValue<TypeSpec::kNoThrowNew>* allocated; ThrowingValue<TypeSpec::kNoThrowNew>* array; ExpectNoThrow([&allocated]() { allocated = new ThrowingValue<TypeSpec::kNoThrowNew>(1); delete allocated; }); ExpectNoThrow([&array]() { array = new ThrowingValue<TypeSpec::kNoThrowNew>[2]; delete[] array; }); } TEST(ThrowingValueTest, NonThrowingDelete) { auto* allocated = new ThrowingValue<>(1); auto* array = new ThrowingValue<>[2]; SetCountdown(); ExpectNoThrow([allocated]() { delete allocated; }); SetCountdown(); ExpectNoThrow([array]() { delete[] array; }); UnsetCountdown(); } TEST(ThrowingValueTest, NonThrowingPlacementDelete) { constexpr int kArrayLen = 2; constexpr size_t kExtraSpaceLen = sizeof(size_t) * 2; alignas(ThrowingValue<>) unsigned char buf[sizeof(ThrowingValue<>)]; alignas(ThrowingValue<>) unsigned char array_buf[kExtraSpaceLen + sizeof(ThrowingValue<>[kArrayLen])]; auto* placed = new (&buf) ThrowingValue<>(1); auto placed_array = new (&array_buf) ThrowingValue<>[kArrayLen]; auto* placed_array_end = reinterpret_cast<unsigned char*>(placed_array) + sizeof(ThrowingValue<>[kArrayLen]); EXPECT_LE(placed_array_end, array_buf + sizeof(array_buf)); SetCountdown(); ExpectNoThrow([placed, &buf]() { placed->~ThrowingValue<>(); ThrowingValue<>::operator delete(placed, &buf); }); SetCountdown(); ExpectNoThrow([&, placed_array]() { for (int i = 0; i < kArrayLen; ++i) placed_array[i].~ThrowingValue<>(); ThrowingValue<>::operator delete[](placed_array, &array_buf); }); UnsetCountdown(); } TEST(ThrowingValueTest, NonThrowingDestructor) { auto* allocated = new ThrowingValue<>(); SetCountdown(); ExpectNoThrow([allocated]() { delete allocated; }); UnsetCountdown(); } TEST(ThrowingBoolTest, ThrowingBool) { ThrowingBool t = true; if (t) { } EXPECT_TRUE(t); TestOp([&]() { (void)!t; }); } TEST(ThrowingAllocatorTest, MemoryManagement) { ThrowingAllocator<int> int_alloc; int* ip = int_alloc.allocate(1); int_alloc.deallocate(ip, 1); int* i_array = int_alloc.allocate(2); int_alloc.deallocate(i_array, 2); ThrowingAllocator<ThrowingValue<>> tv_alloc; ThrowingValue<>* ptr = tv_alloc.allocate(1); tv_alloc.deallocate(ptr, 1); ThrowingValue<>* tv_array = tv_alloc.allocate(2); tv_alloc.deallocate(tv_array, 2); } TEST(ThrowingAllocatorTest, CallsGlobalNew) { ThrowingAllocator<ThrowingValue<>, AllocSpec::kNoThrowAllocate> nothrow_alloc; ThrowingValue<>* ptr; SetCountdown(); ExpectNoThrow([&]() { ptr = nothrow_alloc.allocate(1); }); nothrow_alloc.deallocate(ptr, 1); UnsetCountdown(); } TEST(ThrowingAllocatorTest, ThrowingConstructors) { ThrowingAllocator<int> int_alloc; int* ip = nullptr; SetCountdown(); EXPECT_THROW(ip = int_alloc.allocate(1), TestException); ExpectNoThrow([&]() { ip = int_alloc.allocate(1); }); *ip = 1; SetCountdown(); EXPECT_THROW(int_alloc.construct(ip, 2), TestException); EXPECT_EQ(*ip, 1); int_alloc.deallocate(ip, 1); UnsetCountdown(); } TEST(ThrowingAllocatorTest, NonThrowingConstruction) { { ThrowingAllocator<int, AllocSpec::kNoThrowAllocate> int_alloc; int* ip = nullptr; SetCountdown(); ExpectNoThrow([&]() { ip = int_alloc.allocate(1); }); SetCountdown(); ExpectNoThrow([&]() { int_alloc.construct(ip, 2); }); EXPECT_EQ(*ip, 2); int_alloc.deallocate(ip, 1); UnsetCountdown(); } { ThrowingAllocator<int> int_alloc; int* ip = nullptr; ExpectNoThrow([&]() { ip = int_alloc.allocate(1); }); ExpectNoThrow([&]() { int_alloc.construct(ip, 2); }); EXPECT_EQ(*ip, 2); int_alloc.deallocate(ip, 1); } { ThrowingAllocator<ThrowingValue<>, AllocSpec::kNoThrowAllocate> nothrow_alloc; ThrowingValue<>* ptr; SetCountdown(); ExpectNoThrow([&]() { ptr = nothrow_alloc.allocate(1); }); SetCountdown(); ExpectNoThrow( [&]() { nothrow_alloc.construct(ptr, 2, testing::nothrow_ctor); }); EXPECT_EQ(ptr->Get(), 2); nothrow_alloc.destroy(ptr); nothrow_alloc.deallocate(ptr, 1); UnsetCountdown(); } { ThrowingAllocator<int> a; SetCountdown(); ExpectNoThrow([&]() { ThrowingAllocator<double> a1 = a; }); SetCountdown(); ExpectNoThrow([&]() { ThrowingAllocator<double> a1 = std::move(a); }); UnsetCountdown(); } } TEST(ThrowingAllocatorTest, ThrowingAllocatorConstruction) { ThrowingAllocator<int> a; TestOp([]() { ThrowingAllocator<int> a; }); TestOp([&]() { a.select_on_container_copy_construction(); }); } TEST(ThrowingAllocatorTest, State) { ThrowingAllocator<int> a1, a2; EXPECT_NE(a1, a2); auto a3 = a1; EXPECT_EQ(a3, a1); int* ip = a1.allocate(1); EXPECT_EQ(a3, a1); a3.deallocate(ip, 1); EXPECT_EQ(a3, a1); } TEST(ThrowingAllocatorTest, InVector) { std::vector<ThrowingValue<>, ThrowingAllocator<ThrowingValue<>>> v; for (int i = 0; i < 20; ++i) v.push_back({}); for (int i = 0; i < 20; ++i) v.pop_back(); } TEST(ThrowingAllocatorTest, InList) { std::list<ThrowingValue<>, ThrowingAllocator<ThrowingValue<>>> l; for (int i = 0; i < 20; ++i) l.push_back({}); for (int i = 0; i < 20; ++i) l.pop_back(); for (int i = 0; i < 20; ++i) l.push_front({}); for (int i = 0; i < 20; ++i) l.pop_front(); } template <typename TesterInstance, typename = void> struct NullaryTestValidator : public std::false_type {}; template <typename TesterInstance> struct NullaryTestValidator< TesterInstance, absl::void_t<decltype(std::declval<TesterInstance>().Test())>> : public std::true_type {}; template <typename TesterInstance> bool HasNullaryTest(const TesterInstance&) { return NullaryTestValidator<TesterInstance>::value; } void DummyOp(void*) {} template <typename TesterInstance, typename = void> struct UnaryTestValidator : public std::false_type {}; template <typename TesterInstance> struct UnaryTestValidator< TesterInstance, absl::void_t<decltype(std::declval<TesterInstance>().Test(DummyOp))>> : public std::true_type {}; template <typename TesterInstance> bool HasUnaryTest(const TesterInstance&) { return UnaryTestValidator<TesterInstance>::value; } TEST(ExceptionSafetyTesterTest, IncompleteTypesAreNotTestable) { using T = exceptions_internal::UninitializedT; auto op = [](T* t) {}; auto inv = [](T*) { return testing::AssertionSuccess(); }; auto fac = []() { return absl::make_unique<T>(); }; auto without_fac = testing::MakeExceptionSafetyTester().WithOperation(op).WithContracts( inv, testing::strong_guarantee); EXPECT_FALSE(HasNullaryTest(without_fac)); EXPECT_FALSE(HasUnaryTest(without_fac)); auto without_op = testing::MakeExceptionSafetyTester() .WithContracts(inv, testing::strong_guarantee) .WithFactory(fac); EXPECT_FALSE(HasNullaryTest(without_op)); EXPECT_TRUE(HasUnaryTest(without_op)); auto without_inv = testing::MakeExceptionSafetyTester().WithOperation(op).WithFactory(fac); EXPECT_FALSE(HasNullaryTest(without_inv)); EXPECT_FALSE(HasUnaryTest(without_inv)); } struct ExampleStruct {}; std::unique_ptr<ExampleStruct> ExampleFunctionFactory() { return absl::make_unique<ExampleStruct>(); } void ExampleFunctionOperation(ExampleStruct*) {} testing::AssertionResult ExampleFunctionContract(ExampleStruct*) { return testing::AssertionSuccess(); } struct { std::unique_ptr<ExampleStruct> operator()() const { return ExampleFunctionFactory(); } } example_struct_factory; struct { void operator()(ExampleStruct*) const {} } example_struct_operation; struct { testing::AssertionResult operator()(ExampleStruct* example_struct) const { return ExampleFunctionContract(example_struct); } } example_struct_contract; auto example_lambda_factory = []() { return ExampleFunctionFactory(); }; auto example_lambda_operation = [](ExampleStruct*) {}; auto example_lambda_contract = [](ExampleStruct* example_struct) { return ExampleFunctionContract(example_struct); }; TEST(ExceptionSafetyTesterTest, MixedFunctionTypes) { EXPECT_TRUE(testing::MakeExceptionSafetyTester() .WithFactory(ExampleFunctionFactory) .WithOperation(ExampleFunctionOperation) .WithContracts(ExampleFunctionContract) .Test()); EXPECT_TRUE(testing::MakeExceptionSafetyTester() .WithFactory(&ExampleFunctionFactory) .WithOperation(&ExampleFunctionOperation) .WithContracts(&ExampleFunctionContract) .Test()); EXPECT_TRUE(testing::MakeExceptionSafetyTester() .WithFactory(example_struct_factory) .WithOperation(example_struct_operation) .WithContracts(example_struct_contract) .Test()); EXPECT_TRUE(testing::MakeExceptionSafetyTester() .WithFactory(example_lambda_factory) .WithOperation(example_lambda_operation) .WithContracts(example_lambda_contract) .Test()); } struct NonNegative { bool operator==(const NonNegative& other) const { return i == other.i; } int i; }; testing::AssertionResult CheckNonNegativeInvariants(NonNegative* g) { if (g->i >= 0) { return testing::AssertionSuccess(); } return testing::AssertionFailure() << "i should be non-negative but is " << g->i; } struct { template <typename T> void operator()(T* t) const { (*t)(); } } invoker; auto tester = testing::MakeExceptionSafetyTester().WithOperation(invoker).WithContracts( CheckNonNegativeInvariants); auto strong_tester = tester.WithContracts(testing::strong_guarantee); struct FailsBasicGuarantee : public NonNegative { void operator()() { --i; ThrowingValue<> bomb; ++i; } }; TEST(ExceptionCheckTest, BasicGuaranteeFailure) { EXPECT_FALSE(tester.WithInitialValue(FailsBasicGuarantee{}).Test()); } struct FollowsBasicGuarantee : public NonNegative { void operator()() { ++i; ThrowingValue<> bomb; } }; TEST(ExceptionCheckTest, BasicGuarantee) { EXPECT_TRUE(tester.WithInitialValue(FollowsBasicGuarantee{}).Test()); } TEST(ExceptionCheckTest, StrongGuaranteeFailure) { EXPECT_FALSE(strong_tester.WithInitialValue(FailsBasicGuarantee{}).Test()); EXPECT_FALSE(strong_tester.WithInitialValue(FollowsBasicGuarantee{}).Test()); } struct BasicGuaranteeWithExtraContracts : public NonNegative { void operator()() { int old_i = i; i = kExceptionSentinel; ThrowingValue<> bomb; i = ++old_i; } static constexpr int kExceptionSentinel = 9999; }; #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL constexpr int BasicGuaranteeWithExtraContracts::kExceptionSentinel; #endif TEST(ExceptionCheckTest, BasicGuaranteeWithExtraContracts) { auto tester_with_val = tester.WithInitialValue(BasicGuaranteeWithExtraContracts{}); EXPECT_TRUE(tester_with_val.Test()); EXPECT_TRUE( tester_with_val .WithContracts([](BasicGuaranteeWithExtraContracts* o) { if (o->i == BasicGuaranteeWithExtraContracts::kExceptionSentinel) { return testing::AssertionSuccess(); } return testing::AssertionFailure() << "i should be " << BasicGuaranteeWithExtraContracts::kExceptionSentinel << ", but is " << o->i; }) .Test()); } struct FollowsStrongGuarantee : public NonNegative { void operator()() { ThrowingValue<> bomb; } }; TEST(ExceptionCheckTest, StrongGuarantee) { EXPECT_TRUE(tester.WithInitialValue(FollowsStrongGuarantee{}).Test()); EXPECT_TRUE(strong_tester.WithInitialValue(FollowsStrongGuarantee{}).Test()); } struct HasReset : public NonNegative { void operator()() { i = -1; ThrowingValue<> bomb; i = 1; } void reset() { i = 0; } }; testing::AssertionResult CheckHasResetContracts(HasReset* h) { h->reset(); return testing::AssertionResult(h->i == 0); } TEST(ExceptionCheckTest, ModifyingChecker) { auto set_to_1000 = [](FollowsBasicGuarantee* g) { g->i = 1000; return testing::AssertionSuccess(); }; auto is_1000 = [](FollowsBasicGuarantee* g) { return testing::AssertionResult(g->i == 1000); }; auto increment = [](FollowsStrongGuarantee* g) { ++g->i; return testing::AssertionSuccess(); }; EXPECT_FALSE(tester.WithInitialValue(FollowsBasicGuarantee{}) .WithContracts(set_to_1000, is_1000) .Test()); EXPECT_TRUE(strong_tester.WithInitialValue(FollowsStrongGuarantee{}) .WithContracts(increment) .Test()); EXPECT_TRUE(testing::MakeExceptionSafetyTester() .WithInitialValue(HasReset{}) .WithContracts(CheckHasResetContracts) .Test(invoker)); } TEST(ExceptionSafetyTesterTest, ResetsCountdown) { auto test = testing::MakeExceptionSafetyTester() .WithInitialValue(ThrowingValue<>()) .WithContracts([](ThrowingValue<>*) { return AssertionSuccess(); }) .WithOperation([](ThrowingValue<>*) {}); ASSERT_TRUE(test.Test()); EXPECT_TRUE(test.Test()); } struct NonCopyable : public NonNegative { NonCopyable(const NonCopyable&) = delete; NonCopyable() : NonNegative{0} {} void operator()() { ThrowingValue<> bomb; } }; TEST(ExceptionCheckTest, NonCopyable) { auto factory = []() { return absl::make_unique<NonCopyable>(); }; EXPECT_TRUE(tester.WithFactory(factory).Test()); EXPECT_TRUE(strong_tester.WithFactory(factory).Test()); } struct NonEqualityComparable : public NonNegative { void operator()() { ThrowingValue<> bomb; } void ModifyOnThrow() { ++i; ThrowingValue<> bomb; static_cast<void>(bomb); --i; } }; TEST(ExceptionCheckTest, NonEqualityComparable) { auto nec_is_strong = [](NonEqualityComparable* nec) { return testing::AssertionResult(nec->i == NonEqualityComparable().i); }; auto strong_nec_tester = tester.WithInitialValue(NonEqualityComparable{}) .WithContracts(nec_is_strong); EXPECT_TRUE(strong_nec_tester.Test()); EXPECT_FALSE(strong_nec_tester.Test( [](NonEqualityComparable* n) { n->ModifyOnThrow(); })); } template <typename T> struct ExhaustivenessTester { void operator()() { successes |= 1; T b1; static_cast<void>(b1); successes |= (1 << 1); T b2; static_cast<void>(b2); successes |= (1 << 2); T b3; static_cast<void>(b3); successes |= (1 << 3); } bool operator==(const ExhaustivenessTester<ThrowingValue<>>&) const { return true; } static unsigned char successes; }; struct { template <typename T> testing::AssertionResult operator()(ExhaustivenessTester<T>*) const { return testing::AssertionSuccess(); } } CheckExhaustivenessTesterContracts; template <typename T> unsigned char ExhaustivenessTester<T>::successes = 0; TEST(ExceptionCheckTest, Exhaustiveness) { auto exhaust_tester = testing::MakeExceptionSafetyTester() .WithContracts(CheckExhaustivenessTesterContracts) .WithOperation(invoker); EXPECT_TRUE( exhaust_tester.WithInitialValue(ExhaustivenessTester<int>{}).Test()); EXPECT_EQ(ExhaustivenessTester<int>::successes, 0xF); EXPECT_TRUE( exhaust_tester.WithInitialValue(ExhaustivenessTester<ThrowingValue<>>{}) .WithContracts(testing::strong_guarantee) .Test()); EXPECT_EQ(ExhaustivenessTester<ThrowingValue<>>::successes, 0xF); } struct LeaksIfCtorThrows : private exceptions_internal::TrackedObject { LeaksIfCtorThrows() : TrackedObject(ABSL_PRETTY_FUNCTION) { ++counter; ThrowingValue<> v; static_cast<void>(v); --counter; } LeaksIfCtorThrows(const LeaksIfCtorThrows&) noexcept : TrackedObject(ABSL_PRETTY_FUNCTION) {} static int counter; }; int LeaksIfCtorThrows::counter = 0; TEST(ExceptionCheckTest, TestLeakyCtor) { testing::TestThrowingCtor<LeaksIfCtorThrows>(); EXPECT_EQ(LeaksIfCtorThrows::counter, 1); LeaksIfCtorThrows::counter = 0; } struct Tracked : private exceptions_internal::TrackedObject { Tracked() : TrackedObject(ABSL_PRETTY_FUNCTION) {} }; TEST(ConstructorTrackerTest, CreatedBefore) { Tracked a, b, c; exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown); } TEST(ConstructorTrackerTest, CreatedAfter) { exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown); Tracked a, b, c; } TEST(ConstructorTrackerTest, NotDestroyedAfter) { alignas(Tracked) unsigned char storage[sizeof(Tracked)]; EXPECT_NONFATAL_FAILURE( { exceptions_internal::ConstructorTracker ct( exceptions_internal::countdown); new (&storage) Tracked(); }, "not destroyed"); } TEST(ConstructorTrackerTest, DestroyedTwice) { exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown); EXPECT_NONFATAL_FAILURE( { Tracked t; t.~Tracked(); }, "re-destroyed"); } TEST(ConstructorTrackerTest, ConstructedTwice) { exceptions_internal::ConstructorTracker ct(exceptions_internal::countdown); alignas(Tracked) unsigned char storage[sizeof(Tracked)]; EXPECT_NONFATAL_FAILURE( { new (&storage) Tracked(); new (&storage) Tracked(); reinterpret_cast<Tracked*>(&storage)->~Tracked(); }, "re-constructed"); } TEST(ThrowingValueTraitsTest, RelationalOperators) { ThrowingValue<> a, b; EXPECT_TRUE((std::is_convertible<decltype(a == b), bool>::value)); EXPECT_TRUE((std::is_convertible<decltype(a != b), bool>::value)); EXPECT_TRUE((std::is_convertible<decltype(a < b), bool>::value)); EXPECT_TRUE((std::is_convertible<decltype(a <= b), bool>::value)); EXPECT_TRUE((std::is_convertible<decltype(a > b), bool>::value)); EXPECT_TRUE((std::is_convertible<decltype(a >= b), bool>::value)); } TEST(ThrowingAllocatorTraitsTest, Assignablility) { EXPECT_TRUE(absl::is_move_assignable<ThrowingAllocator<int>>::value); EXPECT_TRUE(absl::is_copy_assignable<ThrowingAllocator<int>>::value); EXPECT_TRUE(std::is_nothrow_move_assignable<ThrowingAllocator<int>>::value); EXPECT_TRUE(std::is_nothrow_copy_assignable<ThrowingAllocator<int>>::value); } } } #endif
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/exception_safety_testing.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/exception_safety_testing_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
3545902a-4b31-4b27-abc6-663c18776ccb
cpp
abseil/abseil-cpp
strerror
absl/base/internal/strerror.cc
absl/base/internal/strerror_test.cc
#include "absl/base/internal/strerror.h" #include <array> #include <cerrno> #include <cstddef> #include <cstdio> #include <cstring> #include <string> #include <type_traits> #include "absl/base/internal/errno_saver.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { namespace { const char* StrErrorAdaptor(int errnum, char* buf, size_t buflen) { #if defined(_WIN32) int rc = strerror_s(buf, buflen, errnum); buf[buflen - 1] = '\0'; if (rc == 0 && strncmp(buf, "Unknown error", buflen) == 0) *buf = '\0'; return buf; #else auto ret = strerror_r(errnum, buf, buflen); if (std::is_same<decltype(ret), int>::value) { if (ret) *buf = '\0'; return buf; } else { return reinterpret_cast<const char*>(ret); } #endif } std::string StrErrorInternal(int errnum) { char buf[100]; const char* str = StrErrorAdaptor(errnum, buf, sizeof buf); if (*str == '\0') { snprintf(buf, sizeof buf, "Unknown error %d", errnum); str = buf; } return str; } constexpr int kSysNerr = 135; std::array<std::string, kSysNerr>* NewStrErrorTable() { auto* table = new std::array<std::string, kSysNerr>; for (size_t i = 0; i < table->size(); ++i) { (*table)[i] = StrErrorInternal(static_cast<int>(i)); } return table; } } std::string StrError(int errnum) { absl::base_internal::ErrnoSaver errno_saver; static const auto* table = NewStrErrorTable(); if (errnum >= 0 && static_cast<size_t>(errnum) < table->size()) { return (*table)[static_cast<size_t>(errnum)]; } return StrErrorInternal(errnum); } } ABSL_NAMESPACE_END }
#include "absl/base/internal/strerror.h" #include <atomic> #include <cerrno> #include <cstdio> #include <cstring> #include <string> #include <thread> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/match.h" namespace { using ::testing::AnyOf; using ::testing::Eq; TEST(StrErrorTest, ValidErrorCode) { errno = ERANGE; EXPECT_THAT(absl::base_internal::StrError(EDOM), Eq(strerror(EDOM))); EXPECT_THAT(errno, Eq(ERANGE)); } TEST(StrErrorTest, InvalidErrorCode) { errno = ERANGE; EXPECT_THAT(absl::base_internal::StrError(-1), AnyOf(Eq("No error information"), Eq("Unknown error -1"))); EXPECT_THAT(errno, Eq(ERANGE)); } TEST(StrErrorTest, MultipleThreads) { const int kNumCodes = 1000; std::vector<std::string> expected_strings(kNumCodes); for (int i = 0; i < kNumCodes; ++i) { expected_strings[i] = strerror(i); } std::atomic_int counter(0); auto thread_fun = [&]() { for (int i = 0; i < kNumCodes; ++i) { ++counter; errno = ERANGE; const std::string value = absl::base_internal::StrError(i); int check_err = errno; EXPECT_THAT(check_err, Eq(ERANGE)); if (!absl::StartsWith(value, "Unknown error ")) { EXPECT_THAT(value, Eq(expected_strings[i])); } } }; const int kNumThreads = 100; std::vector<std::thread> threads; for (int i = 0; i < kNumThreads; ++i) { threads.push_back(std::thread(thread_fun)); } for (auto& thread : threads) { thread.join(); } EXPECT_THAT(counter, Eq(kNumThreads * kNumCodes)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/strerror.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/strerror_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
1d635e1b-7e20-4b37-ba2e-5c6e6e9195df
cpp
abseil/abseil-cpp
poison
absl/base/internal/poison.cc
absl/base/internal/poison_test.cc
#include "absl/base/internal/poison.h" #include <cstdlib> #include "absl/base/config.h" #include "absl/base/internal/direct_mmap.h" #ifndef _WIN32 #include <unistd.h> #endif #if defined(ABSL_HAVE_ADDRESS_SANITIZER) #include <sanitizer/asan_interface.h> #elif defined(ABSL_HAVE_MEMORY_SANITIZER) #include <sanitizer/msan_interface.h> #elif defined(ABSL_HAVE_MMAP) #include <sys/mman.h> #endif #if defined(_WIN32) #include <windows.h> #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { namespace { size_t GetPageSize() { #ifdef _WIN32 SYSTEM_INFO system_info; GetSystemInfo(&system_info); return system_info.dwPageSize; #elif defined(__wasm__) || defined(__asmjs__) || defined(__hexagon__) return getpagesize(); #else return static_cast<size_t>(sysconf(_SC_PAGESIZE)); #endif } } void* InitializePoisonedPointerInternal() { const size_t block_size = GetPageSize(); #if defined(ABSL_HAVE_ADDRESS_SANITIZER) void* data = malloc(block_size); ASAN_POISON_MEMORY_REGION(data, block_size); #elif defined(ABSL_HAVE_MEMORY_SANITIZER) void* data = malloc(block_size); __msan_poison(data, block_size); #elif defined(ABSL_HAVE_MMAP) void* data = DirectMmap(nullptr, block_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (data == MAP_FAILED) return GetBadPointerInternal(); #elif defined(_WIN32) void* data = VirtualAlloc(nullptr, block_size, MEM_RESERVE | MEM_COMMIT, PAGE_NOACCESS); if (data == nullptr) return GetBadPointerInternal(); #else return GetBadPointerInternal(); #endif return static_cast<char*>(data) + block_size / 2; } } ABSL_NAMESPACE_END }
#include "absl/base/internal/poison.h" #include <iostream> #include "gtest/gtest.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { namespace { TEST(PoisonTest, CrashesOnDereference) { #ifdef __ANDROID__ GTEST_SKIP() << "On Android, poisoned pointer dereference times out instead " "of crashing."; #endif int* poisoned_ptr = static_cast<int*>(get_poisoned_pointer()); EXPECT_DEATH_IF_SUPPORTED(std::cout << *poisoned_ptr, ""); EXPECT_DEATH_IF_SUPPORTED(std::cout << *(poisoned_ptr - 10), ""); EXPECT_DEATH_IF_SUPPORTED(std::cout << *(poisoned_ptr + 10), ""); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/poison.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/poison_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
d46c051e-480a-4fb0-a00d-f446649c745a
cpp
abseil/abseil-cpp
thread_identity
absl/base/internal/thread_identity.cc
absl/base/internal/thread_identity_test.cc
#include "absl/base/internal/thread_identity.h" #if !defined(_WIN32) || defined(__MINGW32__) #include <pthread.h> #ifndef __wasi__ #include <signal.h> #endif #endif #include <atomic> #include <cassert> #include <memory> #include "absl/base/attributes.h" #include "absl/base/call_once.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/spinlock.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { #if ABSL_THREAD_IDENTITY_MODE != ABSL_THREAD_IDENTITY_MODE_USE_CPP11 namespace { absl::once_flag init_thread_identity_key_once; pthread_key_t thread_identity_pthread_key; std::atomic<bool> pthread_key_initialized(false); void AllocateThreadIdentityKey(ThreadIdentityReclaimerFunction reclaimer) { pthread_key_create(&thread_identity_pthread_key, reclaimer); pthread_key_initialized.store(true, std::memory_order_release); } } #endif #if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \ ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11 ABSL_CONST_INIT #if ABSL_HAVE_ATTRIBUTE(visibility) && !defined(__APPLE__) __attribute__((visibility("protected"))) #endif #if ABSL_PER_THREAD_TLS ABSL_PER_THREAD_TLS_KEYWORD ThreadIdentity* thread_identity_ptr = nullptr; #elif defined(ABSL_HAVE_THREAD_LOCAL) thread_local ThreadIdentity* thread_identity_ptr = nullptr; #endif #endif void SetCurrentThreadIdentity(ThreadIdentity* identity, ThreadIdentityReclaimerFunction reclaimer) { assert(CurrentThreadIdentityIfPresent() == nullptr); #if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC absl::call_once(init_thread_identity_key_once, AllocateThreadIdentityKey, reclaimer); #if defined(__wasi__) || defined(__EMSCRIPTEN__) || defined(__MINGW32__) || \ defined(__hexagon__) pthread_setspecific(thread_identity_pthread_key, reinterpret_cast<void*>(identity)); #else sigset_t all_signals; sigset_t curr_signals; sigfillset(&all_signals); pthread_sigmask(SIG_SETMASK, &all_signals, &curr_signals); pthread_setspecific(thread_identity_pthread_key, reinterpret_cast<void*>(identity)); pthread_sigmask(SIG_SETMASK, &curr_signals, nullptr); #endif #elif ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS absl::call_once(init_thread_identity_key_once, AllocateThreadIdentityKey, reclaimer); pthread_setspecific(thread_identity_pthread_key, reinterpret_cast<void*>(identity)); thread_identity_ptr = identity; #elif ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11 thread_local std::unique_ptr<ThreadIdentity, ThreadIdentityReclaimerFunction> holder(identity, reclaimer); thread_identity_ptr = identity; #else #error Unimplemented ABSL_THREAD_IDENTITY_MODE #endif } #if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \ ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11 #ifndef ABSL_INTERNAL_INLINE_CURRENT_THREAD_IDENTITY_IF_PRESENT ThreadIdentity* CurrentThreadIdentityIfPresent() { return thread_identity_ptr; } #endif #endif void ClearCurrentThreadIdentity() { #if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_TLS || \ ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_CPP11 thread_identity_ptr = nullptr; #elif ABSL_THREAD_IDENTITY_MODE == \ ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC assert(CurrentThreadIdentityIfPresent() == nullptr); #endif } #if ABSL_THREAD_IDENTITY_MODE == ABSL_THREAD_IDENTITY_MODE_USE_POSIX_SETSPECIFIC ThreadIdentity* CurrentThreadIdentityIfPresent() { bool initialized = pthread_key_initialized.load(std::memory_order_acquire); if (!initialized) { return nullptr; } return reinterpret_cast<ThreadIdentity*>( pthread_getspecific(thread_identity_pthread_key)); } #endif } ABSL_NAMESPACE_END }
#include "absl/base/internal/thread_identity.h" #include <thread> #include <vector> #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/internal/spinlock.h" #include "absl/base/macros.h" #include "absl/base/thread_annotations.h" #include "absl/synchronization/internal/per_thread_sem.h" #include "absl/synchronization/mutex.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { namespace { ABSL_CONST_INIT static absl::base_internal::SpinLock map_lock( absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY); ABSL_CONST_INIT static int num_identities_reused ABSL_GUARDED_BY(map_lock); static const void* const kCheckNoIdentity = reinterpret_cast<void*>(1); static void TestThreadIdentityCurrent(const void* assert_no_identity) { ThreadIdentity* identity; if (assert_no_identity == kCheckNoIdentity) { identity = CurrentThreadIdentityIfPresent(); EXPECT_TRUE(identity == nullptr); } identity = synchronization_internal::GetOrCreateCurrentThreadIdentity(); EXPECT_TRUE(identity != nullptr); ThreadIdentity* identity_no_init; identity_no_init = CurrentThreadIdentityIfPresent(); EXPECT_TRUE(identity == identity_no_init); EXPECT_EQ(0, reinterpret_cast<intptr_t>(&identity->per_thread_synch) % PerThreadSynch::kAlignment); EXPECT_EQ(identity, identity->per_thread_synch.thread_identity()); absl::base_internal::SpinLockHolder l(&map_lock); num_identities_reused++; } TEST(ThreadIdentityTest, BasicIdentityWorks) { TestThreadIdentityCurrent(nullptr); } TEST(ThreadIdentityTest, BasicIdentityWorksThreaded) { static const int kNumLoops = 3; static const int kNumThreads = 32; for (int iter = 0; iter < kNumLoops; iter++) { std::vector<std::thread> threads; for (int i = 0; i < kNumThreads; ++i) { threads.push_back( std::thread(TestThreadIdentityCurrent, kCheckNoIdentity)); } for (auto& thread : threads) { thread.join(); } } absl::base_internal::SpinLockHolder l(&map_lock); EXPECT_LT(kNumThreads, num_identities_reused); } TEST(ThreadIdentityTest, ReusedThreadIdentityMutexTest) { static const int kNumLoops = 10; static const int kNumThreads = 12; static const int kNumMutexes = 3; static const int kNumLockLoops = 5; Mutex mutexes[kNumMutexes]; for (int iter = 0; iter < kNumLoops; ++iter) { std::vector<std::thread> threads; for (int thread = 0; thread < kNumThreads; ++thread) { threads.push_back(std::thread([&]() { for (int l = 0; l < kNumLockLoops; ++l) { for (int m = 0; m < kNumMutexes; ++m) { MutexLock lock(&mutexes[m]); } } })); } for (auto& thread : threads) { thread.join(); } } } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/thread_identity.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/thread_identity_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
485d01de-bfb2-4fa4-8ce6-7a875fdfc513
cpp
abseil/abseil-cpp
low_level_alloc
absl/base/internal/low_level_alloc.cc
absl/base/internal/low_level_alloc_test.cc
#include "absl/base/internal/low_level_alloc.h" #include <type_traits> #include "absl/base/call_once.h" #include "absl/base/config.h" #include "absl/base/internal/direct_mmap.h" #include "absl/base/internal/scheduling_mode.h" #include "absl/base/macros.h" #include "absl/base/thread_annotations.h" #ifndef ABSL_LOW_LEVEL_ALLOC_MISSING #ifndef _WIN32 #include <pthread.h> #include <signal.h> #include <sys/mman.h> #include <unistd.h> #else #include <windows.h> #endif #ifdef __linux__ #include <sys/prctl.h> #endif #include <string.h> #include <algorithm> #include <atomic> #include <cerrno> #include <cstddef> #include <new> #include "absl/base/dynamic_annotations.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/internal/spinlock.h" #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS) #define MAP_ANONYMOUS MAP_ANON #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { static const int kMaxLevel = 30; namespace { struct AllocList { struct Header { uintptr_t size; uintptr_t magic; LowLevelAlloc::Arena *arena; void *dummy_for_alignment; } header; int levels; AllocList *next[kMaxLevel]; }; } static int IntLog2(size_t size, size_t base) { int result = 0; for (size_t i = size; i > base; i >>= 1) { result++; } return result; } static int Random(uint32_t *state) { uint32_t r = *state; int result = 1; while ((((r = r * 1103515245 + 12345) >> 30) & 1) == 0) { result++; } *state = r; return result; } static int LLA_SkiplistLevels(size_t size, size_t base, uint32_t *random) { size_t max_fit = (size - offsetof(AllocList, next)) / sizeof(AllocList *); int level = IntLog2(size, base) + (random != nullptr ? Random(random) : 1); if (static_cast<size_t>(level) > max_fit) level = static_cast<int>(max_fit); if (level > kMaxLevel - 1) level = kMaxLevel - 1; ABSL_RAW_CHECK(level >= 1, "block not big enough for even one level"); return level; } static AllocList *LLA_SkiplistSearch(AllocList *head, AllocList *e, AllocList **prev) { AllocList *p = head; for (int level = head->levels - 1; level >= 0; level--) { for (AllocList *n; (n = p->next[level]) != nullptr && n < e; p = n) { } prev[level] = p; } return (head->levels == 0) ? nullptr : prev[0]->next[0]; } static void LLA_SkiplistInsert(AllocList *head, AllocList *e, AllocList **prev) { LLA_SkiplistSearch(head, e, prev); for (; head->levels < e->levels; head->levels++) { prev[head->levels] = head; } for (int i = 0; i != e->levels; i++) { e->next[i] = prev[i]->next[i]; prev[i]->next[i] = e; } } static void LLA_SkiplistDelete(AllocList *head, AllocList *e, AllocList **prev) { AllocList *found = LLA_SkiplistSearch(head, e, prev); ABSL_RAW_CHECK(e == found, "element not in freelist"); for (int i = 0; i != e->levels && prev[i]->next[i] == e; i++) { prev[i]->next[i] = e->next[i]; } while (head->levels > 0 && head->next[head->levels - 1] == nullptr) { head->levels--; } } struct LowLevelAlloc::Arena { explicit Arena(uint32_t flags_value); base_internal::SpinLock mu; AllocList freelist ABSL_GUARDED_BY(mu); int32_t allocation_count ABSL_GUARDED_BY(mu); const uint32_t flags; const size_t pagesize; const size_t round_up; const size_t min_size; uint32_t random ABSL_GUARDED_BY(mu); }; namespace { alignas(LowLevelAlloc::Arena) unsigned char default_arena_storage[sizeof( LowLevelAlloc::Arena)]; alignas(LowLevelAlloc::Arena) unsigned char unhooked_arena_storage[sizeof( LowLevelAlloc::Arena)]; #ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING alignas( LowLevelAlloc::Arena) unsigned char unhooked_async_sig_safe_arena_storage [sizeof(LowLevelAlloc::Arena)]; #endif absl::once_flag create_globals_once; void CreateGlobalArenas() { new (&default_arena_storage) LowLevelAlloc::Arena(LowLevelAlloc::kCallMallocHook); new (&unhooked_arena_storage) LowLevelAlloc::Arena(0); #ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING new (&unhooked_async_sig_safe_arena_storage) LowLevelAlloc::Arena(LowLevelAlloc::kAsyncSignalSafe); #endif } LowLevelAlloc::Arena *UnhookedArena() { base_internal::LowLevelCallOnce(&create_globals_once, CreateGlobalArenas); return reinterpret_cast<LowLevelAlloc::Arena *>(&unhooked_arena_storage); } #ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING LowLevelAlloc::Arena *UnhookedAsyncSigSafeArena() { base_internal::LowLevelCallOnce(&create_globals_once, CreateGlobalArenas); return reinterpret_cast<LowLevelAlloc::Arena *>( &unhooked_async_sig_safe_arena_storage); } #endif } LowLevelAlloc::Arena *LowLevelAlloc::DefaultArena() { base_internal::LowLevelCallOnce(&create_globals_once, CreateGlobalArenas); return reinterpret_cast<LowLevelAlloc::Arena *>(&default_arena_storage); } static const uintptr_t kMagicAllocated = 0x4c833e95U; static const uintptr_t kMagicUnallocated = ~kMagicAllocated; namespace { class ABSL_SCOPED_LOCKABLE ArenaLock { public: explicit ArenaLock(LowLevelAlloc::Arena *arena) ABSL_EXCLUSIVE_LOCK_FUNCTION(arena->mu) : arena_(arena) { #ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING if ((arena->flags & LowLevelAlloc::kAsyncSignalSafe) != 0) { sigset_t all; sigfillset(&all); mask_valid_ = pthread_sigmask(SIG_BLOCK, &all, &mask_) == 0; } #endif arena_->mu.Lock(); } ~ArenaLock() { ABSL_RAW_CHECK(left_, "haven't left Arena region"); } void Leave() ABSL_UNLOCK_FUNCTION() { arena_->mu.Unlock(); #ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING if (mask_valid_) { const int err = pthread_sigmask(SIG_SETMASK, &mask_, nullptr); if (err != 0) { ABSL_RAW_LOG(FATAL, "pthread_sigmask failed: %d", err); } } #endif left_ = true; } private: bool left_ = false; #ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING bool mask_valid_ = false; sigset_t mask_; #endif LowLevelAlloc::Arena *arena_; ArenaLock(const ArenaLock &) = delete; ArenaLock &operator=(const ArenaLock &) = delete; }; } inline static uintptr_t Magic(uintptr_t magic, AllocList::Header *ptr) { return magic ^ reinterpret_cast<uintptr_t>(ptr); } namespace { size_t GetPageSize() { #ifdef _WIN32 SYSTEM_INFO system_info; GetSystemInfo(&system_info); return std::max(system_info.dwPageSize, system_info.dwAllocationGranularity); #elif defined(__wasm__) || defined(__asmjs__) || defined(__hexagon__) return getpagesize(); #else return static_cast<size_t>(sysconf(_SC_PAGESIZE)); #endif } size_t RoundedUpBlockSize() { size_t round_up = 16; while (round_up < sizeof(AllocList::Header)) { round_up += round_up; } return round_up; } } LowLevelAlloc::Arena::Arena(uint32_t flags_value) : mu(base_internal::SCHEDULE_KERNEL_ONLY), allocation_count(0), flags(flags_value), pagesize(GetPageSize()), round_up(RoundedUpBlockSize()), min_size(2 * round_up), random(0) { freelist.header.size = 0; freelist.header.magic = Magic(kMagicUnallocated, &freelist.header); freelist.header.arena = this; freelist.levels = 0; memset(freelist.next, 0, sizeof(freelist.next)); } LowLevelAlloc::Arena *LowLevelAlloc::NewArena(uint32_t flags) { Arena *meta_data_arena = DefaultArena(); #ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING if ((flags & LowLevelAlloc::kAsyncSignalSafe) != 0) { meta_data_arena = UnhookedAsyncSigSafeArena(); } else #endif if ((flags & LowLevelAlloc::kCallMallocHook) == 0) { meta_data_arena = UnhookedArena(); } Arena *result = new (AllocWithArena(sizeof(*result), meta_data_arena)) Arena(flags); return result; } bool LowLevelAlloc::DeleteArena(Arena *arena) { ABSL_RAW_CHECK( arena != nullptr && arena != DefaultArena() && arena != UnhookedArena(), "may not delete default arena"); ArenaLock section(arena); if (arena->allocation_count != 0) { section.Leave(); return false; } while (arena->freelist.next[0] != nullptr) { AllocList *region = arena->freelist.next[0]; size_t size = region->header.size; arena->freelist.next[0] = region->next[0]; ABSL_RAW_CHECK( region->header.magic == Magic(kMagicUnallocated, &region->header), "bad magic number in DeleteArena()"); ABSL_RAW_CHECK(region->header.arena == arena, "bad arena pointer in DeleteArena()"); ABSL_RAW_CHECK(size % arena->pagesize == 0, "empty arena has non-page-aligned block size"); ABSL_RAW_CHECK(reinterpret_cast<uintptr_t>(region) % arena->pagesize == 0, "empty arena has non-page-aligned block"); int munmap_result; #ifdef _WIN32 munmap_result = VirtualFree(region, 0, MEM_RELEASE); ABSL_RAW_CHECK(munmap_result != 0, "LowLevelAlloc::DeleteArena: VitualFree failed"); #else #ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING if ((arena->flags & LowLevelAlloc::kAsyncSignalSafe) == 0) { munmap_result = munmap(region, size); } else { munmap_result = base_internal::DirectMunmap(region, size); } #else munmap_result = munmap(region, size); #endif if (munmap_result != 0) { ABSL_RAW_LOG(FATAL, "LowLevelAlloc::DeleteArena: munmap failed: %d", errno); } #endif } section.Leave(); arena->~Arena(); Free(arena); return true; } static inline uintptr_t CheckedAdd(uintptr_t a, uintptr_t b) { uintptr_t sum = a + b; ABSL_RAW_CHECK(sum >= a, "LowLevelAlloc arithmetic overflow"); return sum; } static inline uintptr_t RoundUp(uintptr_t addr, uintptr_t align) { return CheckedAdd(addr, align - 1) & ~(align - 1); } static AllocList *Next(int i, AllocList *prev, LowLevelAlloc::Arena *arena) { ABSL_RAW_CHECK(i < prev->levels, "too few levels in Next()"); AllocList *next = prev->next[i]; if (next != nullptr) { ABSL_RAW_CHECK( next->header.magic == Magic(kMagicUnallocated, &next->header), "bad magic number in Next()"); ABSL_RAW_CHECK(next->header.arena == arena, "bad arena pointer in Next()"); if (prev != &arena->freelist) { ABSL_RAW_CHECK(prev < next, "unordered freelist"); ABSL_RAW_CHECK(reinterpret_cast<char *>(prev) + prev->header.size < reinterpret_cast<char *>(next), "malformed freelist"); } } return next; } static void Coalesce(AllocList *a) { AllocList *n = a->next[0]; if (n != nullptr && reinterpret_cast<char *>(a) + a->header.size == reinterpret_cast<char *>(n)) { LowLevelAlloc::Arena *arena = a->header.arena; a->header.size += n->header.size; n->header.magic = 0; n->header.arena = nullptr; AllocList *prev[kMaxLevel]; LLA_SkiplistDelete(&arena->freelist, n, prev); LLA_SkiplistDelete(&arena->freelist, a, prev); a->levels = LLA_SkiplistLevels(a->header.size, arena->min_size, &arena->random); LLA_SkiplistInsert(&arena->freelist, a, prev); } } static void AddToFreelist(void *v, LowLevelAlloc::Arena *arena) { AllocList *f = reinterpret_cast<AllocList *>(reinterpret_cast<char *>(v) - sizeof(f->header)); ABSL_RAW_CHECK(f->header.magic == Magic(kMagicAllocated, &f->header), "bad magic number in AddToFreelist()"); ABSL_RAW_CHECK(f->header.arena == arena, "bad arena pointer in AddToFreelist()"); f->levels = LLA_SkiplistLevels(f->header.size, arena->min_size, &arena->random); AllocList *prev[kMaxLevel]; LLA_SkiplistInsert(&arena->freelist, f, prev); f->header.magic = Magic(kMagicUnallocated, &f->header); Coalesce(f); Coalesce(prev[0]); } void LowLevelAlloc::Free(void *v) { if (v != nullptr) { AllocList *f = reinterpret_cast<AllocList *>(reinterpret_cast<char *>(v) - sizeof(f->header)); LowLevelAlloc::Arena *arena = f->header.arena; ArenaLock section(arena); AddToFreelist(v, arena); ABSL_RAW_CHECK(arena->allocation_count > 0, "nothing in arena to free"); arena->allocation_count--; section.Leave(); } } static void *DoAllocWithArena(size_t request, LowLevelAlloc::Arena *arena) { void *result = nullptr; if (request != 0) { AllocList *s; ArenaLock section(arena); size_t req_rnd = RoundUp(CheckedAdd(request, sizeof(s->header)), arena->round_up); for (;;) { int i = LLA_SkiplistLevels(req_rnd, arena->min_size, nullptr) - 1; if (i < arena->freelist.levels) { AllocList *before = &arena->freelist; while ((s = Next(i, before, arena)) != nullptr && s->header.size < req_rnd) { before = s; } if (s != nullptr) { break; } } arena->mu.Unlock(); size_t new_pages_size = RoundUp(req_rnd, arena->pagesize * 16); void *new_pages; #ifdef _WIN32 new_pages = VirtualAlloc(nullptr, new_pages_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); ABSL_RAW_CHECK(new_pages != nullptr, "VirtualAlloc failed"); #else #ifndef ABSL_LOW_LEVEL_ALLOC_ASYNC_SIGNAL_SAFE_MISSING if ((arena->flags & LowLevelAlloc::kAsyncSignalSafe) != 0) { new_pages = base_internal::DirectMmap(nullptr, new_pages_size, PROT_WRITE|PROT_READ, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0); } else { new_pages = mmap(nullptr, new_pages_size, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); } #else new_pages = mmap(nullptr, new_pages_size, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); #endif if (new_pages == MAP_FAILED) { ABSL_RAW_LOG(FATAL, "mmap error: %d", errno); } #ifdef __linux__ #if defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME) prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, new_pages, new_pages_size, "absl"); #endif #endif #endif arena->mu.Lock(); s = reinterpret_cast<AllocList *>(new_pages); s->header.size = new_pages_size; s->header.magic = Magic(kMagicAllocated, &s->header); s->header.arena = arena; AddToFreelist(&s->levels, arena); } AllocList *prev[kMaxLevel]; LLA_SkiplistDelete(&arena->freelist, s, prev); if (CheckedAdd(req_rnd, arena->min_size) <= s->header.size) { AllocList *n = reinterpret_cast<AllocList *>(req_rnd + reinterpret_cast<char *>(s)); n->header.size = s->header.size - req_rnd; n->header.magic = Magic(kMagicAllocated, &n->header); n->header.arena = arena; s->header.size = req_rnd; AddToFreelist(&n->levels, arena); } s->header.magic = Magic(kMagicAllocated, &s->header); ABSL_RAW_CHECK(s->header.arena == arena, ""); arena->allocation_count++; section.Leave(); result = &s->levels; } ABSL_ANNOTATE_MEMORY_IS_UNINITIALIZED(result, request); return result; } void *LowLevelAlloc::Alloc(size_t request) { void *result = DoAllocWithArena(request, DefaultArena()); return result; } void *LowLevelAlloc::AllocWithArena(size_t request, Arena *arena) { ABSL_RAW_CHECK(arena != nullptr, "must pass a valid arena"); void *result = DoAllocWithArena(request, arena); return result; } } ABSL_NAMESPACE_END } #endif
#include "absl/base/internal/low_level_alloc.h" #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <thread> #include <unordered_map> #include <utility> #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif #include "absl/container/node_hash_map.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace base_internal { namespace { #define TEST_ASSERT(x) \ if (!(x)) { \ printf("TEST_ASSERT(%s) FAILED ON LINE %d\n", #x, __LINE__); \ abort(); \ } struct BlockDesc { char *ptr; int len; int fill; }; static void CheckBlockDesc(const BlockDesc &d) { for (int i = 0; i != d.len; i++) { TEST_ASSERT((d.ptr[i] & 0xff) == ((d.fill + i) & 0xff)); } } static void RandomizeBlockDesc(BlockDesc *d) { d->fill = rand() & 0xff; for (int i = 0; i != d->len; i++) { d->ptr[i] = (d->fill + i) & 0xff; } } static bool using_low_level_alloc = false; static void Test(bool use_new_arena, bool call_malloc_hook, int n) { typedef absl::node_hash_map<int, BlockDesc> AllocMap; AllocMap allocated; AllocMap::iterator it; BlockDesc block_desc; int rnd; LowLevelAlloc::Arena *arena = nullptr; if (use_new_arena) { int32_t flags = call_malloc_hook ? LowLevelAlloc::kCallMallocHook : 0; arena = LowLevelAlloc::NewArena(flags); } for (int i = 0; i != n; i++) { if (i != 0 && i % 10000 == 0) { printf("."); fflush(stdout); } switch (rand() & 1) { case 0: using_low_level_alloc = true; block_desc.len = rand() & 0x3fff; block_desc.ptr = reinterpret_cast<char *>( arena == nullptr ? LowLevelAlloc::Alloc(block_desc.len) : LowLevelAlloc::AllocWithArena(block_desc.len, arena)); using_low_level_alloc = false; RandomizeBlockDesc(&block_desc); rnd = rand(); it = allocated.find(rnd); if (it != allocated.end()) { CheckBlockDesc(it->second); using_low_level_alloc = true; LowLevelAlloc::Free(it->second.ptr); using_low_level_alloc = false; it->second = block_desc; } else { allocated[rnd] = block_desc; } break; case 1: it = allocated.begin(); if (it != allocated.end()) { CheckBlockDesc(it->second); using_low_level_alloc = true; LowLevelAlloc::Free(it->second.ptr); using_low_level_alloc = false; allocated.erase(it); } break; } } while ((it = allocated.begin()) != allocated.end()) { CheckBlockDesc(it->second); using_low_level_alloc = true; LowLevelAlloc::Free(it->second.ptr); using_low_level_alloc = false; allocated.erase(it); } if (use_new_arena) { TEST_ASSERT(LowLevelAlloc::DeleteArena(arena)); } } static struct BeforeMain { BeforeMain() { Test(false, false, 50000); Test(true, false, 50000); Test(true, true, 50000); } } before_main; } } ABSL_NAMESPACE_END } int main(int argc, char *argv[]) { printf("PASS\n"); #ifdef __EMSCRIPTEN__ MAIN_THREAD_EM_ASM({ if (ENVIRONMENT_IS_WEB) { if (typeof TEST_FINISH === 'function') { TEST_FINISH($0); } else { console.error('Attempted to exit with status ' + $0); console.error('But TEST_FINSIHED is not a function.'); } } }, 0); #endif return 0; }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/low_level_alloc.cc
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/internal/low_level_alloc_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
2acab193-0d60-4af4-aaab-b8d9cb4d5d73
cpp
abseil/abseil-cpp
has_ostream_operator
absl/strings/has_ostream_operator.h
absl/strings/has_ostream_operator_test.cc
#ifndef ABSL_STRINGS_HAS_OSTREAM_OPERATOR_H_ #define ABSL_STRINGS_HAS_OSTREAM_OPERATOR_H_ #include <ostream> #include <type_traits> #include <utility> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename T, typename = void> struct HasOstreamOperator : std::false_type {}; template <typename T> struct HasOstreamOperator< T, std::enable_if_t<std::is_same< std::ostream&, decltype(std::declval<std::ostream&>() << std::declval<const T&>())>::value>> : std::true_type {}; ABSL_NAMESPACE_END } #endif
#include "absl/strings/has_ostream_operator.h" #include <ostream> #include <string> #include "gtest/gtest.h" #include "absl/types/optional.h" namespace { struct TypeWithoutOstreamOp {}; struct TypeWithOstreamOp { friend std::ostream& operator<<(std::ostream& os, const TypeWithOstreamOp&) { return os; } }; TEST(HasOstreamOperatorTest, Works) { EXPECT_TRUE(absl::HasOstreamOperator<int>::value); EXPECT_TRUE(absl::HasOstreamOperator<std::string>::value); EXPECT_FALSE(absl::HasOstreamOperator<absl::optional<int>>::value); EXPECT_FALSE(absl::HasOstreamOperator<TypeWithoutOstreamOp>::value); EXPECT_TRUE(absl::HasOstreamOperator<TypeWithOstreamOp>::value); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/has_ostream_operator.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/has_ostream_operator_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
eebc771f-d79d-49fa-8145-74c80aa8fd38
cpp
abseil/abseil-cpp
str_format
absl/strings/str_format.h
absl/strings/str_format_test.cc
#ifndef ABSL_STRINGS_STR_FORMAT_H_ #define ABSL_STRINGS_STR_FORMAT_H_ #include <cstdint> #include <cstdio> #include <string> #include <type_traits> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/nullability.h" #include "absl/strings/internal/str_format/arg.h" #include "absl/strings/internal/str_format/bind.h" #include "absl/strings/internal/str_format/checker.h" #include "absl/strings/internal/str_format/extension.h" #include "absl/strings/internal/str_format/parser.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN class UntypedFormatSpec { public: UntypedFormatSpec() = delete; UntypedFormatSpec(const UntypedFormatSpec&) = delete; UntypedFormatSpec& operator=(const UntypedFormatSpec&) = delete; explicit UntypedFormatSpec(string_view s) : spec_(s) {} protected: explicit UntypedFormatSpec( absl::Nonnull<const str_format_internal::ParsedFormatBase*> pc) : spec_(pc) {} private: friend str_format_internal::UntypedFormatSpecImpl; str_format_internal::UntypedFormatSpecImpl spec_; }; template <typename T> str_format_internal::StreamedWrapper<T> FormatStreamed(const T& v) { return str_format_internal::StreamedWrapper<T>(v); } class FormatCountCapture { public: explicit FormatCountCapture(absl::Nonnull<int*> p) : p_(p) {} private: friend struct str_format_internal::FormatCountCaptureHelper; absl::Nonnull<int*> Unused() { return p_; } absl::Nonnull<int*> p_; }; template <typename... Args> using FormatSpec = str_format_internal::FormatSpecTemplate< str_format_internal::ArgumentToConv<Args>()...>; #if defined(__cpp_nontype_template_parameter_auto) template <auto... Conv> using ParsedFormat = absl::str_format_internal::ExtendedParsedFormat< absl::str_format_internal::ToFormatConversionCharSet(Conv)...>; #else template <char... Conv> using ParsedFormat = str_format_internal::ExtendedParsedFormat< absl::str_format_internal::ToFormatConversionCharSet(Conv)...>; #endif template <typename... Args> ABSL_MUST_USE_RESULT std::string StrFormat(const FormatSpec<Args...>& format, const Args&... args) { return str_format_internal::FormatPack( str_format_internal::UntypedFormatSpecImpl::Extract(format), {str_format_internal::FormatArgImpl(args)...}); } template <typename... Args> std::string& StrAppendFormat(absl::Nonnull<std::string*> dst, const FormatSpec<Args...>& format, const Args&... args) { return str_format_internal::AppendPack( dst, str_format_internal::UntypedFormatSpecImpl::Extract(format), {str_format_internal::FormatArgImpl(args)...}); } template <typename... Args> ABSL_MUST_USE_RESULT str_format_internal::Streamable StreamFormat( const FormatSpec<Args...>& format, const Args&... args) { return str_format_internal::Streamable( str_format_internal::UntypedFormatSpecImpl::Extract(format), {str_format_internal::FormatArgImpl(args)...}); } template <typename... Args> int PrintF(const FormatSpec<Args...>& format, const Args&... args) { return str_format_internal::FprintF( stdout, str_format_internal::UntypedFormatSpecImpl::Extract(format), {str_format_internal::FormatArgImpl(args)...}); } template <typename... Args> int FPrintF(absl::Nonnull<std::FILE*> output, const FormatSpec<Args...>& format, const Args&... args) { return str_format_internal::FprintF( output, str_format_internal::UntypedFormatSpecImpl::Extract(format), {str_format_internal::FormatArgImpl(args)...}); } template <typename... Args> int SNPrintF(absl::Nonnull<char*> output, std::size_t size, const FormatSpec<Args...>& format, const Args&... args) { return str_format_internal::SnprintF( output, size, str_format_internal::UntypedFormatSpecImpl::Extract(format), {str_format_internal::FormatArgImpl(args)...}); } class FormatRawSink { public: template <typename T, typename = typename std::enable_if<std::is_constructible< str_format_internal::FormatRawSinkImpl, T*>::value>::type> FormatRawSink(absl::Nonnull<T*> raw) : sink_(raw) {} private: friend str_format_internal::FormatRawSinkImpl; str_format_internal::FormatRawSinkImpl sink_; }; template <typename... Args> bool Format(FormatRawSink raw_sink, const FormatSpec<Args...>& format, const Args&... args) { return str_format_internal::FormatUntyped( str_format_internal::FormatRawSinkImpl::Extract(raw_sink), str_format_internal::UntypedFormatSpecImpl::Extract(format), {str_format_internal::FormatArgImpl(args)...}); } using FormatArg = str_format_internal::FormatArgImpl; ABSL_MUST_USE_RESULT inline bool FormatUntyped( FormatRawSink raw_sink, const UntypedFormatSpec& format, absl::Span<const FormatArg> args) { return str_format_internal::FormatUntyped( str_format_internal::FormatRawSinkImpl::Extract(raw_sink), str_format_internal::UntypedFormatSpecImpl::Extract(format), args); } enum class FormatConversionChar : uint8_t { c, s, d, i, o, u, x, X, f, F, e, E, g, G, a, A, n, p, v }; class FormatConversionSpec { public: bool is_basic() const { return impl_.is_basic(); } bool has_left_flag() const { return impl_.has_left_flag(); } bool has_show_pos_flag() const { return impl_.has_show_pos_flag(); } bool has_sign_col_flag() const { return impl_.has_sign_col_flag(); } bool has_alt_flag() const { return impl_.has_alt_flag(); } bool has_zero_flag() const { return impl_.has_zero_flag(); } FormatConversionChar conversion_char() const { return impl_.conversion_char(); } int width() const { return impl_.width(); } int precision() const { return impl_.precision(); } private: explicit FormatConversionSpec( str_format_internal::FormatConversionSpecImpl impl) : impl_(impl) {} friend str_format_internal::FormatConversionSpecImpl; absl::str_format_internal::FormatConversionSpecImpl impl_; }; constexpr FormatConversionCharSet operator|(FormatConversionCharSet a, FormatConversionCharSet b) { return static_cast<FormatConversionCharSet>(static_cast<uint64_t>(a) | static_cast<uint64_t>(b)); } enum class FormatConversionCharSet : uint64_t { c = str_format_internal::FormatConversionCharToConvInt('c'), s = str_format_internal::FormatConversionCharToConvInt('s'), d = str_format_internal::FormatConversionCharToConvInt('d'), i = str_format_internal::FormatConversionCharToConvInt('i'), o = str_format_internal::FormatConversionCharToConvInt('o'), u = str_format_internal::FormatConversionCharToConvInt('u'), x = str_format_internal::FormatConversionCharToConvInt('x'), X = str_format_internal::FormatConversionCharToConvInt('X'), f = str_format_internal::FormatConversionCharToConvInt('f'), F = str_format_internal::FormatConversionCharToConvInt('F'), e = str_format_internal::FormatConversionCharToConvInt('e'), E = str_format_internal::FormatConversionCharToConvInt('E'), g = str_format_internal::FormatConversionCharToConvInt('g'), G = str_format_internal::FormatConversionCharToConvInt('G'), a = str_format_internal::FormatConversionCharToConvInt('a'), A = str_format_internal::FormatConversionCharToConvInt('A'), n = str_format_internal::FormatConversionCharToConvInt('n'), p = str_format_internal::FormatConversionCharToConvInt('p'), v = str_format_internal::FormatConversionCharToConvInt('v'), kStar = static_cast<uint64_t>( absl::str_format_internal::FormatConversionCharSetInternal::kStar), kIntegral = d | i | u | o | x | X, kFloating = a | e | f | g | A | E | F | G, kNumeric = kIntegral | kFloating, kString = s, kPointer = p, }; class FormatSink { public: void Append(size_t count, char ch) { sink_->Append(count, ch); } void Append(string_view v) { sink_->Append(v); } bool PutPaddedString(string_view v, int width, int precision, bool left) { return sink_->PutPaddedString(v, width, precision, left); } friend void AbslFormatFlush(absl::Nonnull<FormatSink*> sink, absl::string_view v) { sink->Append(v); } private: friend str_format_internal::FormatSinkImpl; explicit FormatSink(absl::Nonnull<str_format_internal::FormatSinkImpl*> s) : sink_(s) {} absl::Nonnull<str_format_internal::FormatSinkImpl*> sink_; }; template <FormatConversionCharSet C> struct FormatConvertResult { bool value; }; ABSL_NAMESPACE_END } #endif
#include "absl/strings/str_format.h" #include <cerrno> #include <cstdarg> #include <cstdint> #include <cstdio> #include <ostream> #include <sstream> #include <string> #include <type_traits> #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/base/macros.h" #include "absl/strings/cord.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { using str_format_internal::FormatArgImpl; using FormatEntryPointTest = ::testing::Test; TEST_F(FormatEntryPointTest, Format) { std::string sink; EXPECT_TRUE(Format(&sink, "A format %d", 123)); EXPECT_EQ("A format 123", sink); sink.clear(); ParsedFormat<'d'> pc("A format %d"); EXPECT_TRUE(Format(&sink, pc, 123)); EXPECT_EQ("A format 123", sink); } TEST_F(FormatEntryPointTest, FormatWithV) { std::string sink; EXPECT_TRUE(Format(&sink, "A format %v", 123)); EXPECT_EQ("A format 123", sink); sink.clear(); ParsedFormat<'v'> pc("A format %v"); EXPECT_TRUE(Format(&sink, pc, 123)); EXPECT_EQ("A format 123", sink); } TEST_F(FormatEntryPointTest, UntypedFormat) { constexpr const char* formats[] = { "", "a", "%80d", #if !defined(_MSC_VER) && !defined(__ANDROID__) && !defined(__native_client__) "complicated multipart %% %1$d format %1$0999d", #endif }; for (const char* fmt : formats) { std::string actual; int i = 123; FormatArgImpl arg_123(i); absl::Span<const FormatArgImpl> args(&arg_123, 1); UntypedFormatSpec format(fmt); EXPECT_TRUE(FormatUntyped(&actual, format, args)); char buf[4096]{}; snprintf(buf, sizeof(buf), fmt, 123); EXPECT_EQ( str_format_internal::FormatPack( str_format_internal::UntypedFormatSpecImpl::Extract(format), args), buf); EXPECT_EQ(actual, buf); } ParsedFormat<'d'> pc("A format %d"); int i = 345; FormatArg arg(i); std::string out; EXPECT_TRUE(str_format_internal::FormatUntyped( &out, str_format_internal::UntypedFormatSpecImpl(&pc), {&arg, 1})); EXPECT_EQ("A format 345", out); } TEST_F(FormatEntryPointTest, StringFormat) { EXPECT_EQ("123", StrFormat("%d", 123)); constexpr absl::string_view view("=%d=", 4); EXPECT_EQ("=123=", StrFormat(view, 123)); } TEST_F(FormatEntryPointTest, StringFormatV) { std::string hello = "hello"; EXPECT_EQ("hello", StrFormat("%v", hello)); EXPECT_EQ("123", StrFormat("%v", 123)); constexpr absl::string_view view("=%v=", 4); EXPECT_EQ("=123=", StrFormat(view, 123)); } TEST_F(FormatEntryPointTest, AppendFormat) { std::string s; std::string& r = StrAppendFormat(&s, "%d", 123); EXPECT_EQ(&s, &r); EXPECT_EQ("123", r); } TEST_F(FormatEntryPointTest, AppendFormatWithV) { std::string s; std::string& r = StrAppendFormat(&s, "%v", 123); EXPECT_EQ(&s, &r); EXPECT_EQ("123", r); } TEST_F(FormatEntryPointTest, AppendFormatFail) { std::string s = "orig"; UntypedFormatSpec format(" more %d"); FormatArgImpl arg("not an int"); EXPECT_EQ("orig", str_format_internal::AppendPack( &s, str_format_internal::UntypedFormatSpecImpl::Extract(format), {&arg, 1})); } TEST_F(FormatEntryPointTest, AppendFormatFailWithV) { std::string s = "orig"; UntypedFormatSpec format(" more %v"); FormatArgImpl arg("not an int"); EXPECT_EQ("orig", str_format_internal::AppendPack( &s, str_format_internal::UntypedFormatSpecImpl::Extract(format), {&arg, 1})); } TEST_F(FormatEntryPointTest, ManyArgs) { EXPECT_EQ( "60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 " "36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 " "12 11 10 9 8 7 6 5 4 3 2 1", StrFormat("%60$d %59$d %58$d %57$d %56$d %55$d %54$d %53$d %52$d %51$d " "%50$d %49$d %48$d %47$d %46$d %45$d %44$d %43$d %42$d %41$d " "%40$d %39$d %38$d %37$d %36$d %35$d %34$d %33$d %32$d %31$d " "%30$d %29$d %28$d %27$d %26$d %25$d %24$d %23$d %22$d %21$d " "%20$d %19$d %18$d %17$d %16$d %15$d %14$d %13$d %12$d %11$d " "%10$d %9$d %8$d %7$d %6$d %5$d %4$d %3$d %2$d %1$d", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60)); } TEST_F(FormatEntryPointTest, Preparsed) { ParsedFormat<'d'> pc("%d"); EXPECT_EQ("123", StrFormat(pc, 123)); EXPECT_EQ("123", StrFormat(ParsedFormat<'d'>("%d"), 123)); constexpr absl::string_view view("=%d=", 4); EXPECT_EQ("=123=", StrFormat(ParsedFormat<'d'>(view), 123)); } TEST_F(FormatEntryPointTest, PreparsedWithV) { ParsedFormat<'v'> pc("%v"); EXPECT_EQ("123", StrFormat(pc, 123)); EXPECT_EQ("123", StrFormat(ParsedFormat<'v'>("%v"), 123)); constexpr absl::string_view view("=%v=", 4); EXPECT_EQ("=123=", StrFormat(ParsedFormat<'v'>(view), 123)); } TEST_F(FormatEntryPointTest, FormatCountCapture) { int n = 0; EXPECT_EQ("", StrFormat("%n", FormatCountCapture(&n))); EXPECT_EQ(0, n); EXPECT_EQ("123", StrFormat("%d%n", 123, FormatCountCapture(&n))); EXPECT_EQ(3, n); } TEST_F(FormatEntryPointTest, FormatCountCaptureWithV) { int n = 0; EXPECT_EQ("", StrFormat("%n", FormatCountCapture(&n))); EXPECT_EQ(0, n); EXPECT_EQ("123", StrFormat("%v%n", 123, FormatCountCapture(&n))); EXPECT_EQ(3, n); } TEST_F(FormatEntryPointTest, FormatCountCaptureWrongType) { int n = 0; UntypedFormatSpec format("%d%n"); int i = 123, *ip = &n; FormatArgImpl args[2] = {FormatArgImpl(i), FormatArgImpl(ip)}; EXPECT_EQ("", str_format_internal::FormatPack( str_format_internal::UntypedFormatSpecImpl::Extract(format), absl::MakeSpan(args))); } TEST_F(FormatEntryPointTest, FormatCountCaptureWrongTypeWithV) { int n = 0; UntypedFormatSpec format("%v%n"); int i = 123, *ip = &n; FormatArgImpl args[2] = {FormatArgImpl(i), FormatArgImpl(ip)}; EXPECT_EQ("", str_format_internal::FormatPack( str_format_internal::UntypedFormatSpecImpl::Extract(format), absl::MakeSpan(args))); } TEST_F(FormatEntryPointTest, FormatCountCaptureMultiple) { int n1 = 0; int n2 = 0; EXPECT_EQ(" 1 2", StrFormat("%5d%n%10d%n", 1, FormatCountCapture(&n1), 2, FormatCountCapture(&n2))); EXPECT_EQ(5, n1); EXPECT_EQ(15, n2); } TEST_F(FormatEntryPointTest, FormatCountCaptureExample) { int n; std::string s; StrAppendFormat(&s, "%s: %n%s\n", "(1,1)", FormatCountCapture(&n), "(1,2)"); StrAppendFormat(&s, "%*s%s\n", n, "", "(2,2)"); EXPECT_EQ(7, n); EXPECT_EQ( "(1,1): (1,2)\n" " (2,2)\n", s); } TEST_F(FormatEntryPointTest, FormatCountCaptureExampleWithV) { int n; std::string s; std::string a1 = "(1,1)"; std::string a2 = "(1,2)"; std::string a3 = "(2,2)"; StrAppendFormat(&s, "%v: %n%v\n", a1, FormatCountCapture(&n), a2); StrAppendFormat(&s, "%*s%v\n", n, "", a3); EXPECT_EQ(7, n); EXPECT_EQ( "(1,1): (1,2)\n" " (2,2)\n", s); } TEST_F(FormatEntryPointTest, Stream) { const std::string formats[] = { "", "a", "%80d", "%d %u %c %s %f %g", #if !defined(_MSC_VER) && !defined(__ANDROID__) && !defined(__native_client__) "complicated multipart %% %1$d format %1$080d", #endif }; std::string buf(4096, '\0'); for (const auto& fmt : formats) { const auto parsed = ParsedFormat<'d', 'u', 'c', 's', 'f', 'g'>::NewAllowIgnored(fmt); std::ostringstream oss; oss << StreamFormat(*parsed, 123, 3, 49, "multistreaming!!!", 1.01, 1.01); int fmt_result = snprintf(&*buf.begin(), buf.size(), fmt.c_str(), 123, 3, 49, "multistreaming!!!", 1.01, 1.01); ASSERT_TRUE(oss) << fmt; ASSERT_TRUE(fmt_result >= 0 && static_cast<size_t>(fmt_result) < buf.size()) << fmt_result; EXPECT_EQ(buf.c_str(), oss.str()); } } TEST_F(FormatEntryPointTest, StreamWithV) { const std::string formats[] = { "", "a", "%v %u %c %v %f %v", }; const std::string formats_for_buf[] = { "", "a", "%d %u %c %s %f %g", }; std::string buf(4096, '\0'); for (auto i = 0; i < ABSL_ARRAYSIZE(formats); ++i) { const auto parsed = ParsedFormat<'v', 'u', 'c', 'v', 'f', 'v'>::NewAllowIgnored(formats[i]); std::ostringstream oss; oss << StreamFormat(*parsed, 123, 3, 49, absl::string_view("multistreaming!!!"), 1.01, 1.01); int fmt_result = snprintf(&*buf.begin(), buf.size(), formats_for_buf[i].c_str(), 123, 3, 49, "multistreaming!!!", 1.01, 1.01); ASSERT_TRUE(oss) << formats[i]; ASSERT_TRUE(fmt_result >= 0 && static_cast<size_t>(fmt_result) < buf.size()) << fmt_result; EXPECT_EQ(buf.c_str(), oss.str()); } } TEST_F(FormatEntryPointTest, StreamOk) { std::ostringstream oss; oss << StreamFormat("hello %d", 123); EXPECT_EQ("hello 123", oss.str()); EXPECT_TRUE(oss.good()); } TEST_F(FormatEntryPointTest, StreamOkWithV) { std::ostringstream oss; oss << StreamFormat("hello %v", 123); EXPECT_EQ("hello 123", oss.str()); EXPECT_TRUE(oss.good()); } TEST_F(FormatEntryPointTest, StreamFail) { std::ostringstream oss; UntypedFormatSpec format("hello %d"); FormatArgImpl arg("non-numeric"); oss << str_format_internal::Streamable( str_format_internal::UntypedFormatSpecImpl::Extract(format), {&arg, 1}); EXPECT_EQ("hello ", oss.str()); EXPECT_TRUE(oss.fail()); } TEST_F(FormatEntryPointTest, StreamFailWithV) { std::ostringstream oss; UntypedFormatSpec format("hello %v"); FormatArgImpl arg("non-numeric"); oss << str_format_internal::Streamable( str_format_internal::UntypedFormatSpecImpl::Extract(format), {&arg, 1}); EXPECT_EQ("hello ", oss.str()); EXPECT_TRUE(oss.fail()); } std::string WithSnprintf(const char* fmt, ...) { std::string buf; buf.resize(128); va_list va; va_start(va, fmt); int r = vsnprintf(&*buf.begin(), buf.size(), fmt, va); va_end(va); EXPECT_GE(r, 0); EXPECT_LT(r, buf.size()); buf.resize(r); return buf; } TEST_F(FormatEntryPointTest, FloatPrecisionArg) { EXPECT_EQ("0.1", StrFormat("%.1f", 0.1)); EXPECT_EQ("0.1", WithSnprintf("%.1f", 0.1)); EXPECT_EQ(" 0.1", StrFormat("%*.1f", 5, 0.1)); EXPECT_EQ(" 0.1", WithSnprintf("%*.1f", 5, 0.1)); EXPECT_EQ("0.1", StrFormat("%.*f", 1, 0.1)); EXPECT_EQ("0.1", WithSnprintf("%.*f", 1, 0.1)); EXPECT_EQ(" 0.1", StrFormat("%*.*f", 5, 1, 0.1)); EXPECT_EQ(" 0.1", WithSnprintf("%*.*f", 5, 1, 0.1)); } namespace streamed_test { struct X {}; std::ostream& operator<<(std::ostream& os, const X&) { return os << "X"; } } TEST_F(FormatEntryPointTest, FormatStreamed) { EXPECT_EQ("123", StrFormat("%s", FormatStreamed(123))); EXPECT_EQ(" 123", StrFormat("%5s", FormatStreamed(123))); EXPECT_EQ("123 ", StrFormat("%-5s", FormatStreamed(123))); EXPECT_EQ("X", StrFormat("%s", FormatStreamed(streamed_test::X()))); EXPECT_EQ("123", StrFormat("%s", FormatStreamed(StreamFormat("%d", 123)))); } TEST_F(FormatEntryPointTest, FormatStreamedWithV) { EXPECT_EQ("123", StrFormat("%v", FormatStreamed(123))); EXPECT_EQ("X", StrFormat("%v", FormatStreamed(streamed_test::X()))); EXPECT_EQ("123", StrFormat("%v", FormatStreamed(StreamFormat("%d", 123)))); } class TempFile { public: TempFile() : file_(std::tmpfile()) {} ~TempFile() { std::fclose(file_); } std::FILE* file() const { return file_; } std::string ReadFile() { std::fseek(file_, 0, SEEK_END); int size = std::ftell(file_); EXPECT_GT(size, 0); std::rewind(file_); std::string str(2 * size, ' '); int read_bytes = std::fread(&str[0], 1, str.size(), file_); EXPECT_EQ(read_bytes, size); str.resize(read_bytes); EXPECT_TRUE(std::feof(file_)); return str; } private: std::FILE* file_; }; TEST_F(FormatEntryPointTest, FPrintF) { TempFile tmp; int result = FPrintF(tmp.file(), "STRING: %s NUMBER: %010d", std::string("ABC"), -19); EXPECT_EQ(result, 30); EXPECT_EQ(tmp.ReadFile(), "STRING: ABC NUMBER: -000000019"); } TEST_F(FormatEntryPointTest, FPrintFWithV) { TempFile tmp; int result = FPrintF(tmp.file(), "STRING: %v NUMBER: %010d", std::string("ABC"), -19); EXPECT_EQ(result, 30); EXPECT_EQ(tmp.ReadFile(), "STRING: ABC NUMBER: -000000019"); } TEST_F(FormatEntryPointTest, FPrintFError) { errno = 0; int result = FPrintF(stdin, "ABC"); EXPECT_LT(result, 0); EXPECT_EQ(errno, EBADF); } #ifdef __GLIBC__ TEST_F(FormatEntryPointTest, FprintfTooLarge) { std::FILE* f = std::fopen("/dev/null", "w"); int width = 2000000000; errno = 0; int result = FPrintF(f, "%*d %*d", width, 0, width, 0); EXPECT_LT(result, 0); EXPECT_EQ(errno, EFBIG); std::fclose(f); } TEST_F(FormatEntryPointTest, PrintF) { int stdout_tmp = dup(STDOUT_FILENO); TempFile tmp; std::fflush(stdout); dup2(fileno(tmp.file()), STDOUT_FILENO); int result = PrintF("STRING: %s NUMBER: %010d", std::string("ABC"), -19); std::fflush(stdout); dup2(stdout_tmp, STDOUT_FILENO); close(stdout_tmp); EXPECT_EQ(result, 30); EXPECT_EQ(tmp.ReadFile(), "STRING: ABC NUMBER: -000000019"); } TEST_F(FormatEntryPointTest, PrintFWithV) { int stdout_tmp = dup(STDOUT_FILENO); TempFile tmp; std::fflush(stdout); dup2(fileno(tmp.file()), STDOUT_FILENO); int result = PrintF("STRING: %v NUMBER: %010d", std::string("ABC"), -19); std::fflush(stdout); dup2(stdout_tmp, STDOUT_FILENO); close(stdout_tmp); EXPECT_EQ(result, 30); EXPECT_EQ(tmp.ReadFile(), "STRING: ABC NUMBER: -000000019"); } #endif TEST_F(FormatEntryPointTest, SNPrintF) { char buffer[16]; int result = SNPrintF(buffer, sizeof(buffer), "STRING: %s", std::string("ABC")); EXPECT_EQ(result, 11); EXPECT_EQ(std::string(buffer), "STRING: ABC"); result = SNPrintF(buffer, sizeof(buffer), "NUMBER: %d", 123456); EXPECT_EQ(result, 14); EXPECT_EQ(std::string(buffer), "NUMBER: 123456"); result = SNPrintF(buffer, sizeof(buffer), "NUMBER: %d", 1234567); EXPECT_EQ(result, 15); EXPECT_EQ(std::string(buffer), "NUMBER: 1234567"); result = SNPrintF(buffer, sizeof(buffer), "NUMBER: %d", 12345678); EXPECT_EQ(result, 16); EXPECT_EQ(std::string(buffer), "NUMBER: 1234567"); result = SNPrintF(buffer, sizeof(buffer), "NUMBER: %d", 123456789); EXPECT_EQ(result, 17); EXPECT_EQ(std::string(buffer), "NUMBER: 1234567"); char* null_output = nullptr; result = SNPrintF(null_output, 0, "Just checking the %s of the output.", "size"); EXPECT_EQ(result, 37); } TEST_F(FormatEntryPointTest, SNPrintFWithV) { char buffer[16]; int result = SNPrintF(buffer, sizeof(buffer), "STRING: %v", std::string("ABC")); EXPECT_EQ(result, 11); EXPECT_EQ(std::string(buffer), "STRING: ABC"); result = SNPrintF(buffer, sizeof(buffer), "NUMBER: %v", 123456); EXPECT_EQ(result, 14); EXPECT_EQ(std::string(buffer), "NUMBER: 123456"); result = SNPrintF(buffer, sizeof(buffer), "NUMBER: %v", 1234567); EXPECT_EQ(result, 15); EXPECT_EQ(std::string(buffer), "NUMBER: 1234567"); result = SNPrintF(buffer, sizeof(buffer), "NUMBER: %v", 12345678); EXPECT_EQ(result, 16); EXPECT_EQ(std::string(buffer), "NUMBER: 1234567"); result = SNPrintF(buffer, sizeof(buffer), "NUMBER: %v", 123456789); EXPECT_EQ(result, 17); EXPECT_EQ(std::string(buffer), "NUMBER: 1234567"); std::string size = "size"; char* null_output = nullptr; result = SNPrintF(null_output, 0, "Just checking the %v of the output.", size); EXPECT_EQ(result, 37); } TEST(StrFormat, BehavesAsDocumented) { std::string s = absl::StrFormat("%s, %d!", "Hello", 123); EXPECT_EQ("Hello, 123!", s); std::string hello = "Hello"; std::string s2 = absl::StrFormat("%v, %v!", hello, 123); EXPECT_EQ("Hello, 123!", s2); EXPECT_EQ(absl::StrFormat("%1$+3.2Lf", 1.1), "+1.10"); EXPECT_EQ(StrFormat("%c", 'a'), "a"); EXPECT_EQ(StrFormat("%c", 0x20), " "); EXPECT_EQ(StrFormat("%c", int{'a'}), "a"); EXPECT_EQ(StrFormat("%c", long{'a'}), "a"); EXPECT_EQ(StrFormat("%c", uint64_t{'a'}), "a"); EXPECT_EQ(StrFormat("%s", "C"), "C"); EXPECT_EQ(StrFormat("%v", std::string("C")), "C"); EXPECT_EQ(StrFormat("%s", std::string("C++")), "C++"); EXPECT_EQ(StrFormat("%v", std::string("C++")), "C++"); EXPECT_EQ(StrFormat("%s", string_view("view")), "view"); EXPECT_EQ(StrFormat("%v", string_view("view")), "view"); EXPECT_EQ(StrFormat("%s", absl::Cord("cord")), "cord"); EXPECT_EQ(StrFormat("%v", absl::Cord("cord")), "cord"); EXPECT_EQ(StrFormat("%d", char{10}), "10"); EXPECT_EQ(StrFormat("%d", int{10}), "10"); EXPECT_EQ(StrFormat("%d", long{10}), "10"); EXPECT_EQ(StrFormat("%d", uint64_t{10}), "10"); EXPECT_EQ(StrFormat("%v", int{10}), "10"); EXPECT_EQ(StrFormat("%v", long{10}), "10"); EXPECT_EQ(StrFormat("%v", uint64_t{10}), "10"); EXPECT_EQ(StrFormat("%d", -10), "-10"); EXPECT_EQ(StrFormat("%i", -10), "-10"); EXPECT_EQ(StrFormat("%v", -10), "-10"); EXPECT_EQ(StrFormat("%o", 10), "12"); EXPECT_EQ(StrFormat("%u", 10), "10"); EXPECT_EQ(StrFormat("%v", 10), "10"); EXPECT_EQ(StrFormat("%x", 10), "a"); EXPECT_EQ(StrFormat("%X", 10), "A"); EXPECT_EQ(StrFormat("%.1f", float{1}), "1.0"); EXPECT_EQ(StrFormat("%.1f", double{1}), "1.0"); const long double long_double = 1.0; EXPECT_EQ(StrFormat("%.1f", long_double), "1.0"); EXPECT_EQ(StrFormat("%.1f", char{1}), "1.0"); EXPECT_EQ(StrFormat("%.1f", int{1}), "1.0"); EXPECT_EQ(StrFormat("%.1f", long{1}), "1.0"); EXPECT_EQ(StrFormat("%.1f", uint64_t{1}), "1.0"); EXPECT_EQ(StrFormat("%f", 123456789), "123456789.000000"); EXPECT_EQ(StrFormat("%F", 123456789), "123456789.000000"); EXPECT_EQ(StrFormat("%e", .01), "1.000000e-02"); EXPECT_EQ(StrFormat("%E", .01), "1.000000E-02"); EXPECT_EQ(StrFormat("%g", .01), "0.01"); EXPECT_EQ(StrFormat("%g", 1e10), "1e+10"); EXPECT_EQ(StrFormat("%G", 1e10), "1E+10"); EXPECT_EQ(StrFormat("%v", .01), "0.01"); EXPECT_EQ(StrFormat("%v", 1e10), "1e+10"); #if !defined(__ANDROID_API__) || __ANDROID_API__ > 21 EXPECT_EQ(StrFormat("%.1a", -3.0), "-0x1.8p+1"); EXPECT_EQ(StrFormat("%.1A", -3.0), "-0X1.8P+1"); #endif int64_t value = 0x7ffdeb4; auto ptr_value = static_cast<uintptr_t>(value); const int& something = *reinterpret_cast<const int*>(ptr_value); EXPECT_EQ(StrFormat("%p", &something), StrFormat("0x%x", ptr_value)); (void)StrFormat("%p", nullptr); EXPECT_EQ(StrFormat("%3d", 1), " 1"); EXPECT_EQ(StrFormat("%3d", 123456), "123456"); EXPECT_EQ(StrFormat("%06.2f", 1.234), "001.23"); EXPECT_EQ(StrFormat("%+d", 1), "+1"); EXPECT_EQ(StrFormat("% d", 1), " 1"); EXPECT_EQ(StrFormat("%-4d", -1), "-1 "); EXPECT_EQ(StrFormat("%#o", 10), "012"); EXPECT_EQ(StrFormat("%#x", 15), "0xf"); EXPECT_EQ(StrFormat("%04d", 8), "0008"); EXPECT_EQ(StrFormat("%#04x", 0), "0000"); EXPECT_EQ(StrFormat("%#04x", 1), "0x01"); EXPECT_EQ(absl::StrFormat("%2$s, %3$s, %1$s!", "vici", "veni", "vidi"), "veni, vidi, vici!"); EXPECT_EQ(StrFormat("%hhd", int{1}), "1"); EXPECT_EQ(StrFormat("%hd", int{1}), "1"); EXPECT_EQ(StrFormat("%ld", int{1}), "1"); EXPECT_EQ(StrFormat("%lld", int{1}), "1"); EXPECT_EQ(StrFormat("%Ld", int{1}), "1"); EXPECT_EQ(StrFormat("%jd", int{1}), "1"); EXPECT_EQ(StrFormat("%zd", int{1}), "1"); EXPECT_EQ(StrFormat("%td", int{1}), "1"); EXPECT_EQ(StrFormat("%qd", int{1}), "1"); EXPECT_EQ(StrFormat("%v", true), "true"); EXPECT_EQ(StrFormat("%v", false), "false"); EXPECT_EQ(StrFormat("%d", true), "1"); } using str_format_internal::ExtendedParsedFormat; using str_format_internal::ParsedFormatBase; struct SummarizeConsumer { std::string* out; explicit SummarizeConsumer(std::string* out) : out(out) {} bool Append(string_view s) { *out += "[" + std::string(s) + "]"; return true; } bool ConvertOne(const str_format_internal::UnboundConversion& conv, string_view s) { *out += "{"; *out += std::string(s); *out += ":"; *out += std::to_string(conv.arg_position) + "$"; if (conv.width.is_from_arg()) { *out += std::to_string(conv.width.get_from_arg()) + "$*"; } if (conv.precision.is_from_arg()) { *out += "." + std::to_string(conv.precision.get_from_arg()) + "$*"; } *out += str_format_internal::FormatConversionCharToChar(conv.conv); *out += "}"; return true; } }; std::string SummarizeParsedFormat(const ParsedFormatBase& pc) { std::string out; if (!pc.ProcessFormat(SummarizeConsumer(&out))) out += "!"; return out; } using ParsedFormatTest = ::testing::Test; TEST_F(ParsedFormatTest, SimpleChecked) { EXPECT_EQ("[ABC]{d:1$d}[DEF]", SummarizeParsedFormat(ParsedFormat<'d'>("ABC%dDEF"))); EXPECT_EQ("{s:1$s}[FFF]{d:2$d}[ZZZ]{f:3$f}", SummarizeParsedFormat(ParsedFormat<'s', 'd', 'f'>("%sFFF%dZZZ%f"))); EXPECT_EQ("{s:1$s}[ ]{.*d:3$.2$*d}", SummarizeParsedFormat(ParsedFormat<'s', '*', 'd'>("%s %.*d"))); } TEST_F(ParsedFormatTest, SimpleCheckedWithV) { EXPECT_EQ("[ABC]{v:1$v}[DEF]", SummarizeParsedFormat(ParsedFormat<'v'>("ABC%vDEF"))); EXPECT_EQ("{v:1$v}[FFF]{v:2$v}[ZZZ]{f:3$f}", SummarizeParsedFormat(ParsedFormat<'v', 'v', 'f'>("%vFFF%vZZZ%f"))); EXPECT_EQ("{v:1$v}[ ]{.*d:3$.2$*d}", SummarizeParsedFormat(ParsedFormat<'v', '*', 'd'>("%v %.*d"))); } TEST_F(ParsedFormatTest, SimpleUncheckedCorrect) { auto f = ParsedFormat<'d'>::New("ABC%dDEF"); ASSERT_TRUE(f); EXPECT_EQ("[ABC]{d:1$d}[DEF]", SummarizeParsedFormat(*f)); std::string format = "%sFFF%dZZZ%f"; auto f2 = ParsedFormat<'s', 'd', 'f'>::New(format); ASSERT_TRUE(f2); EXPECT_EQ("{s:1$s}[FFF]{d:2$d}[ZZZ]{f:3$f}", SummarizeParsedFormat(*f2)); f2 = ParsedFormat<'s', 'd', 'f'>::New("%s %d %f"); ASSERT_TRUE(f2); EXPECT_EQ("{s:1$s}[ ]{d:2$d}[ ]{f:3$f}", SummarizeParsedFormat(*f2)); auto star = ParsedFormat<'*', 'd'>::New("%*d"); ASSERT_TRUE(star); EXPECT_EQ("{*d:2$1$*d}", SummarizeParsedFormat(*star)); auto dollar = ParsedFormat<'d', 's'>::New("%2$s %1$d"); ASSERT_TRUE(dollar); EXPECT_EQ("{2$s:2$s}[ ]{1$d:1$d}", SummarizeParsedFormat(*dollar)); dollar = ParsedFormat<'d', 's'>::New("%2$s %1$d %1$d"); ASSERT_TRUE(dollar); EXPECT_EQ("{2$s:2$s}[ ]{1$d:1$d}[ ]{1$d:1$d}", SummarizeParsedFormat(*dollar)); } TEST_F(ParsedFormatTest, SimpleUncheckedCorrectWithV) { auto f = ParsedFormat<'v'>::New("ABC%vDEF"); ASSERT_TRUE(f); EXPECT_EQ("[ABC]{v:1$v}[DEF]", SummarizeParsedFormat(*f)); std::string format = "%vFFF%vZZZ%f"; auto f2 = ParsedFormat<'v', 'v', 'f'>::New(format); ASSERT_TRUE(f2); EXPECT_EQ("{v:1$v}[FFF]{v:2$v}[ZZZ]{f:3$f}", SummarizeParsedFormat(*f2)); f2 = ParsedFormat<'v', 'v', 'f'>::New("%v %v %f"); ASSERT_TRUE(f2); EXPECT_EQ("{v:1$v}[ ]{v:2$v}[ ]{f:3$f}", SummarizeParsedFormat(*f2)); } TEST_F(ParsedFormatTest, SimpleUncheckedIgnoredArgs) { EXPECT_FALSE((ParsedFormat<'d', 's'>::New("ABC"))); EXPECT_FALSE((ParsedFormat<'d', 's'>::New("%dABC"))); EXPECT_FALSE((ParsedFormat<'d', 's'>::New("ABC%2$s"))); auto f = ParsedFormat<'d', 's'>::NewAllowIgnored("ABC"); ASSERT_TRUE(f); EXPECT_EQ("[ABC]", SummarizeParsedFormat(*f)); f = ParsedFormat<'d', 's'>::NewAllowIgnored("%dABC"); ASSERT_TRUE(f); EXPECT_EQ("{d:1$d}[ABC]", SummarizeParsedFormat(*f)); f = ParsedFormat<'d', 's'>::NewAllowIgnored("ABC%2$s"); ASSERT_TRUE(f); EXPECT_EQ("[ABC]{2$s:2$s}", SummarizeParsedFormat(*f)); } TEST_F(ParsedFormatTest, SimpleUncheckedIgnoredArgsWithV) { EXPECT_FALSE((ParsedFormat<'v', 'v'>::New("ABC"))); EXPECT_FALSE((ParsedFormat<'v', 'v'>::New("%vABC"))); EXPECT_FALSE((ParsedFormat<'v', 's'>::New("ABC%2$s"))); auto f = ParsedFormat<'v', 'v'>::NewAllowIgnored("ABC"); ASSERT_TRUE(f); EXPECT_EQ("[ABC]", SummarizeParsedFormat(*f)); f = ParsedFormat<'v', 'v'>::NewAllowIgnored("%vABC"); ASSERT_TRUE(f); EXPECT_EQ("{v:1$v}[ABC]", SummarizeParsedFormat(*f)); } TEST_F(ParsedFormatTest, SimpleUncheckedUnsupported) { EXPECT_FALSE(ParsedFormat<'d'>::New("%1$d %1$x")); EXPECT_FALSE(ParsedFormat<'x'>::New("%1$d %1$x")); } TEST_F(ParsedFormatTest, SimpleUncheckedIncorrect) { EXPECT_FALSE(ParsedFormat<'d'>::New("")); EXPECT_FALSE(ParsedFormat<'d'>::New("ABC%dDEF%d")); std::string format = "%sFFF%dZZZ%f"; EXPECT_FALSE((ParsedFormat<'s', 'd', 'g'>::New(format))); } TEST_F(ParsedFormatTest, SimpleUncheckedIncorrectWithV) { EXPECT_FALSE(ParsedFormat<'v'>::New("")); EXPECT_FALSE(ParsedFormat<'v'>::New("ABC%vDEF%v")); std::string format = "%vFFF%vZZZ%f"; EXPECT_FALSE((ParsedFormat<'v', 'v', 'g'>::New(format))); } #if defined(__cpp_nontype_template_parameter_auto) template <auto T> std::true_type IsValidParsedFormatArgTest(ParsedFormat<T>*); template <auto T> std::false_type IsValidParsedFormatArgTest(...); template <auto T> using IsValidParsedFormatArg = decltype(IsValidParsedFormatArgTest<T>(nullptr)); TEST_F(ParsedFormatTest, OnlyValidTypesAllowed) { ASSERT_TRUE(IsValidParsedFormatArg<'c'>::value); ASSERT_TRUE(IsValidParsedFormatArg<FormatConversionCharSet::d>::value); ASSERT_TRUE(IsValidParsedFormatArg<absl::FormatConversionCharSet::d | absl::FormatConversionCharSet::x>::value); ASSERT_TRUE( IsValidParsedFormatArg<absl::FormatConversionCharSet::kIntegral>::value); ASSERT_FALSE(IsValidParsedFormatArg<'x' | 'd'>::value); ASSERT_FALSE(IsValidParsedFormatArg<absl::FormatConversionChar::d>::value); } TEST_F(ParsedFormatTest, ExtendedTyping) { EXPECT_FALSE(ParsedFormat<FormatConversionCharSet::d>::New("")); ASSERT_TRUE(ParsedFormat<absl::FormatConversionCharSet::d>::New("%d")); auto v1 = ParsedFormat<'d', absl::FormatConversionCharSet::s>::New("%d%s"); ASSERT_TRUE(v1); auto v2 = ParsedFormat<absl::FormatConversionCharSet::d, 's'>::New("%d%s"); ASSERT_TRUE(v2); auto v3 = ParsedFormat<absl::FormatConversionCharSet::d | absl::FormatConversionCharSet::s, 's'>::New("%d%s"); ASSERT_TRUE(v3); auto v4 = ParsedFormat<absl::FormatConversionCharSet::d | absl::FormatConversionCharSet::s, 's'>::New("%s%s"); ASSERT_TRUE(v4); } TEST_F(ParsedFormatTest, ExtendedTypingWithV) { EXPECT_FALSE(ParsedFormat<FormatConversionCharSet::v>::New("")); ASSERT_TRUE(ParsedFormat<absl::FormatConversionCharSet::v>::New("%v")); auto v1 = ParsedFormat<'v', absl::FormatConversionCharSet::v>::New("%v%v"); ASSERT_TRUE(v1); auto v2 = ParsedFormat<absl::FormatConversionCharSet::v, 'v'>::New("%v%v"); ASSERT_TRUE(v2); auto v3 = ParsedFormat<absl::FormatConversionCharSet::v | absl::FormatConversionCharSet::v, 'v'>::New("%v%v"); ASSERT_TRUE(v3); auto v4 = ParsedFormat<absl::FormatConversionCharSet::v | absl::FormatConversionCharSet::v, 'v'>::New("%v%v"); ASSERT_TRUE(v4); } #endif TEST_F(ParsedFormatTest, UncheckedCorrect) { auto f = ExtendedParsedFormat<absl::FormatConversionCharSet::d>::New("ABC%dDEF"); ASSERT_TRUE(f); EXPECT_EQ("[ABC]{d:1$d}[DEF]", SummarizeParsedFormat(*f)); std::string format = "%sFFF%dZZZ%f"; auto f2 = ExtendedParsedFormat< absl::FormatConversionCharSet::kString, absl::FormatConversionCharSet::d, absl::FormatConversionCharSet::kFloating>::New(format); ASSERT_TRUE(f2); EXPECT_EQ("{s:1$s}[FFF]{d:2$d}[ZZZ]{f:3$f}", SummarizeParsedFormat(*f2)); f2 = ExtendedParsedFormat< absl::FormatConversionCharSet::kString, absl::FormatConversionCharSet::d, absl::FormatConversionCharSet::kFloating>::New("%s %d %f"); ASSERT_TRUE(f2); EXPECT_EQ("{s:1$s}[ ]{d:2$d}[ ]{f:3$f}", SummarizeParsedFormat(*f2)); auto star = ExtendedParsedFormat<absl::FormatConversionCharSet::kStar, absl::FormatConversionCharSet::d>::New("%*d"); ASSERT_TRUE(star); EXPECT_EQ("{*d:2$1$*d}", SummarizeParsedFormat(*star)); auto dollar = ExtendedParsedFormat<absl::FormatConversionCharSet::d, absl::FormatConversionCharSet::s>::New("%2$s %1$d"); ASSERT_TRUE(dollar); EXPECT_EQ("{2$s:2$s}[ ]{1$d:1$d}", SummarizeParsedFormat(*dollar)); dollar = ExtendedParsedFormat< absl::FormatConversionCharSet::d, absl::FormatConversionCharSet::s>::New("%2$s %1$d %1$d"); ASSERT_TRUE(dollar); EXPECT_EQ("{2$s:2$s}[ ]{1$d:1$d}[ ]{1$d:1$d}", SummarizeParsedFormat(*dollar)); } TEST_F(ParsedFormatTest, UncheckedCorrectWithV) { auto f = ExtendedParsedFormat<absl::FormatConversionCharSet::v>::New("ABC%vDEF"); ASSERT_TRUE(f); EXPECT_EQ("[ABC]{v:1$v}[DEF]", SummarizeParsedFormat(*f)); std::string format = "%vFFF%vZZZ%f"; auto f2 = ExtendedParsedFormat< absl::FormatConversionCharSet::v, absl::FormatConversionCharSet::v, absl::FormatConversionCharSet::kFloating>::New(format); ASSERT_TRUE(f2); EXPECT_EQ("{v:1$v}[FFF]{v:2$v}[ZZZ]{f:3$f}", SummarizeParsedFormat(*f2)); f2 = ExtendedParsedFormat< absl::FormatConversionCharSet::v, absl::FormatConversionCharSet::v, absl::FormatConversionCharSet::kFloating>::New("%v %v %f"); ASSERT_TRUE(f2); EXPECT_EQ("{v:1$v}[ ]{v:2$v}[ ]{f:3$f}", SummarizeParsedFormat(*f2)); } TEST_F(ParsedFormatTest, UncheckedIgnoredArgs) { EXPECT_FALSE( (ExtendedParsedFormat<absl::FormatConversionCharSet::d, absl::FormatConversionCharSet::s>::New("ABC"))); EXPECT_FALSE( (ExtendedParsedFormat<absl::FormatConversionCharSet::d, absl::FormatConversionCharSet::s>::New("%dABC"))); EXPECT_FALSE( (ExtendedParsedFormat<absl::FormatConversionCharSet::d, absl::FormatConversionCharSet::s>::New("ABC%2$s"))); auto f = ExtendedParsedFormat< absl::FormatConversionCharSet::d, absl::FormatConversionCharSet::s>::NewAllowIgnored("ABC"); ASSERT_TRUE(f); EXPECT_EQ("[ABC]", SummarizeParsedFormat(*f)); f = ExtendedParsedFormat< absl::FormatConversionCharSet::d, absl::FormatConversionCharSet::s>::NewAllowIgnored("%dABC"); ASSERT_TRUE(f); EXPECT_EQ("{d:1$d}[ABC]", SummarizeParsedFormat(*f)); f = ExtendedParsedFormat< absl::FormatConversionCharSet::d, absl::FormatConversionCharSet::s>::NewAllowIgnored("ABC%2$s"); ASSERT_TRUE(f); EXPECT_EQ("[ABC]{2$s:2$s}", SummarizeParsedFormat(*f)); } TEST_F(ParsedFormatTest, UncheckedIgnoredArgsWithV) { EXPECT_FALSE( (ExtendedParsedFormat<absl::FormatConversionCharSet::v, absl::FormatConversionCharSet::v>::New("ABC"))); EXPECT_FALSE( (ExtendedParsedFormat<absl::FormatConversionCharSet::v, absl::FormatConversionCharSet::v>::New("%vABC"))); EXPECT_FALSE((ExtendedParsedFormat<absl::FormatConversionCharSet::v, absl::FormatConversionCharSet::s>:: New("ABC%2$s"))); auto f = ExtendedParsedFormat< absl::FormatConversionCharSet::v, absl::FormatConversionCharSet::v>::NewAllowIgnored("ABC"); ASSERT_TRUE(f); EXPECT_EQ("[ABC]", SummarizeParsedFormat(*f)); f = ExtendedParsedFormat< absl::FormatConversionCharSet::v, absl::FormatConversionCharSet::v>::NewAllowIgnored("%vABC"); ASSERT_TRUE(f); EXPECT_EQ("{v:1$v}[ABC]", SummarizeParsedFormat(*f)); } TEST_F(ParsedFormatTest, UncheckedMultipleTypes) { auto dx = ExtendedParsedFormat<absl::FormatConversionCharSet::d | absl::FormatConversionCharSet::x>::New("%1$d %1$x"); EXPECT_TRUE(dx); EXPECT_EQ("{1$d:1$d}[ ]{1$x:1$x}", SummarizeParsedFormat(*dx)); dx = ExtendedParsedFormat<absl::FormatConversionCharSet::d | absl::FormatConversionCharSet::x>::New("%1$d"); EXPECT_TRUE(dx); EXPECT_EQ("{1$d:1$d}", SummarizeParsedFormat(*dx)); } TEST_F(ParsedFormatTest, UncheckedIncorrect) { EXPECT_FALSE(ExtendedParsedFormat<absl::FormatConversionCharSet::d>::New("")); EXPECT_FALSE(ExtendedParsedFormat<absl::FormatConversionCharSet::d>::New( "ABC%dDEF%d")); std::string format = "%sFFF%dZZZ%f"; EXPECT_FALSE( (ExtendedParsedFormat<absl::FormatConversionCharSet::s, absl::FormatConversionCharSet::d, absl::FormatConversionCharSet::g>::New(format))); } TEST_F(ParsedFormatTest, UncheckedIncorrectWithV) { EXPECT_FALSE(ExtendedParsedFormat<absl::FormatConversionCharSet::v>::New("")); EXPECT_FALSE(ExtendedParsedFormat<absl::FormatConversionCharSet::v>::New( "ABC%vDEF%v")); std::string format = "%vFFF%vZZZ%f"; EXPECT_FALSE( (ExtendedParsedFormat<absl::FormatConversionCharSet::v, absl::FormatConversionCharSet::g>::New(format))); } TEST_F(ParsedFormatTest, RegressionMixPositional) { EXPECT_FALSE( (ExtendedParsedFormat<absl::FormatConversionCharSet::d, absl::FormatConversionCharSet::o>::New("%1$d %o"))); } TEST_F(ParsedFormatTest, DisallowModifiersWithV) { auto f = ParsedFormat<'v'>::New("ABC%80vDEF"); EXPECT_EQ(f, nullptr); f = ParsedFormat<'v'>::New("ABC%0vDEF"); EXPECT_EQ(f, nullptr); f = ParsedFormat<'v'>::New("ABC%.1vDEF"); EXPECT_EQ(f, nullptr); } using FormatWrapperTest = ::testing::Test; template <typename... Args> std::string WrappedFormat(const absl::FormatSpec<Args...>& format, const Args&... args) { return StrFormat(format, args...); } TEST_F(FormatWrapperTest, ConstexprStringFormat) { EXPECT_EQ(WrappedFormat("%s there", "hello"), "hello there"); } TEST_F(FormatWrapperTest, ConstexprStringFormatWithV) { std::string hello = "hello"; EXPECT_EQ(WrappedFormat("%v there", hello), "hello there"); } TEST_F(FormatWrapperTest, ParsedFormat) { ParsedFormat<'s'> format("%s there"); EXPECT_EQ(WrappedFormat(format, "hello"), "hello there"); } TEST_F(FormatWrapperTest, ParsedFormatWithV) { std::string hello = "hello"; ParsedFormat<'v'> format("%v there"); EXPECT_EQ(WrappedFormat(format, hello), "hello there"); } } ABSL_NAMESPACE_END } namespace { using FormatExtensionTest = ::testing::Test; struct Point { friend absl::FormatConvertResult<absl::FormatConversionCharSet::kString | absl::FormatConversionCharSet::kIntegral | absl::FormatConversionCharSet::v> AbslFormatConvert(const Point& p, const absl::FormatConversionSpec& spec, absl::FormatSink* s) { if (spec.conversion_char() == absl::FormatConversionChar::s) { s->Append(absl::StrCat("x=", p.x, " y=", p.y)); } else { s->Append(absl::StrCat(p.x, ",", p.y)); } return {true}; } int x = 10; int y = 20; }; TEST_F(FormatExtensionTest, AbslFormatConvertExample) { Point p; EXPECT_EQ(absl::StrFormat("a %s z", p), "a x=10 y=20 z"); EXPECT_EQ(absl::StrFormat("a %d z", p), "a 10,20 z"); EXPECT_EQ(absl::StrFormat("a %v z", p), "a 10,20 z"); std::string actual; absl::UntypedFormatSpec f1("%f"); EXPECT_FALSE(absl::FormatUntyped(&actual, f1, {absl::FormatArg(p)})); } struct PointStringify { template <typename FormatSink> friend void AbslStringify(FormatSink& sink, const PointStringify& p) { sink.Append(absl::StrCat("(", p.x, ", ", p.y, ")")); } double x = 10.0; double y = 20.0; }; TEST_F(FormatExtensionTest, AbslStringifyExample) { PointStringify p; EXPECT_EQ(absl::StrFormat("a %v z", p), "a (10, 20) z"); } struct PointStringifyUsingFormat { template <typename FormatSink> friend void AbslStringify(FormatSink& sink, const PointStringifyUsingFormat& p) { absl::Format(&sink, "(%g, %g)", p.x, p.y); } double x = 10.0; double y = 20.0; }; TEST_F(FormatExtensionTest, AbslStringifyExampleUsingFormat) { PointStringifyUsingFormat p; EXPECT_EQ(absl::StrFormat("a %v z", p), "a (10, 20) z"); } enum class EnumClassWithStringify { Many = 0, Choices = 1 }; template <typename Sink> void AbslStringify(Sink& sink, EnumClassWithStringify e) { absl::Format(&sink, "%s", e == EnumClassWithStringify::Many ? "Many" : "Choices"); } enum EnumWithStringify { Many, Choices }; template <typename Sink> void AbslStringify(Sink& sink, EnumWithStringify e) { absl::Format(&sink, "%s", e == EnumWithStringify::Many ? "Many" : "Choices"); } TEST_F(FormatExtensionTest, AbslStringifyWithEnumWithV) { const auto e_class = EnumClassWithStringify::Choices; EXPECT_EQ(absl::StrFormat("My choice is %v", e_class), "My choice is Choices"); const auto e = EnumWithStringify::Choices; EXPECT_EQ(absl::StrFormat("My choice is %v", e), "My choice is Choices"); } TEST_F(FormatExtensionTest, AbslStringifyEnumWithD) { const auto e_class = EnumClassWithStringify::Many; EXPECT_EQ(absl::StrFormat("My choice is %d", e_class), "My choice is 0"); const auto e = EnumWithStringify::Choices; EXPECT_EQ(absl::StrFormat("My choice is %d", e), "My choice is 1"); } enum class EnumWithLargerValue { x = 32 }; template <typename Sink> void AbslStringify(Sink& sink, EnumWithLargerValue e) { absl::Format(&sink, "%s", "Many"); } TEST_F(FormatExtensionTest, AbslStringifyEnumOtherSpecifiers) { const auto e = EnumWithLargerValue::x; EXPECT_EQ(absl::StrFormat("My choice is %g", e), "My choice is 32"); EXPECT_EQ(absl::StrFormat("My choice is %x", e), "My choice is 20"); } } std::string CodegenAbslStrFormatInt(int i) { return absl::StrFormat("%d", i); } std::string CodegenAbslStrFormatIntStringInt64(int i, const std::string& s, int64_t i64) { return absl::StrFormat("%d %s %d", i, s, i64); } void CodegenAbslStrAppendFormatInt(std::string* out, int i) { absl::StrAppendFormat(out, "%d", i); } void CodegenAbslStrAppendFormatIntStringInt64(std::string* out, int i, const std::string& s, int64_t i64) { absl::StrAppendFormat(out, "%d %s %d", i, s, i64); }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/str_format.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/str_format_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
dfb8b94c-5fdf-4d12-a88c-7babeb7d3253
cpp
abseil/abseil-cpp
charset
absl/strings/charset.h
absl/strings/charset_test.cc
#ifndef ABSL_STRINGS_CHARSET_H_ #define ABSL_STRINGS_CHARSET_H_ #include <cstddef> #include <cstdint> #include <cstring> #include "absl/base/macros.h" #include "absl/base/port.h" #include "absl/strings/string_view.h" namespace absl { class CharSet { public: constexpr CharSet() : m_() {} constexpr explicit CharSet(absl::string_view str) : m_() { for (char c : str) { SetChar(static_cast<unsigned char>(c)); } } constexpr bool contains(char c) const { return ((m_[static_cast<unsigned char>(c) / 64] >> (static_cast<unsigned char>(c) % 64)) & 0x1) == 0x1; } constexpr bool empty() const { for (uint64_t c : m_) { if (c != 0) return false; } return true; } static constexpr CharSet Char(char x) { return CharSet(CharMaskForWord(x, 0), CharMaskForWord(x, 1), CharMaskForWord(x, 2), CharMaskForWord(x, 3)); } static constexpr CharSet Range(char lo, char hi) { return CharSet(RangeForWord(lo, hi, 0), RangeForWord(lo, hi, 1), RangeForWord(lo, hi, 2), RangeForWord(lo, hi, 3)); } friend constexpr CharSet operator&(const CharSet& a, const CharSet& b) { return CharSet(a.m_[0] & b.m_[0], a.m_[1] & b.m_[1], a.m_[2] & b.m_[2], a.m_[3] & b.m_[3]); } friend constexpr CharSet operator|(const CharSet& a, const CharSet& b) { return CharSet(a.m_[0] | b.m_[0], a.m_[1] | b.m_[1], a.m_[2] | b.m_[2], a.m_[3] | b.m_[3]); } friend constexpr CharSet operator~(const CharSet& a) { return CharSet(~a.m_[0], ~a.m_[1], ~a.m_[2], ~a.m_[3]); } static constexpr CharSet AsciiUppercase() { return CharSet::Range('A', 'Z'); } static constexpr CharSet AsciiLowercase() { return CharSet::Range('a', 'z'); } static constexpr CharSet AsciiDigits() { return CharSet::Range('0', '9'); } static constexpr CharSet AsciiAlphabet() { return AsciiLowercase() | AsciiUppercase(); } static constexpr CharSet AsciiAlphanumerics() { return AsciiDigits() | AsciiAlphabet(); } static constexpr CharSet AsciiHexDigits() { return AsciiDigits() | CharSet::Range('A', 'F') | CharSet::Range('a', 'f'); } static constexpr CharSet AsciiPrintable() { return CharSet::Range(0x20, 0x7e); } static constexpr CharSet AsciiWhitespace() { return CharSet("\t\n\v\f\r "); } static constexpr CharSet AsciiPunctuation() { return AsciiPrintable() & ~AsciiWhitespace() & ~AsciiAlphanumerics(); } private: constexpr CharSet(uint64_t b0, uint64_t b1, uint64_t b2, uint64_t b3) : m_{b0, b1, b2, b3} {} static constexpr uint64_t RangeForWord(char lo, char hi, uint64_t word) { return OpenRangeFromZeroForWord(static_cast<unsigned char>(hi) + 1, word) & ~OpenRangeFromZeroForWord(static_cast<unsigned char>(lo), word); } static constexpr uint64_t OpenRangeFromZeroForWord(uint64_t upper, uint64_t word) { return (upper <= 64 * word) ? 0 : (upper >= 64 * (word + 1)) ? ~static_cast<uint64_t>(0) : (~static_cast<uint64_t>(0) >> (64 - upper % 64)); } static constexpr uint64_t CharMaskForWord(char x, uint64_t word) { return (static_cast<unsigned char>(x) / 64 == word) ? (static_cast<uint64_t>(1) << (static_cast<unsigned char>(x) % 64)) : 0; } constexpr void SetChar(unsigned char c) { m_[c / 64] |= static_cast<uint64_t>(1) << (c % 64); } uint64_t m_[4]; }; } #endif
#include "absl/strings/charset.h" #include <stdio.h> #include <stdlib.h> #include <string> #include <vector> #include "gtest/gtest.h" #include "absl/strings/ascii.h" #include "absl/strings/string_view.h" namespace { constexpr absl::CharSet everything_map = ~absl::CharSet(); constexpr absl::CharSet nothing_map = absl::CharSet(); TEST(Charmap, AllTests) { const absl::CharSet also_nothing_map(""); EXPECT_TRUE(everything_map.contains('\0')); EXPECT_FALSE(nothing_map.contains('\0')); EXPECT_FALSE(also_nothing_map.contains('\0')); for (unsigned char ch = 1; ch != 0; ++ch) { SCOPED_TRACE(ch); EXPECT_TRUE(everything_map.contains(ch)); EXPECT_FALSE(nothing_map.contains(ch)); EXPECT_FALSE(also_nothing_map.contains(ch)); } const absl::CharSet symbols(absl::string_view("&@#@^!@?", 5)); EXPECT_TRUE(symbols.contains('&')); EXPECT_TRUE(symbols.contains('@')); EXPECT_TRUE(symbols.contains('#')); EXPECT_TRUE(symbols.contains('^')); EXPECT_FALSE(symbols.contains('!')); EXPECT_FALSE(symbols.contains('?')); int cnt = 0; for (unsigned char ch = 1; ch != 0; ++ch) cnt += symbols.contains(ch); EXPECT_EQ(cnt, 4); const absl::CharSet lets(absl::string_view("^abcde", 3)); const absl::CharSet lets2(absl::string_view("fghij\0klmnop", 10)); const absl::CharSet lets3("fghij\0klmnop"); EXPECT_TRUE(lets2.contains('k')); EXPECT_FALSE(lets3.contains('k')); EXPECT_FALSE((symbols & lets).empty()); EXPECT_TRUE((lets2 & lets).empty()); EXPECT_FALSE((lets & symbols).empty()); EXPECT_TRUE((lets & lets2).empty()); EXPECT_TRUE(nothing_map.empty()); EXPECT_FALSE(lets.empty()); } std::string Members(const absl::CharSet& m) { std::string r; for (size_t i = 0; i < 256; ++i) if (m.contains(i)) r.push_back(i); return r; } std::string ClosedRangeString(unsigned char lo, unsigned char hi) { std::string s; while (true) { s.push_back(lo); if (lo == hi) break; ++lo; } return s; } TEST(Charmap, Constexpr) { constexpr absl::CharSet kEmpty = absl::CharSet(); EXPECT_EQ(Members(kEmpty), ""); constexpr absl::CharSet kA = absl::CharSet::Char('A'); EXPECT_EQ(Members(kA), "A"); constexpr absl::CharSet kAZ = absl::CharSet::Range('A', 'Z'); EXPECT_EQ(Members(kAZ), "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); constexpr absl::CharSet kIdentifier = absl::CharSet::Range('0', '9') | absl::CharSet::Range('A', 'Z') | absl::CharSet::Range('a', 'z') | absl::CharSet::Char('_'); EXPECT_EQ(Members(kIdentifier), "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "_" "abcdefghijklmnopqrstuvwxyz"); constexpr absl::CharSet kAll = ~absl::CharSet(); for (size_t i = 0; i < 256; ++i) { SCOPED_TRACE(i); EXPECT_TRUE(kAll.contains(i)); } constexpr absl::CharSet kHello = absl::CharSet("Hello, world!"); EXPECT_EQ(Members(kHello), " !,Hdelorw"); constexpr absl::CharSet kABC = absl::CharSet::Range('A', 'Z') & ~absl::CharSet::Range('D', 'Z'); EXPECT_EQ(Members(kABC), "ABC"); constexpr bool kContainsA = absl::CharSet("abc").contains('a'); EXPECT_TRUE(kContainsA); constexpr bool kContainsD = absl::CharSet("abc").contains('d'); EXPECT_FALSE(kContainsD); constexpr bool kEmptyIsEmpty = absl::CharSet().empty(); EXPECT_TRUE(kEmptyIsEmpty); constexpr bool kNotEmptyIsEmpty = absl::CharSet("abc").empty(); EXPECT_FALSE(kNotEmptyIsEmpty); } TEST(Charmap, Range) { std::vector<size_t> poi = {0, 1, 2, 3, 4, 7, 8, 9, 15, 16, 17, 30, 31, 32, 33, 63, 64, 65, 127, 128, 129, 223, 224, 225, 254, 255}; for (auto lo = poi.begin(); lo != poi.end(); ++lo) { SCOPED_TRACE(*lo); for (auto hi = lo; hi != poi.end(); ++hi) { SCOPED_TRACE(*hi); EXPECT_EQ(Members(absl::CharSet::Range(*lo, *hi)), ClosedRangeString(*lo, *hi)); } } } TEST(Charmap, NullByteWithStringView) { char characters[5] = {'a', 'b', '\0', 'd', 'x'}; absl::string_view view(characters, 5); absl::CharSet tester(view); EXPECT_TRUE(tester.contains('a')); EXPECT_TRUE(tester.contains('b')); EXPECT_TRUE(tester.contains('\0')); EXPECT_TRUE(tester.contains('d')); EXPECT_TRUE(tester.contains('x')); EXPECT_FALSE(tester.contains('c')); } TEST(CharmapCtype, Match) { for (int c = 0; c < 256; ++c) { SCOPED_TRACE(c); SCOPED_TRACE(static_cast<char>(c)); EXPECT_EQ(absl::ascii_isupper(c), absl::CharSet::AsciiUppercase().contains(c)); EXPECT_EQ(absl::ascii_islower(c), absl::CharSet::AsciiLowercase().contains(c)); EXPECT_EQ(absl::ascii_isdigit(c), absl::CharSet::AsciiDigits().contains(c)); EXPECT_EQ(absl::ascii_isalpha(c), absl::CharSet::AsciiAlphabet().contains(c)); EXPECT_EQ(absl::ascii_isalnum(c), absl::CharSet::AsciiAlphanumerics().contains(c)); EXPECT_EQ(absl::ascii_isxdigit(c), absl::CharSet::AsciiHexDigits().contains(c)); EXPECT_EQ(absl::ascii_isprint(c), absl::CharSet::AsciiPrintable().contains(c)); EXPECT_EQ(absl::ascii_isspace(c), absl::CharSet::AsciiWhitespace().contains(c)); EXPECT_EQ(absl::ascii_ispunct(c), absl::CharSet::AsciiPunctuation().contains(c)); } } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/charset.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/charset_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
d8539108-120a-419d-853b-1421467cce6e
cpp
abseil/abseil-cpp
has_absl_stringify
absl/strings/has_absl_stringify.h
absl/strings/has_absl_stringify_test.cc
#ifndef ABSL_STRINGS_HAS_ABSL_STRINGIFY_H_ #define ABSL_STRINGS_HAS_ABSL_STRINGIFY_H_ #include <type_traits> #include <utility> #include "absl/base/config.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { class UnimplementedSink { public: void Append(size_t count, char ch); void Append(string_view v); friend void AbslFormatFlush(UnimplementedSink* sink, absl::string_view v); }; } template <typename T, typename = void> struct HasAbslStringify : std::false_type {}; template <typename T> struct HasAbslStringify< T, std::enable_if_t<std::is_void<decltype(AbslStringify( std::declval<strings_internal::UnimplementedSink&>(), std::declval<const T&>()))>::value>> : std::true_type {}; ABSL_NAMESPACE_END } #endif
#include "absl/strings/has_absl_stringify.h" #include <string> #include "gtest/gtest.h" #include "absl/types/optional.h" namespace { struct TypeWithoutAbslStringify {}; struct TypeWithAbslStringify { template <typename Sink> friend void AbslStringify(Sink&, const TypeWithAbslStringify&) {} }; TEST(HasAbslStringifyTest, Works) { EXPECT_FALSE(absl::HasAbslStringify<int>::value); EXPECT_FALSE(absl::HasAbslStringify<std::string>::value); EXPECT_FALSE(absl::HasAbslStringify<TypeWithoutAbslStringify>::value); EXPECT_TRUE(absl::HasAbslStringify<TypeWithAbslStringify>::value); EXPECT_FALSE( absl::HasAbslStringify<absl::optional<TypeWithAbslStringify>>::value); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/has_absl_stringify.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/has_absl_stringify_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
e497c608-fa1c-48c5-bcd4-388e26ca95a6
cpp
abseil/abseil-cpp
str_join
absl/strings/str_join.h
absl/strings/str_join_test.cc
#ifndef ABSL_STRINGS_STR_JOIN_H_ #define ABSL_STRINGS_STR_JOIN_H_ #include <cstdio> #include <cstring> #include <initializer_list> #include <iterator> #include <string> #include <tuple> #include <type_traits> #include <utility> #include "absl/base/macros.h" #include "absl/strings/internal/str_join_internal.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN inline strings_internal::AlphaNumFormatterImpl AlphaNumFormatter() { return strings_internal::AlphaNumFormatterImpl(); } inline strings_internal::StreamFormatterImpl StreamFormatter() { return strings_internal::StreamFormatterImpl(); } template <typename FirstFormatter, typename SecondFormatter> inline strings_internal::PairFormatterImpl<FirstFormatter, SecondFormatter> PairFormatter(FirstFormatter f1, absl::string_view sep, SecondFormatter f2) { return strings_internal::PairFormatterImpl<FirstFormatter, SecondFormatter>( std::move(f1), sep, std::move(f2)); } inline strings_internal::PairFormatterImpl< strings_internal::AlphaNumFormatterImpl, strings_internal::AlphaNumFormatterImpl> PairFormatter(absl::string_view sep) { return PairFormatter(AlphaNumFormatter(), sep, AlphaNumFormatter()); } template <typename Formatter> strings_internal::DereferenceFormatterImpl<Formatter> DereferenceFormatter( Formatter&& f) { return strings_internal::DereferenceFormatterImpl<Formatter>( std::forward<Formatter>(f)); } inline strings_internal::DereferenceFormatterImpl< strings_internal::AlphaNumFormatterImpl> DereferenceFormatter() { return strings_internal::DereferenceFormatterImpl< strings_internal::AlphaNumFormatterImpl>(AlphaNumFormatter()); } template <typename Iterator, typename Formatter> std::string StrJoin(Iterator start, Iterator end, absl::string_view sep, Formatter&& fmt) { return strings_internal::JoinAlgorithm(start, end, sep, fmt); } template <typename Range, typename Formatter> std::string StrJoin(const Range& range, absl::string_view separator, Formatter&& fmt) { return strings_internal::JoinRange(range, separator, fmt); } template <typename T, typename Formatter, typename = typename std::enable_if< !std::is_convertible<T, absl::string_view>::value>::type> std::string StrJoin(std::initializer_list<T> il, absl::string_view separator, Formatter&& fmt) { return strings_internal::JoinRange(il, separator, fmt); } template <typename Formatter> inline std::string StrJoin(std::initializer_list<absl::string_view> il, absl::string_view separator, Formatter&& fmt) { return strings_internal::JoinRange(il, separator, fmt); } template <typename... T, typename Formatter> std::string StrJoin(const std::tuple<T...>& value, absl::string_view separator, Formatter&& fmt) { return strings_internal::JoinAlgorithm(value, separator, fmt); } template <typename Iterator> std::string StrJoin(Iterator start, Iterator end, absl::string_view separator) { return strings_internal::JoinRange(start, end, separator); } template <typename Range> std::string StrJoin(const Range& range, absl::string_view separator) { return strings_internal::JoinRange(range, separator); } template <typename T, typename = typename std::enable_if<!std::is_convertible< T, absl::string_view>::value>::type> std::string StrJoin(std::initializer_list<T> il, absl::string_view separator) { return strings_internal::JoinRange(il, separator); } inline std::string StrJoin(std::initializer_list<absl::string_view> il, absl::string_view separator) { return strings_internal::JoinRange(il, separator); } template <typename... T> std::string StrJoin(const std::tuple<T...>& value, absl::string_view separator) { return strings_internal::JoinTuple(value, separator, std::index_sequence_for<T...>{}); } ABSL_NAMESPACE_END } #endif
#include "absl/strings/str_join.h" #include <cstddef> #include <cstdint> #include <cstdio> #include <functional> #include <initializer_list> #include <iterator> #include <map> #include <memory> #include <ostream> #include <string> #include <tuple> #include <utility> #include <vector> #include "gtest/gtest.h" #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" namespace { TEST(StrJoin, APIExamples) { { std::vector<std::string> v = {"foo", "bar", "baz"}; EXPECT_EQ("foo-bar-baz", absl::StrJoin(v, "-")); } { std::vector<absl::string_view> v = {"foo", "bar", "baz"}; EXPECT_EQ("foo-bar-baz", absl::StrJoin(v, "-")); } { std::vector<const char*> v = {"foo", "bar", "baz"}; EXPECT_EQ("foo-bar-baz", absl::StrJoin(v, "-")); } { std::string a = "foo", b = "bar", c = "baz"; std::vector<char*> v = {&a[0], &b[0], &c[0]}; EXPECT_EQ("foo-bar-baz", absl::StrJoin(v, "-")); } { std::vector<int> v = {1, 2, 3, -4}; EXPECT_EQ("1-2-3--4", absl::StrJoin(v, "-")); } { std::string s = absl::StrJoin({"a", "b", "c"}, "-"); EXPECT_EQ("a-b-c", s); } { std::string s = absl::StrJoin(std::make_tuple(123, "abc", 0.456), "-"); EXPECT_EQ("123-abc-0.456", s); } { std::vector<std::unique_ptr<int>> v; v.emplace_back(new int(1)); v.emplace_back(new int(2)); v.emplace_back(new int(3)); EXPECT_EQ("1-2-3", absl::StrJoin(v, "-")); } { const int a[] = {1, 2, 3, -4}; EXPECT_EQ("1-2-3--4", absl::StrJoin(a, a + ABSL_ARRAYSIZE(a), "-")); } { int x = 1, y = 2, z = 3; std::vector<int*> v = {&x, &y, &z}; EXPECT_EQ("1-2-3", absl::StrJoin(v, "-")); } { int x = 1, y = 2, z = 3; int *px = &x, *py = &y, *pz = &z; std::vector<int**> v = {&px, &py, &pz}; EXPECT_EQ("1-2-3", absl::StrJoin(v, "-")); } { std::string a("a"), b("b"); std::vector<std::string*> v = {&a, &b}; EXPECT_EQ("a-b", absl::StrJoin(v, "-")); } { std::map<std::string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}}; EXPECT_EQ("a=1,b=2,c=3", absl::StrJoin(m, ",", absl::PairFormatter("="))); } { const std::string s = "a=b=c=d"; EXPECT_EQ("a-b-c-d", absl::StrJoin(absl::StrSplit(s, "="), "-")); } { std::vector<std::string> v; EXPECT_EQ("", absl::StrJoin(v, "-")); } { std::vector<std::string> v = {"foo"}; EXPECT_EQ("foo", absl::StrJoin(v, "-")); } { std::vector<std::string> v = {""}; EXPECT_EQ("", absl::StrJoin(v, "-")); } { std::vector<std::string> v = {"a", ""}; EXPECT_EQ("a-", absl::StrJoin(v, "-")); } { std::vector<std::string> v = {"", ""}; EXPECT_EQ("-", absl::StrJoin(v, "-")); } { std::vector<bool> v = {true, false, true}; EXPECT_EQ("1-0-1", absl::StrJoin(v, "-")); } } TEST(StrJoin, CustomFormatter) { std::vector<std::string> v{"One", "Two", "Three"}; { std::string joined = absl::StrJoin(v, "", [](std::string* out, const std::string& in) { absl::StrAppend(out, "(", in, ")"); }); EXPECT_EQ("(One)(Two)(Three)", joined); } { class ImmovableFormatter { public: void operator()(std::string* out, const std::string& in) { absl::StrAppend(out, "(", in, ")"); } ImmovableFormatter() {} ImmovableFormatter(const ImmovableFormatter&) = delete; }; EXPECT_EQ("(One)(Two)(Three)", absl::StrJoin(v, "", ImmovableFormatter())); } { class OverloadedFormatter { public: void operator()(std::string* out, const std::string& in) { absl::StrAppend(out, "(", in, ")"); } void operator()(std::string* out, const std::string& in) const { absl::StrAppend(out, "[", in, "]"); } }; EXPECT_EQ("(One)(Two)(Three)", absl::StrJoin(v, "", OverloadedFormatter())); const OverloadedFormatter fmt = {}; EXPECT_EQ("[One][Two][Three]", absl::StrJoin(v, "", fmt)); } } TEST(AlphaNumFormatter, FormatterAPI) { auto f = absl::AlphaNumFormatter(); std::string s; f(&s, "Testing: "); f(&s, static_cast<int>(1)); f(&s, static_cast<int16_t>(2)); f(&s, static_cast<int64_t>(3)); f(&s, static_cast<float>(4)); f(&s, static_cast<double>(5)); f(&s, static_cast<unsigned>(6)); f(&s, static_cast<size_t>(7)); f(&s, absl::string_view(" OK")); EXPECT_EQ("Testing: 1234567 OK", s); } TEST(AlphaNumFormatter, VectorOfBool) { auto f = absl::AlphaNumFormatter(); std::string s; std::vector<bool> v = {true, false, true}; f(&s, *v.cbegin()); f(&s, *v.begin()); f(&s, v[1]); EXPECT_EQ("110", s); } TEST(AlphaNumFormatter, AlphaNum) { auto f = absl::AlphaNumFormatter(); std::string s; f(&s, absl::AlphaNum("hello")); EXPECT_EQ("hello", s); } struct StreamableType { std::string contents; }; inline std::ostream& operator<<(std::ostream& os, const StreamableType& t) { os << "Streamable:" << t.contents; return os; } TEST(StreamFormatter, FormatterAPI) { auto f = absl::StreamFormatter(); std::string s; f(&s, "Testing: "); f(&s, static_cast<int>(1)); f(&s, static_cast<int16_t>(2)); f(&s, static_cast<int64_t>(3)); f(&s, static_cast<float>(4)); f(&s, static_cast<double>(5)); f(&s, static_cast<unsigned>(6)); f(&s, static_cast<size_t>(7)); f(&s, absl::string_view(" OK ")); StreamableType streamable = {"object"}; f(&s, streamable); EXPECT_EQ("Testing: 1234567 OK Streamable:object", s); } struct TestingParenFormatter { template <typename T> void operator()(std::string* s, const T& t) { absl::StrAppend(s, "(", t, ")"); } }; TEST(PairFormatter, FormatterAPI) { { const auto f = absl::PairFormatter("="); std::string s; f(&s, std::make_pair("a", "b")); f(&s, std::make_pair(1, 2)); EXPECT_EQ("a=b1=2", s); } { auto f = absl::PairFormatter(TestingParenFormatter(), "=", TestingParenFormatter()); std::string s; f(&s, std::make_pair("a", "b")); f(&s, std::make_pair(1, 2)); EXPECT_EQ("(a)=(b)(1)=(2)", s); } } TEST(DereferenceFormatter, FormatterAPI) { { const absl::strings_internal::DereferenceFormatterImpl< absl::strings_internal::AlphaNumFormatterImpl> f; int x = 1, y = 2, z = 3; std::string s; f(&s, &x); f(&s, &y); f(&s, &z); EXPECT_EQ("123", s); } { absl::strings_internal::DereferenceFormatterImpl< absl::strings_internal::DefaultFormatter<std::string>::Type> f; std::string x = "x"; std::string y = "y"; std::string z = "z"; std::string s; f(&s, &x); f(&s, &y); f(&s, &z); EXPECT_EQ(s, "xyz"); } { auto f = absl::DereferenceFormatter(TestingParenFormatter()); int x = 1, y = 2, z = 3; std::string s; f(&s, &x); f(&s, &y); f(&s, &z); EXPECT_EQ("(1)(2)(3)", s); } { absl::strings_internal::DereferenceFormatterImpl< absl::strings_internal::AlphaNumFormatterImpl> f; auto x = std::unique_ptr<int>(new int(1)); auto y = std::unique_ptr<int>(new int(2)); auto z = std::unique_ptr<int>(new int(3)); std::string s; f(&s, x); f(&s, y); f(&s, z); EXPECT_EQ("123", s); } } TEST(StrJoin, PublicAPIOverloads) { std::vector<std::string> v = {"a", "b", "c"}; EXPECT_EQ("a-b-c", absl::StrJoin(v.begin(), v.end(), "-", absl::AlphaNumFormatter())); EXPECT_EQ("a-b-c", absl::StrJoin(v, "-", absl::AlphaNumFormatter())); EXPECT_EQ("a-b-c", absl::StrJoin(v.begin(), v.end(), "-")); EXPECT_EQ("a-b-c", absl::StrJoin(v, "-")); } TEST(StrJoin, Array) { const absl::string_view a[] = {"a", "b", "c"}; EXPECT_EQ("a-b-c", absl::StrJoin(a, "-")); } TEST(StrJoin, InitializerList) { { EXPECT_EQ("a-b-c", absl::StrJoin({"a", "b", "c"}, "-")); } { auto a = {"a", "b", "c"}; EXPECT_EQ("a-b-c", absl::StrJoin(a, "-")); } { std::initializer_list<const char*> a = {"a", "b", "c"}; EXPECT_EQ("a-b-c", absl::StrJoin(a, "-")); } { std::initializer_list<std::string> a = {"a", "b", "c"}; EXPECT_EQ("a-b-c", absl::StrJoin(a, "-")); } { std::initializer_list<absl::string_view> a = {"a", "b", "c"}; EXPECT_EQ("a-b-c", absl::StrJoin(a, "-")); } { auto a = {"a", "b", "c"}; TestingParenFormatter f; EXPECT_EQ("(a)-(b)-(c)", absl::StrJoin(a, "-", f)); } { EXPECT_EQ("1-2-3", absl::StrJoin({1, 2, 3}, "-")); } { auto a = {1, 2, 3}; TestingParenFormatter f; EXPECT_EQ("(1)-(2)-(3)", absl::StrJoin(a, "-", f)); } } TEST(StrJoin, StringViewInitializerList) { { std::string b = "b"; EXPECT_EQ("a-b-c", absl::StrJoin({"a", b, "c"}, "-")); } { TestingParenFormatter f; std::string b = "b"; EXPECT_EQ("(a)-(b)-(c)", absl::StrJoin({"a", b, "c"}, "-", f)); } class NoCopy { public: explicit NoCopy(absl::string_view view) : view_(view) {} NoCopy(const NoCopy&) = delete; operator absl::string_view() { return view_; } private: absl::string_view view_; }; { EXPECT_EQ("a-b-c", absl::StrJoin({NoCopy("a"), NoCopy("b"), NoCopy("c")}, "-")); } { TestingParenFormatter f; EXPECT_EQ("(a)-(b)-(c)", absl::StrJoin({NoCopy("a"), NoCopy("b"), NoCopy("c")}, "-", f)); } } TEST(StrJoin, Tuple) { EXPECT_EQ("", absl::StrJoin(std::make_tuple(), "-")); EXPECT_EQ("hello", absl::StrJoin(std::make_tuple("hello"), "-")); int x(10); std::string y("hello"); double z(3.14); EXPECT_EQ("10-hello-3.14", absl::StrJoin(std::make_tuple(x, y, z), "-")); EXPECT_EQ("10-hello-3.14", absl::StrJoin(std::make_tuple(x, std::cref(y), z), "-")); struct TestFormatter { char buffer[128]; void operator()(std::string* out, int v) { snprintf(buffer, sizeof(buffer), "%#.8x", v); out->append(buffer); } void operator()(std::string* out, double v) { snprintf(buffer, sizeof(buffer), "%#.0f", v); out->append(buffer); } void operator()(std::string* out, const std::string& v) { snprintf(buffer, sizeof(buffer), "%.4s", v.c_str()); out->append(buffer); } }; EXPECT_EQ("0x0000000a-hell-3.", absl::StrJoin(std::make_tuple(x, y, z), "-", TestFormatter())); EXPECT_EQ( "0x0000000a-hell-3.", absl::StrJoin(std::make_tuple(x, std::cref(y), z), "-", TestFormatter())); EXPECT_EQ("0x0000000a-hell-3.", absl::StrJoin(std::make_tuple(&x, &y, &z), "-", absl::DereferenceFormatter(TestFormatter()))); EXPECT_EQ("0x0000000a-hell-3.", absl::StrJoin(std::make_tuple(absl::make_unique<int>(x), absl::make_unique<std::string>(y), absl::make_unique<double>(z)), "-", absl::DereferenceFormatter(TestFormatter()))); EXPECT_EQ("0x0000000a-hell-3.", absl::StrJoin(std::make_tuple(absl::make_unique<int>(x), &y, &z), "-", absl::DereferenceFormatter(TestFormatter()))); } class TestValue { public: TestValue(const char* data, size_t size) : data_(data), size_(size) {} const char* data() const { return data_; } size_t size() const { return size_; } private: const char* data_; size_t size_; }; template <typename ValueT> class TestIterator { public: using iterator_category = std::forward_iterator_tag; using value_type = ValueT; using pointer = void; using reference = const value_type&; using difference_type = int; static TestIterator begin(const std::vector<absl::string_view>& data) { return TestIterator(&data, 0); } static TestIterator end(const std::vector<absl::string_view>& data) { return TestIterator(nullptr, data.size()); } bool operator==(const TestIterator& other) const { return pos_ == other.pos_; } bool operator!=(const TestIterator& other) const { return pos_ != other.pos_; } value_type operator*() const { return ValueT((*data_)[pos_].data(), (*data_)[pos_].size()); } TestIterator& operator++() { ++pos_; return *this; } TestIterator operator++(int) { TestIterator result = *this; ++(*this); return result; } TestIterator& operator--() { --pos_; return *this; } TestIterator operator--(int) { TestIterator result = *this; --(*this); return result; } private: TestIterator(const std::vector<absl::string_view>* data, size_t pos) : data_(data), pos_(pos) {} const std::vector<absl::string_view>* data_; size_t pos_; }; template <typename ValueT> class TestIteratorRange { public: explicit TestIteratorRange(const std::vector<absl::string_view>& data) : begin_(TestIterator<ValueT>::begin(data)), end_(TestIterator<ValueT>::end(data)) {} const TestIterator<ValueT>& begin() const { return begin_; } const TestIterator<ValueT>& end() const { return end_; } private: TestIterator<ValueT> begin_; TestIterator<ValueT> end_; }; TEST(StrJoin, TestIteratorRequirementsNoFormatter) { const std::vector<absl::string_view> a = {"a", "b", "c"}; EXPECT_EQ("a-b-c", absl::StrJoin(TestIteratorRange<absl::string_view>(a), "-")); } TEST(StrJoin, TestIteratorRequirementsCustomFormatter) { const std::vector<absl::string_view> a = {"a", "b", "c"}; EXPECT_EQ("a-b-c", absl::StrJoin(TestIteratorRange<TestValue>(a), "-", [](std::string* out, const TestValue& value) { absl::StrAppend( out, absl::string_view(value.data(), value.size())); })); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/str_join.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/str_join_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
34b7035c-9737-4f53-ba41-25f4e523e4c6
cpp
abseil/abseil-cpp
strip
absl/log/internal/strip.h
absl/strings/strip_test.cc
#ifndef ABSL_LOG_INTERNAL_STRIP_H_ #define ABSL_LOG_INTERNAL_STRIP_H_ #include "absl/base/attributes.h" #include "absl/base/log_severity.h" #include "absl/log/internal/log_message.h" #include "absl/log/internal/nullstream.h" #if defined(STRIP_LOG) && STRIP_LOG #define ABSL_LOG_INTERNAL_ATTRIBUTE_UNUSED_IF_STRIP_LOG ABSL_ATTRIBUTE_UNUSED #define ABSL_LOGGING_INTERNAL_LOG_INFO ::absl::log_internal::NullStream() #define ABSL_LOGGING_INTERNAL_LOG_WARNING ::absl::log_internal::NullStream() #define ABSL_LOGGING_INTERNAL_LOG_ERROR ::absl::log_internal::NullStream() #define ABSL_LOGGING_INTERNAL_LOG_FATAL ::absl::log_internal::NullStreamFatal() #define ABSL_LOGGING_INTERNAL_LOG_QFATAL ::absl::log_internal::NullStreamFatal() #define ABSL_LOGGING_INTERNAL_LOG_DFATAL \ ::absl::log_internal::NullStreamMaybeFatal(::absl::kLogDebugFatal) #define ABSL_LOGGING_INTERNAL_LOG_LEVEL(severity) \ ::absl::log_internal::NullStreamMaybeFatal(absl_log_internal_severity) #define ABSL_LOGGING_INTERNAL_DLOG_FATAL \ ::absl::log_internal::NullStreamMaybeFatal(::absl::LogSeverity::kFatal) #define ABSL_LOGGING_INTERNAL_DLOG_QFATAL \ ::absl::log_internal::NullStreamMaybeFatal(::absl::LogSeverity::kFatal) #define ABSL_LOG_INTERNAL_CHECK(failure_message) ABSL_LOGGING_INTERNAL_LOG_FATAL #define ABSL_LOG_INTERNAL_QCHECK(failure_message) \ ABSL_LOGGING_INTERNAL_LOG_QFATAL #else #define ABSL_LOG_INTERNAL_ATTRIBUTE_UNUSED_IF_STRIP_LOG #define ABSL_LOGGING_INTERNAL_LOG_INFO \ ::absl::log_internal::LogMessage( \ __FILE__, __LINE__, ::absl::log_internal::LogMessage::InfoTag{}) #define ABSL_LOGGING_INTERNAL_LOG_WARNING \ ::absl::log_internal::LogMessage( \ __FILE__, __LINE__, ::absl::log_internal::LogMessage::WarningTag{}) #define ABSL_LOGGING_INTERNAL_LOG_ERROR \ ::absl::log_internal::LogMessage( \ __FILE__, __LINE__, ::absl::log_internal::LogMessage::ErrorTag{}) #define ABSL_LOGGING_INTERNAL_LOG_FATAL \ ::absl::log_internal::LogMessageFatal(__FILE__, __LINE__) #define ABSL_LOGGING_INTERNAL_LOG_QFATAL \ ::absl::log_internal::LogMessageQuietlyFatal(__FILE__, __LINE__) #define ABSL_LOGGING_INTERNAL_LOG_DFATAL \ ::absl::log_internal::LogMessage(__FILE__, __LINE__, ::absl::kLogDebugFatal) #define ABSL_LOGGING_INTERNAL_LOG_LEVEL(severity) \ ::absl::log_internal::LogMessage(__FILE__, __LINE__, \ absl_log_internal_severity) #define ABSL_LOGGING_INTERNAL_DLOG_FATAL \ ::absl::log_internal::LogMessageDebugFatal(__FILE__, __LINE__) #define ABSL_LOGGING_INTERNAL_DLOG_QFATAL \ ::absl::log_internal::LogMessageQuietlyDebugFatal(__FILE__, __LINE__) #define ABSL_LOG_INTERNAL_CHECK(failure_message) \ ::absl::log_internal::LogMessageFatal(__FILE__, __LINE__, failure_message) #define ABSL_LOG_INTERNAL_QCHECK(failure_message) \ ::absl::log_internal::LogMessageQuietlyFatal(__FILE__, __LINE__, \ failure_message) #endif #define ABSL_LOGGING_INTERNAL_DLOG_INFO ABSL_LOGGING_INTERNAL_LOG_INFO #define ABSL_LOGGING_INTERNAL_DLOG_WARNING ABSL_LOGGING_INTERNAL_LOG_WARNING #define ABSL_LOGGING_INTERNAL_DLOG_ERROR ABSL_LOGGING_INTERNAL_LOG_ERROR #define ABSL_LOGGING_INTERNAL_DLOG_DFATAL ABSL_LOGGING_INTERNAL_LOG_DFATAL #define ABSL_LOGGING_INTERNAL_DLOG_LEVEL ABSL_LOGGING_INTERNAL_LOG_LEVEL #endif
#include "absl/strings/strip.h" #include <cassert> #include <cstdio> #include <cstring> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" namespace { TEST(Strip, ConsumePrefixOneChar) { absl::string_view input("abc"); EXPECT_TRUE(absl::ConsumePrefix(&input, "a")); EXPECT_EQ(input, "bc"); EXPECT_FALSE(absl::ConsumePrefix(&input, "x")); EXPECT_EQ(input, "bc"); EXPECT_TRUE(absl::ConsumePrefix(&input, "b")); EXPECT_EQ(input, "c"); EXPECT_TRUE(absl::ConsumePrefix(&input, "c")); EXPECT_EQ(input, ""); EXPECT_FALSE(absl::ConsumePrefix(&input, "a")); EXPECT_EQ(input, ""); } TEST(Strip, ConsumePrefix) { absl::string_view input("abcdef"); EXPECT_FALSE(absl::ConsumePrefix(&input, "abcdefg")); EXPECT_EQ(input, "abcdef"); EXPECT_FALSE(absl::ConsumePrefix(&input, "abce")); EXPECT_EQ(input, "abcdef"); EXPECT_TRUE(absl::ConsumePrefix(&input, "")); EXPECT_EQ(input, "abcdef"); EXPECT_FALSE(absl::ConsumePrefix(&input, "abcdeg")); EXPECT_EQ(input, "abcdef"); EXPECT_TRUE(absl::ConsumePrefix(&input, "abcdef")); EXPECT_EQ(input, ""); input = "abcdef"; EXPECT_TRUE(absl::ConsumePrefix(&input, "abcde")); EXPECT_EQ(input, "f"); } TEST(Strip, ConsumeSuffix) { absl::string_view input("abcdef"); EXPECT_FALSE(absl::ConsumeSuffix(&input, "abcdefg")); EXPECT_EQ(input, "abcdef"); EXPECT_TRUE(absl::ConsumeSuffix(&input, "")); EXPECT_EQ(input, "abcdef"); EXPECT_TRUE(absl::ConsumeSuffix(&input, "def")); EXPECT_EQ(input, "abc"); input = "abcdef"; EXPECT_FALSE(absl::ConsumeSuffix(&input, "abcdeg")); EXPECT_EQ(input, "abcdef"); EXPECT_TRUE(absl::ConsumeSuffix(&input, "f")); EXPECT_EQ(input, "abcde"); EXPECT_TRUE(absl::ConsumeSuffix(&input, "abcde")); EXPECT_EQ(input, ""); } TEST(Strip, StripPrefix) { const absl::string_view null_str; EXPECT_EQ(absl::StripPrefix("foobar", "foo"), "bar"); EXPECT_EQ(absl::StripPrefix("foobar", ""), "foobar"); EXPECT_EQ(absl::StripPrefix("foobar", null_str), "foobar"); EXPECT_EQ(absl::StripPrefix("foobar", "foobar"), ""); EXPECT_EQ(absl::StripPrefix("foobar", "bar"), "foobar"); EXPECT_EQ(absl::StripPrefix("foobar", "foobarr"), "foobar"); EXPECT_EQ(absl::StripPrefix("", ""), ""); } TEST(Strip, StripSuffix) { const absl::string_view null_str; EXPECT_EQ(absl::StripSuffix("foobar", "bar"), "foo"); EXPECT_EQ(absl::StripSuffix("foobar", ""), "foobar"); EXPECT_EQ(absl::StripSuffix("foobar", null_str), "foobar"); EXPECT_EQ(absl::StripSuffix("foobar", "foobar"), ""); EXPECT_EQ(absl::StripSuffix("foobar", "foo"), "foobar"); EXPECT_EQ(absl::StripSuffix("foobar", "ffoobar"), "foobar"); EXPECT_EQ(absl::StripSuffix("", ""), ""); } TEST(Strip, RemoveExtraAsciiWhitespace) { const char* inputs[] = { "No extra space", " Leading whitespace", "Trailing whitespace ", " Leading and trailing ", " Whitespace \t in\v middle ", "'Eeeeep! \n Newlines!\n", "nospaces", }; const char* outputs[] = { "No extra space", "Leading whitespace", "Trailing whitespace", "Leading and trailing", "Whitespace in middle", "'Eeeeep! Newlines!", "nospaces", }; int NUM_TESTS = 7; for (int i = 0; i < NUM_TESTS; i++) { std::string s(inputs[i]); absl::RemoveExtraAsciiWhitespace(&s); EXPECT_STREQ(outputs[i], s.c_str()); } std::string zero_string = ""; assert(zero_string.empty()); absl::RemoveExtraAsciiWhitespace(&zero_string); EXPECT_EQ(zero_string.size(), 0); EXPECT_TRUE(zero_string.empty()); } TEST(Strip, StripTrailingAsciiWhitespace) { std::string test = "foo "; absl::StripTrailingAsciiWhitespace(&test); EXPECT_EQ(test, "foo"); test = " "; absl::StripTrailingAsciiWhitespace(&test); EXPECT_EQ(test, ""); test = ""; absl::StripTrailingAsciiWhitespace(&test); EXPECT_EQ(test, ""); test = " abc\t"; absl::StripTrailingAsciiWhitespace(&test); EXPECT_EQ(test, " abc"); } TEST(String, StripLeadingAsciiWhitespace) { absl::string_view orig = "\t \n\f\r\n\vfoo"; EXPECT_EQ("foo", absl::StripLeadingAsciiWhitespace(orig)); orig = "\t \n\f\r\v\n\t \n\f\r\v\n"; EXPECT_EQ(absl::string_view(), absl::StripLeadingAsciiWhitespace(orig)); } TEST(Strip, StripAsciiWhitespace) { std::string test2 = "\t \f\r\n\vfoo \t\f\r\v\n"; absl::StripAsciiWhitespace(&test2); EXPECT_EQ(test2, "foo"); std::string test3 = "bar"; absl::StripAsciiWhitespace(&test3); EXPECT_EQ(test3, "bar"); std::string test4 = "\t \f\r\n\vfoo"; absl::StripAsciiWhitespace(&test4); EXPECT_EQ(test4, "foo"); std::string test5 = "foo \t\f\r\v\n"; absl::StripAsciiWhitespace(&test5); EXPECT_EQ(test5, "foo"); absl::string_view test6("\t \f\r\n\vfoo \t\f\r\v\n"); test6 = absl::StripAsciiWhitespace(test6); EXPECT_EQ(test6, "foo"); test6 = absl::StripAsciiWhitespace(test6); EXPECT_EQ(test6, "foo"); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/log/internal/strip.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/strip_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
67a73e33-84d3-4cb9-abee-05f1219dfecb
cpp
abseil/abseil-cpp
cordz_update_tracker
absl/strings/internal/cordz_update_tracker.h
absl/strings/internal/cordz_update_tracker_test.cc
#ifndef ABSL_STRINGS_INTERNAL_CORDZ_UPDATE_TRACKER_H_ #define ABSL_STRINGS_INTERNAL_CORDZ_UPDATE_TRACKER_H_ #include <atomic> #include <cstdint> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { class CordzUpdateTracker { public: enum MethodIdentifier { kUnknown, kAppendCord, kAppendCordBuffer, kAppendExternalMemory, kAppendString, kAssignCord, kAssignString, kClear, kConstructorCord, kConstructorString, kCordReader, kFlatten, kGetAppendBuffer, kGetAppendRegion, kMakeCordFromExternal, kMoveAppendCord, kMoveAssignCord, kMovePrependCord, kPrependCord, kPrependCordBuffer, kPrependString, kRemovePrefix, kRemoveSuffix, kSetExpectedChecksum, kSubCord, kNumMethods, }; constexpr CordzUpdateTracker() noexcept : values_{} {} CordzUpdateTracker(const CordzUpdateTracker& rhs) noexcept { *this = rhs; } CordzUpdateTracker& operator=(const CordzUpdateTracker& rhs) noexcept { for (int i = 0; i < kNumMethods; ++i) { values_[i].store(rhs.values_[i].load(std::memory_order_relaxed), std::memory_order_relaxed); } return *this; } int64_t Value(MethodIdentifier method) const { return values_[method].load(std::memory_order_relaxed); } void LossyAdd(MethodIdentifier method, int64_t n = 1) { auto& value = values_[method]; value.store(value.load(std::memory_order_relaxed) + n, std::memory_order_relaxed); } void LossyAdd(const CordzUpdateTracker& src) { for (int i = 0; i < kNumMethods; ++i) { MethodIdentifier method = static_cast<MethodIdentifier>(i); if (int64_t value = src.Value(method)) { LossyAdd(method, value); } } } private: class Counter : public std::atomic<int64_t> { public: constexpr Counter() noexcept : std::atomic<int64_t>(0) {} }; Counter values_[kNumMethods]; }; } ABSL_NAMESPACE_END } #endif
#include "absl/strings/internal/cordz_update_tracker.h" #include <array> #include <thread> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/synchronization/notification.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { namespace { using ::testing::AnyOf; using ::testing::Eq; using Method = CordzUpdateTracker::MethodIdentifier; using Methods = std::array<Method, Method::kNumMethods>; Methods AllMethods() { return Methods{Method::kUnknown, Method::kAppendCord, Method::kAppendCordBuffer, Method::kAppendExternalMemory, Method::kAppendString, Method::kAssignCord, Method::kAssignString, Method::kClear, Method::kConstructorCord, Method::kConstructorString, Method::kCordReader, Method::kFlatten, Method::kGetAppendBuffer, Method::kGetAppendRegion, Method::kMakeCordFromExternal, Method::kMoveAppendCord, Method::kMoveAssignCord, Method::kMovePrependCord, Method::kPrependCord, Method::kPrependCordBuffer, Method::kPrependString, Method::kRemovePrefix, Method::kRemoveSuffix, Method::kSetExpectedChecksum, Method::kSubCord}; } TEST(CordzUpdateTracker, IsConstExprAndInitializesToZero) { constexpr CordzUpdateTracker tracker; for (Method method : AllMethods()) { ASSERT_THAT(tracker.Value(method), Eq(0)); } } TEST(CordzUpdateTracker, LossyAdd) { int64_t n = 1; CordzUpdateTracker tracker; for (Method method : AllMethods()) { tracker.LossyAdd(method, n); EXPECT_THAT(tracker.Value(method), Eq(n)); n += 2; } } TEST(CordzUpdateTracker, CopyConstructor) { int64_t n = 1; CordzUpdateTracker src; for (Method method : AllMethods()) { src.LossyAdd(method, n); n += 2; } n = 1; CordzUpdateTracker tracker(src); for (Method method : AllMethods()) { EXPECT_THAT(tracker.Value(method), Eq(n)); n += 2; } } TEST(CordzUpdateTracker, OperatorAssign) { int64_t n = 1; CordzUpdateTracker src; CordzUpdateTracker tracker; for (Method method : AllMethods()) { src.LossyAdd(method, n); n += 2; } n = 1; tracker = src; for (Method method : AllMethods()) { EXPECT_THAT(tracker.Value(method), Eq(n)); n += 2; } } TEST(CordzUpdateTracker, ThreadSanitizedValueCheck) { absl::Notification done; CordzUpdateTracker tracker; std::thread reader([&done, &tracker] { while (!done.HasBeenNotified()) { int n = 1; for (Method method : AllMethods()) { EXPECT_THAT(tracker.Value(method), AnyOf(Eq(n), Eq(0))); n += 2; } } int n = 1; for (Method method : AllMethods()) { EXPECT_THAT(tracker.Value(method), Eq(n)); n += 2; } }); int64_t n = 1; for (Method method : AllMethods()) { tracker.LossyAdd(method, n); n += 2; } done.Notify(); reader.join(); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cordz_update_tracker.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cordz_update_tracker_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
310248d0-1060-408a-83a6-7cd4790ac06c
cpp
abseil/abseil-cpp
resize_uninitialized
absl/strings/internal/resize_uninitialized.h
absl/strings/internal/resize_uninitialized_test.cc
#ifndef ABSL_STRINGS_INTERNAL_RESIZE_UNINITIALIZED_H_ #define ABSL_STRINGS_INTERNAL_RESIZE_UNINITIALIZED_H_ #include <algorithm> #include <string> #include <type_traits> #include <utility> #include "absl/base/port.h" #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { template <typename string_type, typename = void> struct ResizeUninitializedTraits { using HasMember = std::false_type; static void Resize(string_type* s, size_t new_size) { s->resize(new_size); } }; template <typename string_type> struct ResizeUninitializedTraits< string_type, absl::void_t<decltype(std::declval<string_type&>() .__resize_default_init(237))> > { using HasMember = std::true_type; static void Resize(string_type* s, size_t new_size) { s->__resize_default_init(new_size); } }; template <typename string_type> inline constexpr bool STLStringSupportsNontrashingResize(string_type*) { return ResizeUninitializedTraits<string_type>::HasMember::value; } template <typename string_type, typename = void> inline void STLStringResizeUninitialized(string_type* s, size_t new_size) { ResizeUninitializedTraits<string_type>::Resize(s, new_size); } template <typename string_type> void STLStringReserveAmortized(string_type* s, size_t new_size) { const size_t cap = s->capacity(); if (new_size > cap) { s->reserve((std::max)(new_size, 2 * cap)); } } template <typename string_type, typename = void> struct AppendUninitializedTraits { static void Append(string_type* s, size_t n) { s->append(n, typename string_type::value_type()); } }; template <typename string_type> struct AppendUninitializedTraits< string_type, absl::void_t<decltype(std::declval<string_type&>() .__append_default_init(237))> > { static void Append(string_type* s, size_t n) { s->__append_default_init(n); } }; template <typename string_type> void STLStringResizeUninitializedAmortized(string_type* s, size_t new_size) { const size_t size = s->size(); if (new_size > size) { AppendUninitializedTraits<string_type>::Append(s, new_size - size); } else { s->erase(new_size); } } } ABSL_NAMESPACE_END } #endif
#include "absl/strings/internal/resize_uninitialized.h" #include "gtest/gtest.h" namespace { int resize_call_count = 0; int append_call_count = 0; struct resizable_string { using value_type = char; size_t size() const { return 0; } size_t capacity() const { return 0; } char& operator[](size_t) { static char c = '\0'; return c; } void resize(size_t) { resize_call_count += 1; } void append(size_t, value_type) { append_call_count += 1; } void reserve(size_t) {} resizable_string& erase(size_t = 0, size_t = 0) { return *this; } }; int resize_default_init_call_count = 0; int append_default_init_call_count = 0; struct default_init_string { size_t size() const { return 0; } size_t capacity() const { return 0; } char& operator[](size_t) { static char c = '\0'; return c; } void resize(size_t) { resize_call_count += 1; } void __resize_default_init(size_t) { resize_default_init_call_count += 1; } void __append_default_init(size_t) { append_default_init_call_count += 1; } void reserve(size_t) {} default_init_string& erase(size_t = 0, size_t = 0) { return *this; } }; TEST(ResizeUninit, WithAndWithout) { resize_call_count = 0; append_call_count = 0; resize_default_init_call_count = 0; append_default_init_call_count = 0; { resizable_string rs; EXPECT_EQ(resize_call_count, 0); EXPECT_EQ(append_call_count, 0); EXPECT_EQ(resize_default_init_call_count, 0); EXPECT_EQ(append_default_init_call_count, 0); EXPECT_FALSE( absl::strings_internal::STLStringSupportsNontrashingResize(&rs)); EXPECT_EQ(resize_call_count, 0); EXPECT_EQ(append_call_count, 0); EXPECT_EQ(resize_default_init_call_count, 0); EXPECT_EQ(append_default_init_call_count, 0); absl::strings_internal::STLStringResizeUninitialized(&rs, 237); EXPECT_EQ(resize_call_count, 1); EXPECT_EQ(append_call_count, 0); EXPECT_EQ(resize_default_init_call_count, 0); EXPECT_EQ(append_default_init_call_count, 0); absl::strings_internal::STLStringResizeUninitializedAmortized(&rs, 1000); EXPECT_EQ(resize_call_count, 1); EXPECT_EQ(append_call_count, 1); EXPECT_EQ(resize_default_init_call_count, 0); EXPECT_EQ(append_default_init_call_count, 0); } resize_call_count = 0; append_call_count = 0; resize_default_init_call_count = 0; append_default_init_call_count = 0; { default_init_string rus; EXPECT_EQ(resize_call_count, 0); EXPECT_EQ(append_call_count, 0); EXPECT_EQ(resize_default_init_call_count, 0); EXPECT_EQ(append_default_init_call_count, 0); EXPECT_TRUE( absl::strings_internal::STLStringSupportsNontrashingResize(&rus)); EXPECT_EQ(resize_call_count, 0); EXPECT_EQ(append_call_count, 0); EXPECT_EQ(resize_default_init_call_count, 0); EXPECT_EQ(append_default_init_call_count, 0); absl::strings_internal::STLStringResizeUninitialized(&rus, 237); EXPECT_EQ(resize_call_count, 0); EXPECT_EQ(append_call_count, 0); EXPECT_EQ(resize_default_init_call_count, 1); EXPECT_EQ(append_default_init_call_count, 0); absl::strings_internal::STLStringResizeUninitializedAmortized(&rus, 1000); EXPECT_EQ(resize_call_count, 0); EXPECT_EQ(append_call_count, 0); EXPECT_EQ(resize_default_init_call_count, 1); EXPECT_EQ(append_default_init_call_count, 1); } } TEST(ResizeUninit, Amortized) { std::string str; size_t prev_cap = str.capacity(); int cap_increase_count = 0; for (int i = 0; i < 1000; ++i) { absl::strings_internal::STLStringResizeUninitializedAmortized(&str, i); size_t new_cap = str.capacity(); if (new_cap > prev_cap) ++cap_increase_count; prev_cap = new_cap; } EXPECT_LT(cap_increase_count, 50); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/resize_uninitialized.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/resize_uninitialized_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
346fb862-6591-4707-9ae5-a1961ad6018b
cpp
abseil/abseil-cpp
cord_data_edge
absl/strings/internal/cord_data_edge.h
absl/strings/internal/cord_data_edge_test.cc
#ifndef ABSL_STRINGS_INTERNAL_CORD_DATA_EDGE_H_ #define ABSL_STRINGS_INTERNAL_CORD_DATA_EDGE_H_ #include <cassert> #include <cstddef> #include "absl/base/config.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_flat.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { inline bool IsDataEdge(const CordRep* edge) { assert(edge != nullptr); if (edge->tag == EXTERNAL || edge->tag >= FLAT) return true; if (edge->tag == SUBSTRING) edge = edge->substring()->child; return edge->tag == EXTERNAL || edge->tag >= FLAT; } inline absl::string_view EdgeData(const CordRep* edge) { assert(IsDataEdge(edge)); size_t offset = 0; const size_t length = edge->length; if (edge->IsSubstring()) { offset = edge->substring()->start; edge = edge->substring()->child; } return edge->tag >= FLAT ? absl::string_view{edge->flat()->Data() + offset, length} : absl::string_view{edge->external()->base + offset, length}; } } ABSL_NAMESPACE_END } #endif
#include "absl/strings/internal/cord_data_edge.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cord_rep_test_util.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { namespace { using ::absl::cordrep_testing::MakeExternal; using ::absl::cordrep_testing::MakeFlat; using ::absl::cordrep_testing::MakeSubstring; TEST(CordDataEdgeTest, IsDataEdgeOnFlat) { CordRep* rep = MakeFlat("Lorem ipsum dolor sit amet, consectetur ..."); EXPECT_TRUE(IsDataEdge(rep)); CordRep::Unref(rep); } TEST(CordDataEdgeTest, IsDataEdgeOnExternal) { CordRep* rep = MakeExternal("Lorem ipsum dolor sit amet, consectetur ..."); EXPECT_TRUE(IsDataEdge(rep)); CordRep::Unref(rep); } TEST(CordDataEdgeTest, IsDataEdgeOnSubstringOfFlat) { CordRep* rep = MakeFlat("Lorem ipsum dolor sit amet, consectetur ..."); CordRep* substr = MakeSubstring(1, 20, rep); EXPECT_TRUE(IsDataEdge(substr)); CordRep::Unref(substr); } TEST(CordDataEdgeTest, IsDataEdgeOnSubstringOfExternal) { CordRep* rep = MakeExternal("Lorem ipsum dolor sit amet, consectetur ..."); CordRep* substr = MakeSubstring(1, 20, rep); EXPECT_TRUE(IsDataEdge(substr)); CordRep::Unref(substr); } TEST(CordDataEdgeTest, IsDataEdgeOnBtree) { CordRep* rep = MakeFlat("Lorem ipsum dolor sit amet, consectetur ..."); CordRepBtree* tree = CordRepBtree::New(rep); EXPECT_FALSE(IsDataEdge(tree)); CordRep::Unref(tree); } TEST(CordDataEdgeTest, IsDataEdgeOnBadSubstr) { CordRep* rep = MakeFlat("Lorem ipsum dolor sit amet, consectetur ..."); CordRep* substr = MakeSubstring(1, 18, MakeSubstring(1, 20, rep)); EXPECT_FALSE(IsDataEdge(substr)); CordRep::Unref(substr); } TEST(CordDataEdgeTest, EdgeDataOnFlat) { absl::string_view value = "Lorem ipsum dolor sit amet, consectetur ..."; CordRep* rep = MakeFlat(value); EXPECT_EQ(EdgeData(rep), value); CordRep::Unref(rep); } TEST(CordDataEdgeTest, EdgeDataOnExternal) { absl::string_view value = "Lorem ipsum dolor sit amet, consectetur ..."; CordRep* rep = MakeExternal(value); EXPECT_EQ(EdgeData(rep), value); CordRep::Unref(rep); } TEST(CordDataEdgeTest, EdgeDataOnSubstringOfFlat) { absl::string_view value = "Lorem ipsum dolor sit amet, consectetur ..."; CordRep* rep = MakeFlat(value); CordRep* substr = MakeSubstring(1, 20, rep); EXPECT_EQ(EdgeData(substr), value.substr(1, 20)); CordRep::Unref(substr); } TEST(CordDataEdgeTest, EdgeDataOnSubstringOfExternal) { absl::string_view value = "Lorem ipsum dolor sit amet, consectetur ..."; CordRep* rep = MakeExternal(value); CordRep* substr = MakeSubstring(1, 20, rep); EXPECT_EQ(EdgeData(substr), value.substr(1, 20)); CordRep::Unref(substr); } #if defined(GTEST_HAS_DEATH_TEST) && !defined(NDEBUG) TEST(CordDataEdgeTest, IsDataEdgeOnNullPtr) { EXPECT_DEATH(IsDataEdge(nullptr), ".*"); } TEST(CordDataEdgeTest, EdgeDataOnNullPtr) { EXPECT_DEATH(EdgeData(nullptr), ".*"); } TEST(CordDataEdgeTest, EdgeDataOnBtree) { CordRep* rep = MakeFlat("Lorem ipsum dolor sit amet, consectetur ..."); CordRepBtree* tree = CordRepBtree::New(rep); EXPECT_DEATH(EdgeData(tree), ".*"); CordRep::Unref(tree); } TEST(CordDataEdgeTest, EdgeDataOnBadSubstr) { CordRep* rep = MakeFlat("Lorem ipsum dolor sit amet, consectetur ..."); CordRep* substr = MakeSubstring(1, 18, MakeSubstring(1, 20, rep)); EXPECT_DEATH(EdgeData(substr), ".*"); CordRep::Unref(substr); } #endif } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cord_data_edge.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cord_data_edge_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
8f93cfd3-d9d0-4582-9743-597d6d1201cb
cpp
abseil/abseil-cpp
string_constant
absl/strings/internal/string_constant.h
absl/strings/internal/string_constant_test.cc
#ifndef ABSL_STRINGS_INTERNAL_STRING_CONSTANT_H_ #define ABSL_STRINGS_INTERNAL_STRING_CONSTANT_H_ #include "absl/meta/type_traits.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace strings_internal { template <typename T> struct StringConstant { private: static constexpr bool TryConstexprEval(absl::string_view view) { return view.empty() || 2 * view[0] != 1; } public: static constexpr absl::string_view value = T{}(); constexpr absl::string_view operator()() const { return value; } static_assert(TryConstexprEval(value), "The input string_view must point to constant data."); }; #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL template <typename T> constexpr absl::string_view StringConstant<T>::value; #endif template <typename T> constexpr StringConstant<T> MakeStringConstant(T) { return {}; } } ABSL_NAMESPACE_END } #endif
#include "absl/strings/internal/string_constant.h" #include "absl/meta/type_traits.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace { using absl::strings_internal::MakeStringConstant; struct Callable { constexpr absl::string_view operator()() const { return absl::string_view("Callable", 8); } }; TEST(StringConstant, Traits) { constexpr auto str = MakeStringConstant(Callable{}); using T = decltype(str); EXPECT_TRUE(std::is_empty<T>::value); EXPECT_TRUE(std::is_trivial<T>::value); EXPECT_TRUE(absl::is_trivially_default_constructible<T>::value); EXPECT_TRUE(absl::is_trivially_copy_constructible<T>::value); EXPECT_TRUE(absl::is_trivially_move_constructible<T>::value); EXPECT_TRUE(absl::is_trivially_destructible<T>::value); } TEST(StringConstant, MakeFromCallable) { constexpr auto str = MakeStringConstant(Callable{}); using T = decltype(str); EXPECT_EQ(Callable{}(), T::value); EXPECT_EQ(Callable{}(), str()); } TEST(StringConstant, MakeFromStringConstant) { constexpr auto str = MakeStringConstant(Callable{}); constexpr auto str2 = MakeStringConstant(str); using T = decltype(str2); EXPECT_EQ(Callable{}(), T::value); EXPECT_EQ(Callable{}(), str2()); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/string_constant.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/string_constant_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
17b11f88-09df-48cc-859d-7fed7fb5dec6
cpp
abseil/abseil-cpp
cordz_update_scope
absl/strings/internal/cordz_update_scope.h
absl/strings/internal/cordz_update_scope_test.cc
#ifndef ABSL_STRINGS_INTERNAL_CORDZ_UPDATE_SCOPE_H_ #define ABSL_STRINGS_INTERNAL_CORDZ_UPDATE_SCOPE_H_ #include "absl/base/config.h" #include "absl/base/optimization.h" #include "absl/base/thread_annotations.h" #include "absl/strings/internal/cord_internal.h" #include "absl/strings/internal/cordz_info.h" #include "absl/strings/internal/cordz_update_tracker.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { class ABSL_SCOPED_LOCKABLE CordzUpdateScope { public: CordzUpdateScope(CordzInfo* info, CordzUpdateTracker::MethodIdentifier method) ABSL_EXCLUSIVE_LOCK_FUNCTION(info) : info_(info) { if (ABSL_PREDICT_FALSE(info_)) { info->Lock(method); } } CordzUpdateScope(CordzUpdateScope&& rhs) = delete; CordzUpdateScope(const CordzUpdateScope&) = delete; CordzUpdateScope& operator=(CordzUpdateScope&& rhs) = delete; CordzUpdateScope& operator=(const CordzUpdateScope&) = delete; ~CordzUpdateScope() ABSL_UNLOCK_FUNCTION() { if (ABSL_PREDICT_FALSE(info_)) { info_->Unlock(); } } void SetCordRep(CordRep* rep) const { if (ABSL_PREDICT_FALSE(info_)) { info_->SetCordRep(rep); } } CordzInfo* info() const { return info_; } private: CordzInfo* info_; }; } ABSL_NAMESPACE_END } #endif
#include "absl/strings/internal/cordz_update_scope.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/strings/cordz_test_helpers.h" #include "absl/strings/internal/cord_rep_flat.h" #include "absl/strings/internal/cordz_info.h" #include "absl/strings/internal/cordz_update_tracker.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace cord_internal { namespace { auto constexpr kTrackCordMethod = CordzUpdateTracker::kConstructorString; TEST(CordzUpdateScopeTest, ScopeNullptr) { CordzUpdateScope scope(nullptr, kTrackCordMethod); } TEST(CordzUpdateScopeTest, ScopeSampledCord) { TestCordData cord; CordzInfo::TrackCord(cord.data, kTrackCordMethod, 1); CordzUpdateScope scope(cord.data.cordz_info(), kTrackCordMethod); cord.data.cordz_info()->SetCordRep(nullptr); } } ABSL_NAMESPACE_END } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cordz_update_scope.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/cordz_update_scope_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
565091fa-66f9-40e6-963a-d03190020783
cpp
abseil/abseil-cpp
checker
absl/strings/internal/str_format/checker.h
absl/strings/internal/str_format/checker_test.cc
#ifndef ABSL_STRINGS_INTERNAL_STR_FORMAT_CHECKER_H_ #define ABSL_STRINGS_INTERNAL_STR_FORMAT_CHECKER_H_ #include <algorithm> #include "absl/base/attributes.h" #include "absl/strings/internal/str_format/arg.h" #include "absl/strings/internal/str_format/constexpr_parser.h" #include "absl/strings/internal/str_format/extension.h" #ifndef ABSL_INTERNAL_ENABLE_FORMAT_CHECKER #if ABSL_HAVE_ATTRIBUTE(enable_if) && !defined(__native_client__) && \ !defined(__INTELLISENSE__) #define ABSL_INTERNAL_ENABLE_FORMAT_CHECKER 1 #endif #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace str_format_internal { #ifdef ABSL_INTERNAL_ENABLE_FORMAT_CHECKER template <FormatConversionCharSet... C> constexpr bool ValidFormatImpl(string_view format) { int next_arg = 0; const char* p = format.data(); const char* const end = p + format.size(); constexpr FormatConversionCharSet kAllowedConvs[(std::max)(sizeof...(C), size_t{1})] = {C...}; bool used[(std::max)(sizeof...(C), size_t{1})]{}; constexpr int kNumArgs = sizeof...(C); while (p != end) { while (p != end && *p != '%') ++p; if (p == end) { break; } if (p + 1 >= end) return false; if (p[1] == '%') { p += 2; continue; } UnboundConversion conv(absl::kConstInit); p = ConsumeUnboundConversion(p + 1, end, &conv, &next_arg); if (p == nullptr) return false; if (conv.arg_position <= 0 || conv.arg_position > kNumArgs) { return false; } if (!Contains(kAllowedConvs[conv.arg_position - 1], conv.conv)) { return false; } used[conv.arg_position - 1] = true; for (auto extra : {conv.width, conv.precision}) { if (extra.is_from_arg()) { int pos = extra.get_from_arg(); if (pos <= 0 || pos > kNumArgs) return false; used[pos - 1] = true; if (!Contains(kAllowedConvs[pos - 1], '*')) { return false; } } } } if (sizeof...(C) != 0) { for (bool b : used) { if (!b) return false; } } return true; } #endif } ABSL_NAMESPACE_END } #endif
#include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/str_format.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace str_format_internal { namespace { std::string ConvToString(FormatConversionCharSet conv) { std::string out; #define CONV_SET_CASE(c) \ if (Contains(conv, FormatConversionCharSetInternal::c)) { \ out += #c; \ } ABSL_INTERNAL_CONVERSION_CHARS_EXPAND_(CONV_SET_CASE, ) #undef CONV_SET_CASE if (Contains(conv, FormatConversionCharSetInternal::kStar)) { out += "*"; } return out; } TEST(StrFormatChecker, ArgumentToConv) { FormatConversionCharSet conv = ArgumentToConv<std::string>(); EXPECT_EQ(ConvToString(conv), "sv"); conv = ArgumentToConv<const char*>(); EXPECT_EQ(ConvToString(conv), "sp"); conv = ArgumentToConv<double>(); EXPECT_EQ(ConvToString(conv), "fFeEgGaAv"); conv = ArgumentToConv<int>(); EXPECT_EQ(ConvToString(conv), "cdiouxXfFeEgGaAv*"); conv = ArgumentToConv<std::string*>(); EXPECT_EQ(ConvToString(conv), "p"); } #ifdef ABSL_INTERNAL_ENABLE_FORMAT_CHECKER struct Case { bool result; const char* format; }; template <typename... Args> constexpr Case ValidFormat(const char* format) { return {ValidFormatImpl<ArgumentToConv<Args>()...>(format), format}; } TEST(StrFormatChecker, ValidFormat) { enum e {}; enum class e2 {}; constexpr Case trues[] = { ValidFormat<>("abc"), ValidFormat<e>("%d"), ValidFormat<e2>("%d"), ValidFormat<int>("%% %d"), ValidFormat<int>("%ld"), ValidFormat<int>("%lld"), ValidFormat<std::string>("%s"), ValidFormat<std::string>("%10s"), ValidFormat<int>("%.10x"), ValidFormat<int, int>("%*.3x"), ValidFormat<int>("%1.d"), ValidFormat<int>("%.d"), ValidFormat<int, double>("%d %g"), ValidFormat<int, std::string>("%*s"), ValidFormat<int, double>("%.*f"), ValidFormat<void (*)(), volatile int*>("%p %p"), ValidFormat<string_view, const char*, double, void*>( "string_view=%s const char*=%s double=%f void*=%p)"), ValidFormat<int>("%v"), ValidFormat<int>("%% %1$d"), ValidFormat<int>("%1$ld"), ValidFormat<int>("%1$lld"), ValidFormat<std::string>("%1$s"), ValidFormat<std::string>("%1$10s"), ValidFormat<int>("%1$.10x"), ValidFormat<int>("%1$*1$.*1$d"), ValidFormat<int, int>("%1$*2$.3x"), ValidFormat<int>("%1$1.d"), ValidFormat<int>("%1$.d"), ValidFormat<double, int>("%2$d %1$g"), ValidFormat<int, std::string>("%2$*1$s"), ValidFormat<int, double>("%2$.*1$f"), ValidFormat<void*, string_view, const char*, double>( "string_view=%2$s const char*=%3$s double=%4$f void*=%1$p " "repeat=%3$s)"), ValidFormat<std::string>("%1$v"), }; for (Case c : trues) { EXPECT_TRUE(c.result) << c.format; } constexpr Case falses[] = { ValidFormat<int>(""), ValidFormat<e>("%s"), ValidFormat<e2>("%s"), ValidFormat<>("%s"), ValidFormat<>("%r"), ValidFormat<int>("%s"), ValidFormat<int>("%.1.d"), ValidFormat<int>("%*1d"), ValidFormat<int>("%1-d"), ValidFormat<std::string, int>("%*s"), ValidFormat<int>("%*d"), ValidFormat<std::string>("%p"), ValidFormat<int (*)(int)>("%d"), ValidFormat<int>("%1v"), ValidFormat<int>("%.1v"), ValidFormat<>("%3$d"), ValidFormat<>("%1$r"), ValidFormat<int>("%1$s"), ValidFormat<int>("%1$.1.d"), ValidFormat<int>("%1$*2$1d"), ValidFormat<int>("%1$1-d"), ValidFormat<std::string, int>("%2$*1$s"), ValidFormat<std::string>("%1$p"), ValidFormat<int>("%1$*2$v"), ValidFormat<int, int>("%d %2$d"), }; for (Case c : falses) { EXPECT_FALSE(c.result) << "format<" << c.format << ">"; } } TEST(StrFormatChecker, LongFormat) { #define CHARS_X_40 "1234567890123456789012345678901234567890" #define CHARS_X_400 \ CHARS_X_40 CHARS_X_40 CHARS_X_40 CHARS_X_40 CHARS_X_40 CHARS_X_40 CHARS_X_40 \ CHARS_X_40 CHARS_X_40 CHARS_X_40 #define CHARS_X_4000 \ CHARS_X_400 CHARS_X_400 CHARS_X_400 CHARS_X_400 CHARS_X_400 CHARS_X_400 \ CHARS_X_400 CHARS_X_400 CHARS_X_400 CHARS_X_400 constexpr char long_format[] = CHARS_X_4000 "%d" CHARS_X_4000 "%s" CHARS_X_4000; constexpr bool is_valid = ValidFormat<int, std::string>(long_format).result; EXPECT_TRUE(is_valid); } #endif } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/checker.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/strings/internal/str_format/checker_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
04c6a655-18ac-47eb-9c89-76edaa0f0a6f
cpp
abseil/abseil-cpp
optional
absl/types/internal/optional.h
absl/types/optional_test.cc
#ifndef ABSL_TYPES_INTERNAL_OPTIONAL_H_ #define ABSL_TYPES_INTERNAL_OPTIONAL_H_ #include <functional> #include <new> #include <type_traits> #include <utility> #include "absl/base/internal/inline_variable.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/utility/utility.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename T> class optional; namespace optional_internal { struct init_t { explicit init_t() = default; }; struct empty_struct {}; template <typename T, bool unused = std::is_trivially_destructible<T>::value> class optional_data_dtor_base { struct dummy_type { static_assert(sizeof(T) % sizeof(empty_struct) == 0, ""); empty_struct data[sizeof(T) / sizeof(empty_struct)]; }; protected: bool engaged_; union { T data_; dummy_type dummy_; }; void destruct() noexcept { if (engaged_) { #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif data_.~T(); #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0) #pragma GCC diagnostic pop #endif engaged_ = false; } } constexpr optional_data_dtor_base() noexcept : engaged_(false), dummy_{{}} {} template <typename... Args> constexpr explicit optional_data_dtor_base(in_place_t, Args&&... args) : engaged_(true), data_(std::forward<Args>(args)...) {} ~optional_data_dtor_base() { destruct(); } }; template <typename T> class optional_data_dtor_base<T, true> { struct dummy_type { static_assert(sizeof(T) % sizeof(empty_struct) == 0, ""); empty_struct data[sizeof(T) / sizeof(empty_struct)]; }; protected: bool engaged_; union { T data_; dummy_type dummy_; }; void destruct() noexcept { engaged_ = false; } constexpr optional_data_dtor_base() noexcept : engaged_(false), dummy_{{}} {} template <typename... Args> constexpr explicit optional_data_dtor_base(in_place_t, Args&&... args) : engaged_(true), data_(std::forward<Args>(args)...) {} }; template <typename T> class optional_data_base : public optional_data_dtor_base<T> { protected: using base = optional_data_dtor_base<T>; using base::base; template <typename... Args> void construct(Args&&... args) { ::new (static_cast<void*>(&this->dummy_)) T(std::forward<Args>(args)...); this->engaged_ = true; } template <typename U> void assign(U&& u) { if (this->engaged_) { this->data_ = std::forward<U>(u); } else { construct(std::forward<U>(u)); } } }; template <typename T, bool unused = absl::is_trivially_copy_constructible<T>::value&& absl::is_trivially_copy_assignable<typename std::remove_cv< T>::type>::value&& std::is_trivially_destructible<T>::value> class optional_data; template <typename T> class optional_data<T, true> : public optional_data_base<T> { protected: using optional_data_base<T>::optional_data_base; }; template <typename T> class optional_data<T, false> : public optional_data_base<T> { protected: using optional_data_base<T>::optional_data_base; optional_data() = default; optional_data(const optional_data& rhs) : optional_data_base<T>() { if (rhs.engaged_) { this->construct(rhs.data_); } } optional_data(optional_data&& rhs) noexcept( absl::default_allocator_is_nothrow::value || std::is_nothrow_move_constructible<T>::value) : optional_data_base<T>() { if (rhs.engaged_) { this->construct(std::move(rhs.data_)); } } optional_data& operator=(const optional_data& rhs) { if (rhs.engaged_) { this->assign(rhs.data_); } else { this->destruct(); } return *this; } optional_data& operator=(optional_data&& rhs) noexcept( std::is_nothrow_move_assignable<T>::value&& std::is_nothrow_move_constructible<T>::value) { if (rhs.engaged_) { this->assign(std::move(rhs.data_)); } else { this->destruct(); } return *this; } }; enum class copy_traits { copyable = 0, movable = 1, non_movable = 2 }; template <copy_traits> class optional_ctor_base; template <> class optional_ctor_base<copy_traits::copyable> { public: constexpr optional_ctor_base() = default; optional_ctor_base(const optional_ctor_base&) = default; optional_ctor_base(optional_ctor_base&&) = default; optional_ctor_base& operator=(const optional_ctor_base&) = default; optional_ctor_base& operator=(optional_ctor_base&&) = default; }; template <> class optional_ctor_base<copy_traits::movable> { public: constexpr optional_ctor_base() = default; optional_ctor_base(const optional_ctor_base&) = delete; optional_ctor_base(optional_ctor_base&&) = default; optional_ctor_base& operator=(const optional_ctor_base&) = default; optional_ctor_base& operator=(optional_ctor_base&&) = default; }; template <> class optional_ctor_base<copy_traits::non_movable> { public: constexpr optional_ctor_base() = default; optional_ctor_base(const optional_ctor_base&) = delete; optional_ctor_base(optional_ctor_base&&) = delete; optional_ctor_base& operator=(const optional_ctor_base&) = default; optional_ctor_base& operator=(optional_ctor_base&&) = default; }; template <copy_traits> class optional_assign_base; template <> class optional_assign_base<copy_traits::copyable> { public: constexpr optional_assign_base() = default; optional_assign_base(const optional_assign_base&) = default; optional_assign_base(optional_assign_base&&) = default; optional_assign_base& operator=(const optional_assign_base&) = default; optional_assign_base& operator=(optional_assign_base&&) = default; }; template <> class optional_assign_base<copy_traits::movable> { public: constexpr optional_assign_base() = default; optional_assign_base(const optional_assign_base&) = default; optional_assign_base(optional_assign_base&&) = default; optional_assign_base& operator=(const optional_assign_base&) = delete; optional_assign_base& operator=(optional_assign_base&&) = default; }; template <> class optional_assign_base<copy_traits::non_movable> { public: constexpr optional_assign_base() = default; optional_assign_base(const optional_assign_base&) = default; optional_assign_base(optional_assign_base&&) = default; optional_assign_base& operator=(const optional_assign_base&) = delete; optional_assign_base& operator=(optional_assign_base&&) = delete; }; template <typename T> struct ctor_copy_traits { static constexpr copy_traits traits = std::is_copy_constructible<T>::value ? copy_traits::copyable : std::is_move_constructible<T>::value ? copy_traits::movable : copy_traits::non_movable; }; template <typename T> struct assign_copy_traits { static constexpr copy_traits traits = absl::is_copy_assignable<T>::value && std::is_copy_constructible<T>::value ? copy_traits::copyable : absl::is_move_assignable<T>::value && std::is_move_constructible<T>::value ? copy_traits::movable : copy_traits::non_movable; }; template <typename T, typename U> struct is_constructible_convertible_from_optional : std::integral_constant< bool, std::is_constructible<T, optional<U>&>::value || std::is_constructible<T, optional<U>&&>::value || std::is_constructible<T, const optional<U>&>::value || std::is_constructible<T, const optional<U>&&>::value || std::is_convertible<optional<U>&, T>::value || std::is_convertible<optional<U>&&, T>::value || std::is_convertible<const optional<U>&, T>::value || std::is_convertible<const optional<U>&&, T>::value> {}; template <typename T, typename U> struct is_constructible_convertible_assignable_from_optional : std::integral_constant< bool, is_constructible_convertible_from_optional<T, U>::value || std::is_assignable<T&, optional<U>&>::value || std::is_assignable<T&, optional<U>&&>::value || std::is_assignable<T&, const optional<U>&>::value || std::is_assignable<T&, const optional<U>&&>::value> {}; bool convertible_to_bool(bool); template <typename T, typename = size_t> struct optional_hash_base { optional_hash_base() = delete; optional_hash_base(const optional_hash_base&) = delete; optional_hash_base(optional_hash_base&&) = delete; optional_hash_base& operator=(const optional_hash_base&) = delete; optional_hash_base& operator=(optional_hash_base&&) = delete; }; template <typename T> struct optional_hash_base<T, decltype(std::hash<absl::remove_const_t<T> >()( std::declval<absl::remove_const_t<T> >()))> { using argument_type = absl::optional<T>; using result_type = size_t; size_t operator()(const absl::optional<T>& opt) const { absl::type_traits_internal::AssertHashEnabled<absl::remove_const_t<T>>(); if (opt) { return std::hash<absl::remove_const_t<T> >()(*opt); } else { return static_cast<size_t>(0x297814aaad196e6dULL); } } }; } ABSL_NAMESPACE_END } #endif
#include "absl/types/optional.h" #if !defined(ABSL_USES_STD_OPTIONAL) #include <string> #include <type_traits> #include <utility> #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/log/log.h" #include "absl/meta/type_traits.h" #include "absl/strings/string_view.h" #if defined(__cplusplus) && __cplusplus >= 202002L #define ABSL_VOLATILE_RETURN_TYPES_DEPRECATED 1 #endif template <class T, class...> using GccIceHelper1 = T; template <typename T> struct GccIceHelper2 {}; template <typename T> class GccIce { template <typename U, typename SecondTemplateArgHasToExistForSomeReason = void, typename DependentType = void, typename = std::is_assignable<GccIceHelper1<T, DependentType>&, U>> GccIce& operator=(GccIceHelper2<U> const&) {} }; TEST(OptionalTest, InternalCompilerErrorInGcc5ToGcc10) { GccIce<int> instantiate_ice_with_same_type_as_optional; static_cast<void>(instantiate_ice_with_same_type_as_optional); absl::optional<int> val1; absl::optional<int> val2; val1 = val2; } struct Hashable {}; namespace std { template <> struct hash<Hashable> { size_t operator()(const Hashable&) { return 0; } }; } struct NonHashable {}; namespace { std::string TypeQuals(std::string&) { return "&"; } std::string TypeQuals(std::string&&) { return "&&"; } std::string TypeQuals(const std::string&) { return "c&"; } std::string TypeQuals(const std::string&&) { return "c&&"; } struct StructorListener { int construct0 = 0; int construct1 = 0; int construct2 = 0; int listinit = 0; int copy = 0; int move = 0; int copy_assign = 0; int move_assign = 0; int destruct = 0; int volatile_copy = 0; int volatile_move = 0; int volatile_copy_assign = 0; int volatile_move_assign = 0; }; #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4521) #pragma warning(disable : 4522) #endif struct Listenable { static StructorListener* listener; Listenable() { ++listener->construct0; } explicit Listenable(int ) { ++listener->construct1; } Listenable(int , int ) { ++listener->construct2; } Listenable(std::initializer_list<int> ) { ++listener->listinit; } Listenable(const Listenable& ) { ++listener->copy; } Listenable(const volatile Listenable& ) { ++listener->volatile_copy; } Listenable(volatile Listenable&& ) { ++listener->volatile_move; } Listenable(Listenable&& ) { ++listener->move; } Listenable& operator=(const Listenable& ) { ++listener->copy_assign; return *this; } Listenable& operator=(Listenable&& ) { ++listener->move_assign; return *this; } void operator=(const volatile Listenable& ) volatile { ++listener->volatile_copy_assign; } void operator=(volatile Listenable&& ) volatile { ++listener->volatile_move_assign; } ~Listenable() { ++listener->destruct; } }; #ifdef _MSC_VER #pragma warning(pop) #endif StructorListener* Listenable::listener = nullptr; struct ConstexprType { enum CtorTypes { kCtorDefault, kCtorInt, kCtorInitializerList, kCtorConstChar }; constexpr ConstexprType() : x(kCtorDefault) {} constexpr explicit ConstexprType(int i) : x(kCtorInt) {} constexpr ConstexprType(std::initializer_list<int> il) : x(kCtorInitializerList) {} constexpr ConstexprType(const char*) : x(kCtorConstChar) {} int x; }; struct Copyable { Copyable() {} Copyable(const Copyable&) {} Copyable& operator=(const Copyable&) { return *this; } }; struct MoveableThrow { MoveableThrow() {} MoveableThrow(MoveableThrow&&) {} MoveableThrow& operator=(MoveableThrow&&) { return *this; } }; struct MoveableNoThrow { MoveableNoThrow() {} MoveableNoThrow(MoveableNoThrow&&) noexcept {} MoveableNoThrow& operator=(MoveableNoThrow&&) noexcept { return *this; } }; struct NonMovable { NonMovable() {} NonMovable(const NonMovable&) = delete; NonMovable& operator=(const NonMovable&) = delete; NonMovable(NonMovable&&) = delete; NonMovable& operator=(NonMovable&&) = delete; }; struct NoDefault { NoDefault() = delete; NoDefault(const NoDefault&) {} NoDefault& operator=(const NoDefault&) { return *this; } }; struct ConvertsFromInPlaceT { ConvertsFromInPlaceT(absl::in_place_t) {} }; TEST(optionalTest, DefaultConstructor) { absl::optional<int> empty; EXPECT_FALSE(empty); constexpr absl::optional<int> cempty; static_assert(!cempty.has_value(), ""); EXPECT_TRUE( std::is_nothrow_default_constructible<absl::optional<int>>::value); } TEST(optionalTest, nulloptConstructor) { absl::optional<int> empty(absl::nullopt); EXPECT_FALSE(empty); constexpr absl::optional<int> cempty{absl::nullopt}; static_assert(!cempty.has_value(), ""); EXPECT_TRUE((std::is_nothrow_constructible<absl::optional<int>, absl::nullopt_t>::value)); } TEST(optionalTest, CopyConstructor) { { absl::optional<int> empty, opt42 = 42; absl::optional<int> empty_copy(empty); EXPECT_FALSE(empty_copy); absl::optional<int> opt42_copy(opt42); EXPECT_TRUE(opt42_copy); EXPECT_EQ(42, *opt42_copy); } { absl::optional<const int> empty, opt42 = 42; absl::optional<const int> empty_copy(empty); EXPECT_FALSE(empty_copy); absl::optional<const int> opt42_copy(opt42); EXPECT_TRUE(opt42_copy); EXPECT_EQ(42, *opt42_copy); } #if !defined(ABSL_VOLATILE_RETURN_TYPES_DEPRECATED) { absl::optional<volatile int> empty, opt42 = 42; absl::optional<volatile int> empty_copy(empty); EXPECT_FALSE(empty_copy); absl::optional<volatile int> opt42_copy(opt42); EXPECT_TRUE(opt42_copy); EXPECT_EQ(42, *opt42_copy); } #endif EXPECT_TRUE(std::is_copy_constructible<absl::optional<int>>::value); EXPECT_TRUE(std::is_copy_constructible<absl::optional<Copyable>>::value); EXPECT_FALSE( std::is_copy_constructible<absl::optional<MoveableThrow>>::value); EXPECT_FALSE( std::is_copy_constructible<absl::optional<MoveableNoThrow>>::value); EXPECT_FALSE(std::is_copy_constructible<absl::optional<NonMovable>>::value); EXPECT_FALSE( absl::is_trivially_copy_constructible<absl::optional<Copyable>>::value); EXPECT_TRUE( absl::is_trivially_copy_constructible<absl::optional<int>>::value); EXPECT_TRUE( absl::is_trivially_copy_constructible<absl::optional<const int>>::value); #if !defined(_MSC_VER) && !defined(ABSL_VOLATILE_RETURN_TYPES_DEPRECATED) EXPECT_TRUE(absl::is_trivially_copy_constructible< absl::optional<volatile int>>::value); #endif { constexpr absl::optional<int> o1; constexpr absl::optional<int> o2 = o1; static_assert(!o2, ""); } { constexpr absl::optional<int> o1 = 42; constexpr absl::optional<int> o2 = o1; static_assert(o2, ""); static_assert(*o2 == 42, ""); } { struct TrivialCopyable { constexpr TrivialCopyable() : x(0) {} constexpr explicit TrivialCopyable(int i) : x(i) {} int x; }; constexpr absl::optional<TrivialCopyable> o1(42); constexpr absl::optional<TrivialCopyable> o2 = o1; static_assert(o2, ""); static_assert((*o2).x == 42, ""); #ifndef ABSL_GLIBCXX_OPTIONAL_TRIVIALITY_BUG EXPECT_TRUE(absl::is_trivially_copy_constructible< absl::optional<TrivialCopyable>>::value); EXPECT_TRUE(absl::is_trivially_copy_constructible< absl::optional<const TrivialCopyable>>::value); #endif #if !defined(ABSL_VOLATILE_RETURN_TYPES_DEPRECATED) EXPECT_FALSE(std::is_copy_constructible< absl::optional<volatile TrivialCopyable>>::value); #endif } } TEST(optionalTest, MoveConstructor) { absl::optional<int> empty, opt42 = 42; absl::optional<int> empty_move(std::move(empty)); EXPECT_FALSE(empty_move); absl::optional<int> opt42_move(std::move(opt42)); EXPECT_TRUE(opt42_move); EXPECT_EQ(42, opt42_move); EXPECT_TRUE(std::is_move_constructible<absl::optional<int>>::value); EXPECT_TRUE(std::is_move_constructible<absl::optional<Copyable>>::value); EXPECT_TRUE(std::is_move_constructible<absl::optional<MoveableThrow>>::value); EXPECT_TRUE( std::is_move_constructible<absl::optional<MoveableNoThrow>>::value); EXPECT_FALSE(std::is_move_constructible<absl::optional<NonMovable>>::value); EXPECT_TRUE(std::is_nothrow_move_constructible<absl::optional<int>>::value); EXPECT_EQ( absl::default_allocator_is_nothrow::value, std::is_nothrow_move_constructible<absl::optional<MoveableThrow>>::value); EXPECT_TRUE(std::is_nothrow_move_constructible< absl::optional<MoveableNoThrow>>::value); } TEST(optionalTest, Destructor) { struct Trivial {}; struct NonTrivial { NonTrivial(const NonTrivial&) {} NonTrivial& operator=(const NonTrivial&) { return *this; } ~NonTrivial() {} }; EXPECT_TRUE(std::is_trivially_destructible<absl::optional<int>>::value); EXPECT_TRUE(std::is_trivially_destructible<absl::optional<Trivial>>::value); EXPECT_FALSE( std::is_trivially_destructible<absl::optional<NonTrivial>>::value); } TEST(optionalTest, InPlaceConstructor) { constexpr absl::optional<ConstexprType> opt0{absl::in_place_t()}; static_assert(opt0, ""); static_assert((*opt0).x == ConstexprType::kCtorDefault, ""); constexpr absl::optional<ConstexprType> opt1{absl::in_place_t(), 1}; static_assert(opt1, ""); static_assert((*opt1).x == ConstexprType::kCtorInt, ""); constexpr absl::optional<ConstexprType> opt2{absl::in_place_t(), {1, 2}}; static_assert(opt2, ""); static_assert((*opt2).x == ConstexprType::kCtorInitializerList, ""); EXPECT_FALSE((std::is_constructible<absl::optional<ConvertsFromInPlaceT>, absl::in_place_t>::value)); EXPECT_FALSE((std::is_constructible<absl::optional<ConvertsFromInPlaceT>, const absl::in_place_t&>::value)); EXPECT_TRUE( (std::is_constructible<absl::optional<ConvertsFromInPlaceT>, absl::in_place_t, absl::in_place_t>::value)); EXPECT_FALSE((std::is_constructible<absl::optional<NoDefault>, absl::in_place_t>::value)); EXPECT_FALSE((std::is_constructible<absl::optional<NoDefault>, absl::in_place_t&&>::value)); } TEST(optionalTest, ValueConstructor) { constexpr absl::optional<int> opt0(0); static_assert(opt0, ""); static_assert(*opt0 == 0, ""); EXPECT_TRUE((std::is_convertible<int, absl::optional<int>>::value)); constexpr absl::optional<ConstexprType> opt1 = {"abc"}; static_assert(opt1, ""); static_assert(ConstexprType::kCtorConstChar == (*opt1).x, ""); EXPECT_TRUE( (std::is_convertible<const char*, absl::optional<ConstexprType>>::value)); constexpr absl::optional<ConstexprType> opt2{2}; static_assert(opt2, ""); static_assert(ConstexprType::kCtorInt == (*opt2).x, ""); EXPECT_FALSE( (std::is_convertible<int, absl::optional<ConstexprType>>::value)); #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ == 7 && \ __cplusplus == 201703L #define ABSL_GCC7_OVER_ICS_LIST_BUG 1 #endif #ifndef ABSL_GCC7_OVER_ICS_LIST_BUG constexpr absl::optional<int> opt3({}); static_assert(opt3, ""); static_assert(*opt3 == 0, ""); #endif absl::optional<ConstexprType> opt4({}); EXPECT_FALSE(opt4); } struct Implicit {}; struct Explicit {}; struct Convert { Convert(const Implicit&) : implicit(true), move(false) {} Convert(Implicit&&) : implicit(true), move(true) {} explicit Convert(const Explicit&) : implicit(false), move(false) {} explicit Convert(Explicit&&) : implicit(false), move(true) {} bool implicit; bool move; }; struct ConvertFromOptional { ConvertFromOptional(const Implicit&) : implicit(true), move(false), from_optional(false) {} ConvertFromOptional(Implicit&&) : implicit(true), move(true), from_optional(false) {} ConvertFromOptional( const absl::optional<Implicit>&) : implicit(true), move(false), from_optional(true) {} ConvertFromOptional(absl::optional<Implicit>&&) : implicit(true), move(true), from_optional(true) {} explicit ConvertFromOptional(const Explicit&) : implicit(false), move(false), from_optional(false) {} explicit ConvertFromOptional(Explicit&&) : implicit(false), move(true), from_optional(false) {} explicit ConvertFromOptional(const absl::optional<Explicit>&) : implicit(false), move(false), from_optional(true) {} explicit ConvertFromOptional(absl::optional<Explicit>&&) : implicit(false), move(true), from_optional(true) {} bool implicit; bool move; bool from_optional; }; TEST(optionalTest, ConvertingConstructor) { absl::optional<Implicit> i_empty; absl::optional<Implicit> i(absl::in_place); absl::optional<Explicit> e_empty; absl::optional<Explicit> e(absl::in_place); { absl::optional<Convert> empty = i_empty; EXPECT_FALSE(empty); absl::optional<Convert> opt_copy = i; EXPECT_TRUE(opt_copy); EXPECT_TRUE(opt_copy->implicit); EXPECT_FALSE(opt_copy->move); absl::optional<Convert> opt_move = absl::optional<Implicit>(absl::in_place); EXPECT_TRUE(opt_move); EXPECT_TRUE(opt_move->implicit); EXPECT_TRUE(opt_move->move); } { absl::optional<Convert> empty(e_empty); EXPECT_FALSE(empty); absl::optional<Convert> opt_copy(e); EXPECT_TRUE(opt_copy); EXPECT_FALSE(opt_copy->implicit); EXPECT_FALSE(opt_copy->move); EXPECT_FALSE((std::is_convertible<const absl::optional<Explicit>&, absl::optional<Convert>>::value)); absl::optional<Convert> opt_move{absl::optional<Explicit>(absl::in_place)}; EXPECT_TRUE(opt_move); EXPECT_FALSE(opt_move->implicit); EXPECT_TRUE(opt_move->move); EXPECT_FALSE((std::is_convertible<absl::optional<Explicit>&&, absl::optional<Convert>>::value)); } { static_assert( std::is_convertible<absl::optional<Implicit>, absl::optional<ConvertFromOptional>>::value, ""); absl::optional<ConvertFromOptional> opt0 = i_empty; EXPECT_TRUE(opt0); EXPECT_TRUE(opt0->implicit); EXPECT_FALSE(opt0->move); EXPECT_TRUE(opt0->from_optional); absl::optional<ConvertFromOptional> opt1 = absl::optional<Implicit>(); EXPECT_TRUE(opt1); EXPECT_TRUE(opt1->implicit); EXPECT_TRUE(opt1->move); EXPECT_TRUE(opt1->from_optional); } { absl::optional<ConvertFromOptional> opt0(e_empty); EXPECT_TRUE(opt0); EXPECT_FALSE(opt0->implicit); EXPECT_FALSE(opt0->move); EXPECT_TRUE(opt0->from_optional); EXPECT_FALSE( (std::is_convertible<const absl::optional<Explicit>&, absl::optional<ConvertFromOptional>>::value)); absl::optional<ConvertFromOptional> opt1{absl::optional<Explicit>()}; EXPECT_TRUE(opt1); EXPECT_FALSE(opt1->implicit); EXPECT_TRUE(opt1->move); EXPECT_TRUE(opt1->from_optional); EXPECT_FALSE( (std::is_convertible<absl::optional<Explicit>&&, absl::optional<ConvertFromOptional>>::value)); } } TEST(optionalTest, StructorBasic) { StructorListener listener; Listenable::listener = &listener; { absl::optional<Listenable> empty; EXPECT_FALSE(empty); absl::optional<Listenable> opt0(absl::in_place); EXPECT_TRUE(opt0); absl::optional<Listenable> opt1(absl::in_place, 1); EXPECT_TRUE(opt1); absl::optional<Listenable> opt2(absl::in_place, 1, 2); EXPECT_TRUE(opt2); } EXPECT_EQ(1, listener.construct0); EXPECT_EQ(1, listener.construct1); EXPECT_EQ(1, listener.construct2); EXPECT_EQ(3, listener.destruct); } TEST(optionalTest, CopyMoveStructor) { StructorListener listener; Listenable::listener = &listener; absl::optional<Listenable> original(absl::in_place); EXPECT_EQ(1, listener.construct0); EXPECT_EQ(0, listener.copy); EXPECT_EQ(0, listener.move); absl::optional<Listenable> copy(original); EXPECT_EQ(1, listener.construct0); EXPECT_EQ(1, listener.copy); EXPECT_EQ(0, listener.move); absl::optional<Listenable> move(std::move(original)); EXPECT_EQ(1, listener.construct0); EXPECT_EQ(1, listener.copy); EXPECT_EQ(1, listener.move); } TEST(optionalTest, ListInit) { StructorListener listener; Listenable::listener = &listener; absl::optional<Listenable> listinit1(absl::in_place, {1}); absl::optional<Listenable> listinit2(absl::in_place, {1, 2}); EXPECT_EQ(2, listener.listinit); } TEST(optionalTest, AssignFromNullopt) { absl::optional<int> opt(1); opt = absl::nullopt; EXPECT_FALSE(opt); StructorListener listener; Listenable::listener = &listener; absl::optional<Listenable> opt1(absl::in_place); opt1 = absl::nullopt; EXPECT_FALSE(opt1); EXPECT_EQ(1, listener.construct0); EXPECT_EQ(1, listener.destruct); EXPECT_TRUE(( std::is_nothrow_assignable<absl::optional<int>, absl::nullopt_t>::value)); EXPECT_TRUE((std::is_nothrow_assignable<absl::optional<Listenable>, absl::nullopt_t>::value)); } TEST(optionalTest, CopyAssignment) { const absl::optional<int> empty, opt1 = 1, opt2 = 2; absl::optional<int> empty_to_opt1, opt1_to_opt2, opt2_to_empty; EXPECT_FALSE(empty_to_opt1); empty_to_opt1 = empty; EXPECT_FALSE(empty_to_opt1); empty_to_opt1 = opt1; EXPECT_TRUE(empty_to_opt1); EXPECT_EQ(1, empty_to_opt1.value()); EXPECT_FALSE(opt1_to_opt2); opt1_to_opt2 = opt1; EXPECT_TRUE(opt1_to_opt2); EXPECT_EQ(1, opt1_to_opt2.value()); opt1_to_opt2 = opt2; EXPECT_TRUE(opt1_to_opt2); EXPECT_EQ(2, opt1_to_opt2.value()); EXPECT_FALSE(opt2_to_empty); opt2_to_empty = opt2; EXPECT_TRUE(opt2_to_empty); EXPECT_EQ(2, opt2_to_empty.value()); opt2_to_empty = empty; EXPECT_FALSE(opt2_to_empty); EXPECT_FALSE(absl::is_copy_assignable<absl::optional<const int>>::value); EXPECT_TRUE(absl::is_copy_assignable<absl::optional<Copyable>>::value); EXPECT_FALSE(absl::is_copy_assignable<absl::optional<MoveableThrow>>::value); EXPECT_FALSE( absl::is_copy_assignable<absl::optional<MoveableNoThrow>>::value); EXPECT_FALSE(absl::is_copy_assignable<absl::optional<NonMovable>>::value); EXPECT_TRUE(absl::is_trivially_copy_assignable<int>::value); EXPECT_TRUE(absl::is_trivially_copy_assignable<volatile int>::value); struct Trivial { int i; }; struct NonTrivial { NonTrivial& operator=(const NonTrivial&) { return *this; } int i; }; EXPECT_TRUE(absl::is_trivially_copy_assignable<Trivial>::value); EXPECT_FALSE(absl::is_copy_assignable<const Trivial>::value); EXPECT_FALSE(absl::is_copy_assignable<volatile Trivial>::value); EXPECT_TRUE(absl::is_copy_assignable<NonTrivial>::value); EXPECT_FALSE(absl::is_trivially_copy_assignable<NonTrivial>::value); #if !defined(ABSL_VOLATILE_RETURN_TYPES_DEPRECATED) { StructorListener listener; Listenable::listener = &listener; absl::optional<volatile Listenable> empty, set(absl::in_place); EXPECT_EQ(1, listener.construct0); absl::optional<volatile Listenable> empty_to_empty, empty_to_set, set_to_empty(absl::in_place), set_to_set(absl::in_place); EXPECT_EQ(3, listener.construct0); empty_to_empty = empty; empty_to_set = set; set_to_empty = empty; set_to_set = set; EXPECT_EQ(1, listener.volatile_copy); EXPECT_EQ(0, listener.volatile_move); EXPECT_EQ(1, listener.destruct); EXPECT_EQ(1, listener.volatile_copy_assign); } #endif } TEST(optionalTest, MoveAssignment) { { StructorListener listener; Listenable::listener = &listener; absl::optional<Listenable> empty1, empty2, set1(absl::in_place), set2(absl::in_place); EXPECT_EQ(2, listener.construct0); absl::optional<Listenable> empty_to_empty, empty_to_set, set_to_empty(absl::in_place), set_to_set(absl::in_place); EXPECT_EQ(4, listener.construct0); empty_to_empty = std::move(empty1); empty_to_set = std::move(set1); set_to_empty = std::move(empty2); set_to_set = std::move(set2); EXPECT_EQ(0, listener.copy); EXPECT_EQ(1, listener.move); EXPECT_EQ(1, listener.destruct); EXPECT_EQ(1, listener.move_assign); } #if !defined(ABSL_VOLATILE_RETURN_TYPES_DEPRECATED) { StructorListener listener; Listenable::listener = &listener; absl::optional<volatile Listenable> empty1, empty2, set1(absl::in_place), set2(absl::in_place); EXPECT_EQ(2, listener.construct0); absl::optional<volatile Listenable> empty_to_empty, empty_to_set, set_to_empty(absl::in_place), set_to_set(absl::in_place); EXPECT_EQ(4, listener.construct0); empty_to_empty = std::move(empty1); empty_to_set = std::move(set1); set_to_empty = std::move(empty2); set_to_set = std::move(set2); EXPECT_EQ(0, listener.volatile_copy); EXPECT_EQ(1, listener.volatile_move); EXPECT_EQ(1, listener.destruct); EXPECT_EQ(1, listener.volatile_move_assign); } #endif EXPECT_FALSE(absl::is_move_assignable<absl::optional<const int>>::value); EXPECT_TRUE(absl::is_move_assignable<absl::optional<Copyable>>::value); EXPECT_TRUE(absl::is_move_assignable<absl::optional<MoveableThrow>>::value); EXPECT_TRUE(absl::is_move_assignable<absl::optional<MoveableNoThrow>>::value); EXPECT_FALSE(absl::is_move_assignable<absl::optional<NonMovable>>::value); EXPECT_FALSE( std::is_nothrow_move_assignable<absl::optional<MoveableThrow>>::value); EXPECT_TRUE( std::is_nothrow_move_assignable<absl::optional<MoveableNoThrow>>::value); } struct NoConvertToOptional { NoConvertToOptional(const NoConvertToOptional&) = delete; }; struct CopyConvert { CopyConvert(const NoConvertToOptional&); CopyConvert& operator=(const CopyConvert&) = delete; CopyConvert& operator=(const NoConvertToOptional&); }; struct CopyConvertFromOptional { CopyConvertFromOptional(const NoConvertToOptional&); CopyConvertFromOptional(const absl::optional<NoConvertToOptional>&); CopyConvertFromOptional& operator=(const CopyConvertFromOptional&) = delete; CopyConvertFromOptional& operator=(const NoConvertToOptional&); CopyConvertFromOptional& operator=( const absl::optional<NoConvertToOptional>&); }; struct MoveConvert { MoveConvert(NoConvertToOptional&&); MoveConvert& operator=(const MoveConvert&) = delete; MoveConvert& operator=(NoConvertToOptional&&); }; struct MoveConvertFromOptional { MoveConvertFromOptional(NoConvertToOptional&&); MoveConvertFromOptional(absl::optional<NoConvertToOptional>&&); MoveConvertFromOptional& operator=(const MoveConvertFromOptional&) = delete; MoveConvertFromOptional& operator=(NoConvertToOptional&&); MoveConvertFromOptional& operator=(absl::optional<NoConvertToOptional>&&); }; TEST(optionalTest, ValueAssignment) { absl::optional<int> opt; EXPECT_FALSE(opt); opt = 42; EXPECT_TRUE(opt); EXPECT_EQ(42, opt.value()); opt = absl::nullopt; EXPECT_FALSE(opt); opt = 42; EXPECT_TRUE(opt); EXPECT_EQ(42, opt.value()); opt = 43; EXPECT_TRUE(opt); EXPECT_EQ(43, opt.value()); opt = {}; EXPECT_FALSE(opt); opt = {44}; EXPECT_TRUE(opt); EXPECT_EQ(44, opt.value()); EXPECT_TRUE((std::is_assignable<absl::optional<CopyConvert>&, const NoConvertToOptional&>::value)); EXPECT_TRUE((std::is_assignable<absl::optional<CopyConvertFromOptional>&, const NoConvertToOptional&>::value)); EXPECT_FALSE((std::is_assignable<absl::optional<MoveConvert>&, const NoConvertToOptional&>::value)); EXPECT_TRUE((std::is_assignable<absl::optional<MoveConvert>&, NoConvertToOptional&&>::value)); EXPECT_FALSE((std::is_assignable<absl::optional<MoveConvertFromOptional>&, const NoConvertToOptional&>::value)); EXPECT_TRUE((std::is_assignable<absl::optional<MoveConvertFromOptional>&, NoConvertToOptional&&>::value)); EXPECT_TRUE( (std::is_assignable<absl::optional<CopyConvertFromOptional>&, const absl::optional<NoConvertToOptional>&>::value)); EXPECT_TRUE( (std::is_assignable<absl::optional<MoveConvertFromOptional>&, absl::optional<NoConvertToOptional>&&>::value)); } TEST(optionalTest, ConvertingAssignment) { absl::optional<int> opt_i; absl::optional<char> opt_c('c'); opt_i = opt_c; EXPECT_TRUE(opt_i); EXPECT_EQ(*opt_c, *opt_i); opt_i = absl::optional<char>(); EXPECT_FALSE(opt_i); opt_i = absl::optional<char>('d'); EXPECT_TRUE(opt_i); EXPECT_EQ('d', *opt_i); absl::optional<std::string> opt_str; absl::optional<const char*> opt_cstr("abc"); opt_str = opt_cstr; EXPECT_TRUE(opt_str); EXPECT_EQ(std::string("abc"), *opt_str); opt_str = absl::optional<const char*>(); EXPECT_FALSE(opt_str); opt_str = absl::optional<const char*>("def"); EXPECT_TRUE(opt_str); EXPECT_EQ(std::string("def"), *opt_str); EXPECT_TRUE( (std::is_assignable<absl::optional<CopyConvert>, const absl::optional<NoConvertToOptional>&>::value)); EXPECT_FALSE( (std::is_assignable<absl::optional<MoveConvert>&, const absl::optional<NoConvertToOptional>&>::value)); EXPECT_TRUE( (std::is_assignable<absl::optional<MoveConvert>&, absl::optional<NoConvertToOptional>&&>::value)); EXPECT_FALSE( (std::is_assignable<absl::optional<MoveConvertFromOptional>&, const absl::optional<NoConvertToOptional>&>::value)); } TEST(optionalTest, ResetAndHasValue) { StructorListener listener; Listenable::listener = &listener; absl::optional<Listenable> opt; EXPECT_FALSE(opt); EXPECT_FALSE(opt.has_value()); opt.emplace(); EXPECT_TRUE(opt); EXPECT_TRUE(opt.has_value()); opt.reset(); EXPECT_FALSE(opt); EXPECT_FALSE(opt.has_value()); EXPECT_EQ(1, listener.destruct); opt.reset(); EXPECT_FALSE(opt); EXPECT_FALSE(opt.has_value()); constexpr absl::optional<int> empty; static_assert(!empty.has_value(), ""); constexpr absl::optional<int> nonempty(1); static_assert(nonempty.has_value(), ""); } TEST(optionalTest, Emplace) { StructorListener listener; Listenable::listener = &listener; absl::optional<Listenable> opt; EXPECT_FALSE(opt); opt.emplace(1); EXPECT_TRUE(opt); opt.emplace(1, 2); EXPECT_EQ(1, listener.construct1); EXPECT_EQ(1, listener.construct2); EXPECT_EQ(1, listener.destruct); absl::optional<std::string> o; EXPECT_TRUE((std::is_same<std::string&, decltype(o.emplace("abc"))>::value)); std::string& ref = o.emplace("abc"); EXPECT_EQ(&ref, &o.value()); } TEST(optionalTest, ListEmplace) { StructorListener listener; Listenable::listener = &listener; absl::optional<Listenable> opt; EXPECT_FALSE(opt); opt.emplace({1}); EXPECT_TRUE(opt); opt.emplace({1, 2}); EXPECT_EQ(2, listener.listinit); EXPECT_EQ(1, listener.destruct); absl::optional<Listenable> o; EXPECT_TRUE((std::is_same<Listenable&, decltype(o.emplace({1}))>::value)); Listenable& ref = o.emplace({1}); EXPECT_EQ(&ref, &o.value()); } TEST(optionalTest, Swap) { absl::optional<int> opt_empty, opt1 = 1, opt2 = 2; EXPECT_FALSE(opt_empty); EXPECT_TRUE(opt1); EXPECT_EQ(1, opt1.value()); EXPECT_TRUE(opt2); EXPECT_EQ(2, opt2.value()); swap(opt_empty, opt1); EXPECT_FALSE(opt1); EXPECT_TRUE(opt_empty); EXPECT_EQ(1, opt_empty.value()); EXPECT_TRUE(opt2); EXPECT_EQ(2, opt2.value()); swap(opt_empty, opt1); EXPECT_FALSE(opt_empty); EXPECT_TRUE(opt1); EXPECT_EQ(1, opt1.value()); EXPECT_TRUE(opt2); EXPECT_EQ(2, opt2.value()); swap(opt1, opt2); EXPECT_FALSE(opt_empty); EXPECT_TRUE(opt1); EXPECT_EQ(2, opt1.value()); EXPECT_TRUE(opt2); EXPECT_EQ(1, opt2.value()); EXPECT_TRUE(noexcept(opt1.swap(opt2))); EXPECT_TRUE(noexcept(swap(opt1, opt2))); } template <int v> struct DeletedOpAddr { int value = v; constexpr DeletedOpAddr() = default; constexpr const DeletedOpAddr<v>* operator&() const = delete; DeletedOpAddr<v>* operator&() = delete; }; TEST(optionalTest, OperatorAddr) { constexpr int v = -1; { constexpr absl::optional<DeletedOpAddr<v>> opt(absl::in_place_t{}); static_assert(opt.has_value(), ""); static_assert((*opt).value == v, ""); } { const absl::optional<DeletedOpAddr<v>> opt(absl::in_place_t{}); EXPECT_TRUE(opt.has_value()); EXPECT_TRUE(opt->value == v); EXPECT_TRUE((*opt).value == v); } } TEST(optionalTest, PointerStuff) { absl::optional<std::string> opt(absl::in_place, "foo"); EXPECT_EQ("foo", *opt); const auto& opt_const = opt; EXPECT_EQ("foo", *opt_const); EXPECT_EQ(opt->size(), 3u); EXPECT_EQ(opt_const->size(), 3u); constexpr absl::optional<ConstexprType> opt1(1); static_assert((*opt1).x == ConstexprType::kCtorInt, ""); } TEST(optionalTest, Value) { using O = absl::optional<std::string>; using CO = const absl::optional<std::string>; using OC = absl::optional<const std::string>; O lvalue(absl::in_place, "lvalue"); CO clvalue(absl::in_place, "clvalue"); OC lvalue_c(absl::in_place, "lvalue_c"); EXPECT_EQ("lvalue", lvalue.value()); EXPECT_EQ("clvalue", clvalue.value()); EXPECT_EQ("lvalue_c", lvalue_c.value()); EXPECT_EQ("xvalue", O(absl::in_place, "xvalue").value()); EXPECT_EQ("xvalue_c", OC(absl::in_place, "xvalue_c").value()); EXPECT_EQ("cxvalue", CO(absl::in_place, "cxvalue").value()); EXPECT_EQ("&", TypeQuals(lvalue.value())); EXPECT_EQ("c&", TypeQuals(clvalue.value())); EXPECT_EQ("c&", TypeQuals(lvalue_c.value())); EXPECT_EQ("&&", TypeQuals(O(absl::in_place, "xvalue").value())); EXPECT_EQ("c&&", TypeQuals(CO(absl::in_place, "cxvalue").value())); EXPECT_EQ("c&&", TypeQuals(OC(absl::in_place, "xvalue_c").value())); #if !defined(ABSL_VOLATILE_RETURN_TYPES_DEPRECATED) using OV = absl::optional<volatile int>; OV lvalue_v(absl::in_place, 42); EXPECT_EQ(42, lvalue_v.value()); EXPECT_EQ(42, OV(42).value()); EXPECT_TRUE((std::is_same<volatile int&, decltype(lvalue_v.value())>::value)); EXPECT_TRUE((std::is_same<volatile int&&, decltype(OV(42).value())>::value)); #endif absl::optional<int> empty; #ifdef ABSL_HAVE_EXCEPTIONS EXPECT_THROW((void)empty.value(), absl::bad_optional_access); #else EXPECT_DEATH_IF_SUPPORTED((void)empty.value(), "Bad optional access"); #endif constexpr absl::optional<int> o1(1); static_assert(1 == o1.value(), ""); #ifndef _MSC_VER using COI = const absl::optional<int>; static_assert(2 == COI(2).value(), ""); #endif } TEST(optionalTest, DerefOperator) { using O = absl::optional<std::string>; using CO = const absl::optional<std::string>; using OC = absl::optional<const std::string>; O lvalue(absl::in_place, "lvalue"); CO clvalue(absl::in_place, "clvalue"); OC lvalue_c(absl::in_place, "lvalue_c"); EXPECT_EQ("lvalue", *lvalue); EXPECT_EQ("clvalue", *clvalue); EXPECT_EQ("lvalue_c", *lvalue_c); EXPECT_EQ("xvalue", *O(absl::in_place, "xvalue")); EXPECT_EQ("xvalue_c", *OC(absl::in_place, "xvalue_c")); EXPECT_EQ("cxvalue", *CO(absl::in_place, "cxvalue")); EXPECT_EQ("&", TypeQuals(*lvalue)); EXPECT_EQ("c&", TypeQuals(*clvalue)); EXPECT_EQ("&&", TypeQuals(*O(absl::in_place, "xvalue"))); EXPECT_EQ("c&&", TypeQuals(*CO(absl::in_place, "cxvalue"))); EXPECT_EQ("c&&", TypeQuals(*OC(absl::in_place, "xvalue_c"))); #if !defined(ABSL_VOLATILE_RETURN_TYPES_DEPRECATED) using OV = absl::optional<volatile int>; OV lvalue_v(absl::in_place, 42); EXPECT_EQ(42, *lvalue_v); EXPECT_EQ(42, *OV(42)); EXPECT_TRUE((std::is_same<volatile int&, decltype(*lvalue_v)>::value)); EXPECT_TRUE((std::is_same<volatile int&&, decltype(*OV(42))>::value)); #endif constexpr absl::optional<int> opt1(1); static_assert(*opt1 == 1, ""); #if !defined(_MSC_VER) && !defined(ABSL_SKIP_OVERLOAD_TEST_DUE_TO_GCC_BUG) using COI = const absl::optional<int>; static_assert(*COI(2) == 2, ""); #endif } TEST(optionalTest, ValueOr) { absl::optional<double> opt_empty, opt_set = 1.2; EXPECT_EQ(42.0, opt_empty.value_or(42)); EXPECT_EQ(1.2, opt_set.value_or(42)); EXPECT_EQ(42.0, absl::optional<double>().value_or(42)); EXPECT_EQ(1.2, absl::optional<double>(1.2).value_or(42)); constexpr absl::optional<double> copt_empty, copt_set = {1.2}; static_assert(42.0 == copt_empty.value_or(42), ""); static_assert(1.2 == copt_set.value_or(42), ""); using COD = const absl::optional<double>; static_assert(42.0 == COD().value_or(42), ""); static_assert(1.2 == COD(1.2).value_or(42), ""); } TEST(optionalTest, make_optional) { auto opt_int = absl::make_optional(42); EXPECT_TRUE((std::is_same<decltype(opt_int), absl::optional<int>>::value)); EXPECT_EQ(42, opt_int); StructorListener listener; Listenable::listener = &listener; absl::optional<Listenable> opt0 = absl::make_optional<Listenable>(); EXPECT_EQ(1, listener.construct0); absl::optional<Listenable> opt1 = absl::make_optional<Listenable>(1); EXPECT_EQ(1, listener.construct1); absl::optional<Listenable> opt2 = absl::make_optional<Listenable>(1, 2); EXPECT_EQ(1, listener.construct2); absl::optional<Listenable> opt3 = absl::make_optional<Listenable>({1}); absl::optional<Listenable> opt4 = absl::make_optional<Listenable>({1, 2}); EXPECT_EQ(2, listener.listinit); { constexpr absl::optional<int> c_opt = absl::make_optional(42); static_assert(c_opt.value() == 42, ""); } { struct TrivialCopyable { constexpr TrivialCopyable() : x(0) {} constexpr explicit TrivialCopyable(int i) : x(i) {} int x; }; constexpr TrivialCopyable v; constexpr absl::optional<TrivialCopyable> c_opt0 = absl::make_optional(v); static_assert((*c_opt0).x == 0, ""); constexpr absl::optional<TrivialCopyable> c_opt1 = absl::make_optional<TrivialCopyable>(); static_assert((*c_opt1).x == 0, ""); constexpr absl::optional<TrivialCopyable> c_opt2 = absl::make_optional<TrivialCopyable>(42); static_assert((*c_opt2).x == 42, ""); } } template <typename T, typename U> void optionalTest_Comparisons_EXPECT_LESS(T x, U y) { EXPECT_FALSE(x == y); EXPECT_TRUE(x != y); EXPECT_TRUE(x < y); EXPECT_FALSE(x > y); EXPECT_TRUE(x <= y); EXPECT_FALSE(x >= y); } template <typename T, typename U> void optionalTest_Comparisons_EXPECT_SAME(T x, U y) { EXPECT_TRUE(x == y); EXPECT_FALSE(x != y); EXPECT_FALSE(x < y); EXPECT_FALSE(x > y); EXPECT_TRUE(x <= y); EXPECT_TRUE(x >= y); } template <typename T, typename U> void optionalTest_Comparisons_EXPECT_GREATER(T x, U y) { EXPECT_FALSE(x == y); EXPECT_TRUE(x != y); EXPECT_FALSE(x < y); EXPECT_TRUE(x > y); EXPECT_FALSE(x <= y); EXPECT_TRUE(x >= y); } template <typename T, typename U, typename V> void TestComparisons() { absl::optional<T> ae, a2{2}, a4{4}; absl::optional<U> be, b2{2}, b4{4}; V v3 = 3; optionalTest_Comparisons_EXPECT_SAME(absl::nullopt, be); optionalTest_Comparisons_EXPECT_LESS(absl::nullopt, b2); optionalTest_Comparisons_EXPECT_LESS(absl::nullopt, b4); optionalTest_Comparisons_EXPECT_SAME(ae, absl::nullopt); optionalTest_Comparisons_EXPECT_SAME(ae, be); optionalTest_Comparisons_EXPECT_LESS(ae, b2); optionalTest_Comparisons_EXPECT_LESS(ae, v3); optionalTest_Comparisons_EXPECT_LESS(ae, b4); optionalTest_Comparisons_EXPECT_GREATER(a2, absl::nullopt); optionalTest_Comparisons_EXPECT_GREATER(a2, be); optionalTest_Comparisons_EXPECT_SAME(a2, b2); optionalTest_Comparisons_EXPECT_LESS(a2, v3); optionalTest_Comparisons_EXPECT_LESS(a2, b4); optionalTest_Comparisons_EXPECT_GREATER(v3, be); optionalTest_Comparisons_EXPECT_GREATER(v3, b2); optionalTest_Comparisons_EXPECT_SAME(v3, v3); optionalTest_Comparisons_EXPECT_LESS(v3, b4); optionalTest_Comparisons_EXPECT_GREATER(a4, absl::nullopt); optionalTest_Comparisons_EXPECT_GREATER(a4, be); optionalTest_Comparisons_EXPECT_GREATER(a4, b2); optionalTest_Comparisons_EXPECT_GREATER(a4, v3); optionalTest_Comparisons_EXPECT_SAME(a4, b4); } struct Int1 { Int1() = default; Int1(int i) : i(i) {} int i; }; struct Int2 { Int2() = default; Int2(int i) : i(i) {} int i; }; constexpr bool operator==(const Int1& lhs, const Int2& rhs) { return lhs.i == rhs.i; } constexpr bool operator!=(const Int1& lhs, const Int2& rhs) { return !(lhs == rhs); } constexpr bool operator<(const Int1& lhs, const Int2& rhs) { return lhs.i < rhs.i; } constexpr bool operator<=(const Int1& lhs, const Int2& rhs) { return lhs < rhs || lhs == rhs; } constexpr bool operator>(const Int1& lhs, const Int2& rhs) { return !(lhs <= rhs); } constexpr bool operator>=(const Int1& lhs, const Int2& rhs) { return !(lhs < rhs); } TEST(optionalTest, Comparisons) { TestComparisons<int, int, int>(); TestComparisons<const int, int, int>(); TestComparisons<Int1, int, int>(); TestComparisons<int, Int2, int>(); TestComparisons<Int1, Int2, int>(); absl::optional<std::string> opt_str = "abc"; const char* cstr = "abc"; EXPECT_TRUE(opt_str == cstr); absl::optional<const char*> opt_cstr = cstr; EXPECT_TRUE(opt_str == opt_cstr); absl::optional<absl::string_view> e1; absl::optional<std::string> e2; EXPECT_TRUE(e1 == e2); } TEST(optionalTest, SwapRegression) { StructorListener listener; Listenable::listener = &listener; { absl::optional<Listenable> a; absl::optional<Listenable> b(absl::in_place); a.swap(b); } EXPECT_EQ(1, listener.construct0); EXPECT_EQ(1, listener.move); EXPECT_EQ(2, listener.destruct); { absl::optional<Listenable> a(absl::in_place); absl::optional<Listenable> b; a.swap(b); } EXPECT_EQ(2, listener.construct0); EXPECT_EQ(2, listener.move); EXPECT_EQ(4, listener.destruct); } TEST(optionalTest, BigStringLeakCheck) { constexpr size_t n = 1 << 16; using OS = absl::optional<std::string>; OS a; OS b = absl::nullopt; OS c = std::string(n, 'c'); std::string sd(n, 'd'); OS d = sd; OS e(absl::in_place, n, 'e'); OS f; f.emplace(n, 'f'); OS ca(a); OS cb(b); OS cc(c); OS cd(d); OS ce(e); OS oa; OS ob = absl::nullopt; OS oc = std::string(n, 'c'); std::string sod(n, 'd'); OS od = sod; OS oe(absl::in_place, n, 'e'); OS of; of.emplace(n, 'f'); OS ma(std::move(oa)); OS mb(std::move(ob)); OS mc(std::move(oc)); OS md(std::move(od)); OS me(std::move(oe)); OS mf(std::move(of)); OS aa1; OS ab1 = absl::nullopt; OS ac1 = std::string(n, 'c'); std::string sad1(n, 'd'); OS ad1 = sad1; OS ae1(absl::in_place, n, 'e'); OS af1; af1.emplace(n, 'f'); OS aa2; OS ab2 = absl::nullopt; OS ac2 = std::string(n, 'c'); std::string sad2(n, 'd'); OS ad2 = sad2; OS ae2(absl::in_place, n, 'e'); OS af2; af2.emplace(n, 'f'); aa1 = af2; ab1 = ae2; ac1 = ad2; ad1 = ac2; ae1 = ab2; af1 = aa2; OS aa3; OS ab3 = absl::nullopt; OS ac3 = std::string(n, 'c'); std::string sad3(n, 'd'); OS ad3 = sad3; OS ae3(absl::in_place, n, 'e'); OS af3; af3.emplace(n, 'f'); aa3 = absl::nullopt; ab3 = absl::nullopt; ac3 = absl::nullopt; ad3 = absl::nullopt; ae3 = absl::nullopt; af3 = absl::nullopt; OS aa4; OS ab4 = absl::nullopt; OS ac4 = std::string(n, 'c'); std::string sad4(n, 'd'); OS ad4 = sad4; OS ae4(absl::in_place, n, 'e'); OS af4; af4.emplace(n, 'f'); aa4 = OS(absl::in_place, n, 'a'); ab4 = OS(absl::in_place, n, 'b'); ac4 = OS(absl::in_place, n, 'c'); ad4 = OS(absl::in_place, n, 'd'); ae4 = OS(absl::in_place, n, 'e'); af4 = OS(absl::in_place, n, 'f'); OS aa5; OS ab5 = absl::nullopt; OS ac5 = std::string(n, 'c'); std::string sad5(n, 'd'); OS ad5 = sad5; OS ae5(absl::in_place, n, 'e'); OS af5; af5.emplace(n, 'f'); std::string saa5(n, 'a'); std::string sab5(n, 'a'); std::string sac5(n, 'a'); std::string sad52(n, 'a'); std::string sae5(n, 'a'); std::string saf5(n, 'a'); aa5 = saa5; ab5 = sab5; ac5 = sac5; ad5 = sad52; ae5 = sae5; af5 = saf5; OS aa6; OS ab6 = absl::nullopt; OS ac6 = std::string(n, 'c'); std::string sad6(n, 'd'); OS ad6 = sad6; OS ae6(absl::in_place, n, 'e'); OS af6; af6.emplace(n, 'f'); aa6 = std::string(n, 'a'); ab6 = std::string(n, 'b'); ac6 = std::string(n, 'c'); ad6 = std::string(n, 'd'); ae6 = std::string(n, 'e'); af6 = std::string(n, 'f'); OS aa7; OS ab7 = absl::nullopt; OS ac7 = std::string(n, 'c'); std::string sad7(n, 'd'); OS ad7 = sad7; OS ae7(absl::in_place, n, 'e'); OS af7; af7.emplace(n, 'f'); aa7.emplace(n, 'A'); ab7.emplace(n, 'B'); ac7.emplace(n, 'C'); ad7.emplace(n, 'D'); ae7.emplace(n, 'E'); af7.emplace(n, 'F'); } TEST(optionalTest, MoveAssignRegression) { StructorListener listener; Listenable::listener = &listener; { absl::optional<Listenable> a; Listenable b; a = std::move(b); } EXPECT_EQ(1, listener.construct0); EXPECT_EQ(1, listener.move); EXPECT_EQ(2, listener.destruct); } TEST(optionalTest, ValueType) { EXPECT_TRUE((std::is_same<absl::optional<int>::value_type, int>::value)); EXPECT_TRUE((std::is_same<absl::optional<std::string>::value_type, std::string>::value)); EXPECT_FALSE( (std::is_same<absl::optional<int>::value_type, absl::nullopt_t>::value)); } template <typename T> struct is_hash_enabled_for { template <typename U, typename = decltype(std::hash<U>()(std::declval<U>()))> static std::true_type test(int); template <typename U> static std::false_type test(...); static constexpr bool value = decltype(test<T>(0))::value; }; TEST(optionalTest, Hash) { std::hash<absl::optional<int>> hash; std::set<size_t> hashcodes; hashcodes.insert(hash(absl::nullopt)); for (int i = 0; i < 100; ++i) { hashcodes.insert(hash(i)); } EXPECT_GT(hashcodes.size(), 90u); static_assert(is_hash_enabled_for<absl::optional<int>>::value, ""); static_assert(is_hash_enabled_for<absl::optional<Hashable>>::value, ""); static_assert( absl::type_traits_internal::IsHashable<absl::optional<int>>::value, ""); static_assert( absl::type_traits_internal::IsHashable<absl::optional<Hashable>>::value, ""); absl::type_traits_internal::AssertHashEnabled<absl::optional<int>>(); absl::type_traits_internal::AssertHashEnabled<absl::optional<Hashable>>(); #if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ static_assert(!is_hash_enabled_for<absl::optional<NonHashable>>::value, ""); static_assert(!absl::type_traits_internal::IsHashable< absl::optional<NonHashable>>::value, ""); #endif #ifndef __GLIBCXX__ static_assert(is_hash_enabled_for<absl::optional<const int>>::value, ""); static_assert(is_hash_enabled_for<absl::optional<const Hashable>>::value, ""); std::hash<absl::optional<const int>> c_hash; for (int i = 0; i < 100; ++i) { EXPECT_EQ(hash(i), c_hash(i)); } #endif } struct MoveMeNoThrow { MoveMeNoThrow() : x(0) {} [[noreturn]] MoveMeNoThrow(const MoveMeNoThrow& other) : x(other.x) { LOG(FATAL) << "Should not be called."; } MoveMeNoThrow(MoveMeNoThrow&& other) noexcept : x(other.x) {} int x; }; struct MoveMeThrow { MoveMeThrow() : x(0) {} MoveMeThrow(const MoveMeThrow& other) : x(other.x) {} MoveMeThrow(MoveMeThrow&& other) : x(other.x) {} int x; }; TEST(optionalTest, NoExcept) { static_assert( std::is_nothrow_move_constructible<absl::optional<MoveMeNoThrow>>::value, ""); static_assert(absl::default_allocator_is_nothrow::value == std::is_nothrow_move_constructible< absl::optional<MoveMeThrow>>::value, ""); std::vector<absl::optional<MoveMeNoThrow>> v; for (int i = 0; i < 10; ++i) v.emplace_back(); } struct AnyLike { AnyLike(AnyLike&&) = default; AnyLike(const AnyLike&) = default; template <typename ValueType, typename T = typename std::decay<ValueType>::type, typename std::enable_if< !absl::disjunction< std::is_same<AnyLike, T>, absl::negation<std::is_copy_constructible<T>>>::value, int>::type = 0> AnyLike(ValueType&&) {} AnyLike& operator=(AnyLike&&) = default; AnyLike& operator=(const AnyLike&) = default; template <typename ValueType, typename T = typename std::decay<ValueType>::type> typename std::enable_if< absl::conjunction<absl::negation<std::is_same<AnyLike, T>>, std::is_copy_constructible<T>>::value, AnyLike&>::type operator=(ValueType&& ) { return *this; } }; TEST(optionalTest, ConstructionConstraints) { EXPECT_TRUE((std::is_constructible<AnyLike, absl::optional<AnyLike>>::value)); EXPECT_TRUE( (std::is_constructible<AnyLike, const absl::optional<AnyLike>&>::value)); EXPECT_TRUE((std::is_constructible<absl::optional<AnyLike>, AnyLike>::value)); EXPECT_TRUE( (std::is_constructible<absl::optional<AnyLike>, const AnyLike&>::value)); EXPECT_TRUE((std::is_convertible<absl::optional<AnyLike>, AnyLike>::value)); EXPECT_TRUE( (std::is_convertible<const absl::optional<AnyLike>&, AnyLike>::value)); EXPECT_TRUE((std::is_convertible<AnyLike, absl::optional<AnyLike>>::value)); EXPECT_TRUE( (std::is_convertible<const AnyLike&, absl::optional<AnyLike>>::value)); EXPECT_TRUE(std::is_move_constructible<absl::optional<AnyLike>>::value); EXPECT_TRUE(std::is_copy_constructible<absl::optional<AnyLike>>::value); } TEST(optionalTest, AssignmentConstraints) { EXPECT_TRUE((std::is_assignable<AnyLike&, absl::optional<AnyLike>>::value)); EXPECT_TRUE( (std::is_assignable<AnyLike&, const absl::optional<AnyLike>&>::value)); EXPECT_TRUE((std::is_assignable<absl::optional<AnyLike>&, AnyLike>::value)); EXPECT_TRUE( (std::is_assignable<absl::optional<AnyLike>&, const AnyLike&>::value)); EXPECT_TRUE(std::is_move_assignable<absl::optional<AnyLike>>::value); EXPECT_TRUE(absl::is_copy_assignable<absl::optional<AnyLike>>::value); } #if !defined(__EMSCRIPTEN__) struct NestedClassBug { struct Inner { bool dummy = false; }; absl::optional<Inner> value; }; TEST(optionalTest, InPlaceTSFINAEBug) { NestedClassBug b; ((void)b); using Inner = NestedClassBug::Inner; EXPECT_TRUE((std::is_default_constructible<Inner>::value)); EXPECT_TRUE((std::is_constructible<Inner>::value)); EXPECT_TRUE( (std::is_constructible<absl::optional<Inner>, absl::in_place_t>::value)); absl::optional<Inner> o(absl::in_place); EXPECT_TRUE(o.has_value()); o.emplace(); EXPECT_TRUE(o.has_value()); } #endif } #endif
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/types/internal/optional.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/types/optional_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
65d98835-6fe6-493b-8c8c-b0b35aa47eae
cpp
abseil/abseil-cpp
compare
absl/types/compare.h
absl/types/compare_test.cc
#ifndef ABSL_TYPES_COMPARE_H_ #define ABSL_TYPES_COMPARE_H_ #include "absl/base/config.h" #ifdef ABSL_USES_STD_ORDERING #include <compare> #include <type_traits> #include "absl/meta/type_traits.h" #else #include <cstddef> #include <cstdint> #include <cstdlib> #include <type_traits> #include "absl/base/attributes.h" #include "absl/base/macros.h" #include "absl/meta/type_traits.h" #endif namespace absl { ABSL_NAMESPACE_BEGIN #ifdef ABSL_USES_STD_ORDERING using std::partial_ordering; using std::strong_ordering; using std::weak_ordering; #else namespace compare_internal { using value_type = int8_t; class OnlyLiteralZero { public: #if ABSL_HAVE_ATTRIBUTE(enable_if) constexpr OnlyLiteralZero(int n) __attribute__((enable_if(n == 0, "Only literal `0` is allowed."))) {} #else constexpr OnlyLiteralZero(int OnlyLiteralZero::*) noexcept {} #endif template <typename T, typename = typename std::enable_if< std::is_same<T, std::nullptr_t>::value || (std::is_integral<T>::value && !std::is_same<T, int>::value)>::type> OnlyLiteralZero(T) { static_assert(sizeof(T) < 0, "Only literal `0` is allowed."); } }; enum class eq : value_type { equal = 0, equivalent = equal, nonequal = 1, nonequivalent = nonequal, }; enum class ord : value_type { less = -1, greater = 1 }; enum class ncmp : value_type { unordered = -127 }; #ifdef __cpp_inline_variables #define ABSL_COMPARE_INLINE_BASECLASS_DECL(name) static_assert(true, "") #define ABSL_COMPARE_INLINE_SUBCLASS_DECL(type, name) \ static const type name #define ABSL_COMPARE_INLINE_INIT(type, name, init) \ inline constexpr type type::name(init) #else #define ABSL_COMPARE_INLINE_BASECLASS_DECL(name) \ ABSL_CONST_INIT static const T name #define ABSL_COMPARE_INLINE_SUBCLASS_DECL(type, name) static_assert(true, "") #define ABSL_COMPARE_INLINE_INIT(type, name, init) \ template <typename T> \ const T compare_internal::type##_base<T>::name(init) #endif template <typename T> struct partial_ordering_base { ABSL_COMPARE_INLINE_BASECLASS_DECL(less); ABSL_COMPARE_INLINE_BASECLASS_DECL(equivalent); ABSL_COMPARE_INLINE_BASECLASS_DECL(greater); ABSL_COMPARE_INLINE_BASECLASS_DECL(unordered); }; template <typename T> struct weak_ordering_base { ABSL_COMPARE_INLINE_BASECLASS_DECL(less); ABSL_COMPARE_INLINE_BASECLASS_DECL(equivalent); ABSL_COMPARE_INLINE_BASECLASS_DECL(greater); }; template <typename T> struct strong_ordering_base { ABSL_COMPARE_INLINE_BASECLASS_DECL(less); ABSL_COMPARE_INLINE_BASECLASS_DECL(equal); ABSL_COMPARE_INLINE_BASECLASS_DECL(equivalent); ABSL_COMPARE_INLINE_BASECLASS_DECL(greater); }; } class partial_ordering : public compare_internal::partial_ordering_base<partial_ordering> { explicit constexpr partial_ordering(compare_internal::eq v) noexcept : value_(static_cast<compare_internal::value_type>(v)) {} explicit constexpr partial_ordering(compare_internal::ord v) noexcept : value_(static_cast<compare_internal::value_type>(v)) {} explicit constexpr partial_ordering(compare_internal::ncmp v) noexcept : value_(static_cast<compare_internal::value_type>(v)) {} friend struct compare_internal::partial_ordering_base<partial_ordering>; constexpr bool is_ordered() const noexcept { return value_ != compare_internal::value_type(compare_internal::ncmp::unordered); } public: ABSL_COMPARE_INLINE_SUBCLASS_DECL(partial_ordering, less); ABSL_COMPARE_INLINE_SUBCLASS_DECL(partial_ordering, equivalent); ABSL_COMPARE_INLINE_SUBCLASS_DECL(partial_ordering, greater); ABSL_COMPARE_INLINE_SUBCLASS_DECL(partial_ordering, unordered); 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 { return !v.is_ordered() || v.value_ != 0; } 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 { return v.is_ordered() && v.value_ <= 0; } 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 { return v.is_ordered() && v.value_ >= 0; } 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 { return !v.is_ordered() || 0 != v.value_; } 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 { return v.is_ordered() && 0 <= v.value_; } 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 { return v.is_ordered() && 0 >= v.value_; } friend constexpr bool operator==(partial_ordering v1, partial_ordering v2) noexcept { return v1.value_ == v2.value_; } friend constexpr bool operator!=(partial_ordering v1, partial_ordering v2) noexcept { return v1.value_ != v2.value_; } private: compare_internal::value_type value_; }; ABSL_COMPARE_INLINE_INIT(partial_ordering, less, compare_internal::ord::less); ABSL_COMPARE_INLINE_INIT(partial_ordering, equivalent, compare_internal::eq::equivalent); ABSL_COMPARE_INLINE_INIT(partial_ordering, greater, compare_internal::ord::greater); ABSL_COMPARE_INLINE_INIT(partial_ordering, unordered, compare_internal::ncmp::unordered); class weak_ordering : public compare_internal::weak_ordering_base<weak_ordering> { explicit constexpr weak_ordering(compare_internal::eq v) noexcept : value_(static_cast<compare_internal::value_type>(v)) {} explicit constexpr weak_ordering(compare_internal::ord v) noexcept : value_(static_cast<compare_internal::value_type>(v)) {} friend struct compare_internal::weak_ordering_base<weak_ordering>; public: ABSL_COMPARE_INLINE_SUBCLASS_DECL(weak_ordering, less); ABSL_COMPARE_INLINE_SUBCLASS_DECL(weak_ordering, equivalent); ABSL_COMPARE_INLINE_SUBCLASS_DECL(weak_ordering, greater); constexpr operator partial_ordering() const noexcept { return value_ == 0 ? partial_ordering::equivalent : (value_ < 0 ? partial_ordering::less : partial_ordering::greater); } 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 { return v.value_ != 0; } 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 { return v.value_ <= 0; } 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 { return v.value_ >= 0; } 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 { return 0 != v.value_; } 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 { return 0 <= v.value_; } 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 { return 0 >= v.value_; } friend constexpr bool operator==(weak_ordering v1, weak_ordering v2) noexcept { return v1.value_ == v2.value_; } friend constexpr bool operator!=(weak_ordering v1, weak_ordering v2) noexcept { return v1.value_ != v2.value_; } private: compare_internal::value_type value_; }; ABSL_COMPARE_INLINE_INIT(weak_ordering, less, compare_internal::ord::less); ABSL_COMPARE_INLINE_INIT(weak_ordering, equivalent, compare_internal::eq::equivalent); ABSL_COMPARE_INLINE_INIT(weak_ordering, greater, compare_internal::ord::greater); class strong_ordering : public compare_internal::strong_ordering_base<strong_ordering> { explicit constexpr strong_ordering(compare_internal::eq v) noexcept : value_(static_cast<compare_internal::value_type>(v)) {} explicit constexpr strong_ordering(compare_internal::ord v) noexcept : value_(static_cast<compare_internal::value_type>(v)) {} friend struct compare_internal::strong_ordering_base<strong_ordering>; public: ABSL_COMPARE_INLINE_SUBCLASS_DECL(strong_ordering, less); ABSL_COMPARE_INLINE_SUBCLASS_DECL(strong_ordering, equal); ABSL_COMPARE_INLINE_SUBCLASS_DECL(strong_ordering, equivalent); ABSL_COMPARE_INLINE_SUBCLASS_DECL(strong_ordering, greater); constexpr operator partial_ordering() const noexcept { return value_ == 0 ? partial_ordering::equivalent : (value_ < 0 ? partial_ordering::less : partial_ordering::greater); } constexpr operator weak_ordering() const noexcept { return value_ == 0 ? weak_ordering::equivalent : (value_ < 0 ? weak_ordering::less : weak_ordering::greater); } 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 { return v.value_ != 0; } 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 { return v.value_ <= 0; } 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 { return v.value_ >= 0; } 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 { return 0 != v.value_; } 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 { return 0 <= v.value_; } 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 { return 0 >= v.value_; } friend constexpr bool operator==(strong_ordering v1, strong_ordering v2) noexcept { return v1.value_ == v2.value_; } friend constexpr bool operator!=(strong_ordering v1, strong_ordering v2) noexcept { return v1.value_ != v2.value_; } private: compare_internal::value_type value_; }; ABSL_COMPARE_INLINE_INIT(strong_ordering, less, compare_internal::ord::less); ABSL_COMPARE_INLINE_INIT(strong_ordering, equal, compare_internal::eq::equal); ABSL_COMPARE_INLINE_INIT(strong_ordering, equivalent, compare_internal::eq::equivalent); ABSL_COMPARE_INLINE_INIT(strong_ordering, greater, compare_internal::ord::greater); #undef ABSL_COMPARE_INLINE_BASECLASS_DECL #undef ABSL_COMPARE_INLINE_SUBCLASS_DECL #undef ABSL_COMPARE_INLINE_INIT #endif namespace compare_internal { template <typename BoolT, absl::enable_if_t<std::is_same<bool, BoolT>::value, int> = 0> constexpr bool compare_result_as_less_than(const BoolT r) { return r; } constexpr bool compare_result_as_less_than(const absl::weak_ordering r) { return r < 0; } template <typename Compare, typename K, typename LK> constexpr bool do_less_than_comparison(const Compare &compare, const K &x, const LK &y) { return compare_result_as_less_than(compare(x, y)); } template <typename Int, absl::enable_if_t<std::is_same<int, Int>::value, int> = 0> constexpr absl::weak_ordering compare_result_as_ordering(const Int c) { return c < 0 ? absl::weak_ordering::less : c == 0 ? absl::weak_ordering::equivalent : absl::weak_ordering::greater; } constexpr absl::weak_ordering compare_result_as_ordering( const absl::weak_ordering c) { return c; } template < typename Compare, typename K, typename LK, absl::enable_if_t<!std::is_same<bool, absl::result_of_t<Compare( const K &, const LK &)>>::value, int> = 0> constexpr absl::weak_ordering do_three_way_comparison(const Compare &compare, const K &x, const LK &y) { return compare_result_as_ordering(compare(x, y)); } template < typename Compare, typename K, typename LK, absl::enable_if_t<std::is_same<bool, absl::result_of_t<Compare( const K &, const LK &)>>::value, int> = 0> constexpr absl::weak_ordering do_three_way_comparison(const Compare &compare, const K &x, const LK &y) { return compare(x, y) ? absl::weak_ordering::less : compare(y, x) ? absl::weak_ordering::greater : absl::weak_ordering::equivalent; } } ABSL_NAMESPACE_END } #endif
#include "absl/types/compare.h" #include "gtest/gtest.h" #include "absl/base/casts.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { bool Identity(bool b) { return b; } TEST(Compare, PartialOrdering) { EXPECT_TRUE(Identity(partial_ordering::less < 0)); EXPECT_TRUE(Identity(0 > partial_ordering::less)); EXPECT_TRUE(Identity(partial_ordering::less <= 0)); EXPECT_TRUE(Identity(0 >= partial_ordering::less)); EXPECT_TRUE(Identity(partial_ordering::equivalent == 0)); EXPECT_TRUE(Identity(0 == partial_ordering::equivalent)); EXPECT_TRUE(Identity(partial_ordering::greater > 0)); EXPECT_TRUE(Identity(0 < partial_ordering::greater)); EXPECT_TRUE(Identity(partial_ordering::greater >= 0)); EXPECT_TRUE(Identity(0 <= partial_ordering::greater)); EXPECT_TRUE(Identity(partial_ordering::unordered != 0)); EXPECT_TRUE(Identity(0 != partial_ordering::unordered)); EXPECT_FALSE(Identity(partial_ordering::unordered < 0)); EXPECT_FALSE(Identity(0 < partial_ordering::unordered)); EXPECT_FALSE(Identity(partial_ordering::unordered <= 0)); EXPECT_FALSE(Identity(0 <= partial_ordering::unordered)); EXPECT_FALSE(Identity(partial_ordering::unordered > 0)); EXPECT_FALSE(Identity(0 > partial_ordering::unordered)); EXPECT_FALSE(Identity(partial_ordering::unordered >= 0)); EXPECT_FALSE(Identity(0 >= partial_ordering::unordered)); const partial_ordering values[] = { partial_ordering::less, partial_ordering::equivalent, partial_ordering::greater, partial_ordering::unordered}; for (const auto& lhs : values) { for (const auto& rhs : values) { const bool are_equal = &lhs == &rhs; EXPECT_EQ(lhs == rhs, are_equal); EXPECT_EQ(lhs != rhs, !are_equal); } } } TEST(Compare, WeakOrdering) { EXPECT_TRUE(Identity(weak_ordering::less < 0)); EXPECT_TRUE(Identity(0 > weak_ordering::less)); EXPECT_TRUE(Identity(weak_ordering::less <= 0)); EXPECT_TRUE(Identity(0 >= weak_ordering::less)); EXPECT_TRUE(Identity(weak_ordering::equivalent == 0)); EXPECT_TRUE(Identity(0 == weak_ordering::equivalent)); EXPECT_TRUE(Identity(weak_ordering::greater > 0)); EXPECT_TRUE(Identity(0 < weak_ordering::greater)); EXPECT_TRUE(Identity(weak_ordering::greater >= 0)); EXPECT_TRUE(Identity(0 <= weak_ordering::greater)); const weak_ordering values[] = { weak_ordering::less, weak_ordering::equivalent, weak_ordering::greater}; for (const auto& lhs : values) { for (const auto& rhs : values) { const bool are_equal = &lhs == &rhs; EXPECT_EQ(lhs == rhs, are_equal); EXPECT_EQ(lhs != rhs, !are_equal); } } } TEST(Compare, StrongOrdering) { EXPECT_TRUE(Identity(strong_ordering::less < 0)); EXPECT_TRUE(Identity(0 > strong_ordering::less)); EXPECT_TRUE(Identity(strong_ordering::less <= 0)); EXPECT_TRUE(Identity(0 >= strong_ordering::less)); EXPECT_TRUE(Identity(strong_ordering::equal == 0)); EXPECT_TRUE(Identity(0 == strong_ordering::equal)); EXPECT_TRUE(Identity(strong_ordering::equivalent == 0)); EXPECT_TRUE(Identity(0 == strong_ordering::equivalent)); EXPECT_TRUE(Identity(strong_ordering::greater > 0)); EXPECT_TRUE(Identity(0 < strong_ordering::greater)); EXPECT_TRUE(Identity(strong_ordering::greater >= 0)); EXPECT_TRUE(Identity(0 <= strong_ordering::greater)); const strong_ordering values[] = { strong_ordering::less, strong_ordering::equal, strong_ordering::greater}; for (const auto& lhs : values) { for (const auto& rhs : values) { const bool are_equal = &lhs == &rhs; EXPECT_EQ(lhs == rhs, are_equal); EXPECT_EQ(lhs != rhs, !are_equal); } } EXPECT_TRUE(Identity(strong_ordering::equivalent == strong_ordering::equal)); } TEST(Compare, Conversions) { EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(weak_ordering::less) != 0)); EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(weak_ordering::less) < 0)); EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(weak_ordering::less) <= 0)); EXPECT_TRUE(Identity( implicit_cast<partial_ordering>(weak_ordering::equivalent) == 0)); EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(weak_ordering::greater) != 0)); EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(weak_ordering::greater) > 0)); EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(weak_ordering::greater) >= 0)); EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(strong_ordering::less) != 0)); EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(strong_ordering::less) < 0)); EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(strong_ordering::less) <= 0)); EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(strong_ordering::equal) == 0)); EXPECT_TRUE(Identity( implicit_cast<partial_ordering>(strong_ordering::equivalent) == 0)); EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(strong_ordering::greater) != 0)); EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(strong_ordering::greater) > 0)); EXPECT_TRUE( Identity(implicit_cast<partial_ordering>(strong_ordering::greater) >= 0)); EXPECT_TRUE( Identity(implicit_cast<weak_ordering>(strong_ordering::less) != 0)); EXPECT_TRUE( Identity(implicit_cast<weak_ordering>(strong_ordering::less) < 0)); EXPECT_TRUE( Identity(implicit_cast<weak_ordering>(strong_ordering::less) <= 0)); EXPECT_TRUE( Identity(implicit_cast<weak_ordering>(strong_ordering::equal) == 0)); EXPECT_TRUE( Identity(implicit_cast<weak_ordering>(strong_ordering::equivalent) == 0)); EXPECT_TRUE( Identity(implicit_cast<weak_ordering>(strong_ordering::greater) != 0)); EXPECT_TRUE( Identity(implicit_cast<weak_ordering>(strong_ordering::greater) > 0)); EXPECT_TRUE( Identity(implicit_cast<weak_ordering>(strong_ordering::greater) >= 0)); } struct WeakOrderingLess { template <typename T> absl::weak_ordering operator()(const T& a, const T& b) const { return a < b ? absl::weak_ordering::less : a == b ? absl::weak_ordering::equivalent : absl::weak_ordering::greater; } }; TEST(CompareResultAsLessThan, SanityTest) { EXPECT_FALSE(absl::compare_internal::compare_result_as_less_than(false)); EXPECT_TRUE(absl::compare_internal::compare_result_as_less_than(true)); EXPECT_TRUE( absl::compare_internal::compare_result_as_less_than(weak_ordering::less)); EXPECT_FALSE(absl::compare_internal::compare_result_as_less_than( weak_ordering::equivalent)); EXPECT_FALSE(absl::compare_internal::compare_result_as_less_than( weak_ordering::greater)); } TEST(DoLessThanComparison, SanityTest) { std::less<int> less; WeakOrderingLess weak; EXPECT_TRUE(absl::compare_internal::do_less_than_comparison(less, -1, 0)); EXPECT_TRUE(absl::compare_internal::do_less_than_comparison(weak, -1, 0)); EXPECT_FALSE(absl::compare_internal::do_less_than_comparison(less, 10, 10)); EXPECT_FALSE(absl::compare_internal::do_less_than_comparison(weak, 10, 10)); EXPECT_FALSE(absl::compare_internal::do_less_than_comparison(less, 10, 5)); EXPECT_FALSE(absl::compare_internal::do_less_than_comparison(weak, 10, 5)); } TEST(CompareResultAsOrdering, SanityTest) { EXPECT_TRUE( Identity(absl::compare_internal::compare_result_as_ordering(-1) < 0)); EXPECT_FALSE( Identity(absl::compare_internal::compare_result_as_ordering(-1) == 0)); EXPECT_FALSE( Identity(absl::compare_internal::compare_result_as_ordering(-1) > 0)); EXPECT_TRUE(Identity(absl::compare_internal::compare_result_as_ordering( weak_ordering::less) < 0)); EXPECT_FALSE(Identity(absl::compare_internal::compare_result_as_ordering( weak_ordering::less) == 0)); EXPECT_FALSE(Identity(absl::compare_internal::compare_result_as_ordering( weak_ordering::less) > 0)); EXPECT_FALSE( Identity(absl::compare_internal::compare_result_as_ordering(0) < 0)); EXPECT_TRUE( Identity(absl::compare_internal::compare_result_as_ordering(0) == 0)); EXPECT_FALSE( Identity(absl::compare_internal::compare_result_as_ordering(0) > 0)); EXPECT_FALSE(Identity(absl::compare_internal::compare_result_as_ordering( weak_ordering::equivalent) < 0)); EXPECT_TRUE(Identity(absl::compare_internal::compare_result_as_ordering( weak_ordering::equivalent) == 0)); EXPECT_FALSE(Identity(absl::compare_internal::compare_result_as_ordering( weak_ordering::equivalent) > 0)); EXPECT_FALSE( Identity(absl::compare_internal::compare_result_as_ordering(1) < 0)); EXPECT_FALSE( Identity(absl::compare_internal::compare_result_as_ordering(1) == 0)); EXPECT_TRUE( Identity(absl::compare_internal::compare_result_as_ordering(1) > 0)); EXPECT_FALSE(Identity(absl::compare_internal::compare_result_as_ordering( weak_ordering::greater) < 0)); EXPECT_FALSE(Identity(absl::compare_internal::compare_result_as_ordering( weak_ordering::greater) == 0)); EXPECT_TRUE(Identity(absl::compare_internal::compare_result_as_ordering( weak_ordering::greater) > 0)); } TEST(DoThreeWayComparison, SanityTest) { std::less<int> less; WeakOrderingLess weak; EXPECT_TRUE(Identity( absl::compare_internal::do_three_way_comparison(less, -1, 0) < 0)); EXPECT_FALSE(Identity( absl::compare_internal::do_three_way_comparison(less, -1, 0) == 0)); EXPECT_FALSE(Identity( absl::compare_internal::do_three_way_comparison(less, -1, 0) > 0)); EXPECT_TRUE(Identity( absl::compare_internal::do_three_way_comparison(weak, -1, 0) < 0)); EXPECT_FALSE(Identity( absl::compare_internal::do_three_way_comparison(weak, -1, 0) == 0)); EXPECT_FALSE(Identity( absl::compare_internal::do_three_way_comparison(weak, -1, 0) > 0)); EXPECT_FALSE(Identity( absl::compare_internal::do_three_way_comparison(less, 10, 10) < 0)); EXPECT_TRUE(Identity( absl::compare_internal::do_three_way_comparison(less, 10, 10) == 0)); EXPECT_FALSE(Identity( absl::compare_internal::do_three_way_comparison(less, 10, 10) > 0)); EXPECT_FALSE(Identity( absl::compare_internal::do_three_way_comparison(weak, 10, 10) < 0)); EXPECT_TRUE(Identity( absl::compare_internal::do_three_way_comparison(weak, 10, 10) == 0)); EXPECT_FALSE(Identity( absl::compare_internal::do_three_way_comparison(weak, 10, 10) > 0)); EXPECT_FALSE(Identity( absl::compare_internal::do_three_way_comparison(less, 10, 5) < 0)); EXPECT_FALSE(Identity( absl::compare_internal::do_three_way_comparison(less, 10, 5) == 0)); EXPECT_TRUE(Identity( absl::compare_internal::do_three_way_comparison(less, 10, 5) > 0)); EXPECT_FALSE(Identity( absl::compare_internal::do_three_way_comparison(weak, 10, 5) < 0)); EXPECT_FALSE(Identity( absl::compare_internal::do_three_way_comparison(weak, 10, 5) == 0)); EXPECT_TRUE(Identity( absl::compare_internal::do_three_way_comparison(weak, 10, 5) > 0)); } #ifdef __cpp_inline_variables TEST(Compare, StaticAsserts) { static_assert(partial_ordering::less < 0, ""); static_assert(partial_ordering::equivalent == 0, ""); static_assert(partial_ordering::greater > 0, ""); static_assert(partial_ordering::unordered != 0, ""); static_assert(weak_ordering::less < 0, ""); static_assert(weak_ordering::equivalent == 0, ""); static_assert(weak_ordering::greater > 0, ""); static_assert(strong_ordering::less < 0, ""); static_assert(strong_ordering::equal == 0, ""); static_assert(strong_ordering::equivalent == 0, ""); static_assert(strong_ordering::greater > 0, ""); } #endif } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/types/compare.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/types/compare_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
0ca8dc00-99f1-42ca-a3dd-296a910d479f
cpp
abseil/abseil-cpp
span
absl/types/internal/span.h
absl/types/span_test.cc
#ifndef ABSL_TYPES_INTERNAL_SPAN_H_ #define ABSL_TYPES_INTERNAL_SPAN_H_ #include <algorithm> #include <cstddef> #include <string> #include <type_traits> #include "absl/algorithm/algorithm.h" #include "absl/base/internal/throw_delegate.h" #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename T> class Span; namespace span_internal { template <typename C> constexpr auto GetDataImpl(C& c, char) noexcept -> decltype(c.data()) { return c.data(); } inline char* GetDataImpl(std::string& s, int) noexcept { return &s[0]; } template <typename C> constexpr auto GetData(C& c) noexcept -> decltype(GetDataImpl(c, 0)) { return GetDataImpl(c, 0); } template <typename C> using HasSize = std::is_integral<absl::decay_t<decltype(std::declval<C&>().size())>>; template <typename T, typename C> using HasData = std::is_convertible<absl::decay_t<decltype(GetData(std::declval<C&>()))>*, T* const*>; template <typename C> struct ElementType { using type = typename absl::remove_reference_t<C>::value_type; }; template <typename T, size_t N> struct ElementType<T (&)[N]> { using type = T; }; template <typename C> using ElementT = typename ElementType<C>::type; template <typename T> using EnableIfMutable = typename std::enable_if<!std::is_const<T>::value, int>::type; template <template <typename> class SpanT, typename T> bool EqualImpl(SpanT<T> a, SpanT<T> b) { static_assert(std::is_const<T>::value, ""); return std::equal(a.begin(), a.end(), b.begin(), b.end()); } template <template <typename> class SpanT, typename T> bool LessThanImpl(SpanT<T> a, SpanT<T> b) { static_assert(std::is_const<T>::value, ""); return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end()); } template <typename From, typename To> using EnableIfConvertibleTo = typename std::enable_if<std::is_convertible<From, To>::value>::type; template <typename T, typename = void, typename = void> struct IsView { static constexpr bool value = false; }; template <typename T> struct IsView< T, absl::void_t<decltype(span_internal::GetData(std::declval<const T&>()))>, absl::void_t<decltype(span_internal::GetData(std::declval<T&>()))>> { private: using Container = std::remove_const_t<T>; using ConstData = decltype(span_internal::GetData(std::declval<const Container&>())); using MutData = decltype(span_internal::GetData(std::declval<Container&>())); public: static constexpr bool value = std::is_same<ConstData, MutData>::value; }; template <typename T> using EnableIfIsView = std::enable_if_t<IsView<T>::value, int>; template <typename T> using EnableIfNotIsView = std::enable_if_t<!IsView<T>::value, int>; } ABSL_NAMESPACE_END } #endif
#include "absl/types/span.h" #include <array> #include <initializer_list> #include <numeric> #include <stdexcept> #include <string> #include <type_traits> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/exception_testing.h" #include "absl/base/options.h" #include "absl/container/fixed_array.h" #include "absl/container/inlined_vector.h" #include "absl/hash/hash_testing.h" #include "absl/meta/type_traits.h" #include "absl/strings/str_cat.h" namespace { static_assert(!absl::type_traits_internal::IsOwner<absl::Span<int>>::value && absl::type_traits_internal::IsView<absl::Span<int>>::value, "Span is a view, not an owner"); MATCHER_P(DataIs, data, absl::StrCat("data() ", negation ? "isn't " : "is ", testing::PrintToString(data))) { return arg.data() == data; } template <typename T> auto SpanIs(T data, size_t size) -> decltype(testing::AllOf(DataIs(data), testing::SizeIs(size))) { return testing::AllOf(DataIs(data), testing::SizeIs(size)); } template <typename Container> auto SpanIs(const Container& c) -> decltype(SpanIs(c.data(), c.size())) { return SpanIs(c.data(), c.size()); } std::vector<int> MakeRamp(int len, int offset = 0) { std::vector<int> v(len); std::iota(v.begin(), v.end(), offset); return v; } TEST(IntSpan, EmptyCtors) { absl::Span<int> s; EXPECT_THAT(s, SpanIs(nullptr, 0)); } TEST(IntSpan, PtrLenCtor) { int a[] = {1, 2, 3}; absl::Span<int> s(&a[0], 2); EXPECT_THAT(s, SpanIs(a, 2)); } TEST(IntSpan, ArrayCtor) { int a[] = {1, 2, 3}; absl::Span<int> s(a); EXPECT_THAT(s, SpanIs(a, 3)); EXPECT_TRUE((std::is_constructible<absl::Span<const int>, int[3]>::value)); EXPECT_TRUE( (std::is_constructible<absl::Span<const int>, const int[3]>::value)); EXPECT_FALSE((std::is_constructible<absl::Span<int>, const int[3]>::value)); EXPECT_TRUE((std::is_convertible<int[3], absl::Span<const int>>::value)); EXPECT_TRUE( (std::is_convertible<const int[3], absl::Span<const int>>::value)); } template <typename T> void TakesGenericSpan(absl::Span<T>) {} TEST(IntSpan, ContainerCtor) { std::vector<int> empty; absl::Span<int> s_empty(empty); EXPECT_THAT(s_empty, SpanIs(empty)); std::vector<int> filled{1, 2, 3}; absl::Span<int> s_filled(filled); EXPECT_THAT(s_filled, SpanIs(filled)); absl::Span<int> s_from_span(filled); EXPECT_THAT(s_from_span, SpanIs(s_filled)); absl::Span<const int> const_filled = filled; EXPECT_THAT(const_filled, SpanIs(filled)); absl::Span<const int> const_from_span = s_filled; EXPECT_THAT(const_from_span, SpanIs(s_filled)); EXPECT_TRUE( (std::is_convertible<std::vector<int>&, absl::Span<const int>>::value)); EXPECT_TRUE( (std::is_convertible<absl::Span<int>&, absl::Span<const int>>::value)); TakesGenericSpan(absl::Span<int>(filled)); } struct ContainerWithShallowConstData { std::vector<int> storage; int* data() const { return const_cast<int*>(storage.data()); } int size() const { return storage.size(); } }; TEST(IntSpan, ShallowConstness) { const ContainerWithShallowConstData c{MakeRamp(20)}; absl::Span<int> s( c); s[0] = -1; EXPECT_EQ(c.storage[0], -1); } TEST(CharSpan, StringCtor) { std::string empty = ""; absl::Span<char> s_empty(empty); EXPECT_THAT(s_empty, SpanIs(empty)); std::string abc = "abc"; absl::Span<char> s_abc(abc); EXPECT_THAT(s_abc, SpanIs(abc)); absl::Span<const char> s_const_abc = abc; EXPECT_THAT(s_const_abc, SpanIs(abc)); EXPECT_FALSE((std::is_constructible<absl::Span<int>, std::string>::value)); EXPECT_FALSE( (std::is_constructible<absl::Span<const int>, std::string>::value)); EXPECT_TRUE( (std::is_convertible<std::string, absl::Span<const char>>::value)); } TEST(IntSpan, FromConstPointer) { EXPECT_TRUE((std::is_constructible<absl::Span<const int* const>, std::vector<int*>>::value)); EXPECT_TRUE((std::is_constructible<absl::Span<const int* const>, std::vector<const int*>>::value)); EXPECT_FALSE(( std::is_constructible<absl::Span<const int*>, std::vector<int*>>::value)); EXPECT_FALSE(( std::is_constructible<absl::Span<int*>, std::vector<const int*>>::value)); } struct TypeWithMisleadingData { int& data() { return i; } int size() { return 1; } int i; }; struct TypeWithMisleadingSize { int* data() { return &i; } const char* size() { return "1"; } int i; }; TEST(IntSpan, EvilTypes) { EXPECT_FALSE( (std::is_constructible<absl::Span<int>, TypeWithMisleadingData&>::value)); EXPECT_FALSE( (std::is_constructible<absl::Span<int>, TypeWithMisleadingSize&>::value)); } struct Base { int* data() { return &i; } int size() { return 1; } int i; }; struct Derived : Base {}; TEST(IntSpan, SpanOfDerived) { EXPECT_TRUE((std::is_constructible<absl::Span<int>, Base&>::value)); EXPECT_TRUE((std::is_constructible<absl::Span<int>, Derived&>::value)); EXPECT_FALSE( (std::is_constructible<absl::Span<Base>, std::vector<Derived>>::value)); } void TestInitializerList(absl::Span<const int> s, const std::vector<int>& v) { EXPECT_TRUE(std::equal(s.begin(), s.end(), v.begin(), v.end())); } TEST(ConstIntSpan, InitializerListConversion) { TestInitializerList({}, {}); TestInitializerList({1}, {1}); TestInitializerList({1, 2, 3}, {1, 2, 3}); EXPECT_FALSE((std::is_constructible<absl::Span<int>, std::initializer_list<int>>::value)); EXPECT_FALSE(( std::is_convertible<absl::Span<int>, std::initializer_list<int>>::value)); } TEST(IntSpan, Data) { int i; absl::Span<int> s(&i, 1); EXPECT_EQ(&i, s.data()); } TEST(IntSpan, SizeLengthEmpty) { absl::Span<int> empty; EXPECT_EQ(empty.size(), 0); EXPECT_TRUE(empty.empty()); EXPECT_EQ(empty.size(), empty.length()); auto v = MakeRamp(10); absl::Span<int> s(v); EXPECT_EQ(s.size(), 10); EXPECT_FALSE(s.empty()); EXPECT_EQ(s.size(), s.length()); } TEST(IntSpan, ElementAccess) { auto v = MakeRamp(10); absl::Span<int> s(v); for (int i = 0; i < s.size(); ++i) { EXPECT_EQ(s[i], s.at(i)); } EXPECT_EQ(s.front(), s[0]); EXPECT_EQ(s.back(), s[9]); #if !defined(NDEBUG) || ABSL_OPTION_HARDENED EXPECT_DEATH_IF_SUPPORTED(s[-1], ""); EXPECT_DEATH_IF_SUPPORTED(s[10], ""); #endif } TEST(IntSpan, AtThrows) { auto v = MakeRamp(10); absl::Span<int> s(v); EXPECT_EQ(s.at(9), 9); ABSL_BASE_INTERNAL_EXPECT_FAIL(s.at(10), std::out_of_range, "failed bounds check"); } TEST(IntSpan, RemovePrefixAndSuffix) { auto v = MakeRamp(20, 1); absl::Span<int> s(v); EXPECT_EQ(s.size(), 20); s.remove_suffix(0); s.remove_prefix(0); EXPECT_EQ(s.size(), 20); s.remove_prefix(1); EXPECT_EQ(s.size(), 19); EXPECT_EQ(s[0], 2); s.remove_suffix(1); EXPECT_EQ(s.size(), 18); EXPECT_EQ(s.back(), 19); s.remove_prefix(7); EXPECT_EQ(s.size(), 11); EXPECT_EQ(s[0], 9); s.remove_suffix(11); EXPECT_EQ(s.size(), 0); EXPECT_EQ(v, MakeRamp(20, 1)); #if !defined(NDEBUG) || ABSL_OPTION_HARDENED absl::Span<int> prefix_death(v); EXPECT_DEATH_IF_SUPPORTED(prefix_death.remove_prefix(21), ""); absl::Span<int> suffix_death(v); EXPECT_DEATH_IF_SUPPORTED(suffix_death.remove_suffix(21), ""); #endif } TEST(IntSpan, Subspan) { std::vector<int> empty; EXPECT_EQ(absl::MakeSpan(empty).subspan(), empty); EXPECT_THAT(absl::MakeSpan(empty).subspan(0, 0), SpanIs(empty)); EXPECT_THAT(absl::MakeSpan(empty).subspan(0, absl::Span<const int>::npos), SpanIs(empty)); auto ramp = MakeRamp(10); EXPECT_THAT(absl::MakeSpan(ramp).subspan(), SpanIs(ramp)); EXPECT_THAT(absl::MakeSpan(ramp).subspan(0, 10), SpanIs(ramp)); EXPECT_THAT(absl::MakeSpan(ramp).subspan(0, absl::Span<const int>::npos), SpanIs(ramp)); EXPECT_THAT(absl::MakeSpan(ramp).subspan(0, 3), SpanIs(ramp.data(), 3)); EXPECT_THAT(absl::MakeSpan(ramp).subspan(5, absl::Span<const int>::npos), SpanIs(ramp.data() + 5, 5)); EXPECT_THAT(absl::MakeSpan(ramp).subspan(3, 3), SpanIs(ramp.data() + 3, 3)); EXPECT_THAT(absl::MakeSpan(ramp).subspan(10, 5), SpanIs(ramp.data() + 10, 0)); #ifdef ABSL_HAVE_EXCEPTIONS EXPECT_THROW(absl::MakeSpan(ramp).subspan(11, 5), std::out_of_range); #else EXPECT_DEATH_IF_SUPPORTED(absl::MakeSpan(ramp).subspan(11, 5), ""); #endif } TEST(IntSpan, First) { std::vector<int> empty; EXPECT_THAT(absl::MakeSpan(empty).first(0), SpanIs(empty)); auto ramp = MakeRamp(10); EXPECT_THAT(absl::MakeSpan(ramp).first(0), SpanIs(ramp.data(), 0)); EXPECT_THAT(absl::MakeSpan(ramp).first(10), SpanIs(ramp)); EXPECT_THAT(absl::MakeSpan(ramp).first(3), SpanIs(ramp.data(), 3)); #ifdef ABSL_HAVE_EXCEPTIONS EXPECT_THROW(absl::MakeSpan(ramp).first(11), std::out_of_range); #else EXPECT_DEATH_IF_SUPPORTED(absl::MakeSpan(ramp).first(11), ""); #endif } TEST(IntSpan, Last) { std::vector<int> empty; EXPECT_THAT(absl::MakeSpan(empty).last(0), SpanIs(empty)); auto ramp = MakeRamp(10); EXPECT_THAT(absl::MakeSpan(ramp).last(0), SpanIs(ramp.data() + 10, 0)); EXPECT_THAT(absl::MakeSpan(ramp).last(10), SpanIs(ramp)); EXPECT_THAT(absl::MakeSpan(ramp).last(3), SpanIs(ramp.data() + 7, 3)); #ifdef ABSL_HAVE_EXCEPTIONS EXPECT_THROW(absl::MakeSpan(ramp).last(11), std::out_of_range); #else EXPECT_DEATH_IF_SUPPORTED(absl::MakeSpan(ramp).last(11), ""); #endif } TEST(IntSpan, MakeSpanPtrLength) { std::vector<int> empty; auto s_empty = absl::MakeSpan(empty.data(), empty.size()); EXPECT_THAT(s_empty, SpanIs(empty)); std::array<int, 3> a{{1, 2, 3}}; auto s = absl::MakeSpan(a.data(), a.size()); EXPECT_THAT(s, SpanIs(a)); EXPECT_THAT(absl::MakeConstSpan(empty.data(), empty.size()), SpanIs(s_empty)); EXPECT_THAT(absl::MakeConstSpan(a.data(), a.size()), SpanIs(s)); } TEST(IntSpan, MakeSpanTwoPtrs) { std::vector<int> empty; auto s_empty = absl::MakeSpan(empty.data(), empty.data()); EXPECT_THAT(s_empty, SpanIs(empty)); std::vector<int> v{1, 2, 3}; auto s = absl::MakeSpan(v.data(), v.data() + 1); EXPECT_THAT(s, SpanIs(v.data(), 1)); EXPECT_THAT(absl::MakeConstSpan(empty.data(), empty.data()), SpanIs(s_empty)); EXPECT_THAT(absl::MakeConstSpan(v.data(), v.data() + 1), SpanIs(s)); } TEST(IntSpan, MakeSpanContainer) { std::vector<int> empty; auto s_empty = absl::MakeSpan(empty); EXPECT_THAT(s_empty, SpanIs(empty)); std::vector<int> v{1, 2, 3}; auto s = absl::MakeSpan(v); EXPECT_THAT(s, SpanIs(v)); EXPECT_THAT(absl::MakeConstSpan(empty), SpanIs(s_empty)); EXPECT_THAT(absl::MakeConstSpan(v), SpanIs(s)); EXPECT_THAT(absl::MakeSpan(s), SpanIs(s)); EXPECT_THAT(absl::MakeConstSpan(s), SpanIs(s)); } TEST(CharSpan, MakeSpanString) { std::string empty = ""; auto s_empty = absl::MakeSpan(empty); EXPECT_THAT(s_empty, SpanIs(empty)); std::string str = "abc"; auto s_str = absl::MakeSpan(str); EXPECT_THAT(s_str, SpanIs(str)); EXPECT_THAT(absl::MakeConstSpan(empty), SpanIs(s_empty)); EXPECT_THAT(absl::MakeConstSpan(str), SpanIs(s_str)); } TEST(IntSpan, MakeSpanArray) { int a[] = {1, 2, 3}; auto s = absl::MakeSpan(a); EXPECT_THAT(s, SpanIs(a, 3)); const int ca[] = {1, 2, 3}; auto s_ca = absl::MakeSpan(ca); EXPECT_THAT(s_ca, SpanIs(ca, 3)); EXPECT_THAT(absl::MakeConstSpan(a), SpanIs(s)); EXPECT_THAT(absl::MakeConstSpan(ca), SpanIs(s_ca)); } template <typename Expected, typename T> void CheckType(const T& ) { testing::StaticAssertTypeEq<Expected, T>(); } TEST(IntSpan, MakeSpanTypes) { std::vector<int> vec; const std::vector<int> cvec; int a[1]; const int ca[] = {1}; int* ip = a; const int* cip = ca; std::string s = ""; const std::string cs = ""; CheckType<absl::Span<int>>(absl::MakeSpan(vec)); CheckType<absl::Span<const int>>(absl::MakeSpan(cvec)); CheckType<absl::Span<int>>(absl::MakeSpan(ip, ip + 1)); CheckType<absl::Span<int>>(absl::MakeSpan(ip, 1)); CheckType<absl::Span<const int>>(absl::MakeSpan(cip, cip + 1)); CheckType<absl::Span<const int>>(absl::MakeSpan(cip, 1)); CheckType<absl::Span<int>>(absl::MakeSpan(a)); CheckType<absl::Span<int>>(absl::MakeSpan(a, a + 1)); CheckType<absl::Span<int>>(absl::MakeSpan(a, 1)); CheckType<absl::Span<const int>>(absl::MakeSpan(ca)); CheckType<absl::Span<const int>>(absl::MakeSpan(ca, ca + 1)); CheckType<absl::Span<const int>>(absl::MakeSpan(ca, 1)); CheckType<absl::Span<char>>(absl::MakeSpan(s)); CheckType<absl::Span<const char>>(absl::MakeSpan(cs)); } TEST(ConstIntSpan, MakeConstSpanTypes) { std::vector<int> vec; const std::vector<int> cvec; int array[1]; const int carray[] = {0}; int* ptr = array; const int* cptr = carray; std::string s = ""; std::string cs = ""; CheckType<absl::Span<const int>>(absl::MakeConstSpan(vec)); CheckType<absl::Span<const int>>(absl::MakeConstSpan(cvec)); CheckType<absl::Span<const int>>(absl::MakeConstSpan(ptr, ptr + 1)); CheckType<absl::Span<const int>>(absl::MakeConstSpan(ptr, 1)); CheckType<absl::Span<const int>>(absl::MakeConstSpan(cptr, cptr + 1)); CheckType<absl::Span<const int>>(absl::MakeConstSpan(cptr, 1)); CheckType<absl::Span<const int>>(absl::MakeConstSpan(array)); CheckType<absl::Span<const int>>(absl::MakeConstSpan(carray)); CheckType<absl::Span<const char>>(absl::MakeConstSpan(s)); CheckType<absl::Span<const char>>(absl::MakeConstSpan(cs)); } TEST(IntSpan, Equality) { const int arr1[] = {1, 2, 3, 4, 5}; int arr2[] = {1, 2, 3, 4, 5}; std::vector<int> vec1(std::begin(arr1), std::end(arr1)); std::vector<int> vec2 = vec1; std::vector<int> other_vec = {2, 4, 6, 8, 10}; const absl::Span<const int> from1 = vec1; const absl::Span<const int> from2 = vec2; EXPECT_EQ(from1, from1); EXPECT_FALSE(from1 != from1); EXPECT_EQ(from1, from2); EXPECT_FALSE(from1 != from2); const absl::Span<const int> from_other = other_vec; EXPECT_NE(from1, from_other); EXPECT_FALSE(from1 == from_other); EXPECT_EQ(vec1, from1); EXPECT_FALSE(vec1 != from1); EXPECT_EQ(from1, vec1); EXPECT_FALSE(from1 != vec1); const absl::Span<int> mutable_from1(vec1); const absl::Span<int> mutable_from2(vec2); EXPECT_EQ(from1, mutable_from1); EXPECT_EQ(mutable_from1, from1); EXPECT_EQ(mutable_from1, mutable_from2); EXPECT_EQ(mutable_from2, mutable_from1); EXPECT_EQ(vec1, mutable_from1); EXPECT_FALSE(vec1 != mutable_from1); EXPECT_EQ(mutable_from1, vec1); EXPECT_FALSE(mutable_from1 != vec1); EXPECT_TRUE(arr1 == mutable_from1); EXPECT_FALSE(arr1 != mutable_from1); EXPECT_TRUE(mutable_from1 == arr1); EXPECT_FALSE(mutable_from1 != arr1); EXPECT_TRUE(arr2 == from1); EXPECT_FALSE(arr2 != from1); EXPECT_TRUE(from1 == arr2); EXPECT_FALSE(from1 != arr2); EXPECT_NE(from1, absl::Span<const int>(from1).subspan(0, from1.size() - 1)); ++vec2.back(); EXPECT_NE(from1, from2); } class IntSpanOrderComparisonTest : public testing::Test { public: IntSpanOrderComparisonTest() : arr_before_{1, 2, 3}, arr_after_{1, 2, 4}, carr_after_{1, 2, 4}, vec_before_(std::begin(arr_before_), std::end(arr_before_)), vec_after_(std::begin(arr_after_), std::end(arr_after_)), before_(vec_before_), after_(vec_after_), cbefore_(vec_before_), cafter_(vec_after_) {} protected: int arr_before_[3], arr_after_[3]; const int carr_after_[3]; std::vector<int> vec_before_, vec_after_; absl::Span<int> before_, after_; absl::Span<const int> cbefore_, cafter_; }; TEST_F(IntSpanOrderComparisonTest, CompareSpans) { EXPECT_TRUE(cbefore_ < cafter_); EXPECT_TRUE(cbefore_ <= cafter_); EXPECT_TRUE(cafter_ > cbefore_); EXPECT_TRUE(cafter_ >= cbefore_); EXPECT_FALSE(cbefore_ > cafter_); EXPECT_FALSE(cafter_ < cbefore_); EXPECT_TRUE(before_ < after_); EXPECT_TRUE(before_ <= after_); EXPECT_TRUE(after_ > before_); EXPECT_TRUE(after_ >= before_); EXPECT_FALSE(before_ > after_); EXPECT_FALSE(after_ < before_); EXPECT_TRUE(cbefore_ < after_); EXPECT_TRUE(cbefore_ <= after_); EXPECT_TRUE(after_ > cbefore_); EXPECT_TRUE(after_ >= cbefore_); EXPECT_FALSE(cbefore_ > after_); EXPECT_FALSE(after_ < cbefore_); } TEST_F(IntSpanOrderComparisonTest, SpanOfConstAndContainer) { EXPECT_TRUE(cbefore_ < vec_after_); EXPECT_TRUE(cbefore_ <= vec_after_); EXPECT_TRUE(vec_after_ > cbefore_); EXPECT_TRUE(vec_after_ >= cbefore_); EXPECT_FALSE(cbefore_ > vec_after_); EXPECT_FALSE(vec_after_ < cbefore_); EXPECT_TRUE(arr_before_ < cafter_); EXPECT_TRUE(arr_before_ <= cafter_); EXPECT_TRUE(cafter_ > arr_before_); EXPECT_TRUE(cafter_ >= arr_before_); EXPECT_FALSE(arr_before_ > cafter_); EXPECT_FALSE(cafter_ < arr_before_); } TEST_F(IntSpanOrderComparisonTest, SpanOfMutableAndContainer) { EXPECT_TRUE(vec_before_ < after_); EXPECT_TRUE(vec_before_ <= after_); EXPECT_TRUE(after_ > vec_before_); EXPECT_TRUE(after_ >= vec_before_); EXPECT_FALSE(vec_before_ > after_); EXPECT_FALSE(after_ < vec_before_); EXPECT_TRUE(before_ < carr_after_); EXPECT_TRUE(before_ <= carr_after_); EXPECT_TRUE(carr_after_ > before_); EXPECT_TRUE(carr_after_ >= before_); EXPECT_FALSE(before_ > carr_after_); EXPECT_FALSE(carr_after_ < before_); } TEST_F(IntSpanOrderComparisonTest, EqualSpans) { EXPECT_FALSE(before_ < before_); EXPECT_TRUE(before_ <= before_); EXPECT_FALSE(before_ > before_); EXPECT_TRUE(before_ >= before_); } TEST_F(IntSpanOrderComparisonTest, Subspans) { auto subspan = before_.subspan(0, 1); EXPECT_TRUE(subspan < before_); EXPECT_TRUE(subspan <= before_); EXPECT_TRUE(before_ > subspan); EXPECT_TRUE(before_ >= subspan); EXPECT_FALSE(subspan > before_); EXPECT_FALSE(before_ < subspan); } TEST_F(IntSpanOrderComparisonTest, EmptySpans) { absl::Span<int> empty; EXPECT_FALSE(empty < empty); EXPECT_TRUE(empty <= empty); EXPECT_FALSE(empty > empty); EXPECT_TRUE(empty >= empty); EXPECT_TRUE(empty < before_); EXPECT_TRUE(empty <= before_); EXPECT_TRUE(before_ > empty); EXPECT_TRUE(before_ >= empty); EXPECT_FALSE(empty > before_); EXPECT_FALSE(before_ < empty); } TEST(IntSpan, ExposesContainerTypesAndConsts) { absl::Span<int> slice; CheckType<absl::Span<int>::iterator>(slice.begin()); EXPECT_TRUE((std::is_convertible<decltype(slice.begin()), absl::Span<int>::const_iterator>::value)); CheckType<absl::Span<int>::const_iterator>(slice.cbegin()); EXPECT_TRUE((std::is_convertible<decltype(slice.end()), absl::Span<int>::const_iterator>::value)); CheckType<absl::Span<int>::const_iterator>(slice.cend()); CheckType<absl::Span<int>::reverse_iterator>(slice.rend()); EXPECT_TRUE( (std::is_convertible<decltype(slice.rend()), absl::Span<int>::const_reverse_iterator>::value)); CheckType<absl::Span<int>::const_reverse_iterator>(slice.crend()); testing::StaticAssertTypeEq<int, absl::Span<int>::value_type>(); testing::StaticAssertTypeEq<int, absl::Span<const int>::value_type>(); testing::StaticAssertTypeEq<int, absl::Span<int>::element_type>(); testing::StaticAssertTypeEq<const int, absl::Span<const int>::element_type>(); testing::StaticAssertTypeEq<int*, absl::Span<int>::pointer>(); testing::StaticAssertTypeEq<const int*, absl::Span<const int>::pointer>(); testing::StaticAssertTypeEq<int&, absl::Span<int>::reference>(); testing::StaticAssertTypeEq<const int&, absl::Span<const int>::reference>(); testing::StaticAssertTypeEq<const int&, absl::Span<int>::const_reference>(); testing::StaticAssertTypeEq<const int&, absl::Span<const int>::const_reference>(); EXPECT_EQ(static_cast<absl::Span<int>::size_type>(-1), absl::Span<int>::npos); } TEST(IntSpan, IteratorsAndReferences) { auto accept_pointer = [](int*) {}; auto accept_reference = [](int&) {}; auto accept_iterator = [](absl::Span<int>::iterator) {}; auto accept_const_iterator = [](absl::Span<int>::const_iterator) {}; auto accept_reverse_iterator = [](absl::Span<int>::reverse_iterator) {}; auto accept_const_reverse_iterator = [](absl::Span<int>::const_reverse_iterator) {}; int a[1]; absl::Span<int> s = a; accept_pointer(s.data()); accept_iterator(s.begin()); accept_const_iterator(s.begin()); accept_const_iterator(s.cbegin()); accept_iterator(s.end()); accept_const_iterator(s.end()); accept_const_iterator(s.cend()); accept_reverse_iterator(s.rbegin()); accept_const_reverse_iterator(s.rbegin()); accept_const_reverse_iterator(s.crbegin()); accept_reverse_iterator(s.rend()); accept_const_reverse_iterator(s.rend()); accept_const_reverse_iterator(s.crend()); accept_reference(s[0]); accept_reference(s.at(0)); accept_reference(s.front()); accept_reference(s.back()); } TEST(IntSpan, IteratorsAndReferences_Const) { auto accept_pointer = [](int*) {}; auto accept_reference = [](int&) {}; auto accept_iterator = [](absl::Span<int>::iterator) {}; auto accept_const_iterator = [](absl::Span<int>::const_iterator) {}; auto accept_reverse_iterator = [](absl::Span<int>::reverse_iterator) {}; auto accept_const_reverse_iterator = [](absl::Span<int>::const_reverse_iterator) {}; int a[1]; const absl::Span<int> s = a; accept_pointer(s.data()); accept_iterator(s.begin()); accept_const_iterator(s.begin()); accept_const_iterator(s.cbegin()); accept_iterator(s.end()); accept_const_iterator(s.end()); accept_const_iterator(s.cend()); accept_reverse_iterator(s.rbegin()); accept_const_reverse_iterator(s.rbegin()); accept_const_reverse_iterator(s.crbegin()); accept_reverse_iterator(s.rend()); accept_const_reverse_iterator(s.rend()); accept_const_reverse_iterator(s.crend()); accept_reference(s[0]); accept_reference(s.at(0)); accept_reference(s.front()); accept_reference(s.back()); } TEST(IntSpan, NoexceptTest) { int a[] = {1, 2, 3}; std::vector<int> v; EXPECT_TRUE(noexcept(absl::Span<const int>())); EXPECT_TRUE(noexcept(absl::Span<const int>(a, 2))); EXPECT_TRUE(noexcept(absl::Span<const int>(a))); EXPECT_TRUE(noexcept(absl::Span<const int>(v))); EXPECT_TRUE(noexcept(absl::Span<int>(v))); EXPECT_TRUE(noexcept(absl::Span<const int>({1, 2, 3}))); EXPECT_TRUE(noexcept(absl::MakeSpan(v))); EXPECT_TRUE(noexcept(absl::MakeSpan(a))); EXPECT_TRUE(noexcept(absl::MakeSpan(a, 2))); EXPECT_TRUE(noexcept(absl::MakeSpan(a, a + 1))); EXPECT_TRUE(noexcept(absl::MakeConstSpan(v))); EXPECT_TRUE(noexcept(absl::MakeConstSpan(a))); EXPECT_TRUE(noexcept(absl::MakeConstSpan(a, 2))); EXPECT_TRUE(noexcept(absl::MakeConstSpan(a, a + 1))); absl::Span<int> s(v); EXPECT_TRUE(noexcept(s.data())); EXPECT_TRUE(noexcept(s.size())); EXPECT_TRUE(noexcept(s.length())); EXPECT_TRUE(noexcept(s.empty())); EXPECT_TRUE(noexcept(s[0])); EXPECT_TRUE(noexcept(s.front())); EXPECT_TRUE(noexcept(s.back())); EXPECT_TRUE(noexcept(s.begin())); EXPECT_TRUE(noexcept(s.cbegin())); EXPECT_TRUE(noexcept(s.end())); EXPECT_TRUE(noexcept(s.cend())); EXPECT_TRUE(noexcept(s.rbegin())); EXPECT_TRUE(noexcept(s.crbegin())); EXPECT_TRUE(noexcept(s.rend())); EXPECT_TRUE(noexcept(s.crend())); EXPECT_TRUE(noexcept(s.remove_prefix(0))); EXPECT_TRUE(noexcept(s.remove_suffix(0))); } template <int i> struct ConstexprTester {}; #define ABSL_TEST_CONSTEXPR(expr) \ do { \ ABSL_ATTRIBUTE_UNUSED ConstexprTester<(expr, 1)> t; \ } while (0) struct ContainerWithConstexprMethods { constexpr int size() const { return 1; } constexpr const int* data() const { return &i; } const int i; }; TEST(ConstIntSpan, ConstexprTest) { static constexpr int a[] = {1, 2, 3}; static constexpr int sized_arr[2] = {1, 2}; static constexpr ContainerWithConstexprMethods c{1}; ABSL_TEST_CONSTEXPR(absl::Span<const int>()); ABSL_TEST_CONSTEXPR(absl::Span<const int>(a, 2)); ABSL_TEST_CONSTEXPR(absl::Span<const int>(sized_arr)); ABSL_TEST_CONSTEXPR(absl::Span<const int>(c)); ABSL_TEST_CONSTEXPR(absl::MakeSpan(&a[0], 1)); ABSL_TEST_CONSTEXPR(absl::MakeSpan(c)); ABSL_TEST_CONSTEXPR(absl::MakeSpan(a)); ABSL_TEST_CONSTEXPR(absl::MakeConstSpan(&a[0], 1)); ABSL_TEST_CONSTEXPR(absl::MakeConstSpan(c)); ABSL_TEST_CONSTEXPR(absl::MakeConstSpan(a)); constexpr absl::Span<const int> span = c; ABSL_TEST_CONSTEXPR(span.data()); ABSL_TEST_CONSTEXPR(span.size()); ABSL_TEST_CONSTEXPR(span.length()); ABSL_TEST_CONSTEXPR(span.empty()); ABSL_TEST_CONSTEXPR(span.begin()); ABSL_TEST_CONSTEXPR(span.cbegin()); ABSL_TEST_CONSTEXPR(span.subspan(0, 0)); ABSL_TEST_CONSTEXPR(span.first(1)); ABSL_TEST_CONSTEXPR(span.last(1)); ABSL_TEST_CONSTEXPR(span[0]); } struct BigStruct { char bytes[10000]; }; TEST(Span, SpanSize) { EXPECT_LE(sizeof(absl::Span<int>), 2 * sizeof(void*)); EXPECT_LE(sizeof(absl::Span<BigStruct>), 2 * sizeof(void*)); } TEST(Span, Hash) { int array[] = {1, 2, 3, 4}; int array2[] = {1, 2, 3}; using T = absl::Span<const int>; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( { T(), T(nullptr, 0), T(array, 0), T(array2, 0), T(array, 3), T(array2), T({1, 2, 3}), T(array, 1), T(array, 2), T(array + 1, 2), T(array + 2, 2)})); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/types/internal/span.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/types/span_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
34c8dafc-d129-4f28-a135-dae212b8739a
cpp
abseil/abseil-cpp
any
absl/types/any.h
absl/types/any_test.cc
#ifndef ABSL_TYPES_ANY_H_ #define ABSL_TYPES_ANY_H_ #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/utility/utility.h" #ifdef ABSL_USES_STD_ANY #include <any> namespace absl { ABSL_NAMESPACE_BEGIN using std::any; using std::any_cast; using std::bad_any_cast; using std::make_any; ABSL_NAMESPACE_END } #else #include <algorithm> #include <cstddef> #include <initializer_list> #include <memory> #include <stdexcept> #include <type_traits> #include <typeinfo> #include <utility> #include "absl/base/internal/fast_type_id.h" #include "absl/meta/type_traits.h" #include "absl/types/bad_any_cast.h" namespace absl { ABSL_NAMESPACE_BEGIN class any; void swap(any& x, any& y) noexcept; template <typename T, typename... Args> any make_any(Args&&... args); template <typename T, typename U, typename... Args> any make_any(std::initializer_list<U> il, Args&&... args); template <typename ValueType> ValueType any_cast(const any& operand); template <typename ValueType> ValueType any_cast(any& operand); template <typename ValueType> ValueType any_cast(any&& operand); template <typename ValueType> const ValueType* any_cast(const any* operand) noexcept; template <typename ValueType> ValueType* any_cast(any* operand) noexcept; class any { private: template <typename T> struct IsInPlaceType; public: constexpr any() noexcept; any(const any& other) : obj_(other.has_value() ? other.obj_->Clone() : std::unique_ptr<ObjInterface>()) {} any(any&& other) noexcept = default; template < typename T, typename VT = absl::decay_t<T>, absl::enable_if_t<!absl::disjunction< std::is_same<any, VT>, IsInPlaceType<VT>, absl::negation<std::is_copy_constructible<VT> > >::value>* = nullptr> any(T&& value) : obj_(new Obj<VT>(in_place, std::forward<T>(value))) {} template <typename T, typename... Args, typename VT = absl::decay_t<T>, absl::enable_if_t<absl::conjunction< std::is_copy_constructible<VT>, std::is_constructible<VT, Args...>>::value>* = nullptr> explicit any(in_place_type_t<T> , Args&&... args) : obj_(new Obj<VT>(in_place, std::forward<Args>(args)...)) {} template < typename T, typename U, typename... Args, typename VT = absl::decay_t<T>, absl::enable_if_t< absl::conjunction<std::is_copy_constructible<VT>, std::is_constructible<VT, std::initializer_list<U>&, Args...>>::value>* = nullptr> explicit any(in_place_type_t<T> , std::initializer_list<U> ilist, Args&&... args) : obj_(new Obj<VT>(in_place, ilist, std::forward<Args>(args)...)) {} any& operator=(const any& rhs) { any(rhs).swap(*this); return *this; } any& operator=(any&& rhs) noexcept { any(std::move(rhs)).swap(*this); return *this; } template <typename T, typename VT = absl::decay_t<T>, absl::enable_if_t<absl::conjunction< absl::negation<std::is_same<VT, any>>, std::is_copy_constructible<VT>>::value>* = nullptr> any& operator=(T&& rhs) { any tmp(in_place_type_t<VT>(), std::forward<T>(rhs)); tmp.swap(*this); return *this; } template < typename T, typename... Args, typename VT = absl::decay_t<T>, absl::enable_if_t<std::is_copy_constructible<VT>::value && std::is_constructible<VT, Args...>::value>* = nullptr> VT& emplace(Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND { reset(); Obj<VT>* const object_ptr = new Obj<VT>(in_place, std::forward<Args>(args)...); obj_ = std::unique_ptr<ObjInterface>(object_ptr); return object_ptr->value; } template < typename T, typename U, typename... Args, typename VT = absl::decay_t<T>, absl::enable_if_t<std::is_copy_constructible<VT>::value && std::is_constructible<VT, std::initializer_list<U>&, Args...>::value>* = nullptr> VT& emplace(std::initializer_list<U> ilist, Args&&... args) ABSL_ATTRIBUTE_LIFETIME_BOUND { reset(); Obj<VT>* const object_ptr = new Obj<VT>(in_place, ilist, std::forward<Args>(args)...); obj_ = std::unique_ptr<ObjInterface>(object_ptr); return object_ptr->value; } void reset() noexcept { obj_ = nullptr; } void swap(any& other) noexcept { obj_.swap(other.obj_); } bool has_value() const noexcept { return obj_ != nullptr; } #ifdef ABSL_INTERNAL_HAS_RTTI const std::type_info& type() const noexcept { if (has_value()) { return obj_->Type(); } return typeid(void); } #endif private: class ObjInterface { public: virtual ~ObjInterface() = default; virtual std::unique_ptr<ObjInterface> Clone() const = 0; virtual const void* ObjTypeId() const noexcept = 0; #ifdef ABSL_INTERNAL_HAS_RTTI virtual const std::type_info& Type() const noexcept = 0; #endif }; template <typename T> class Obj : public ObjInterface { public: template <typename... Args> explicit Obj(in_place_t , Args&&... args) : value(std::forward<Args>(args)...) {} std::unique_ptr<ObjInterface> Clone() const final { return std::unique_ptr<ObjInterface>(new Obj(in_place, value)); } const void* ObjTypeId() const noexcept final { return IdForType<T>(); } #ifdef ABSL_INTERNAL_HAS_RTTI const std::type_info& Type() const noexcept final { return typeid(T); } #endif T value; }; std::unique_ptr<ObjInterface> CloneObj() const { if (!obj_) return nullptr; return obj_->Clone(); } template <typename T> constexpr static const void* IdForType() { using NormalizedType = typename std::remove_cv<typename std::remove_reference<T>::type>::type; return base_internal::FastTypeId<NormalizedType>(); } const void* GetObjTypeId() const { return obj_ ? obj_->ObjTypeId() : base_internal::FastTypeId<void>(); } template <typename ValueType> friend ValueType any_cast(const any& operand); template <typename ValueType> friend ValueType any_cast(any& operand); template <typename T> friend const T* any_cast(const any* operand) noexcept; template <typename T> friend T* any_cast(any* operand) noexcept; std::unique_ptr<ObjInterface> obj_; }; constexpr any::any() noexcept = default; template <typename T> struct any::IsInPlaceType : std::false_type {}; template <typename T> struct any::IsInPlaceType<in_place_type_t<T>> : std::true_type {}; inline void swap(any& x, any& y) noexcept { x.swap(y); } template <typename T, typename... Args> any make_any(Args&&... args) { return any(in_place_type_t<T>(), std::forward<Args>(args)...); } template <typename T, typename U, typename... Args> any make_any(std::initializer_list<U> il, Args&&... args) { return any(in_place_type_t<T>(), il, std::forward<Args>(args)...); } template <typename ValueType> ValueType any_cast(const any& operand) { using U = typename std::remove_cv< typename std::remove_reference<ValueType>::type>::type; static_assert(std::is_constructible<ValueType, const U&>::value, "Invalid ValueType"); auto* const result = (any_cast<U>)(&operand); if (result == nullptr) { any_internal::ThrowBadAnyCast(); } return static_cast<ValueType>(*result); } template <typename ValueType> ValueType any_cast(any& operand) { using U = typename std::remove_cv< typename std::remove_reference<ValueType>::type>::type; static_assert(std::is_constructible<ValueType, U&>::value, "Invalid ValueType"); auto* result = (any_cast<U>)(&operand); if (result == nullptr) { any_internal::ThrowBadAnyCast(); } return static_cast<ValueType>(*result); } template <typename ValueType> ValueType any_cast(any&& operand) { using U = typename std::remove_cv< typename std::remove_reference<ValueType>::type>::type; static_assert(std::is_constructible<ValueType, U>::value, "Invalid ValueType"); return static_cast<ValueType>(std::move((any_cast<U&>)(operand))); } template <typename T> const T* any_cast(const any* operand) noexcept { using U = typename std::remove_cv<typename std::remove_reference<T>::type>::type; return operand && operand->GetObjTypeId() == any::IdForType<U>() ? std::addressof( static_cast<const any::Obj<U>*>(operand->obj_.get())->value) : nullptr; } template <typename T> T* any_cast(any* operand) noexcept { using U = typename std::remove_cv<typename std::remove_reference<T>::type>::type; return operand && operand->GetObjTypeId() == any::IdForType<U>() ? std::addressof( static_cast<any::Obj<U>*>(operand->obj_.get())->value) : nullptr; } ABSL_NAMESPACE_END } #endif #endif
#include "absl/types/any.h" #if !defined(ABSL_USES_STD_ANY) #include <initializer_list> #include <type_traits> #include <utility> #include <vector> #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/base/internal/exception_testing.h" #include "absl/container/internal/test_instance_tracker.h" #include "absl/log/log.h" namespace { using absl::test_internal::CopyableOnlyInstance; using absl::test_internal::InstanceTracker; template <typename T> const T& AsConst(const T& t) { return t; } struct MoveOnly { MoveOnly() = default; explicit MoveOnly(int value) : value(value) {} MoveOnly(MoveOnly&&) = default; MoveOnly& operator=(MoveOnly&&) = default; int value = 0; }; struct CopyOnly { CopyOnly() = default; explicit CopyOnly(int value) : value(value) {} CopyOnly(CopyOnly&&) = delete; CopyOnly& operator=(CopyOnly&&) = delete; CopyOnly(const CopyOnly&) = default; CopyOnly& operator=(const CopyOnly&) = default; int value = 0; }; struct MoveOnlyWithListConstructor { MoveOnlyWithListConstructor() = default; explicit MoveOnlyWithListConstructor(std::initializer_list<int> , int value) : value(value) {} MoveOnlyWithListConstructor(MoveOnlyWithListConstructor&&) = default; MoveOnlyWithListConstructor& operator=(MoveOnlyWithListConstructor&&) = default; int value = 0; }; struct IntMoveOnlyCopyOnly { IntMoveOnlyCopyOnly(int value, MoveOnly , CopyOnly ) : value(value) {} int value; }; struct ListMoveOnlyCopyOnly { ListMoveOnlyCopyOnly(std::initializer_list<int> ilist, MoveOnly , CopyOnly ) : values(ilist) {} std::vector<int> values; }; using FunctionType = void(); void FunctionToEmplace() {} using ArrayType = int[2]; using DecayedArray = absl::decay_t<ArrayType>; TEST(AnyTest, Noexcept) { static_assert(std::is_nothrow_default_constructible<absl::any>(), ""); static_assert(std::is_nothrow_move_constructible<absl::any>(), ""); static_assert(std::is_nothrow_move_assignable<absl::any>(), ""); static_assert(noexcept(std::declval<absl::any&>().has_value()), ""); static_assert(noexcept(std::declval<absl::any&>().type()), ""); static_assert(noexcept(absl::any_cast<int>(std::declval<absl::any*>())), ""); static_assert( noexcept(std::declval<absl::any&>().swap(std::declval<absl::any&>())), ""); using std::swap; static_assert( noexcept(swap(std::declval<absl::any&>(), std::declval<absl::any&>())), ""); } TEST(AnyTest, HasValue) { absl::any o; EXPECT_FALSE(o.has_value()); o.emplace<int>(); EXPECT_TRUE(o.has_value()); o.reset(); EXPECT_FALSE(o.has_value()); } TEST(AnyTest, Type) { absl::any o; EXPECT_EQ(typeid(void), o.type()); o.emplace<int>(5); EXPECT_EQ(typeid(int), o.type()); o.emplace<float>(5.f); EXPECT_EQ(typeid(float), o.type()); o.reset(); EXPECT_EQ(typeid(void), o.type()); } TEST(AnyTest, EmptyPointerCast) { { absl::any o; EXPECT_EQ(nullptr, absl::any_cast<int>(&o)); o.emplace<int>(); EXPECT_NE(nullptr, absl::any_cast<int>(&o)); o.reset(); EXPECT_EQ(nullptr, absl::any_cast<int>(&o)); } { absl::any o; EXPECT_EQ(nullptr, absl::any_cast<int>(&AsConst(o))); o.emplace<int>(); EXPECT_NE(nullptr, absl::any_cast<int>(&AsConst(o))); o.reset(); EXPECT_EQ(nullptr, absl::any_cast<int>(&AsConst(o))); } } TEST(AnyTest, InPlaceConstruction) { const CopyOnly copy_only{}; absl::any o(absl::in_place_type_t<IntMoveOnlyCopyOnly>(), 5, MoveOnly(), copy_only); IntMoveOnlyCopyOnly& v = absl::any_cast<IntMoveOnlyCopyOnly&>(o); EXPECT_EQ(5, v.value); } TEST(AnyTest, InPlaceConstructionVariableTemplate) { const CopyOnly copy_only{}; absl::any o(absl::in_place_type<IntMoveOnlyCopyOnly>, 5, MoveOnly(), copy_only); auto& v = absl::any_cast<IntMoveOnlyCopyOnly&>(o); EXPECT_EQ(5, v.value); } TEST(AnyTest, InPlaceConstructionWithCV) { const CopyOnly copy_only{}; absl::any o(absl::in_place_type_t<const volatile IntMoveOnlyCopyOnly>(), 5, MoveOnly(), copy_only); IntMoveOnlyCopyOnly& v = absl::any_cast<IntMoveOnlyCopyOnly&>(o); EXPECT_EQ(5, v.value); } TEST(AnyTest, InPlaceConstructionWithCVVariableTemplate) { const CopyOnly copy_only{}; absl::any o(absl::in_place_type<const volatile IntMoveOnlyCopyOnly>, 5, MoveOnly(), copy_only); auto& v = absl::any_cast<IntMoveOnlyCopyOnly&>(o); EXPECT_EQ(5, v.value); } TEST(AnyTest, InPlaceConstructionWithFunction) { absl::any o(absl::in_place_type_t<FunctionType>(), FunctionToEmplace); FunctionType*& construction_result = absl::any_cast<FunctionType*&>(o); EXPECT_EQ(&FunctionToEmplace, construction_result); } TEST(AnyTest, InPlaceConstructionWithFunctionVariableTemplate) { absl::any o(absl::in_place_type<FunctionType>, FunctionToEmplace); auto& construction_result = absl::any_cast<FunctionType*&>(o); EXPECT_EQ(&FunctionToEmplace, construction_result); } TEST(AnyTest, InPlaceConstructionWithArray) { ArrayType ar = {5, 42}; absl::any o(absl::in_place_type_t<ArrayType>(), ar); DecayedArray& construction_result = absl::any_cast<DecayedArray&>(o); EXPECT_EQ(&ar[0], construction_result); } TEST(AnyTest, InPlaceConstructionWithArrayVariableTemplate) { ArrayType ar = {5, 42}; absl::any o(absl::in_place_type<ArrayType>, ar); auto& construction_result = absl::any_cast<DecayedArray&>(o); EXPECT_EQ(&ar[0], construction_result); } TEST(AnyTest, InPlaceConstructionIlist) { const CopyOnly copy_only{}; absl::any o(absl::in_place_type_t<ListMoveOnlyCopyOnly>(), {1, 2, 3, 4}, MoveOnly(), copy_only); ListMoveOnlyCopyOnly& v = absl::any_cast<ListMoveOnlyCopyOnly&>(o); std::vector<int> expected_values = {1, 2, 3, 4}; EXPECT_EQ(expected_values, v.values); } TEST(AnyTest, InPlaceConstructionIlistVariableTemplate) { const CopyOnly copy_only{}; absl::any o(absl::in_place_type<ListMoveOnlyCopyOnly>, {1, 2, 3, 4}, MoveOnly(), copy_only); auto& v = absl::any_cast<ListMoveOnlyCopyOnly&>(o); std::vector<int> expected_values = {1, 2, 3, 4}; EXPECT_EQ(expected_values, v.values); } TEST(AnyTest, InPlaceConstructionIlistWithCV) { const CopyOnly copy_only{}; absl::any o(absl::in_place_type_t<const volatile ListMoveOnlyCopyOnly>(), {1, 2, 3, 4}, MoveOnly(), copy_only); ListMoveOnlyCopyOnly& v = absl::any_cast<ListMoveOnlyCopyOnly&>(o); std::vector<int> expected_values = {1, 2, 3, 4}; EXPECT_EQ(expected_values, v.values); } TEST(AnyTest, InPlaceConstructionIlistWithCVVariableTemplate) { const CopyOnly copy_only{}; absl::any o(absl::in_place_type<const volatile ListMoveOnlyCopyOnly>, {1, 2, 3, 4}, MoveOnly(), copy_only); auto& v = absl::any_cast<ListMoveOnlyCopyOnly&>(o); std::vector<int> expected_values = {1, 2, 3, 4}; EXPECT_EQ(expected_values, v.values); } TEST(AnyTest, InPlaceNoArgs) { absl::any o(absl::in_place_type_t<int>{}); EXPECT_EQ(0, absl::any_cast<int&>(o)); } TEST(AnyTest, InPlaceNoArgsVariableTemplate) { absl::any o(absl::in_place_type<int>); EXPECT_EQ(0, absl::any_cast<int&>(o)); } template <typename Enabler, typename T, typename... Args> struct CanEmplaceAnyImpl : std::false_type {}; template <typename T, typename... Args> struct CanEmplaceAnyImpl< absl::void_t<decltype( std::declval<absl::any&>().emplace<T>(std::declval<Args>()...))>, T, Args...> : std::true_type {}; template <typename T, typename... Args> using CanEmplaceAny = CanEmplaceAnyImpl<void, T, Args...>; TEST(AnyTest, Emplace) { const CopyOnly copy_only{}; absl::any o; EXPECT_TRUE((std::is_same<decltype(o.emplace<IntMoveOnlyCopyOnly>( 5, MoveOnly(), copy_only)), IntMoveOnlyCopyOnly&>::value)); IntMoveOnlyCopyOnly& emplace_result = o.emplace<IntMoveOnlyCopyOnly>(5, MoveOnly(), copy_only); EXPECT_EQ(5, emplace_result.value); IntMoveOnlyCopyOnly& v = absl::any_cast<IntMoveOnlyCopyOnly&>(o); EXPECT_EQ(5, v.value); EXPECT_EQ(&emplace_result, &v); static_assert(!CanEmplaceAny<int, int, int>::value, ""); static_assert(!CanEmplaceAny<MoveOnly, MoveOnly>::value, ""); } TEST(AnyTest, EmplaceWithCV) { const CopyOnly copy_only{}; absl::any o; EXPECT_TRUE( (std::is_same<decltype(o.emplace<const volatile IntMoveOnlyCopyOnly>( 5, MoveOnly(), copy_only)), IntMoveOnlyCopyOnly&>::value)); IntMoveOnlyCopyOnly& emplace_result = o.emplace<const volatile IntMoveOnlyCopyOnly>(5, MoveOnly(), copy_only); EXPECT_EQ(5, emplace_result.value); IntMoveOnlyCopyOnly& v = absl::any_cast<IntMoveOnlyCopyOnly&>(o); EXPECT_EQ(5, v.value); EXPECT_EQ(&emplace_result, &v); } TEST(AnyTest, EmplaceWithFunction) { absl::any o; EXPECT_TRUE( (std::is_same<decltype(o.emplace<FunctionType>(FunctionToEmplace)), FunctionType*&>::value)); FunctionType*& emplace_result = o.emplace<FunctionType>(FunctionToEmplace); EXPECT_EQ(&FunctionToEmplace, emplace_result); } TEST(AnyTest, EmplaceWithArray) { absl::any o; ArrayType ar = {5, 42}; EXPECT_TRUE( (std::is_same<decltype(o.emplace<ArrayType>(ar)), DecayedArray&>::value)); DecayedArray& emplace_result = o.emplace<ArrayType>(ar); EXPECT_EQ(&ar[0], emplace_result); } TEST(AnyTest, EmplaceIlist) { const CopyOnly copy_only{}; absl::any o; EXPECT_TRUE((std::is_same<decltype(o.emplace<ListMoveOnlyCopyOnly>( {1, 2, 3, 4}, MoveOnly(), copy_only)), ListMoveOnlyCopyOnly&>::value)); ListMoveOnlyCopyOnly& emplace_result = o.emplace<ListMoveOnlyCopyOnly>({1, 2, 3, 4}, MoveOnly(), copy_only); ListMoveOnlyCopyOnly& v = absl::any_cast<ListMoveOnlyCopyOnly&>(o); EXPECT_EQ(&v, &emplace_result); std::vector<int> expected_values = {1, 2, 3, 4}; EXPECT_EQ(expected_values, v.values); static_assert(!CanEmplaceAny<int, std::initializer_list<int>>::value, ""); static_assert(!CanEmplaceAny<MoveOnlyWithListConstructor, std::initializer_list<int>, int>::value, ""); } TEST(AnyTest, EmplaceIlistWithCV) { const CopyOnly copy_only{}; absl::any o; EXPECT_TRUE( (std::is_same<decltype(o.emplace<const volatile ListMoveOnlyCopyOnly>( {1, 2, 3, 4}, MoveOnly(), copy_only)), ListMoveOnlyCopyOnly&>::value)); ListMoveOnlyCopyOnly& emplace_result = o.emplace<const volatile ListMoveOnlyCopyOnly>({1, 2, 3, 4}, MoveOnly(), copy_only); ListMoveOnlyCopyOnly& v = absl::any_cast<ListMoveOnlyCopyOnly&>(o); EXPECT_EQ(&v, &emplace_result); std::vector<int> expected_values = {1, 2, 3, 4}; EXPECT_EQ(expected_values, v.values); } TEST(AnyTest, EmplaceNoArgs) { absl::any o; o.emplace<int>(); EXPECT_EQ(0, absl::any_cast<int>(o)); } TEST(AnyTest, ConversionConstruction) { { absl::any o = 5; EXPECT_EQ(5, absl::any_cast<int>(o)); } { const CopyOnly copy_only(5); absl::any o = copy_only; EXPECT_EQ(5, absl::any_cast<CopyOnly&>(o).value); } static_assert(!std::is_convertible<MoveOnly, absl::any>::value, ""); } TEST(AnyTest, ConversionAssignment) { { absl::any o; o = 5; EXPECT_EQ(5, absl::any_cast<int>(o)); } { const CopyOnly copy_only(5); absl::any o; o = copy_only; EXPECT_EQ(5, absl::any_cast<CopyOnly&>(o).value); } static_assert(!std::is_assignable<MoveOnly, absl::any>::value, ""); } #ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable : 4521) #endif struct WeirdConstructor42 { explicit WeirdConstructor42(int value) : value(value) {} WeirdConstructor42(const WeirdConstructor42& other) : value(other.value) {} WeirdConstructor42( WeirdConstructor42& ) : value(42) {} int value; }; #ifdef _MSC_VER #pragma warning( pop ) #endif TEST(AnyTest, WeirdConversionConstruction) { { const WeirdConstructor42 source(5); absl::any o = source; EXPECT_EQ(5, absl::any_cast<WeirdConstructor42&>(o).value); } { WeirdConstructor42 source(5); absl::any o = source; EXPECT_EQ(42, absl::any_cast<WeirdConstructor42&>(o).value); } } TEST(AnyTest, WeirdConversionAssignment) { { const WeirdConstructor42 source(5); absl::any o; o = source; EXPECT_EQ(5, absl::any_cast<WeirdConstructor42&>(o).value); } { WeirdConstructor42 source(5); absl::any o; o = source; EXPECT_EQ(42, absl::any_cast<WeirdConstructor42&>(o).value); } } struct Value {}; TEST(AnyTest, AnyCastValue) { { absl::any o; o.emplace<int>(5); EXPECT_EQ(5, absl::any_cast<int>(o)); EXPECT_EQ(5, absl::any_cast<int>(AsConst(o))); static_assert( std::is_same<decltype(absl::any_cast<Value>(o)), Value>::value, ""); } { absl::any o; o.emplace<int>(5); EXPECT_EQ(5, absl::any_cast<const int>(o)); EXPECT_EQ(5, absl::any_cast<const int>(AsConst(o))); static_assert(std::is_same<decltype(absl::any_cast<const Value>(o)), const Value>::value, ""); } } TEST(AnyTest, AnyCastReference) { { absl::any o; o.emplace<int>(5); EXPECT_EQ(5, absl::any_cast<int&>(o)); EXPECT_EQ(5, absl::any_cast<const int&>(AsConst(o))); static_assert( std::is_same<decltype(absl::any_cast<Value&>(o)), Value&>::value, ""); } { absl::any o; o.emplace<int>(5); EXPECT_EQ(5, absl::any_cast<const int>(o)); EXPECT_EQ(5, absl::any_cast<const int>(AsConst(o))); static_assert(std::is_same<decltype(absl::any_cast<const Value&>(o)), const Value&>::value, ""); } { absl::any o; o.emplace<int>(5); EXPECT_EQ(5, absl::any_cast<int&&>(std::move(o))); static_assert(std::is_same<decltype(absl::any_cast<Value&&>(std::move(o))), Value&&>::value, ""); } { absl::any o; o.emplace<int>(5); EXPECT_EQ(5, absl::any_cast<const int>(std::move(o))); static_assert( std::is_same<decltype(absl::any_cast<const Value&&>(std::move(o))), const Value&&>::value, ""); } } TEST(AnyTest, AnyCastPointer) { { absl::any o; EXPECT_EQ(nullptr, absl::any_cast<char>(&o)); o.emplace<int>(5); EXPECT_EQ(nullptr, absl::any_cast<char>(&o)); o.emplace<char>('a'); EXPECT_EQ('a', *absl::any_cast<char>(&o)); static_assert( std::is_same<decltype(absl::any_cast<Value>(&o)), Value*>::value, ""); } { absl::any o; EXPECT_EQ(nullptr, absl::any_cast<const char>(&o)); o.emplace<int>(5); EXPECT_EQ(nullptr, absl::any_cast<const char>(&o)); o.emplace<char>('a'); EXPECT_EQ('a', *absl::any_cast<const char>(&o)); static_assert(std::is_same<decltype(absl::any_cast<const Value>(&o)), const Value*>::value, ""); } } TEST(AnyTest, MakeAny) { const CopyOnly copy_only{}; auto o = absl::make_any<IntMoveOnlyCopyOnly>(5, MoveOnly(), copy_only); static_assert(std::is_same<decltype(o), absl::any>::value, ""); EXPECT_EQ(5, absl::any_cast<IntMoveOnlyCopyOnly&>(o).value); } TEST(AnyTest, MakeAnyIList) { const CopyOnly copy_only{}; auto o = absl::make_any<ListMoveOnlyCopyOnly>({1, 2, 3}, MoveOnly(), copy_only); static_assert(std::is_same<decltype(o), absl::any>::value, ""); ListMoveOnlyCopyOnly& v = absl::any_cast<ListMoveOnlyCopyOnly&>(o); std::vector<int> expected_values = {1, 2, 3}; EXPECT_EQ(expected_values, v.values); } TEST(AnyTest, Copy) { InstanceTracker tracker_raii; { absl::any o(absl::in_place_type<CopyableOnlyInstance>, 123); CopyableOnlyInstance* f1 = absl::any_cast<CopyableOnlyInstance>(&o); absl::any o2(o); const CopyableOnlyInstance* f2 = absl::any_cast<CopyableOnlyInstance>(&o2); EXPECT_EQ(123, f2->value()); EXPECT_NE(f1, f2); absl::any o3; o3 = o2; const CopyableOnlyInstance* f3 = absl::any_cast<CopyableOnlyInstance>(&o3); EXPECT_EQ(123, f3->value()); EXPECT_NE(f2, f3); const absl::any o4(4); absl::any o5 = o4; EXPECT_EQ(4, absl::any_cast<int>(o4)); EXPECT_EQ(4, absl::any_cast<int>(o5)); absl::any o6 = std::move(o4); EXPECT_EQ(4, absl::any_cast<int>(o4)); EXPECT_EQ(4, absl::any_cast<int>(o6)); } } TEST(AnyTest, Move) { InstanceTracker tracker_raii; absl::any any1; any1.emplace<CopyableOnlyInstance>(5); absl::any any2 = any1; EXPECT_EQ(5, absl::any_cast<CopyableOnlyInstance&>(any1).value()); EXPECT_EQ(5, absl::any_cast<CopyableOnlyInstance&>(any2).value()); EXPECT_EQ(1, tracker_raii.copies()); absl::any any3 = std::move(any2); EXPECT_EQ(5, absl::any_cast<CopyableOnlyInstance&>(any3).value()); EXPECT_EQ(1, tracker_raii.copies()); absl::any any4; any4 = std::move(any3); EXPECT_EQ(5, absl::any_cast<CopyableOnlyInstance&>(any4).value()); EXPECT_EQ(1, tracker_raii.copies()); absl::any tmp4(4); absl::any o4(std::move(tmp4)); EXPECT_EQ(4, absl::any_cast<int>(o4)); o4 = *&o4; EXPECT_EQ(4, absl::any_cast<int>(o4)); EXPECT_TRUE(o4.has_value()); absl::any o5; absl::any tmp5(5); o5 = std::move(tmp5); EXPECT_EQ(5, absl::any_cast<int>(o5)); } TEST(AnyTest, Reset) { absl::any o; o.emplace<int>(); o.reset(); EXPECT_FALSE(o.has_value()); o.emplace<char>(); EXPECT_TRUE(o.has_value()); } TEST(AnyTest, ConversionConstructionCausesOneCopy) { InstanceTracker tracker_raii; CopyableOnlyInstance counter(5); absl::any o(counter); EXPECT_EQ(5, absl::any_cast<CopyableOnlyInstance&>(o).value()); EXPECT_EQ(1, tracker_raii.copies()); } #if defined(ABSL_USES_STD_ANY) #define ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(...) \ ABSL_BASE_INTERNAL_EXPECT_FAIL((__VA_ARGS__), absl::bad_any_cast, \ "") #else #define ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(...) \ ABSL_BASE_INTERNAL_EXPECT_FAIL((__VA_ARGS__), absl::bad_any_cast, \ "Bad any cast") #endif TEST(AnyTest, ThrowBadAlloc) { { absl::any a; ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<int&>(a)); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<const int&>(a)); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<int&&>(absl::any{})); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<const int&&>(absl::any{})); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<int>(a)); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<const int>(a)); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<int>(absl::any{})); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<const int>(absl::any{})); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<const int&>(AsConst(a))); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<int>(AsConst(a))); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<const int>(AsConst(a))); } { absl::any a(absl::in_place_type<int>); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<float&>(a)); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<const float&>(a)); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<float&&>(absl::any{})); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST( absl::any_cast<const float&&>(absl::any{})); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<float>(a)); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<const float>(a)); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<float>(absl::any{})); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<const float>(absl::any{})); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<const float&>(AsConst(a))); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<float>(AsConst(a))); ABSL_ANY_TEST_EXPECT_BAD_ANY_CAST(absl::any_cast<const float>(AsConst(a))); } } class BadCopy {}; struct BadCopyable { BadCopyable() = default; BadCopyable(BadCopyable&&) = default; BadCopyable(const BadCopyable&) { #ifdef ABSL_HAVE_EXCEPTIONS throw BadCopy(); #else LOG(FATAL) << "Bad copy"; #endif } }; #define ABSL_ANY_TEST_EXPECT_BAD_COPY(...) \ ABSL_BASE_INTERNAL_EXPECT_FAIL((__VA_ARGS__), BadCopy, "Bad copy") TEST(AnyTest, FailedCopy) { { const BadCopyable bad{}; ABSL_ANY_TEST_EXPECT_BAD_COPY(absl::any{bad}); } { absl::any src(absl::in_place_type<BadCopyable>); ABSL_ANY_TEST_EXPECT_BAD_COPY(absl::any{src}); } { BadCopyable bad; absl::any target; ABSL_ANY_TEST_EXPECT_BAD_COPY(target = bad); } { BadCopyable bad; absl::any target(absl::in_place_type<BadCopyable>); ABSL_ANY_TEST_EXPECT_BAD_COPY(target = bad); EXPECT_TRUE(target.has_value()); } { absl::any src(absl::in_place_type<BadCopyable>); absl::any target; ABSL_ANY_TEST_EXPECT_BAD_COPY(target = src); EXPECT_FALSE(target.has_value()); } { absl::any src(absl::in_place_type<BadCopyable>); absl::any target(absl::in_place_type<BadCopyable>); ABSL_ANY_TEST_EXPECT_BAD_COPY(target = src); EXPECT_TRUE(target.has_value()); } } TEST(AnyTest, FailedEmplace) { BadCopyable bad; absl::any target; ABSL_ANY_TEST_EXPECT_BAD_COPY(target.emplace<BadCopyable>(bad)); } #ifdef __GNUC__ TEST(AnyTest, DISABLED_FailedEmplaceInPlace) { #else TEST(AnyTest, FailedEmplaceInPlace) { #endif BadCopyable bad; absl::any target(absl::in_place_type<int>); ABSL_ANY_TEST_EXPECT_BAD_COPY(target.emplace<BadCopyable>(bad)); EXPECT_FALSE(target.has_value()); } } #endif
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/types/any.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/types/any_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
21f6d857-ce15-46d1-8170-184759908803
cpp
abseil/abseil-cpp
variant
absl/types/internal/variant.h
absl/types/variant_test.cc
#ifndef ABSL_TYPES_INTERNAL_VARIANT_H_ #define ABSL_TYPES_INTERNAL_VARIANT_H_ #include <cassert> #include <cstddef> #include <cstdlib> #include <memory> #include <stdexcept> #include <tuple> #include <type_traits> #include <utility> #include "absl/base/config.h" #include "absl/base/internal/identity.h" #include "absl/base/internal/inline_variable.h" #include "absl/base/internal/invoke.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/meta/type_traits.h" #include "absl/types/bad_variant_access.h" #include "absl/utility/utility.h" #if !defined(ABSL_USES_STD_VARIANT) namespace absl { ABSL_NAMESPACE_BEGIN template <class... Types> class variant; ABSL_INTERNAL_INLINE_CONSTEXPR(size_t, variant_npos, static_cast<size_t>(-1)); template <class T> struct variant_size; template <std::size_t I, class T> struct variant_alternative; namespace variant_internal { template <std::size_t I, class T> struct VariantAlternativeSfinae {}; template <std::size_t I, class T0, class... Tn> struct VariantAlternativeSfinae<I, variant<T0, Tn...>> : VariantAlternativeSfinae<I - 1, variant<Tn...>> {}; template <class T0, class... Ts> struct VariantAlternativeSfinae<0, variant<T0, Ts...>> { using type = T0; }; template <std::size_t I, class T> using VariantAlternativeSfinaeT = typename VariantAlternativeSfinae<I, T>::type; template <class T, class U> struct GiveQualsTo; template <class T, class U> struct GiveQualsTo<T&, U> { using type = U&; }; template <class T, class U> struct GiveQualsTo<T&&, U> { using type = U&&; }; template <class T, class U> struct GiveQualsTo<const T&, U> { using type = const U&; }; template <class T, class U> struct GiveQualsTo<const T&&, U> { using type = const U&&; }; template <class T, class U> struct GiveQualsTo<volatile T&, U> { using type = volatile U&; }; template <class T, class U> struct GiveQualsTo<volatile T&&, U> { using type = volatile U&&; }; template <class T, class U> struct GiveQualsTo<volatile const T&, U> { using type = volatile const U&; }; template <class T, class U> struct GiveQualsTo<volatile const T&&, U> { using type = volatile const U&&; }; template <class T, class U> using GiveQualsToT = typename GiveQualsTo<T, U>::type; template <std::size_t I> using SizeT = std::integral_constant<std::size_t, I>; using NPos = SizeT<variant_npos>; template <class Variant, class T, class = void> struct IndexOfConstructedType {}; template <std::size_t I, class Variant> struct VariantAccessResultImpl; template <std::size_t I, template <class...> class Variantemplate, class... T> struct VariantAccessResultImpl<I, Variantemplate<T...>&> { using type = typename absl::variant_alternative<I, variant<T...>>::type&; }; template <std::size_t I, template <class...> class Variantemplate, class... T> struct VariantAccessResultImpl<I, const Variantemplate<T...>&> { using type = const typename absl::variant_alternative<I, variant<T...>>::type&; }; template <std::size_t I, template <class...> class Variantemplate, class... T> struct VariantAccessResultImpl<I, Variantemplate<T...>&&> { using type = typename absl::variant_alternative<I, variant<T...>>::type&&; }; template <std::size_t I, template <class...> class Variantemplate, class... T> struct VariantAccessResultImpl<I, const Variantemplate<T...>&&> { using type = const typename absl::variant_alternative<I, variant<T...>>::type&&; }; template <std::size_t I, class Variant> using VariantAccessResult = typename VariantAccessResultImpl<I, Variant&&>::type; template <class T, std::size_t Size> struct SimpleArray { static_assert(Size != 0, ""); T value[Size]; }; template <class T> struct AccessedType { using type = T; }; template <class T> using AccessedTypeT = typename AccessedType<T>::type; template <class T, std::size_t Size> struct AccessedType<SimpleArray<T, Size>> { using type = AccessedTypeT<T>; }; template <class T> constexpr T AccessSimpleArray(const T& value) { return value; } template <class T, std::size_t Size, class... SizeT> constexpr AccessedTypeT<T> AccessSimpleArray(const SimpleArray<T, Size>& table, std::size_t head_index, SizeT... tail_indices) { return AccessSimpleArray(table.value[head_index], tail_indices...); } template <class T> using AlwaysZero = SizeT<0>; template <class Op, class... Vs> struct VisitIndicesResultImpl { using type = absl::result_of_t<Op(AlwaysZero<Vs>...)>; }; template <class Op, class... Vs> using VisitIndicesResultT = typename VisitIndicesResultImpl<Op, Vs...>::type; template <class ReturnType, class FunctionObject, class EndIndices, class BoundIndices> struct MakeVisitationMatrix; template <class ReturnType, class FunctionObject, std::size_t... Indices> constexpr ReturnType call_with_indices(FunctionObject&& function) { static_assert( std::is_same<ReturnType, decltype(std::declval<FunctionObject>()( SizeT<Indices>()...))>::value, "Not all visitation overloads have the same return type."); return std::forward<FunctionObject>(function)(SizeT<Indices>()...); } template <class ReturnType, class FunctionObject, std::size_t... BoundIndices> struct MakeVisitationMatrix<ReturnType, FunctionObject, index_sequence<>, index_sequence<BoundIndices...>> { using ResultType = ReturnType (*)(FunctionObject&&); static constexpr ResultType Run() { return &call_with_indices<ReturnType, FunctionObject, (BoundIndices - 1)...>; } }; template <typename Is, std::size_t J> struct AppendToIndexSequence; template <typename Is, std::size_t J> using AppendToIndexSequenceT = typename AppendToIndexSequence<Is, J>::type; template <std::size_t... Is, std::size_t J> struct AppendToIndexSequence<index_sequence<Is...>, J> { using type = index_sequence<Is..., J>; }; template <class ReturnType, class FunctionObject, class EndIndices, class CurrIndices, class BoundIndices> struct MakeVisitationMatrixImpl; template <class ReturnType, class FunctionObject, class EndIndices, std::size_t... CurrIndices, class BoundIndices> struct MakeVisitationMatrixImpl<ReturnType, FunctionObject, EndIndices, index_sequence<CurrIndices...>, BoundIndices> { using ResultType = SimpleArray< typename MakeVisitationMatrix<ReturnType, FunctionObject, EndIndices, index_sequence<>>::ResultType, sizeof...(CurrIndices)>; static constexpr ResultType Run() { return {{MakeVisitationMatrix< ReturnType, FunctionObject, EndIndices, AppendToIndexSequenceT<BoundIndices, CurrIndices>>::Run()...}}; } }; template <class ReturnType, class FunctionObject, std::size_t HeadEndIndex, std::size_t... TailEndIndices, std::size_t... BoundIndices> struct MakeVisitationMatrix<ReturnType, FunctionObject, index_sequence<HeadEndIndex, TailEndIndices...>, index_sequence<BoundIndices...>> : MakeVisitationMatrixImpl<ReturnType, FunctionObject, index_sequence<TailEndIndices...>, absl::make_index_sequence<HeadEndIndex>, index_sequence<BoundIndices...>> {}; struct UnreachableSwitchCase { template <class Op> [[noreturn]] static VisitIndicesResultT<Op, std::size_t> Run( Op&& ) { ABSL_UNREACHABLE(); } }; template <class Op, std::size_t I> struct ReachableSwitchCase { static VisitIndicesResultT<Op, std::size_t> Run(Op&& op) { return absl::base_internal::invoke(std::forward<Op>(op), SizeT<I>()); } }; ABSL_INTERNAL_INLINE_CONSTEXPR(std::size_t, MaxUnrolledVisitCases, 33); template <bool IsReachable> struct PickCaseImpl { template <class Op, std::size_t I> using Apply = UnreachableSwitchCase; }; template <> struct PickCaseImpl<true> { template <class Op, std::size_t I> using Apply = ReachableSwitchCase<Op, I>; }; template <class Op, std::size_t I, std::size_t EndIndex> using PickCase = typename PickCaseImpl<(I < EndIndex)>::template Apply<Op, I>; template <class ReturnType> [[noreturn]] ReturnType TypedThrowBadVariantAccess() { absl::variant_internal::ThrowBadVariantAccess(); } template <std::size_t... NumAlternatives> struct NumCasesOfSwitch; template <std::size_t HeadNumAlternatives, std::size_t... TailNumAlternatives> struct NumCasesOfSwitch<HeadNumAlternatives, TailNumAlternatives...> { static constexpr std::size_t value = (HeadNumAlternatives + 1) * NumCasesOfSwitch<TailNumAlternatives...>::value; }; template <> struct NumCasesOfSwitch<> { static constexpr std::size_t value = 1; }; template <std::size_t EndIndex> struct VisitIndicesSwitch { static_assert(EndIndex <= MaxUnrolledVisitCases, "Maximum unrolled switch size exceeded."); template <class Op> static VisitIndicesResultT<Op, std::size_t> Run(Op&& op, std::size_t i) { switch (i) { case 0: return PickCase<Op, 0, EndIndex>::Run(std::forward<Op>(op)); case 1: return PickCase<Op, 1, EndIndex>::Run(std::forward<Op>(op)); case 2: return PickCase<Op, 2, EndIndex>::Run(std::forward<Op>(op)); case 3: return PickCase<Op, 3, EndIndex>::Run(std::forward<Op>(op)); case 4: return PickCase<Op, 4, EndIndex>::Run(std::forward<Op>(op)); case 5: return PickCase<Op, 5, EndIndex>::Run(std::forward<Op>(op)); case 6: return PickCase<Op, 6, EndIndex>::Run(std::forward<Op>(op)); case 7: return PickCase<Op, 7, EndIndex>::Run(std::forward<Op>(op)); case 8: return PickCase<Op, 8, EndIndex>::Run(std::forward<Op>(op)); case 9: return PickCase<Op, 9, EndIndex>::Run(std::forward<Op>(op)); case 10: return PickCase<Op, 10, EndIndex>::Run(std::forward<Op>(op)); case 11: return PickCase<Op, 11, EndIndex>::Run(std::forward<Op>(op)); case 12: return PickCase<Op, 12, EndIndex>::Run(std::forward<Op>(op)); case 13: return PickCase<Op, 13, EndIndex>::Run(std::forward<Op>(op)); case 14: return PickCase<Op, 14, EndIndex>::Run(std::forward<Op>(op)); case 15: return PickCase<Op, 15, EndIndex>::Run(std::forward<Op>(op)); case 16: return PickCase<Op, 16, EndIndex>::Run(std::forward<Op>(op)); case 17: return PickCase<Op, 17, EndIndex>::Run(std::forward<Op>(op)); case 18: return PickCase<Op, 18, EndIndex>::Run(std::forward<Op>(op)); case 19: return PickCase<Op, 19, EndIndex>::Run(std::forward<Op>(op)); case 20: return PickCase<Op, 20, EndIndex>::Run(std::forward<Op>(op)); case 21: return PickCase<Op, 21, EndIndex>::Run(std::forward<Op>(op)); case 22: return PickCase<Op, 22, EndIndex>::Run(std::forward<Op>(op)); case 23: return PickCase<Op, 23, EndIndex>::Run(std::forward<Op>(op)); case 24: return PickCase<Op, 24, EndIndex>::Run(std::forward<Op>(op)); case 25: return PickCase<Op, 25, EndIndex>::Run(std::forward<Op>(op)); case 26: return PickCase<Op, 26, EndIndex>::Run(std::forward<Op>(op)); case 27: return PickCase<Op, 27, EndIndex>::Run(std::forward<Op>(op)); case 28: return PickCase<Op, 28, EndIndex>::Run(std::forward<Op>(op)); case 29: return PickCase<Op, 29, EndIndex>::Run(std::forward<Op>(op)); case 30: return PickCase<Op, 30, EndIndex>::Run(std::forward<Op>(op)); case 31: return PickCase<Op, 31, EndIndex>::Run(std::forward<Op>(op)); case 32: return PickCase<Op, 32, EndIndex>::Run(std::forward<Op>(op)); default: ABSL_ASSERT(i == variant_npos); return absl::base_internal::invoke(std::forward<Op>(op), NPos()); } } }; template <std::size_t... EndIndices> struct VisitIndicesFallback { template <class Op, class... SizeT> static VisitIndicesResultT<Op, SizeT...> Run(Op&& op, SizeT... indices) { return AccessSimpleArray( MakeVisitationMatrix<VisitIndicesResultT<Op, SizeT...>, Op, index_sequence<(EndIndices + 1)...>, index_sequence<>>::Run(), (indices + 1)...)(std::forward<Op>(op)); } }; template <std::size_t...> struct FlattenIndices; template <std::size_t HeadSize, std::size_t... TailSize> struct FlattenIndices<HeadSize, TailSize...> { template <class... SizeType> static constexpr std::size_t Run(std::size_t head, SizeType... tail) { return head + HeadSize * FlattenIndices<TailSize...>::Run(tail...); } }; template <> struct FlattenIndices<> { static constexpr std::size_t Run() { return 0; } }; template <std::size_t I, std::size_t IndexToGet, std::size_t HeadSize, std::size_t... TailSize> struct UnflattenIndex { static constexpr std::size_t value = UnflattenIndex<I / HeadSize, IndexToGet - 1, TailSize...>::value; }; template <std::size_t I, std::size_t HeadSize, std::size_t... TailSize> struct UnflattenIndex<I, 0, HeadSize, TailSize...> { static constexpr std::size_t value = (I % HeadSize); }; template <class IndexSequence, std::size_t... EndIndices> struct VisitIndicesVariadicImpl; template <std::size_t... N, std::size_t... EndIndices> struct VisitIndicesVariadicImpl<absl::index_sequence<N...>, EndIndices...> { template <class Op> struct FlattenedOp { template <std::size_t I> VisitIndicesResultT<Op, decltype(EndIndices)...> operator()( SizeT<I> ) && { return base_internal::invoke( std::forward<Op>(op), SizeT<UnflattenIndex<I, N, (EndIndices + 1)...>::value - std::size_t{1}>()...); } Op&& op; }; template <class Op, class... SizeType> static VisitIndicesResultT<Op, decltype(EndIndices)...> Run(Op&& op, SizeType... i) { return VisitIndicesSwitch<NumCasesOfSwitch<EndIndices...>::value>::Run( FlattenedOp<Op>{std::forward<Op>(op)}, FlattenIndices<(EndIndices + std::size_t{1})...>::Run( (i + std::size_t{1})...)); } }; template <std::size_t... EndIndices> struct VisitIndicesVariadic : VisitIndicesVariadicImpl<absl::make_index_sequence<sizeof...(EndIndices)>, EndIndices...> {}; template <std::size_t... EndIndices> struct VisitIndices : absl::conditional_t<(NumCasesOfSwitch<EndIndices...>::value <= MaxUnrolledVisitCases), VisitIndicesVariadic<EndIndices...>, VisitIndicesFallback<EndIndices...>> {}; template <std::size_t EndIndex> struct VisitIndices<EndIndex> : absl::conditional_t<(EndIndex <= MaxUnrolledVisitCases), VisitIndicesSwitch<EndIndex>, VisitIndicesFallback<EndIndex>> {}; #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4172) #endif template <class Self, std::size_t I> inline VariantAccessResult<I, Self> AccessUnion(Self&& self, SizeT<I> ) { return reinterpret_cast<VariantAccessResult<I, Self>>(self); } #ifdef _MSC_VER #pragma warning(pop) #endif template <class T> void DeducedDestroy(T& self) { self.~T(); } struct VariantCoreAccess { template <class VariantType> static typename VariantType::Variant& Derived(VariantType& self) { return static_cast<typename VariantType::Variant&>(self); } template <class VariantType> static const typename VariantType::Variant& Derived( const VariantType& self) { return static_cast<const typename VariantType::Variant&>(self); } template <class VariantType> static void Destroy(VariantType& self) { Derived(self).destroy(); self.index_ = absl::variant_npos; } template <class Variant> static void SetIndex(Variant& self, std::size_t i) { self.index_ = i; } template <class Variant> static void InitFrom(Variant& self, Variant&& other) { VisitIndices<absl::variant_size<Variant>::value>::Run( InitFromVisitor<Variant, Variant&&>{&self, std::forward<Variant>(other)}, other.index()); self.index_ = other.index(); } template <std::size_t I, class Variant> static VariantAccessResult<I, Variant> Access(Variant&& self) { return static_cast<VariantAccessResult<I, Variant>>( variant_internal::AccessUnion(self.state_, SizeT<I>())); } template <std::size_t I, class Variant> static VariantAccessResult<I, Variant> CheckedAccess(Variant&& self) { if (ABSL_PREDICT_FALSE(self.index_ != I)) { TypedThrowBadVariantAccess<VariantAccessResult<I, Variant>>(); } return Access<I>(std::forward<Variant>(self)); } template <class VType> struct MoveAssignVisitor { using DerivedType = typename VType::Variant; template <std::size_t NewIndex> void operator()(SizeT<NewIndex> ) const { if (left->index_ == NewIndex) { Access<NewIndex>(*left) = std::move(Access<NewIndex>(*right)); } else { Derived(*left).template emplace<NewIndex>( std::move(Access<NewIndex>(*right))); } } void operator()(SizeT<absl::variant_npos> ) const { Destroy(*left); } VType* left; VType* right; }; template <class VType> static MoveAssignVisitor<VType> MakeMoveAssignVisitor(VType* left, VType* other) { return {left, other}; } template <class VType> struct CopyAssignVisitor { using DerivedType = typename VType::Variant; template <std::size_t NewIndex> void operator()(SizeT<NewIndex> ) const { using New = typename absl::variant_alternative<NewIndex, DerivedType>::type; if (left->index_ == NewIndex) { Access<NewIndex>(*left) = Access<NewIndex>(*right); } else if (std::is_nothrow_copy_constructible<New>::value || !std::is_nothrow_move_constructible<New>::value) { Derived(*left).template emplace<NewIndex>(Access<NewIndex>(*right)); } else { Derived(*left) = DerivedType(Derived(*right)); } } void operator()(SizeT<absl::variant_npos> ) const { Destroy(*left); } VType* left; const VType* right; }; template <class VType> static CopyAssignVisitor<VType> MakeCopyAssignVisitor(VType* left, const VType& other) { return {left, &other}; } template <class Left, class QualifiedNew> struct ConversionAssignVisitor { using NewIndex = variant_internal::IndexOfConstructedType<Left, QualifiedNew>; void operator()(SizeT<NewIndex::value> ) const { Access<NewIndex::value>(*left) = std::forward<QualifiedNew>(other); } template <std::size_t OldIndex> void operator()(SizeT<OldIndex> ) const { using New = typename absl::variant_alternative<NewIndex::value, Left>::type; if (std::is_nothrow_constructible<New, QualifiedNew>::value || !std::is_nothrow_move_constructible<New>::value) { left->template emplace<NewIndex::value>( std::forward<QualifiedNew>(other)); } else { left->template emplace<NewIndex::value>( New(std::forward<QualifiedNew>(other))); } } Left* left; QualifiedNew&& other; }; template <class Left, class QualifiedNew> static ConversionAssignVisitor<Left, QualifiedNew> MakeConversionAssignVisitor(Left* left, QualifiedNew&& qual) { return {left, std::forward<QualifiedNew>(qual)}; } template <std::size_t NewIndex, class Self, class... Args> static typename absl::variant_alternative<NewIndex, Self>::type& Replace( Self* self, Args&&... args) { Destroy(*self); using New = typename absl::variant_alternative<NewIndex, Self>::type; New* const result = ::new (static_cast<void*>(&self->state_)) New(std::forward<Args>(args)...); self->index_ = NewIndex; return *result; } template <class LeftVariant, class QualifiedRightVariant> struct InitFromVisitor { template <std::size_t NewIndex> void operator()(SizeT<NewIndex> ) const { using Alternative = typename variant_alternative<NewIndex, LeftVariant>::type; ::new (static_cast<void*>(&left->state_)) Alternative( Access<NewIndex>(std::forward<QualifiedRightVariant>(right))); } void operator()(SizeT<absl::variant_npos> ) const { } LeftVariant* left; QualifiedRightVariant&& right; }; }; template <class Expected, class... T> struct IndexOfImpl; template <class Expected> struct IndexOfImpl<Expected> { using IndexFromEnd = SizeT<0>; using MatchedIndexFromEnd = IndexFromEnd; using MultipleMatches = std::false_type; }; template <class Expected, class Head, class... Tail> struct IndexOfImpl<Expected, Head, Tail...> : IndexOfImpl<Expected, Tail...> { using IndexFromEnd = SizeT<IndexOfImpl<Expected, Tail...>::IndexFromEnd::value + 1>; }; template <class Expected, class... Tail> struct IndexOfImpl<Expected, Expected, Tail...> : IndexOfImpl<Expected, Tail...> { using IndexFromEnd = SizeT<IndexOfImpl<Expected, Tail...>::IndexFromEnd::value + 1>; using MatchedIndexFromEnd = IndexFromEnd; using MultipleMatches = std::integral_constant< bool, IndexOfImpl<Expected, Tail...>::MatchedIndexFromEnd::value != 0>; }; template <class Expected, class... Types> struct IndexOfMeta { using Results = IndexOfImpl<Expected, Types...>; static_assert(!Results::MultipleMatches::value, "Attempted to access a variant by specifying a type that " "matches more than one alternative."); static_assert(Results::MatchedIndexFromEnd::value != 0, "Attempted to access a variant by specifying a type that does " "not match any alternative."); using type = SizeT<sizeof...(Types) - Results::MatchedIndexFromEnd::value>; }; template <class Expected, class... Types> using IndexOf = typename IndexOfMeta<Expected, Types...>::type; template <class Variant, class T, std::size_t CurrIndex> struct UnambiguousIndexOfImpl; template <class T, std::size_t CurrIndex> struct UnambiguousIndexOfImpl<variant<>, T, CurrIndex> : SizeT<CurrIndex> {}; template <class Head, class... Tail, class T, std::size_t CurrIndex> struct UnambiguousIndexOfImpl<variant<Head, Tail...>, T, CurrIndex> : UnambiguousIndexOfImpl<variant<Tail...>, T, CurrIndex + 1>::type {}; template <class Head, class... Tail, std::size_t CurrIndex> struct UnambiguousIndexOfImpl<variant<Head, Tail...>, Head, CurrIndex> : SizeT<UnambiguousIndexOfImpl<variant<Tail...>, Head, 0>::value == sizeof...(Tail) ? CurrIndex : CurrIndex + sizeof...(Tail) + 1> {}; template <class Variant, class T> struct UnambiguousIndexOf; struct NoMatch { struct type {}; }; template <class... Alts, class T> struct UnambiguousIndexOf<variant<Alts...>, T> : std::conditional<UnambiguousIndexOfImpl<variant<Alts...>, T, 0>::value != sizeof...(Alts), UnambiguousIndexOfImpl<variant<Alts...>, T, 0>, NoMatch>::type::type {}; template <class T, std::size_t > using UnambiguousTypeOfImpl = T; template <class Variant, class T> using UnambiguousTypeOfT = UnambiguousTypeOfImpl<T, UnambiguousIndexOf<Variant, T>::value>; template <class H, class... T> class VariantStateBase; template <class Variant, std::size_t I = 0> struct ImaginaryFun; template <std::size_t I> struct ImaginaryFun<variant<>, I> { static void Run() = delete; }; template <class H, class... T, std::size_t I> struct ImaginaryFun<variant<H, T...>, I> : ImaginaryFun<variant<T...>, I + 1> { using ImaginaryFun<variant<T...>, I + 1>::Run; static SizeT<I> Run(const H&, SizeT<I>); static SizeT<I> Run(H&&, SizeT<I>); }; template <class Self, class T> struct IsNeitherSelfNorInPlace : std::true_type {}; template <class Self> struct IsNeitherSelfNorInPlace<Self, Self> : std::false_type {}; template <class Self, class T> struct IsNeitherSelfNorInPlace<Self, in_place_type_t<T>> : std::false_type {}; template <class Self, std::size_t I> struct IsNeitherSelfNorInPlace<Self, in_place_index_t<I>> : std::false_type {}; template <class Variant, class T> struct IndexOfConstructedType< Variant, T, void_t<decltype(ImaginaryFun<Variant>::Run(std::declval<T>(), {}))>> : decltype(ImaginaryFun<Variant>::Run(std::declval<T>(), {})) {}; template <std::size_t... Is> struct ContainsVariantNPos : absl::negation<std::is_same< std::integer_sequence<bool, 0 <= Is...>, std::integer_sequence<bool, Is != absl::variant_npos...>>> {}; template <class Op, class... QualifiedVariants> using RawVisitResult = absl::result_of_t<Op(VariantAccessResult<0, QualifiedVariants>...)>; template <class Op, class... QualifiedVariants> struct VisitResultImpl { using type = absl::result_of_t<Op(VariantAccessResult<0, QualifiedVariants>...)>; }; template <class Op, class... QualifiedVariants> using VisitResult = typename VisitResultImpl<Op, QualifiedVariants...>::type; template <class Op, class... QualifiedVariants> struct PerformVisitation { using ReturnType = VisitResult<Op, QualifiedVariants...>; template <std::size_t... Is> constexpr ReturnType operator()(SizeT<Is>... indices) const { return Run(typename ContainsVariantNPos<Is...>::type{}, absl::index_sequence_for<QualifiedVariants...>(), indices...); } template <std::size_t... TupIs, std::size_t... Is> constexpr ReturnType Run(std::false_type , index_sequence<TupIs...>, SizeT<Is>...) const { static_assert( std::is_same<ReturnType, absl::result_of_t<Op(VariantAccessResult< Is, QualifiedVariants>...)>>::value, "All visitation overloads must have the same return type."); return absl::base_internal::invoke( std::forward<Op>(op), VariantCoreAccess::Access<Is>( std::forward<QualifiedVariants>(std::get<TupIs>(variant_tup)))...); } template <std::size_t... TupIs, std::size_t... Is> [[noreturn]] ReturnType Run(std::true_type , index_sequence<TupIs...>, SizeT<Is>...) const { absl::variant_internal::ThrowBadVariantAccess(); } std::tuple<QualifiedVariants&&...> variant_tup; Op&& op; }; template <class... T> union Union; struct NoopConstructorTag {}; template <std::size_t I> struct EmplaceTag {}; template <> union Union<> { constexpr explicit Union(NoopConstructorTag) noexcept {} }; #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4624) #endif template <class Head, class... Tail> union Union<Head, Tail...> { using TailUnion = Union<Tail...>; explicit constexpr Union(NoopConstructorTag ) noexcept : tail(NoopConstructorTag()) {} template <class... P> explicit constexpr Union(EmplaceTag<0>, P&&... args) : head(std::forward<P>(args)...) {} template <std::size_t I, class... P> explicit constexpr Union(EmplaceTag<I>, P&&... args) : tail(EmplaceTag<I - 1>{}, std::forward<P>(args)...) {} Head head; TailUnion tail; }; #ifdef _MSC_VER #pragma warning(pop) #endif template <class... T> union DestructibleUnionImpl; template <> union DestructibleUnionImpl<> { constexpr explicit DestructibleUnionImpl(NoopConstructorTag) noexcept {} }; template <class Head, class... Tail> union DestructibleUnionImpl<Head, Tail...> { using TailUnion = DestructibleUnionImpl<Tail...>; explicit constexpr DestructibleUnionImpl(NoopConstructorTag ) noexcept : tail(NoopConstructorTag()) {} template <class... P> explicit constexpr DestructibleUnionImpl(EmplaceTag<0>, P&&... args) : head(std::forward<P>(args)...) {} template <std::size_t I, class... P> explicit constexpr DestructibleUnionImpl(EmplaceTag<I>, P&&... args) : tail(EmplaceTag<I - 1>{}, std::forward<P>(args)...) {} ~DestructibleUnionImpl() {} Head head; TailUnion tail; }; template <class... T> using DestructibleUnion = absl::conditional_t<std::is_destructible<Union<T...>>::value, Union<T...>, DestructibleUnionImpl<T...>>; template <class H, class... T> class VariantStateBase { protected: using Variant = variant<H, T...>; template <class LazyH = H, class ConstructibleH = absl::enable_if_t< std::is_default_constructible<LazyH>::value, LazyH>> constexpr VariantStateBase() noexcept( std::is_nothrow_default_constructible<ConstructibleH>::value) : state_(EmplaceTag<0>()), index_(0) {} template <std::size_t I, class... P> explicit constexpr VariantStateBase(EmplaceTag<I> tag, P&&... args) : state_(tag, std::forward<P>(args)...), index_(I) {} explicit constexpr VariantStateBase(NoopConstructorTag) : state_(NoopConstructorTag()), index_(variant_npos) {} void destroy() {} DestructibleUnion<H, T...> state_; std::size_t index_; }; using absl::internal::type_identity; template <typename... Ts> struct OverloadSet; template <typename T, typename... Ts> struct OverloadSet<T, Ts...> : OverloadSet<Ts...> { using Base = OverloadSet<Ts...>; static type_identity<T> Overload(const T&); using Base::Overload; }; template <> struct OverloadSet<> { static void Overload(...); }; template <class T> using LessThanResult = decltype(std::declval<T>() < std::declval<T>()); template <class T> using GreaterThanResult = decltype(std::declval<T>() > std::declval<T>()); template <class T> using LessThanOrEqualResult = decltype(std::declval<T>() <= std::declval<T>()); template <class T> using GreaterThanOrEqualResult = decltype(std::declval<T>() >= std::declval<T>()); template <class T> using EqualResult = decltype(std::declval<T>() == std::declval<T>()); template <class T> using NotEqualResult = decltype(std::declval<T>() != std::declval<T>()); using type_traits_internal::is_detected_convertible; template <class... T> using RequireAllHaveEqualT = absl::enable_if_t< absl::conjunction<is_detected_convertible<bool, EqualResult, T>...>::value, bool>; template <class... T> using RequireAllHaveNotEqualT = absl::enable_if_t<absl::conjunction<is_detected_convertible< bool, NotEqualResult, T>...>::value, bool>; template <class... T> using RequireAllHaveLessThanT = absl::enable_if_t<absl::conjunction<is_detected_convertible< bool, LessThanResult, T>...>::value, bool>; template <class... T> using RequireAllHaveLessThanOrEqualT = absl::enable_if_t<absl::conjunction<is_detected_convertible< bool, LessThanOrEqualResult, T>...>::value, bool>; template <class... T> using RequireAllHaveGreaterThanOrEqualT = absl::enable_if_t<absl::conjunction<is_detected_convertible< bool, GreaterThanOrEqualResult, T>...>::value, bool>; template <class... T> using RequireAllHaveGreaterThanT = absl::enable_if_t<absl::conjunction<is_detected_convertible< bool, GreaterThanResult, T>...>::value, bool>; template <typename T> struct VariantHelper; template <typename... Ts> struct VariantHelper<variant<Ts...>> { template <typename U> using BestMatch = decltype(variant_internal::OverloadSet<Ts...>::Overload( std::declval<U>())); template <typename U> struct CanAccept : std::integral_constant<bool, !std::is_void<BestMatch<U>>::value> {}; template <typename Other> struct CanConvertFrom; template <typename... Us> struct CanConvertFrom<variant<Us...>> : public absl::conjunction<CanAccept<Us>...> {}; }; struct TrivialMoveOnly { TrivialMoveOnly(TrivialMoveOnly&&) = default; }; template <typename T> struct IsTriviallyMoveConstructible : std::is_move_constructible<Union<T, TrivialMoveOnly>> {}; template <class... T> class VariantStateBaseDestructorNontrivial; template <class... T> class VariantMoveBaseNontrivial; template <class... T> class VariantCopyBaseNontrivial; template <class... T> class VariantMoveAssignBaseNontrivial; template <class... T> class VariantCopyAssignBaseNontrivial; template <class... T> using VariantStateBaseDestructor = absl::conditional_t<std::is_destructible<Union<T...>>::value, VariantStateBase<T...>, VariantStateBaseDestructorNontrivial<T...>>; template <class... T> using VariantMoveBase = absl::conditional_t< absl::disjunction< absl::negation<absl::conjunction<std::is_move_constructible<T>...>>, absl::conjunction<IsTriviallyMoveConstructible<T>...>>::value, VariantStateBaseDestructor<T...>, VariantMoveBaseNontrivial<T...>>; template <class... T> using VariantCopyBase = absl::conditional_t< absl::disjunction< absl::negation<absl::conjunction<std::is_copy_constructible<T>...>>, std::is_copy_constructible<Union<T...>>>::value, VariantMoveBase<T...>, VariantCopyBaseNontrivial<T...>>; template <class... T> using VariantMoveAssignBase = absl::conditional_t< absl::disjunction< absl::conjunction<absl::is_move_assignable<Union<T...>>, std::is_move_constructible<Union<T...>>, std::is_destructible<Union<T...>>>, absl::negation<absl::conjunction<std::is_move_constructible<T>..., is_move_assignable<T>...>>>::value, VariantCopyBase<T...>, VariantMoveAssignBaseNontrivial<T...>>; template <class... T> using VariantCopyAssignBase = absl::conditional_t< absl::disjunction< absl::conjunction<absl::is_copy_assignable<Union<T...>>, std::is_copy_constructible<Union<T...>>, std::is_destructible<Union<T...>>>, absl::negation<absl::conjunction<std::is_copy_constructible<T>..., is_copy_assignable<T>...>>>::value, VariantMoveAssignBase<T...>, VariantCopyAssignBaseNontrivial<T...>>; template <class... T> using VariantBase = VariantCopyAssignBase<T...>; template <class... T> class VariantStateBaseDestructorNontrivial : protected VariantStateBase<T...> { private: using Base = VariantStateBase<T...>; protected: using Base::Base; VariantStateBaseDestructorNontrivial() = default; VariantStateBaseDestructorNontrivial(VariantStateBaseDestructorNontrivial&&) = default; VariantStateBaseDestructorNontrivial( const VariantStateBaseDestructorNontrivial&) = default; VariantStateBaseDestructorNontrivial& operator=( VariantStateBaseDestructorNontrivial&&) = default; VariantStateBaseDestructorNontrivial& operator=( const VariantStateBaseDestructorNontrivial&) = default; struct Destroyer { template <std::size_t I> void operator()(SizeT<I> i) const { using Alternative = typename absl::variant_alternative<I, variant<T...>>::type; variant_internal::AccessUnion(self->state_, i).~Alternative(); } void operator()(SizeT<absl::variant_npos> ) const { } VariantStateBaseDestructorNontrivial* self; }; void destroy() { VisitIndices<sizeof...(T)>::Run(Destroyer{this}, index_); } ~VariantStateBaseDestructorNontrivial() { destroy(); } protected: using Base::index_; using Base::state_; }; template <class... T> class VariantMoveBaseNontrivial : protected VariantStateBaseDestructor<T...> { private: using Base = VariantStateBaseDestructor<T...>; protected: using Base::Base; struct Construct { template <std::size_t I> void operator()(SizeT<I> i) const { using Alternative = typename absl::variant_alternative<I, variant<T...>>::type; ::new (static_cast<void*>(&self->state_)) Alternative( variant_internal::AccessUnion(std::move(other->state_), i)); } void operator()(SizeT<absl::variant_npos> ) const {} VariantMoveBaseNontrivial* self; VariantMoveBaseNontrivial* other; }; VariantMoveBaseNontrivial() = default; VariantMoveBaseNontrivial(VariantMoveBaseNontrivial&& other) noexcept( absl::conjunction<std::is_nothrow_move_constructible<T>...>::value) : Base(NoopConstructorTag()) { VisitIndices<sizeof...(T)>::Run(Construct{this, &other}, other.index_); index_ = other.index_; } VariantMoveBaseNontrivial(VariantMoveBaseNontrivial const&) = default; VariantMoveBaseNontrivial& operator=(VariantMoveBaseNontrivial&&) = default; VariantMoveBaseNontrivial& operator=(VariantMoveBaseNontrivial const&) = default; protected: using Base::index_; using Base::state_; }; template <class... T> class VariantCopyBaseNontrivial : protected VariantMoveBase<T...> { private: using Base = VariantMoveBase<T...>; protected: using Base::Base; VariantCopyBaseNontrivial() = default; VariantCopyBaseNontrivial(VariantCopyBaseNontrivial&&) = default; struct Construct { template <std::size_t I> void operator()(SizeT<I> i) const { using Alternative = typename absl::variant_alternative<I, variant<T...>>::type; ::new (static_cast<void*>(&self->state_)) Alternative(variant_internal::AccessUnion(other->state_, i)); } void operator()(SizeT<absl::variant_npos> ) const {} VariantCopyBaseNontrivial* self; const VariantCopyBaseNontrivial* other; }; VariantCopyBaseNontrivial(VariantCopyBaseNontrivial const& other) : Base(NoopConstructorTag()) { VisitIndices<sizeof...(T)>::Run(Construct{this, &other}, other.index_); index_ = other.index_; } VariantCopyBaseNontrivial& operator=(VariantCopyBaseNontrivial&&) = default; VariantCopyBaseNontrivial& operator=(VariantCopyBaseNontrivial const&) = default; protected: using Base::index_; using Base::state_; }; template <class... T> class VariantMoveAssignBaseNontrivial : protected VariantCopyBase<T...> { friend struct VariantCoreAccess; private: using Base = VariantCopyBase<T...>; protected: using Base::Base; VariantMoveAssignBaseNontrivial() = default; VariantMoveAssignBaseNontrivial(VariantMoveAssignBaseNontrivial&&) = default; VariantMoveAssignBaseNontrivial(const VariantMoveAssignBaseNontrivial&) = default; VariantMoveAssignBaseNontrivial& operator=( VariantMoveAssignBaseNontrivial const&) = default; VariantMoveAssignBaseNontrivial& operator=(VariantMoveAssignBaseNontrivial&& other) noexcept( absl::conjunction<std::is_nothrow_move_constructible<T>..., std::is_nothrow_move_assignable<T>...>::value) { VisitIndices<sizeof...(T)>::Run( VariantCoreAccess::MakeMoveAssignVisitor(this, &other), other.index_); return *this; } protected: using Base::index_; using Base::state_; }; template <class... T> class VariantCopyAssignBaseNontrivial : protected VariantMoveAssignBase<T...> { friend struct VariantCoreAccess; private: using Base = VariantMoveAssignBase<T...>; protected: using Base::Base; VariantCopyAssignBaseNontrivial() = default; VariantCopyAssignBaseNontrivial(VariantCopyAssignBaseNontrivial&&) = default; VariantCopyAssignBaseNontrivial(const VariantCopyAssignBaseNontrivial&) = default; VariantCopyAssignBaseNontrivial& operator=( VariantCopyAssignBaseNontrivial&&) = default; VariantCopyAssignBaseNontrivial& operator=( const VariantCopyAssignBaseNontrivial& other) { VisitIndices<sizeof...(T)>::Run( VariantCoreAccess::MakeCopyAssignVisitor(this, other), other.index_); return *this; } protected: using Base::index_; using Base::state_; }; template <class... Types> struct EqualsOp { const variant<Types...>* v; const variant<Types...>* w; constexpr bool operator()(SizeT<absl::variant_npos> ) const { return true; } template <std::size_t I> constexpr bool operator()(SizeT<I> ) const { return VariantCoreAccess::Access<I>(*v) == VariantCoreAccess::Access<I>(*w); } }; template <class... Types> struct NotEqualsOp { const variant<Types...>* v; const variant<Types...>* w; constexpr bool operator()(SizeT<absl::variant_npos> ) const { return false; } template <std::size_t I> constexpr bool operator()(SizeT<I> ) const { return VariantCoreAccess::Access<I>(*v) != VariantCoreAccess::Access<I>(*w); } }; template <class... Types> struct LessThanOp { const variant<Types...>* v; const variant<Types...>* w; constexpr bool operator()(SizeT<absl::variant_npos> ) const { return false; } template <std::size_t I> constexpr bool operator()(SizeT<I> ) const { return VariantCoreAccess::Access<I>(*v) < VariantCoreAccess::Access<I>(*w); } }; template <class... Types> struct GreaterThanOp { const variant<Types...>* v; const variant<Types...>* w; constexpr bool operator()(SizeT<absl::variant_npos> ) const { return false; } template <std::size_t I> constexpr bool operator()(SizeT<I> ) const { return VariantCoreAccess::Access<I>(*v) > VariantCoreAccess::Access<I>(*w); } }; template <class... Types> struct LessThanOrEqualsOp { const variant<Types...>* v; const variant<Types...>* w; constexpr bool operator()(SizeT<absl::variant_npos> ) const { return true; } template <std::size_t I> constexpr bool operator()(SizeT<I> ) const { return VariantCoreAccess::Access<I>(*v) <= VariantCoreAccess::Access<I>(*w); } }; template <class... Types> struct GreaterThanOrEqualsOp { const variant<Types...>* v; const variant<Types...>* w; constexpr bool operator()(SizeT<absl::variant_npos> ) const { return true; } template <std::size_t I> constexpr bool operator()(SizeT<I> ) const { return VariantCoreAccess::Access<I>(*v) >= VariantCoreAccess::Access<I>(*w); } }; template <class... Types> struct SwapSameIndex { variant<Types...>* v; variant<Types...>* w; template <std::size_t I> void operator()(SizeT<I>) const { type_traits_internal::Swap(VariantCoreAccess::Access<I>(*v), VariantCoreAccess::Access<I>(*w)); } void operator()(SizeT<variant_npos>) const {} }; template <class... Types> struct Swap { variant<Types...>* v; variant<Types...>* w; void generic_swap() const { variant<Types...> tmp(std::move(*w)); VariantCoreAccess::Destroy(*w); VariantCoreAccess::InitFrom(*w, std::move(*v)); VariantCoreAccess::Destroy(*v); VariantCoreAccess::InitFrom(*v, std::move(tmp)); } void operator()(SizeT<absl::variant_npos> ) const { if (!v->valueless_by_exception()) { generic_swap(); } } template <std::size_t Wi> void operator()(SizeT<Wi> ) { if (v->index() == Wi) { VisitIndices<sizeof...(Types)>::Run(SwapSameIndex<Types...>{v, w}, Wi); } else { generic_swap(); } } }; template <typename Variant, typename = void, typename... Ts> struct VariantHashBase { VariantHashBase() = delete; VariantHashBase(const VariantHashBase&) = delete; VariantHashBase(VariantHashBase&&) = delete; VariantHashBase& operator=(const VariantHashBase&) = delete; VariantHashBase& operator=(VariantHashBase&&) = delete; }; struct VariantHashVisitor { template <typename T> size_t operator()(const T& t) { return std::hash<T>{}(t); } }; template <typename Variant, typename... Ts> struct VariantHashBase<Variant, absl::enable_if_t<absl::conjunction< type_traits_internal::IsHashable<Ts>...>::value>, Ts...> { using argument_type = Variant; using result_type = size_t; size_t operator()(const Variant& var) const { type_traits_internal::AssertHashEnabled<Ts...>(); if (var.valueless_by_exception()) { return 239799884; } size_t result = VisitIndices<variant_size<Variant>::value>::Run( PerformVisitation<VariantHashVisitor, const Variant&>{ std::forward_as_tuple(var), VariantHashVisitor{}}, var.index()); return result ^ var.index(); } }; } ABSL_NAMESPACE_END } #endif #endif
#include "absl/types/variant.h" #if !defined(ABSL_USES_STD_VARIANT) #include <algorithm> #include <cstddef> #include <functional> #include <initializer_list> #include <memory> #include <ostream> #include <queue> #include <type_traits> #include <unordered_set> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/base/port.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/strings/string_view.h" #ifdef ABSL_HAVE_EXCEPTIONS #define ABSL_VARIANT_TEST_EXPECT_FAIL(expr, exception_t, text) \ EXPECT_THROW(expr, exception_t) #else #define ABSL_VARIANT_TEST_EXPECT_FAIL(expr, exception_t, text) \ EXPECT_DEATH_IF_SUPPORTED(expr, text) #endif #define ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS(...) \ ABSL_VARIANT_TEST_EXPECT_FAIL((void)(__VA_ARGS__), absl::bad_variant_access, \ "Bad variant access") struct Hashable {}; namespace std { template <> struct hash<Hashable> { size_t operator()(const Hashable&); }; } struct NonHashable {}; namespace absl { ABSL_NAMESPACE_BEGIN namespace { using ::testing::DoubleEq; using ::testing::Pointee; using ::testing::VariantWith; struct MoveCanThrow { MoveCanThrow() : v(0) {} MoveCanThrow(int v) : v(v) {} MoveCanThrow(const MoveCanThrow& other) : v(other.v) {} MoveCanThrow& operator=(const MoveCanThrow& ) { return *this; } int v; }; bool operator==(MoveCanThrow lhs, MoveCanThrow rhs) { return lhs.v == rhs.v; } bool operator!=(MoveCanThrow lhs, MoveCanThrow rhs) { return lhs.v != rhs.v; } bool operator<(MoveCanThrow lhs, MoveCanThrow rhs) { return lhs.v < rhs.v; } bool operator<=(MoveCanThrow lhs, MoveCanThrow rhs) { return lhs.v <= rhs.v; } bool operator>=(MoveCanThrow lhs, MoveCanThrow rhs) { return lhs.v >= rhs.v; } bool operator>(MoveCanThrow lhs, MoveCanThrow rhs) { return lhs.v > rhs.v; } struct SpecialSwap { explicit SpecialSwap(int i) : i(i) {} friend void swap(SpecialSwap& a, SpecialSwap& b) { a.special_swap = b.special_swap = true; std::swap(a.i, b.i); } bool operator==(SpecialSwap other) const { return i == other.i; } int i; bool special_swap = false; }; struct MoveOnlyWithListConstructor { MoveOnlyWithListConstructor() = default; explicit MoveOnlyWithListConstructor(std::initializer_list<int> , int value) : value(value) {} MoveOnlyWithListConstructor(MoveOnlyWithListConstructor&&) = default; MoveOnlyWithListConstructor& operator=(MoveOnlyWithListConstructor&&) = default; int value = 0; }; #ifdef ABSL_HAVE_EXCEPTIONS struct ConversionException {}; template <class T> struct ExceptionOnConversion { operator T() const { throw ConversionException(); } }; template <class H, class... T> void ToValuelessByException(absl::variant<H, T...>& v) { try { v.template emplace<0>(ExceptionOnConversion<H>()); } catch (ConversionException& ) { } } #endif template<typename T, size_t N> struct ValueHolder { explicit ValueHolder(const T& x) : value(x) {} typedef T value_type; value_type value; static const size_t kIndex = N; }; template<typename T, size_t N> const size_t ValueHolder<T, N>::kIndex; template<typename T, size_t N> inline bool operator==(const ValueHolder<T, N>& left, const ValueHolder<T, N>& right) { return left.value == right.value; } template<typename T, size_t N> inline bool operator!=(const ValueHolder<T, N>& left, const ValueHolder<T, N>& right) { return left.value != right.value; } template<typename T, size_t N> inline std::ostream& operator<<( std::ostream& stream, const ValueHolder<T, N>& object) { return stream << object.value; } template<typename T> struct VariantFactory { typedef variant<ValueHolder<T, 1>, ValueHolder<T, 2>, ValueHolder<T, 3>, ValueHolder<T, 4>> Type; }; typedef ::testing::Types<ValueHolder<size_t, 1>, ValueHolder<size_t, 2>, ValueHolder<size_t, 3>, ValueHolder<size_t, 4>> VariantTypes; struct IncrementInDtor { explicit IncrementInDtor(int* counter) : counter(counter) {} ~IncrementInDtor() { *counter += 1; } int* counter; }; struct IncrementInDtorCopyCanThrow { explicit IncrementInDtorCopyCanThrow(int* counter) : counter(counter) {} IncrementInDtorCopyCanThrow(IncrementInDtorCopyCanThrow&& other) noexcept = default; IncrementInDtorCopyCanThrow(const IncrementInDtorCopyCanThrow& other) : counter(other.counter) {} IncrementInDtorCopyCanThrow& operator=( IncrementInDtorCopyCanThrow&&) noexcept = default; IncrementInDtorCopyCanThrow& operator=( IncrementInDtorCopyCanThrow const& other) { counter = other.counter; return *this; } ~IncrementInDtorCopyCanThrow() { *counter += 1; } int* counter; }; inline bool operator==(const IncrementInDtor& left, const IncrementInDtor& right) { return left.counter == right.counter; } inline std::ostream& operator<<( std::ostream& stream, const IncrementInDtor& object) { return stream << object.counter; } class CopyNoAssign { public: explicit CopyNoAssign(int value) : foo(value) {} CopyNoAssign(const CopyNoAssign& other) : foo(other.foo) {} int foo; private: const CopyNoAssign& operator=(const CopyNoAssign&); }; class NonCopyable { public: NonCopyable() : value(0) {} explicit NonCopyable(int value1) : value(value1) {} NonCopyable(int value1, int value2) : value(value1 + value2) {} NonCopyable(int value1, int value2, int value3) : value(value1 + value2 + value3) {} NonCopyable(int value1, int value2, int value3, int value4) : value(value1 + value2 + value3 + value4) {} NonCopyable(const NonCopyable&) = delete; NonCopyable& operator=(const NonCopyable&) = delete; int value; }; template <typename T> class VariantTypesTest : public ::testing::Test {}; TYPED_TEST_SUITE(VariantTypesTest, VariantTypes); struct NonNoexceptDefaultConstructible { NonNoexceptDefaultConstructible() {} int value = 5; }; struct NonDefaultConstructible { NonDefaultConstructible() = delete; }; TEST(VariantTest, TestDefaultConstructor) { { using X = variant<int>; constexpr variant<int> x{}; ASSERT_FALSE(x.valueless_by_exception()); ASSERT_EQ(0u, x.index()); EXPECT_EQ(0, absl::get<0>(x)); EXPECT_TRUE(std::is_nothrow_default_constructible<X>::value); } { using X = variant<NonNoexceptDefaultConstructible>; X x{}; ASSERT_FALSE(x.valueless_by_exception()); ASSERT_EQ(0u, x.index()); EXPECT_EQ(5, absl::get<0>(x).value); EXPECT_FALSE(std::is_nothrow_default_constructible<X>::value); } { using X = variant<int, NonNoexceptDefaultConstructible>; X x{}; ASSERT_FALSE(x.valueless_by_exception()); ASSERT_EQ(0u, x.index()); EXPECT_EQ(0, absl::get<0>(x)); EXPECT_TRUE(std::is_nothrow_default_constructible<X>::value); } { using X = variant<NonNoexceptDefaultConstructible, int>; X x{}; ASSERT_FALSE(x.valueless_by_exception()); ASSERT_EQ(0u, x.index()); EXPECT_EQ(5, absl::get<0>(x).value); EXPECT_FALSE(std::is_nothrow_default_constructible<X>::value); } EXPECT_FALSE( std::is_default_constructible<variant<NonDefaultConstructible>>::value); EXPECT_FALSE((std::is_default_constructible< variant<NonDefaultConstructible, int>>::value)); EXPECT_TRUE((std::is_default_constructible< variant<int, NonDefaultConstructible>>::value)); } TYPED_TEST(VariantTypesTest, TestCopyCtor) { typedef typename VariantFactory<typename TypeParam::value_type>::Type Variant; using value_type1 = absl::variant_alternative_t<0, Variant>; using value_type2 = absl::variant_alternative_t<1, Variant>; using value_type3 = absl::variant_alternative_t<2, Variant>; using value_type4 = absl::variant_alternative_t<3, Variant>; const TypeParam value(TypeParam::kIndex); Variant original(value); Variant copied(original); EXPECT_TRUE(absl::holds_alternative<value_type1>(copied) || TypeParam::kIndex != 1); EXPECT_TRUE(absl::holds_alternative<value_type2>(copied) || TypeParam::kIndex != 2); EXPECT_TRUE(absl::holds_alternative<value_type3>(copied) || TypeParam::kIndex != 3); EXPECT_TRUE(absl::holds_alternative<value_type4>(copied) || TypeParam::kIndex != 4); EXPECT_TRUE((absl::get_if<value_type1>(&original) == absl::get_if<value_type1>(&copied)) || TypeParam::kIndex == 1); EXPECT_TRUE((absl::get_if<value_type2>(&original) == absl::get_if<value_type2>(&copied)) || TypeParam::kIndex == 2); EXPECT_TRUE((absl::get_if<value_type3>(&original) == absl::get_if<value_type3>(&copied)) || TypeParam::kIndex == 3); EXPECT_TRUE((absl::get_if<value_type4>(&original) == absl::get_if<value_type4>(&copied)) || TypeParam::kIndex == 4); EXPECT_TRUE((absl::get_if<value_type1>(&original) == absl::get_if<value_type1>(&copied)) || TypeParam::kIndex == 1); EXPECT_TRUE((absl::get_if<value_type2>(&original) == absl::get_if<value_type2>(&copied)) || TypeParam::kIndex == 2); EXPECT_TRUE((absl::get_if<value_type3>(&original) == absl::get_if<value_type3>(&copied)) || TypeParam::kIndex == 3); EXPECT_TRUE((absl::get_if<value_type4>(&original) == absl::get_if<value_type4>(&copied)) || TypeParam::kIndex == 4); const TypeParam* ovalptr = absl::get_if<TypeParam>(&original); const TypeParam* cvalptr = absl::get_if<TypeParam>(&copied); ASSERT_TRUE(ovalptr != nullptr); ASSERT_TRUE(cvalptr != nullptr); EXPECT_EQ(*ovalptr, *cvalptr); TypeParam* mutable_ovalptr = absl::get_if<TypeParam>(&original); TypeParam* mutable_cvalptr = absl::get_if<TypeParam>(&copied); ASSERT_TRUE(mutable_ovalptr != nullptr); ASSERT_TRUE(mutable_cvalptr != nullptr); EXPECT_EQ(*mutable_ovalptr, *mutable_cvalptr); } template <class> struct MoveOnly { MoveOnly() = default; explicit MoveOnly(int value) : value(value) {} MoveOnly(MoveOnly&&) = default; MoveOnly& operator=(MoveOnly&&) = default; int value = 5; }; TEST(VariantTest, TestMoveConstruct) { using V = variant<MoveOnly<class A>, MoveOnly<class B>, MoveOnly<class C>>; V v(in_place_index<1>, 10); V v2 = std::move(v); EXPECT_EQ(10, absl::get<1>(v2).value); } template <class T> union SingleUnion { T member; }; template <class T> struct is_trivially_move_constructible : std::is_move_constructible<SingleUnion<T>>::type {}; template <class T> struct is_trivially_move_assignable : absl::is_move_assignable<SingleUnion<T>>::type {}; TEST(VariantTest, NothrowMoveConstructible) { using U = std::unique_ptr<int>; struct E { E(E&&) {} }; static_assert(std::is_nothrow_move_constructible<variant<U>>::value, ""); static_assert(std::is_nothrow_move_constructible<variant<U, int>>::value, ""); static_assert(!std::is_nothrow_move_constructible<variant<U, E>>::value, ""); } TYPED_TEST(VariantTypesTest, TestValueCtor) { typedef typename VariantFactory<typename TypeParam::value_type>::Type Variant; using value_type1 = absl::variant_alternative_t<0, Variant>; using value_type2 = absl::variant_alternative_t<1, Variant>; using value_type3 = absl::variant_alternative_t<2, Variant>; using value_type4 = absl::variant_alternative_t<3, Variant>; const TypeParam value(TypeParam::kIndex); Variant v(value); EXPECT_TRUE(absl::holds_alternative<value_type1>(v) || TypeParam::kIndex != 1); EXPECT_TRUE(absl::holds_alternative<value_type2>(v) || TypeParam::kIndex != 2); EXPECT_TRUE(absl::holds_alternative<value_type3>(v) || TypeParam::kIndex != 3); EXPECT_TRUE(absl::holds_alternative<value_type4>(v) || TypeParam::kIndex != 4); EXPECT_TRUE(nullptr != absl::get_if<value_type1>(&v) || TypeParam::kIndex != 1); EXPECT_TRUE(nullptr != absl::get_if<value_type2>(&v) || TypeParam::kIndex != 2); EXPECT_TRUE(nullptr != absl::get_if<value_type3>(&v) || TypeParam::kIndex != 3); EXPECT_TRUE(nullptr != absl::get_if<value_type4>(&v) || TypeParam::kIndex != 4); EXPECT_TRUE(nullptr != absl::get_if<value_type1>(&v) || TypeParam::kIndex != 1); EXPECT_TRUE(nullptr != absl::get_if<value_type2>(&v) || TypeParam::kIndex != 2); EXPECT_TRUE(nullptr != absl::get_if<value_type3>(&v) || TypeParam::kIndex != 3); EXPECT_TRUE(nullptr != absl::get_if<value_type4>(&v) || TypeParam::kIndex != 4); const TypeParam* valptr = absl::get_if<TypeParam>(&v); ASSERT_TRUE(nullptr != valptr); EXPECT_EQ(value.value, valptr->value); const TypeParam* mutable_valptr = absl::get_if<TypeParam>(&v); ASSERT_TRUE(nullptr != mutable_valptr); EXPECT_EQ(value.value, mutable_valptr->value); } TEST(VariantTest, AmbiguousValueConstructor) { EXPECT_FALSE((std::is_convertible<int, absl::variant<int, int>>::value)); EXPECT_FALSE((std::is_constructible<absl::variant<int, int>, int>::value)); } TEST(VariantTest, InPlaceType) { using Var = variant<int, std::string, NonCopyable, std::vector<int>>; Var v1(in_place_type_t<int>(), 7); ASSERT_TRUE(absl::holds_alternative<int>(v1)); EXPECT_EQ(7, absl::get<int>(v1)); Var v2(in_place_type_t<std::string>(), "ABC"); ASSERT_TRUE(absl::holds_alternative<std::string>(v2)); EXPECT_EQ("ABC", absl::get<std::string>(v2)); Var v3(in_place_type_t<std::string>(), "ABC", 2u); ASSERT_TRUE(absl::holds_alternative<std::string>(v3)); EXPECT_EQ("AB", absl::get<std::string>(v3)); Var v4(in_place_type_t<NonCopyable>{}); ASSERT_TRUE(absl::holds_alternative<NonCopyable>(v4)); Var v5(in_place_type_t<std::vector<int>>(), {1, 2, 3}); ASSERT_TRUE(absl::holds_alternative<std::vector<int>>(v5)); EXPECT_THAT(absl::get<std::vector<int>>(v5), ::testing::ElementsAre(1, 2, 3)); } TEST(VariantTest, InPlaceTypeVariableTemplate) { using Var = variant<int, std::string, NonCopyable, std::vector<int>>; Var v1(in_place_type<int>, 7); ASSERT_TRUE(absl::holds_alternative<int>(v1)); EXPECT_EQ(7, absl::get<int>(v1)); Var v2(in_place_type<std::string>, "ABC"); ASSERT_TRUE(absl::holds_alternative<std::string>(v2)); EXPECT_EQ("ABC", absl::get<std::string>(v2)); Var v3(in_place_type<std::string>, "ABC", 2u); ASSERT_TRUE(absl::holds_alternative<std::string>(v3)); EXPECT_EQ("AB", absl::get<std::string>(v3)); Var v4(in_place_type<NonCopyable>); ASSERT_TRUE(absl::holds_alternative<NonCopyable>(v4)); Var v5(in_place_type<std::vector<int>>, {1, 2, 3}); ASSERT_TRUE(absl::holds_alternative<std::vector<int>>(v5)); EXPECT_THAT(absl::get<std::vector<int>>(v5), ::testing::ElementsAre(1, 2, 3)); } TEST(VariantTest, InPlaceTypeInitializerList) { using Var = variant<int, std::string, NonCopyable, MoveOnlyWithListConstructor>; Var v1(in_place_type_t<MoveOnlyWithListConstructor>(), {1, 2, 3, 4, 5}, 6); ASSERT_TRUE(absl::holds_alternative<MoveOnlyWithListConstructor>(v1)); EXPECT_EQ(6, absl::get<MoveOnlyWithListConstructor>(v1).value); } TEST(VariantTest, InPlaceTypeInitializerListVariabletemplate) { using Var = variant<int, std::string, NonCopyable, MoveOnlyWithListConstructor>; Var v1(in_place_type<MoveOnlyWithListConstructor>, {1, 2, 3, 4, 5}, 6); ASSERT_TRUE(absl::holds_alternative<MoveOnlyWithListConstructor>(v1)); EXPECT_EQ(6, absl::get<MoveOnlyWithListConstructor>(v1).value); } TEST(VariantTest, InPlaceIndex) { using Var = variant<int, std::string, NonCopyable, std::vector<int>>; Var v1(in_place_index_t<0>(), 7); ASSERT_TRUE(absl::holds_alternative<int>(v1)); EXPECT_EQ(7, absl::get<int>(v1)); Var v2(in_place_index_t<1>(), "ABC"); ASSERT_TRUE(absl::holds_alternative<std::string>(v2)); EXPECT_EQ("ABC", absl::get<std::string>(v2)); Var v3(in_place_index_t<1>(), "ABC", 2u); ASSERT_TRUE(absl::holds_alternative<std::string>(v3)); EXPECT_EQ("AB", absl::get<std::string>(v3)); Var v4(in_place_index_t<2>{}); EXPECT_TRUE(absl::holds_alternative<NonCopyable>(v4)); EXPECT_TRUE(absl::holds_alternative<NonCopyable>( variant<NonCopyable>(in_place_index_t<0>{}))); Var v5(in_place_index_t<3>(), {1, 2, 3}); ASSERT_TRUE(absl::holds_alternative<std::vector<int>>(v5)); EXPECT_THAT(absl::get<std::vector<int>>(v5), ::testing::ElementsAre(1, 2, 3)); } TEST(VariantTest, InPlaceIndexVariableTemplate) { using Var = variant<int, std::string, NonCopyable, std::vector<int>>; Var v1(in_place_index<0>, 7); ASSERT_TRUE(absl::holds_alternative<int>(v1)); EXPECT_EQ(7, absl::get<int>(v1)); Var v2(in_place_index<1>, "ABC"); ASSERT_TRUE(absl::holds_alternative<std::string>(v2)); EXPECT_EQ("ABC", absl::get<std::string>(v2)); Var v3(in_place_index<1>, "ABC", 2u); ASSERT_TRUE(absl::holds_alternative<std::string>(v3)); EXPECT_EQ("AB", absl::get<std::string>(v3)); Var v4(in_place_index<2>); EXPECT_TRUE(absl::holds_alternative<NonCopyable>(v4)); EXPECT_TRUE(absl::holds_alternative<NonCopyable>( variant<NonCopyable>(in_place_index<0>))); Var v5(in_place_index<3>, {1, 2, 3}); ASSERT_TRUE(absl::holds_alternative<std::vector<int>>(v5)); EXPECT_THAT(absl::get<std::vector<int>>(v5), ::testing::ElementsAre(1, 2, 3)); } TEST(VariantTest, InPlaceIndexInitializerList) { using Var = variant<int, std::string, NonCopyable, MoveOnlyWithListConstructor>; Var v1(in_place_index_t<3>(), {1, 2, 3, 4, 5}, 6); ASSERT_TRUE(absl::holds_alternative<MoveOnlyWithListConstructor>(v1)); EXPECT_EQ(6, absl::get<MoveOnlyWithListConstructor>(v1).value); } TEST(VariantTest, InPlaceIndexInitializerListVariableTemplate) { using Var = variant<int, std::string, NonCopyable, MoveOnlyWithListConstructor>; Var v1(in_place_index<3>, {1, 2, 3, 4, 5}, 6); ASSERT_TRUE(absl::holds_alternative<MoveOnlyWithListConstructor>(v1)); EXPECT_EQ(6, absl::get<MoveOnlyWithListConstructor>(v1).value); } TEST(VariantTest, TestDtor) { typedef VariantFactory<IncrementInDtor>::Type Variant; using value_type1 = absl::variant_alternative_t<0, Variant>; using value_type2 = absl::variant_alternative_t<1, Variant>; using value_type3 = absl::variant_alternative_t<2, Variant>; using value_type4 = absl::variant_alternative_t<3, Variant>; int counter = 0; IncrementInDtor counter_adjuster(&counter); EXPECT_EQ(0, counter); value_type1 value1(counter_adjuster); { Variant object(value1); } EXPECT_EQ(1, counter); value_type2 value2(counter_adjuster); { Variant object(value2); } EXPECT_EQ(2, counter); value_type3 value3(counter_adjuster); { Variant object(value3); } EXPECT_EQ(3, counter); value_type4 value4(counter_adjuster); { Variant object(value4); } EXPECT_EQ(4, counter); } #ifdef ABSL_HAVE_EXCEPTIONS #if defined(ABSL_INTERNAL_MSVC_2017_DBG_MODE) TEST(VariantTest, DISABLED_TestDtorValuelessByException) #else TEST(VariantTest, TestDtorValuelessByException) #endif { int counter = 0; IncrementInDtor counter_adjuster(&counter); { using Variant = VariantFactory<IncrementInDtor>::Type; Variant v(in_place_index<0>, counter_adjuster); EXPECT_EQ(0, counter); ToValuelessByException(v); ASSERT_TRUE(v.valueless_by_exception()); EXPECT_EQ(1, counter); } EXPECT_EQ(1, counter); } #endif TEST(VariantTest, TestSelfAssignment) { typedef VariantFactory<IncrementInDtor>::Type Variant; int counter = 0; IncrementInDtor counter_adjuster(&counter); absl::variant_alternative_t<0, Variant> value(counter_adjuster); Variant object(value); object.operator=(object); EXPECT_EQ(0, counter); const std::string long_str(128, 'a'); std::string foo = long_str; foo = *&foo; EXPECT_EQ(long_str, foo); variant<int, std::string> so = long_str; ASSERT_EQ(1u, so.index()); EXPECT_EQ(long_str, absl::get<1>(so)); so = *&so; ASSERT_EQ(1u, so.index()); EXPECT_EQ(long_str, absl::get<1>(so)); } TYPED_TEST(VariantTypesTest, TestAssignmentCopiesValueSameTypes) { typedef typename VariantFactory<typename TypeParam::value_type>::Type Variant; const TypeParam value(TypeParam::kIndex); const Variant source(value); Variant target(TypeParam(value.value + 1)); ASSERT_TRUE(absl::holds_alternative<TypeParam>(source)); ASSERT_TRUE(absl::holds_alternative<TypeParam>(target)); ASSERT_NE(absl::get<TypeParam>(source), absl::get<TypeParam>(target)); target = source; ASSERT_TRUE(absl::holds_alternative<TypeParam>(source)); ASSERT_TRUE(absl::holds_alternative<TypeParam>(target)); EXPECT_EQ(absl::get<TypeParam>(source), absl::get<TypeParam>(target)); } TYPED_TEST(VariantTypesTest, TestAssignmentCopiesValuesVaryingSourceType) { typedef typename VariantFactory<typename TypeParam::value_type>::Type Variant; using value_type1 = absl::variant_alternative_t<0, Variant>; const TypeParam value(TypeParam::kIndex); const Variant source(value); ASSERT_TRUE(absl::holds_alternative<TypeParam>(source)); Variant target(value_type1(1)); ASSERT_TRUE(absl::holds_alternative<value_type1>(target)); target = source; EXPECT_TRUE(absl::holds_alternative<TypeParam>(source)); EXPECT_TRUE(absl::holds_alternative<TypeParam>(target)); EXPECT_EQ(absl::get<TypeParam>(source), absl::get<TypeParam>(target)); } TYPED_TEST(VariantTypesTest, TestAssignmentCopiesValuesVaryingTargetType) { typedef typename VariantFactory<typename TypeParam::value_type>::Type Variant; using value_type1 = absl::variant_alternative_t<0, Variant>; const Variant source(value_type1(1)); ASSERT_TRUE(absl::holds_alternative<value_type1>(source)); const TypeParam value(TypeParam::kIndex); Variant target(value); ASSERT_TRUE(absl::holds_alternative<TypeParam>(target)); target = source; EXPECT_TRUE(absl::holds_alternative<value_type1>(target)); EXPECT_TRUE(absl::holds_alternative<value_type1>(source)); EXPECT_EQ(absl::get<value_type1>(source), absl::get<value_type1>(target)); } TEST(VariantTest, TestAssign) { typedef VariantFactory<IncrementInDtor>::Type Variant; using value_type1 = absl::variant_alternative_t<0, Variant>; using value_type2 = absl::variant_alternative_t<1, Variant>; using value_type3 = absl::variant_alternative_t<2, Variant>; using value_type4 = absl::variant_alternative_t<3, Variant>; const int kSize = 4; int counter[kSize]; std::unique_ptr<IncrementInDtor> counter_adjustor[kSize]; for (int i = 0; i != kSize; i++) { counter[i] = 0; counter_adjustor[i] = absl::make_unique<IncrementInDtor>(&counter[i]); } value_type1 v1(*counter_adjustor[0]); value_type2 v2(*counter_adjustor[1]); value_type3 v3(*counter_adjustor[2]); value_type4 v4(*counter_adjustor[3]); { Variant object(v1); object = v2; object = v3; object = v4; object = v1; } EXPECT_EQ(2, counter[0]); EXPECT_EQ(1, counter[1]); EXPECT_EQ(1, counter[2]); EXPECT_EQ(1, counter[3]); std::fill(std::begin(counter), std::end(counter), 0); { Variant object(v1); object.operator=(object); EXPECT_EQ(0, counter[0]); } { Variant object(v2); object.operator=(object); EXPECT_EQ(0, counter[1]); } { Variant object(v3); object.operator=(object); EXPECT_EQ(0, counter[2]); } { Variant object(v4); object.operator=(object); EXPECT_EQ(0, counter[3]); } EXPECT_EQ(1, counter[0]); EXPECT_EQ(1, counter[1]); EXPECT_EQ(1, counter[2]); EXPECT_EQ(1, counter[3]); } TEST(VariantTest, TestBackupAssign) { typedef VariantFactory<IncrementInDtorCopyCanThrow>::Type Variant; using value_type1 = absl::variant_alternative_t<0, Variant>; using value_type2 = absl::variant_alternative_t<1, Variant>; using value_type3 = absl::variant_alternative_t<2, Variant>; using value_type4 = absl::variant_alternative_t<3, Variant>; const int kSize = 4; int counter[kSize]; std::unique_ptr<IncrementInDtorCopyCanThrow> counter_adjustor[kSize]; for (int i = 0; i != kSize; i++) { counter[i] = 0; counter_adjustor[i].reset(new IncrementInDtorCopyCanThrow(&counter[i])); } value_type1 v1(*counter_adjustor[0]); value_type2 v2(*counter_adjustor[1]); value_type3 v3(*counter_adjustor[2]); value_type4 v4(*counter_adjustor[3]); { Variant object(v1); object = v2; object = v3; object = v4; object = v1; } #if !(defined(ABSL_USES_STD_VARIANT) && defined(__GLIBCXX__)) EXPECT_EQ(3, counter[0]); EXPECT_EQ(2, counter[1]); EXPECT_EQ(2, counter[2]); EXPECT_EQ(2, counter[3]); #endif std::fill(std::begin(counter), std::end(counter), 0); { Variant object(v1); object.operator=(object); EXPECT_EQ(0, counter[0]); } { Variant object(v2); object.operator=(object); EXPECT_EQ(0, counter[1]); } { Variant object(v3); object.operator=(object); EXPECT_EQ(0, counter[2]); } { Variant object(v4); object.operator=(object); EXPECT_EQ(0, counter[3]); } EXPECT_EQ(1, counter[0]); EXPECT_EQ(1, counter[1]); EXPECT_EQ(1, counter[2]); EXPECT_EQ(1, counter[3]); } TEST(VariantTest, TestEmplaceBasic) { using Variant = variant<int, char>; Variant v(absl::in_place_index<0>, 0); { char& emplace_result = v.emplace<char>(); ASSERT_TRUE(absl::holds_alternative<char>(v)); EXPECT_EQ(absl::get<char>(v), 0); EXPECT_EQ(&emplace_result, &absl::get<char>(v)); } absl::get<char>(v) = 'a'; v.emplace<char>('b'); ASSERT_TRUE(absl::holds_alternative<char>(v)); EXPECT_EQ(absl::get<char>(v), 'b'); { int& emplace_result = v.emplace<int>(); EXPECT_TRUE(absl::holds_alternative<int>(v)); EXPECT_EQ(absl::get<int>(v), 0); EXPECT_EQ(&emplace_result, &absl::get<int>(v)); } } TEST(VariantTest, TestEmplaceInitializerList) { using Var = variant<int, std::string, NonCopyable, MoveOnlyWithListConstructor>; Var v1(absl::in_place_index<0>, 555); MoveOnlyWithListConstructor& emplace_result = v1.emplace<MoveOnlyWithListConstructor>({1, 2, 3, 4, 5}, 6); ASSERT_TRUE(absl::holds_alternative<MoveOnlyWithListConstructor>(v1)); EXPECT_EQ(6, absl::get<MoveOnlyWithListConstructor>(v1).value); EXPECT_EQ(&emplace_result, &absl::get<MoveOnlyWithListConstructor>(v1)); } TEST(VariantTest, TestEmplaceIndex) { using Variant = variant<int, char>; Variant v(absl::in_place_index<0>, 555); { char& emplace_result = v.emplace<1>(); ASSERT_TRUE(absl::holds_alternative<char>(v)); EXPECT_EQ(absl::get<char>(v), 0); EXPECT_EQ(&emplace_result, &absl::get<char>(v)); } absl::get<char>(v) = 'a'; v.emplace<1>('b'); ASSERT_TRUE(absl::holds_alternative<char>(v)); EXPECT_EQ(absl::get<char>(v), 'b'); { int& emplace_result = v.emplace<0>(); EXPECT_TRUE(absl::holds_alternative<int>(v)); EXPECT_EQ(absl::get<int>(v), 0); EXPECT_EQ(&emplace_result, &absl::get<int>(v)); } } TEST(VariantTest, TestEmplaceIndexInitializerList) { using Var = variant<int, std::string, NonCopyable, MoveOnlyWithListConstructor>; Var v1(absl::in_place_index<0>, 555); MoveOnlyWithListConstructor& emplace_result = v1.emplace<3>({1, 2, 3, 4, 5}, 6); ASSERT_TRUE(absl::holds_alternative<MoveOnlyWithListConstructor>(v1)); EXPECT_EQ(6, absl::get<MoveOnlyWithListConstructor>(v1).value); EXPECT_EQ(&emplace_result, &absl::get<MoveOnlyWithListConstructor>(v1)); } TEST(VariantTest, Index) { using Var = variant<int, std::string, double>; Var v = 1; EXPECT_EQ(0u, v.index()); v = "str"; EXPECT_EQ(1u, v.index()); v = 0.; EXPECT_EQ(2u, v.index()); Var v2 = v; EXPECT_EQ(2u, v2.index()); v2.emplace<int>(3); EXPECT_EQ(0u, v2.index()); } TEST(VariantTest, NotValuelessByException) { using Var = variant<int, std::string, double>; Var v = 1; EXPECT_FALSE(v.valueless_by_exception()); v = "str"; EXPECT_FALSE(v.valueless_by_exception()); v = 0.; EXPECT_FALSE(v.valueless_by_exception()); Var v2 = v; EXPECT_FALSE(v.valueless_by_exception()); v2.emplace<int>(3); EXPECT_FALSE(v.valueless_by_exception()); } #ifdef ABSL_HAVE_EXCEPTIONS TEST(VariantTest, IndexValuelessByException) { using Var = variant<MoveCanThrow, std::string, double>; Var v(absl::in_place_index<0>); EXPECT_EQ(0u, v.index()); ToValuelessByException(v); EXPECT_EQ(absl::variant_npos, v.index()); v = "str"; EXPECT_EQ(1u, v.index()); } TEST(VariantTest, ValuelessByException) { using Var = variant<MoveCanThrow, std::string, double>; Var v(absl::in_place_index<0>); EXPECT_FALSE(v.valueless_by_exception()); ToValuelessByException(v); EXPECT_TRUE(v.valueless_by_exception()); v = "str"; EXPECT_FALSE(v.valueless_by_exception()); } #endif TEST(VariantTest, MemberSwap) { SpecialSwap v1(3); SpecialSwap v2(7); variant<SpecialSwap> a = v1, b = v2; EXPECT_THAT(a, VariantWith<SpecialSwap>(v1)); EXPECT_THAT(b, VariantWith<SpecialSwap>(v2)); a.swap(b); EXPECT_THAT(a, VariantWith<SpecialSwap>(v2)); EXPECT_THAT(b, VariantWith<SpecialSwap>(v1)); EXPECT_TRUE(absl::get<SpecialSwap>(a).special_swap); using V = variant<MoveCanThrow, std::string, int>; int i = 33; std::string s = "abc"; { V lhs(i), rhs(s); lhs.swap(rhs); EXPECT_THAT(lhs, VariantWith<std::string>(s)); EXPECT_THAT(rhs, VariantWith<int>(i)); } #ifdef ABSL_HAVE_EXCEPTIONS V valueless(in_place_index<0>); ToValuelessByException(valueless); { V lhs(valueless), rhs(i); lhs.swap(rhs); EXPECT_THAT(lhs, VariantWith<int>(i)); EXPECT_TRUE(rhs.valueless_by_exception()); } { V lhs(s), rhs(valueless); lhs.swap(rhs); EXPECT_THAT(rhs, VariantWith<std::string>(s)); EXPECT_TRUE(lhs.valueless_by_exception()); } { V lhs(valueless), rhs(valueless); lhs.swap(rhs); EXPECT_TRUE(lhs.valueless_by_exception()); EXPECT_TRUE(rhs.valueless_by_exception()); } #endif } TEST(VariantTest, VariantSize) { { using Size1Variant = absl::variant<int>; EXPECT_EQ(1u, absl::variant_size<Size1Variant>::value); EXPECT_EQ(1u, absl::variant_size<const Size1Variant>::value); EXPECT_EQ(1u, absl::variant_size<volatile Size1Variant>::value); EXPECT_EQ(1u, absl::variant_size<const volatile Size1Variant>::value); } { using Size3Variant = absl::variant<int, float, int>; EXPECT_EQ(3u, absl::variant_size<Size3Variant>::value); EXPECT_EQ(3u, absl::variant_size<const Size3Variant>::value); EXPECT_EQ(3u, absl::variant_size<volatile Size3Variant>::value); EXPECT_EQ(3u, absl::variant_size<const volatile Size3Variant>::value); } } TEST(VariantTest, VariantAlternative) { { using V = absl::variant<float, int, const char*>; EXPECT_TRUE( (std::is_same<float, absl::variant_alternative_t<0, V>>::value)); EXPECT_TRUE((std::is_same<const float, absl::variant_alternative_t<0, const V>>::value)); EXPECT_TRUE( (std::is_same<volatile float, absl::variant_alternative_t<0, volatile V>>::value)); EXPECT_TRUE(( std::is_same<const volatile float, absl::variant_alternative_t<0, const volatile V>>::value)); EXPECT_TRUE((std::is_same<int, absl::variant_alternative_t<1, V>>::value)); EXPECT_TRUE((std::is_same<const int, absl::variant_alternative_t<1, const V>>::value)); EXPECT_TRUE( (std::is_same<volatile int, absl::variant_alternative_t<1, volatile V>>::value)); EXPECT_TRUE(( std::is_same<const volatile int, absl::variant_alternative_t<1, const volatile V>>::value)); EXPECT_TRUE( (std::is_same<const char*, absl::variant_alternative_t<2, V>>::value)); EXPECT_TRUE((std::is_same<const char* const, absl::variant_alternative_t<2, const V>>::value)); EXPECT_TRUE( (std::is_same<const char* volatile, absl::variant_alternative_t<2, volatile V>>::value)); EXPECT_TRUE(( std::is_same<const char* const volatile, absl::variant_alternative_t<2, const volatile V>>::value)); } { using V = absl::variant<float, volatile int, const char*>; EXPECT_TRUE( (std::is_same<float, absl::variant_alternative_t<0, V>>::value)); EXPECT_TRUE((std::is_same<const float, absl::variant_alternative_t<0, const V>>::value)); EXPECT_TRUE( (std::is_same<volatile float, absl::variant_alternative_t<0, volatile V>>::value)); EXPECT_TRUE(( std::is_same<const volatile float, absl::variant_alternative_t<0, const volatile V>>::value)); EXPECT_TRUE( (std::is_same<volatile int, absl::variant_alternative_t<1, V>>::value)); EXPECT_TRUE((std::is_same<const volatile int, absl::variant_alternative_t<1, const V>>::value)); EXPECT_TRUE( (std::is_same<volatile int, absl::variant_alternative_t<1, volatile V>>::value)); EXPECT_TRUE(( std::is_same<const volatile int, absl::variant_alternative_t<1, const volatile V>>::value)); EXPECT_TRUE( (std::is_same<const char*, absl::variant_alternative_t<2, V>>::value)); EXPECT_TRUE((std::is_same<const char* const, absl::variant_alternative_t<2, const V>>::value)); EXPECT_TRUE( (std::is_same<const char* volatile, absl::variant_alternative_t<2, volatile V>>::value)); EXPECT_TRUE(( std::is_same<const char* const volatile, absl::variant_alternative_t<2, const volatile V>>::value)); } } TEST(VariantTest, HoldsAlternative) { using Var = variant<int, std::string, double>; Var v = 1; EXPECT_TRUE(absl::holds_alternative<int>(v)); EXPECT_FALSE(absl::holds_alternative<std::string>(v)); EXPECT_FALSE(absl::holds_alternative<double>(v)); v = "str"; EXPECT_FALSE(absl::holds_alternative<int>(v)); EXPECT_TRUE(absl::holds_alternative<std::string>(v)); EXPECT_FALSE(absl::holds_alternative<double>(v)); v = 0.; EXPECT_FALSE(absl::holds_alternative<int>(v)); EXPECT_FALSE(absl::holds_alternative<std::string>(v)); EXPECT_TRUE(absl::holds_alternative<double>(v)); Var v2 = v; EXPECT_FALSE(absl::holds_alternative<int>(v2)); EXPECT_FALSE(absl::holds_alternative<std::string>(v2)); EXPECT_TRUE(absl::holds_alternative<double>(v2)); v2.emplace<int>(3); EXPECT_TRUE(absl::holds_alternative<int>(v2)); EXPECT_FALSE(absl::holds_alternative<std::string>(v2)); EXPECT_FALSE(absl::holds_alternative<double>(v2)); } TEST(VariantTest, GetIndex) { using Var = variant<int, std::string, double, int>; { Var v(absl::in_place_index<0>, 0); using LValueGetType = decltype(absl::get<0>(v)); using RValueGetType = decltype(absl::get<0>(std::move(v))); EXPECT_TRUE((std::is_same<LValueGetType, int&>::value)); EXPECT_TRUE((std::is_same<RValueGetType, int&&>::value)); EXPECT_EQ(absl::get<0>(v), 0); EXPECT_EQ(absl::get<0>(std::move(v)), 0); const Var& const_v = v; using ConstLValueGetType = decltype(absl::get<0>(const_v)); using ConstRValueGetType = decltype(absl::get<0>(std::move(const_v))); EXPECT_TRUE((std::is_same<ConstLValueGetType, const int&>::value)); EXPECT_TRUE((std::is_same<ConstRValueGetType, const int&&>::value)); EXPECT_EQ(absl::get<0>(const_v), 0); EXPECT_EQ(absl::get<0>(std::move(const_v)), 0); } { Var v = std::string("Hello"); using LValueGetType = decltype(absl::get<1>(v)); using RValueGetType = decltype(absl::get<1>(std::move(v))); EXPECT_TRUE((std::is_same<LValueGetType, std::string&>::value)); EXPECT_TRUE((std::is_same<RValueGetType, std::string&&>::value)); EXPECT_EQ(absl::get<1>(v), "Hello"); EXPECT_EQ(absl::get<1>(std::move(v)), "Hello"); const Var& const_v = v; using ConstLValueGetType = decltype(absl::get<1>(const_v)); using ConstRValueGetType = decltype(absl::get<1>(std::move(const_v))); EXPECT_TRUE((std::is_same<ConstLValueGetType, const std::string&>::value)); EXPECT_TRUE((std::is_same<ConstRValueGetType, const std::string&&>::value)); EXPECT_EQ(absl::get<1>(const_v), "Hello"); EXPECT_EQ(absl::get<1>(std::move(const_v)), "Hello"); } { Var v = 2.0; using LValueGetType = decltype(absl::get<2>(v)); using RValueGetType = decltype(absl::get<2>(std::move(v))); EXPECT_TRUE((std::is_same<LValueGetType, double&>::value)); EXPECT_TRUE((std::is_same<RValueGetType, double&&>::value)); EXPECT_EQ(absl::get<2>(v), 2.); EXPECT_EQ(absl::get<2>(std::move(v)), 2.); const Var& const_v = v; using ConstLValueGetType = decltype(absl::get<2>(const_v)); using ConstRValueGetType = decltype(absl::get<2>(std::move(const_v))); EXPECT_TRUE((std::is_same<ConstLValueGetType, const double&>::value)); EXPECT_TRUE((std::is_same<ConstRValueGetType, const double&&>::value)); EXPECT_EQ(absl::get<2>(const_v), 2.); EXPECT_EQ(absl::get<2>(std::move(const_v)), 2.); } { Var v(absl::in_place_index<0>, 0); v.emplace<3>(1); using LValueGetType = decltype(absl::get<3>(v)); using RValueGetType = decltype(absl::get<3>(std::move(v))); EXPECT_TRUE((std::is_same<LValueGetType, int&>::value)); EXPECT_TRUE((std::is_same<RValueGetType, int&&>::value)); EXPECT_EQ(absl::get<3>(v), 1); EXPECT_EQ(absl::get<3>(std::move(v)), 1); const Var& const_v = v; using ConstLValueGetType = decltype(absl::get<3>(const_v)); using ConstRValueGetType = decltype(absl::get<3>(std::move(const_v))); EXPECT_TRUE((std::is_same<ConstLValueGetType, const int&>::value)); EXPECT_TRUE((std::is_same<ConstRValueGetType, const int&&>::value)); EXPECT_EQ(absl::get<3>(const_v), 1); EXPECT_EQ(absl::get<3>(std::move(const_v)), 1); } } TEST(VariantTest, BadGetIndex) { using Var = variant<int, std::string, double>; { Var v = 1; ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS(absl::get<1>(v)); ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS(absl::get<1>(std::move(v))); const Var& const_v = v; ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS(absl::get<1>(const_v)); ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS( absl::get<1>(std::move(const_v))); } { Var v = std::string("Hello"); ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS(absl::get<0>(v)); ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS(absl::get<0>(std::move(v))); const Var& const_v = v; ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS(absl::get<0>(const_v)); ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS( absl::get<0>(std::move(const_v))); } } TEST(VariantTest, GetType) { using Var = variant<int, std::string, double>; { Var v = 1; using LValueGetType = decltype(absl::get<int>(v)); using RValueGetType = decltype(absl::get<int>(std::move(v))); EXPECT_TRUE((std::is_same<LValueGetType, int&>::value)); EXPECT_TRUE((std::is_same<RValueGetType, int&&>::value)); EXPECT_EQ(absl::get<int>(v), 1); EXPECT_EQ(absl::get<int>(std::move(v)), 1); const Var& const_v = v; using ConstLValueGetType = decltype(absl::get<int>(const_v)); using ConstRValueGetType = decltype(absl::get<int>(std::move(const_v))); EXPECT_TRUE((std::is_same<ConstLValueGetType, const int&>::value)); EXPECT_TRUE((std::is_same<ConstRValueGetType, const int&&>::value)); EXPECT_EQ(absl::get<int>(const_v), 1); EXPECT_EQ(absl::get<int>(std::move(const_v)), 1); } { Var v = std::string("Hello"); using LValueGetType = decltype(absl::get<1>(v)); using RValueGetType = decltype(absl::get<1>(std::move(v))); EXPECT_TRUE((std::is_same<LValueGetType, std::string&>::value)); EXPECT_TRUE((std::is_same<RValueGetType, std::string&&>::value)); EXPECT_EQ(absl::get<std::string>(v), "Hello"); EXPECT_EQ(absl::get<std::string>(std::move(v)), "Hello"); const Var& const_v = v; using ConstLValueGetType = decltype(absl::get<1>(const_v)); using ConstRValueGetType = decltype(absl::get<1>(std::move(const_v))); EXPECT_TRUE((std::is_same<ConstLValueGetType, const std::string&>::value)); EXPECT_TRUE((std::is_same<ConstRValueGetType, const std::string&&>::value)); EXPECT_EQ(absl::get<std::string>(const_v), "Hello"); EXPECT_EQ(absl::get<std::string>(std::move(const_v)), "Hello"); } { Var v = 2.0; using LValueGetType = decltype(absl::get<2>(v)); using RValueGetType = decltype(absl::get<2>(std::move(v))); EXPECT_TRUE((std::is_same<LValueGetType, double&>::value)); EXPECT_TRUE((std::is_same<RValueGetType, double&&>::value)); EXPECT_EQ(absl::get<double>(v), 2.); EXPECT_EQ(absl::get<double>(std::move(v)), 2.); const Var& const_v = v; using ConstLValueGetType = decltype(absl::get<2>(const_v)); using ConstRValueGetType = decltype(absl::get<2>(std::move(const_v))); EXPECT_TRUE((std::is_same<ConstLValueGetType, const double&>::value)); EXPECT_TRUE((std::is_same<ConstRValueGetType, const double&&>::value)); EXPECT_EQ(absl::get<double>(const_v), 2.); EXPECT_EQ(absl::get<double>(std::move(const_v)), 2.); } } TEST(VariantTest, BadGetType) { using Var = variant<int, std::string, double>; { Var v = 1; ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS(absl::get<std::string>(v)); ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS( absl::get<std::string>(std::move(v))); const Var& const_v = v; ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS( absl::get<std::string>(const_v)); ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS( absl::get<std::string>(std::move(const_v))); } { Var v = std::string("Hello"); ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS(absl::get<int>(v)); ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS(absl::get<int>(std::move(v))); const Var& const_v = v; ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS(absl::get<int>(const_v)); ABSL_VARIANT_TEST_EXPECT_BAD_VARIANT_ACCESS( absl::get<int>(std::move(const_v))); } } TEST(VariantTest, GetIfIndex) { using Var = variant<int, std::string, double, int>; { Var v(absl::in_place_index<0>, 0); EXPECT_TRUE(noexcept(absl::get_if<0>(&v))); { auto* elem = absl::get_if<0>(&v); EXPECT_TRUE((std::is_same<decltype(elem), int*>::value)); ASSERT_NE(elem, nullptr); EXPECT_EQ(*elem, 0); { auto* bad_elem = absl::get_if<1>(&v); EXPECT_TRUE((std::is_same<decltype(bad_elem), std::string*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<2>(&v); EXPECT_TRUE((std::is_same<decltype(bad_elem), double*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<3>(&v); EXPECT_TRUE((std::is_same<decltype(bad_elem), int*>::value)); EXPECT_EQ(bad_elem, nullptr); } } const Var& const_v = v; EXPECT_TRUE(noexcept(absl::get_if<0>(&const_v))); { auto* elem = absl::get_if<0>(&const_v); EXPECT_TRUE((std::is_same<decltype(elem), const int*>::value)); ASSERT_NE(elem, nullptr); EXPECT_EQ(*elem, 0); { auto* bad_elem = absl::get_if<1>(&const_v); EXPECT_TRUE( (std::is_same<decltype(bad_elem), const std::string*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<2>(&const_v); EXPECT_TRUE((std::is_same<decltype(bad_elem), const double*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<3>(&const_v); EXPECT_EQ(bad_elem, nullptr); EXPECT_TRUE((std::is_same<decltype(bad_elem), const int*>::value)); } } } { Var v = std::string("Hello"); EXPECT_TRUE(noexcept(absl::get_if<1>(&v))); { auto* elem = absl::get_if<1>(&v); EXPECT_TRUE((std::is_same<decltype(elem), std::string*>::value)); ASSERT_NE(elem, nullptr); EXPECT_EQ(*elem, "Hello"); { auto* bad_elem = absl::get_if<0>(&v); EXPECT_TRUE((std::is_same<decltype(bad_elem), int*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<2>(&v); EXPECT_TRUE((std::is_same<decltype(bad_elem), double*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<3>(&v); EXPECT_TRUE((std::is_same<decltype(bad_elem), int*>::value)); EXPECT_EQ(bad_elem, nullptr); } } const Var& const_v = v; EXPECT_TRUE(noexcept(absl::get_if<1>(&const_v))); { auto* elem = absl::get_if<1>(&const_v); EXPECT_TRUE((std::is_same<decltype(elem), const std::string*>::value)); ASSERT_NE(elem, nullptr); EXPECT_EQ(*elem, "Hello"); { auto* bad_elem = absl::get_if<0>(&const_v); EXPECT_TRUE((std::is_same<decltype(bad_elem), const int*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<2>(&const_v); EXPECT_TRUE((std::is_same<decltype(bad_elem), const double*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<3>(&const_v); EXPECT_EQ(bad_elem, nullptr); EXPECT_TRUE((std::is_same<decltype(bad_elem), const int*>::value)); } } } { Var v = 2.0; EXPECT_TRUE(noexcept(absl::get_if<2>(&v))); { auto* elem = absl::get_if<2>(&v); EXPECT_TRUE((std::is_same<decltype(elem), double*>::value)); ASSERT_NE(elem, nullptr); EXPECT_EQ(*elem, 2.0); { auto* bad_elem = absl::get_if<0>(&v); EXPECT_TRUE((std::is_same<decltype(bad_elem), int*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<1>(&v); EXPECT_TRUE((std::is_same<decltype(bad_elem), std::string*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<3>(&v); EXPECT_TRUE((std::is_same<decltype(bad_elem), int*>::value)); EXPECT_EQ(bad_elem, nullptr); } } const Var& const_v = v; EXPECT_TRUE(noexcept(absl::get_if<2>(&const_v))); { auto* elem = absl::get_if<2>(&const_v); EXPECT_TRUE((std::is_same<decltype(elem), const double*>::value)); ASSERT_NE(elem, nullptr); EXPECT_EQ(*elem, 2.0); { auto* bad_elem = absl::get_if<0>(&const_v); EXPECT_TRUE((std::is_same<decltype(bad_elem), const int*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<1>(&const_v); EXPECT_TRUE( (std::is_same<decltype(bad_elem), const std::string*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<3>(&const_v); EXPECT_EQ(bad_elem, nullptr); EXPECT_TRUE((std::is_same<decltype(bad_elem), const int*>::value)); } } } { Var v(absl::in_place_index<0>, 0); v.emplace<3>(1); EXPECT_TRUE(noexcept(absl::get_if<3>(&v))); { auto* elem = absl::get_if<3>(&v); EXPECT_TRUE((std::is_same<decltype(elem), int*>::value)); ASSERT_NE(elem, nullptr); EXPECT_EQ(*elem, 1); { auto* bad_elem = absl::get_if<0>(&v); EXPECT_TRUE((std::is_same<decltype(bad_elem), int*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<1>(&v); EXPECT_TRUE((std::is_same<decltype(bad_elem), std::string*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<2>(&v); EXPECT_TRUE((std::is_same<decltype(bad_elem), double*>::value)); EXPECT_EQ(bad_elem, nullptr); } } const Var& const_v = v; EXPECT_TRUE(noexcept(absl::get_if<3>(&const_v))); { auto* elem = absl::get_if<3>(&const_v); EXPECT_TRUE((std::is_same<decltype(elem), const int*>::value)); ASSERT_NE(elem, nullptr); EXPECT_EQ(*elem, 1); { auto* bad_elem = absl::get_if<0>(&const_v); EXPECT_TRUE((std::is_same<decltype(bad_elem), const int*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<1>(&const_v); EXPECT_TRUE( (std::is_same<decltype(bad_elem), const std::string*>::value)); EXPECT_EQ(bad_elem, nullptr); } { auto* bad_elem = absl::get_if<2>(&const_v); EXPECT_EQ(bad_elem, nullptr); EXPECT_TRUE((std::is_same<decltype(bad_elem), const double*>::value)); } } } } TEST(VariantTest, OperatorEquals) { variant<int, std::string> a(1), b(1); EXPECT_TRUE(a == b); EXPECT_TRUE(b == a); EXPECT_FALSE(a != b); EXPECT_FALSE(b != a); b = "str"; EXPECT_FALSE(a == b); EXPECT_FALSE(b == a); EXPECT_TRUE(a != b); EXPECT_TRUE(b != a); b = 0; EXPECT_FALSE(a == b); EXPECT_FALSE(b == a); EXPECT_TRUE(a != b); EXPECT_TRUE(b != a); a = b = "foo"; EXPECT_TRUE(a == b); EXPECT_TRUE(b == a); EXPECT_FALSE(a != b); EXPECT_FALSE(b != a); a = "bar"; EXPECT_FALSE(a == b); EXPECT_FALSE(b == a); EXPECT_TRUE(a != b); EXPECT_TRUE(b != a); } TEST(VariantTest, OperatorRelational) { variant<int, std::string> a(1), b(1); EXPECT_FALSE(a < b); EXPECT_FALSE(b < a); EXPECT_FALSE(a > b); EXPECT_FALSE(b > a); EXPECT_TRUE(a <= b); EXPECT_TRUE(b <= a); EXPECT_TRUE(a >= b); EXPECT_TRUE(b >= a); b = "str"; EXPECT_TRUE(a < b); EXPECT_FALSE(b < a); EXPECT_FALSE(a > b); EXPECT_TRUE(b > a); EXPECT_TRUE(a <= b); EXPECT_FALSE(b <= a); EXPECT_FALSE(a >= b); EXPECT_TRUE(b >= a); b = 0; EXPECT_FALSE(a < b); EXPECT_TRUE(b < a); EXPECT_TRUE(a > b); EXPECT_FALSE(b > a); EXPECT_FALSE(a <= b); EXPECT_TRUE(b <= a); EXPECT_TRUE(a >= b); EXPECT_FALSE(b >= a); a = b = "foo"; EXPECT_FALSE(a < b); EXPECT_FALSE(b < a); EXPECT_FALSE(a > b); EXPECT_FALSE(b > a); EXPECT_TRUE(a <= b); EXPECT_TRUE(b <= a); EXPECT_TRUE(a >= b); EXPECT_TRUE(b >= a); a = "bar"; EXPECT_TRUE(a < b); EXPECT_FALSE(b < a); EXPECT_FALSE(a > b); EXPECT_TRUE(b > a); EXPECT_TRUE(a <= b); EXPECT_FALSE(b <= a); EXPECT_FALSE(a >= b); EXPECT_TRUE(b >= a); } #ifdef ABSL_HAVE_EXCEPTIONS TEST(VariantTest, ValuelessOperatorEquals) { variant<MoveCanThrow, std::string> int_v(1), string_v("Hello"), valueless(absl::in_place_index<0>), other_valueless(absl::in_place_index<0>); ToValuelessByException(valueless); ToValuelessByException(other_valueless); EXPECT_TRUE(valueless == other_valueless); EXPECT_TRUE(other_valueless == valueless); EXPECT_FALSE(valueless == int_v); EXPECT_FALSE(valueless == string_v); EXPECT_FALSE(int_v == valueless); EXPECT_FALSE(string_v == valueless); EXPECT_FALSE(valueless != other_valueless); EXPECT_FALSE(other_valueless != valueless); EXPECT_TRUE(valueless != int_v); EXPECT_TRUE(valueless != string_v); EXPECT_TRUE(int_v != valueless); EXPECT_TRUE(string_v != valueless); } TEST(VariantTest, ValuelessOperatorRelational) { variant<MoveCanThrow, std::string> int_v(1), string_v("Hello"), valueless(absl::in_place_index<0>), other_valueless(absl::in_place_index<0>); ToValuelessByException(valueless); ToValuelessByException(other_valueless); EXPECT_FALSE(valueless < other_valueless); EXPECT_FALSE(other_valueless < valueless); EXPECT_TRUE(valueless < int_v); EXPECT_TRUE(valueless < string_v); EXPECT_FALSE(int_v < valueless); EXPECT_FALSE(string_v < valueless); EXPECT_TRUE(valueless <= other_valueless); EXPECT_TRUE(other_valueless <= valueless); EXPECT_TRUE(valueless <= int_v); EXPECT_TRUE(valueless <= string_v); EXPECT_FALSE(int_v <= valueless); EXPECT_FALSE(string_v <= valueless); EXPECT_TRUE(valueless >= other_valueless); EXPECT_TRUE(other_valueless >= valueless); EXPECT_FALSE(valueless >= int_v); EXPECT_FALSE(valueless >= string_v); EXPECT_TRUE(int_v >= valueless); EXPECT_TRUE(string_v >= valueless); EXPECT_FALSE(valueless > other_valueless); EXPECT_FALSE(other_valueless > valueless); EXPECT_FALSE(valueless > int_v); EXPECT_FALSE(valueless > string_v); EXPECT_TRUE(int_v > valueless); EXPECT_TRUE(string_v > valueless); } #endif template <typename T> struct ConvertTo { template <typename U> T operator()(const U& u) const { return u; } }; TEST(VariantTest, VisitSimple) { variant<std::string, const char*> v = "A"; std::string str = absl::visit(ConvertTo<std::string>{}, v); EXPECT_EQ("A", str); v = std::string("B"); absl::string_view piece = absl::visit(ConvertTo<absl::string_view>{}, v); EXPECT_EQ("B", piece); struct StrLen { size_t operator()(const char* s) const { return strlen(s); } size_t operator()(const std::string& s) const { return s.size(); } }; v = "SomeStr"; EXPECT_EQ(7u, absl::visit(StrLen{}, v)); v = std::string("VeryLargeThisTime"); EXPECT_EQ(17u, absl::visit(StrLen{}, v)); } TEST(VariantTest, VisitRValue) { variant<std::string> v = std::string("X"); struct Visitor { bool operator()(const std::string&) const { return false; } bool operator()(std::string&&) const { return true; } int operator()(const std::string&, const std::string&) const { return 0; } int operator()(const std::string&, std::string&&) const { return 1; } int operator()(std::string&&, const std::string&) const { return 2; } int operator()(std::string&&, std::string&&) const { return 3; } }; EXPECT_FALSE(absl::visit(Visitor{}, v)); EXPECT_TRUE(absl::visit(Visitor{}, std::move(v))); EXPECT_EQ(0, absl::visit(Visitor{}, v, v)); EXPECT_EQ(1, absl::visit(Visitor{}, v, std::move(v))); EXPECT_EQ(2, absl::visit(Visitor{}, std::move(v), v)); EXPECT_EQ(3, absl::visit(Visitor{}, std::move(v), std::move(v))); } TEST(VariantTest, VisitRValueVisitor) { variant<std::string> v = std::string("X"); struct Visitor { bool operator()(const std::string&) const& { return false; } bool operator()(const std::string&) && { return true; } }; Visitor visitor; EXPECT_FALSE(absl::visit(visitor, v)); EXPECT_TRUE(absl::visit(Visitor{}, v)); } TEST(VariantTest, VisitResultTypeDifferent) { variant<std::string> v = std::string("X"); struct LValue_LValue {}; struct RValue_LValue {}; struct LValue_RValue {}; struct RValue_RValue {}; struct Visitor { LValue_LValue operator()(const std::string&) const& { return {}; } RValue_LValue operator()(std::string&&) const& { return {}; } LValue_RValue operator()(const std::string&) && { return {}; } RValue_RValue operator()(std::string&&) && { return {}; } } visitor; EXPECT_TRUE( (std::is_same<LValue_LValue, decltype(absl::visit(visitor, v))>::value)); EXPECT_TRUE( (std::is_same<RValue_LValue, decltype(absl::visit(visitor, std::move(v)))>::value)); EXPECT_TRUE(( std::is_same<LValue_RValue, decltype(absl::visit(Visitor{}, v))>::value)); EXPECT_TRUE( (std::is_same<RValue_RValue, decltype(absl::visit(Visitor{}, std::move(v)))>::value)); } TEST(VariantTest, VisitVariadic) { using A = variant<int, std::string>; using B = variant<std::unique_ptr<int>, absl::string_view>; struct Visitor { std::pair<int, int> operator()(int a, std::unique_ptr<int> b) const { return {a, *b}; } std::pair<int, int> operator()(absl::string_view a, std::unique_ptr<int> b) const { return {static_cast<int>(a.size()), static_cast<int>(*b)}; } std::pair<int, int> operator()(int a, absl::string_view b) const { return {a, static_cast<int>(b.size())}; } std::pair<int, int> operator()(absl::string_view a, absl::string_view b) const { return {static_cast<int>(a.size()), static_cast<int>(b.size())}; } }; EXPECT_THAT(absl::visit(Visitor(), A(1), B(std::unique_ptr<int>(new int(7)))), ::testing::Pair(1, 7)); EXPECT_THAT(absl::visit(Visitor(), A(1), B(absl::string_view("ABC"))), ::testing::Pair(1, 3)); EXPECT_THAT(absl::visit(Visitor(), A(std::string("BBBBB")), B(std::unique_ptr<int>(new int(7)))), ::testing::Pair(5, 7)); EXPECT_THAT(absl::visit(Visitor(), A(std::string("BBBBB")), B(absl::string_view("ABC"))), ::testing::Pair(5, 3)); } TEST(VariantTest, VisitNoArgs) { EXPECT_EQ(5, absl::visit([] { return 5; })); } struct ConstFunctor { int operator()(int a, int b) const { return a - b; } }; struct MutableFunctor { int operator()(int a, int b) { return a - b; } }; struct Class { int Method(int a, int b) { return a - b; } int ConstMethod(int a, int b) const { return a - b; } int member; }; TEST(VariantTest, VisitReferenceWrapper) { ConstFunctor cf; MutableFunctor mf; absl::variant<int> three = 3; absl::variant<int> two = 2; EXPECT_EQ(1, absl::visit(std::cref(cf), three, two)); EXPECT_EQ(1, absl::visit(std::ref(cf), three, two)); EXPECT_EQ(1, absl::visit(std::ref(mf), three, two)); } #if !(defined(ABSL_USES_STD_VARIANT) && defined(__GLIBCXX__)) TEST(VariantTest, VisitMemberFunction) { absl::variant<std::unique_ptr<Class>> p(absl::make_unique<Class>()); absl::variant<std::unique_ptr<const Class>> cp( absl::make_unique<const Class>()); absl::variant<int> three = 3; absl::variant<int> two = 2; EXPECT_EQ(1, absl::visit(&Class::Method, p, three, two)); EXPECT_EQ(1, absl::visit(&Class::ConstMethod, p, three, two)); EXPECT_EQ(1, absl::visit(&Class::ConstMethod, cp, three, two)); } TEST(VariantTest, VisitDataMember) { absl::variant<std::unique_ptr<Class>> p(absl::make_unique<Class>(Class{42})); absl::variant<std::unique_ptr<const Class>> cp( absl::make_unique<const Class>(Class{42})); EXPECT_EQ(42, absl::visit(&Class::member, p)); absl::visit(&Class::member, p) = 5; EXPECT_EQ(5, absl::visit(&Class::member, p)); EXPECT_EQ(42, absl::visit(&Class::member, cp)); } #endif TEST(VariantTest, MonostateBasic) { absl::monostate mono; (void)mono; EXPECT_TRUE(absl::is_trivially_default_constructible<absl::monostate>::value); EXPECT_TRUE(is_trivially_move_constructible<absl::monostate>::value); EXPECT_TRUE(absl::is_trivially_copy_constructible<absl::monostate>::value); EXPECT_TRUE(is_trivially_move_assignable<absl::monostate>::value); EXPECT_TRUE(absl::is_trivially_copy_assignable<absl::monostate>::value); EXPECT_TRUE(absl::is_trivially_destructible<absl::monostate>::value); } TEST(VariantTest, VariantMonostateDefaultConstruction) { absl::variant<absl::monostate, NonDefaultConstructible> var; EXPECT_EQ(var.index(), 0u); } TEST(VariantTest, MonostateComparisons) { absl::monostate lhs, rhs; EXPECT_EQ(lhs, lhs); EXPECT_EQ(lhs, rhs); EXPECT_FALSE(lhs != lhs); EXPECT_FALSE(lhs != rhs); EXPECT_FALSE(lhs < lhs); EXPECT_FALSE(lhs < rhs); EXPECT_FALSE(lhs > lhs); EXPECT_FALSE(lhs > rhs); EXPECT_LE(lhs, lhs); EXPECT_LE(lhs, rhs); EXPECT_GE(lhs, lhs); EXPECT_GE(lhs, rhs); EXPECT_TRUE(noexcept(std::declval<absl::monostate>() == std::declval<absl::monostate>())); EXPECT_TRUE(noexcept(std::declval<absl::monostate>() != std::declval<absl::monostate>())); EXPECT_TRUE(noexcept(std::declval<absl::monostate>() < std::declval<absl::monostate>())); EXPECT_TRUE(noexcept(std::declval<absl::monostate>() > std::declval<absl::monostate>())); EXPECT_TRUE(noexcept(std::declval<absl::monostate>() <= std::declval<absl::monostate>())); EXPECT_TRUE(noexcept(std::declval<absl::monostate>() >= std::declval<absl::monostate>())); } TEST(VariantTest, NonmemberSwap) { using std::swap; SpecialSwap v1(3); SpecialSwap v2(7); variant<SpecialSwap> a = v1, b = v2; EXPECT_THAT(a, VariantWith<SpecialSwap>(v1)); EXPECT_THAT(b, VariantWith<SpecialSwap>(v2)); std::swap(a, b); EXPECT_THAT(a, VariantWith<SpecialSwap>(v2)); EXPECT_THAT(b, VariantWith<SpecialSwap>(v1)); #ifndef ABSL_USES_STD_VARIANT EXPECT_FALSE(absl::get<SpecialSwap>(a).special_swap); #endif swap(a, b); EXPECT_THAT(a, VariantWith<SpecialSwap>(v1)); EXPECT_THAT(b, VariantWith<SpecialSwap>(v2)); EXPECT_TRUE(absl::get<SpecialSwap>(b).special_swap); } TEST(VariantTest, BadAccess) { EXPECT_TRUE(noexcept(absl::bad_variant_access())); absl::bad_variant_access exception_obj; std::exception* base = &exception_obj; (void)base; } TEST(VariantTest, MonostateHash) { absl::monostate mono, other_mono; std::hash<absl::monostate> const hasher{}; static_assert(std::is_same<decltype(hasher(mono)), std::size_t>::value, ""); EXPECT_EQ(hasher(mono), hasher(other_mono)); } TEST(VariantTest, Hash) { static_assert(type_traits_internal::IsHashable<variant<int>>::value, ""); static_assert(type_traits_internal::IsHashable<variant<Hashable>>::value, ""); static_assert(type_traits_internal::IsHashable<variant<int, Hashable>>::value, ""); #if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ static_assert(!type_traits_internal::IsHashable<variant<NonHashable>>::value, ""); static_assert( !type_traits_internal::IsHashable<variant<Hashable, NonHashable>>::value, ""); #endif #if !(defined(_MSC_VER) && defined(ABSL_USES_STD_VARIANT)) { variant<int, int> v0(in_place_index<0>, 42); variant<int, int> v1(in_place_index<1>, 42); std::hash<variant<int, int>> hash; EXPECT_NE(hash(v0), hash(v1)); } #endif { std::hash<variant<int>> hash; std::set<size_t> hashcodes; for (int i = 0; i < 100; ++i) { hashcodes.insert(hash(i)); } EXPECT_GT(hashcodes.size(), 90u); static_assert(type_traits_internal::IsHashable<variant<const int>>::value, ""); static_assert( type_traits_internal::IsHashable<variant<const Hashable>>::value, ""); std::hash<absl::variant<const int>> c_hash; for (int i = 0; i < 100; ++i) { EXPECT_EQ(hash(i), c_hash(i)); } } } #if !defined(ABSL_USES_STD_VARIANT) TEST(VariantTest, TestConvertingSet) { typedef variant<double> Variant; Variant v(1.0); const int two = 2; v = two; EXPECT_TRUE(absl::holds_alternative<double>(v)); ASSERT_TRUE(nullptr != absl::get_if<double>(&v)); EXPECT_DOUBLE_EQ(2, absl::get<double>(v)); } #endif TEST(VariantTest, Container) { typedef variant<int, float> Variant; std::vector<Variant> vec; vec.push_back(Variant(10)); vec.push_back(Variant(20.0f)); vec.resize(10, Variant(0)); } TEST(VariantTest, TestVariantWithNonCopyableType) { typedef variant<int, NonCopyable> Variant; const int kValue = 1; Variant v(kValue); ASSERT_TRUE(absl::holds_alternative<int>(v)); EXPECT_EQ(kValue, absl::get<int>(v)); } TEST(VariantTest, TestEmplace) { typedef variant<int, NonCopyable> Variant; const int kValue = 1; Variant v(kValue); ASSERT_TRUE(absl::holds_alternative<int>(v)); EXPECT_EQ(kValue, absl::get<int>(v)); v.emplace<NonCopyable>(); ASSERT_TRUE(absl::holds_alternative<NonCopyable>(v)); EXPECT_EQ(0, absl::get<NonCopyable>(v).value); v = kValue; ASSERT_TRUE(absl::holds_alternative<int>(v)); v.emplace<NonCopyable>(1); ASSERT_TRUE(absl::holds_alternative<NonCopyable>(v)); EXPECT_EQ(1, absl::get<NonCopyable>(v).value); v = kValue; ASSERT_TRUE(absl::holds_alternative<int>(v)); v.emplace<NonCopyable>(1, 2); ASSERT_TRUE(absl::holds_alternative<NonCopyable>(v)); EXPECT_EQ(3, absl::get<NonCopyable>(v).value); v = kValue; ASSERT_TRUE(absl::holds_alternative<int>(v)); v.emplace<NonCopyable>(1, 2, 3); ASSERT_TRUE(absl::holds_alternative<NonCopyable>(v)); EXPECT_EQ(6, absl::get<NonCopyable>(v).value); v = kValue; ASSERT_TRUE(absl::holds_alternative<int>(v)); v.emplace<NonCopyable>(1, 2, 3, 4); ASSERT_TRUE(absl::holds_alternative<NonCopyable>(v)); EXPECT_EQ(10, absl::get<NonCopyable>(v).value); v = kValue; ASSERT_TRUE(absl::holds_alternative<int>(v)); } TEST(VariantTest, TestEmplaceDestroysCurrentValue) { typedef variant<int, IncrementInDtor, NonCopyable> Variant; int counter = 0; Variant v(0); ASSERT_TRUE(absl::holds_alternative<int>(v)); v.emplace<IncrementInDtor>(&counter); ASSERT_TRUE(absl::holds_alternative<IncrementInDtor>(v)); ASSERT_EQ(0, counter); v.emplace<NonCopyable>(); ASSERT_TRUE(absl::holds_alternative<NonCopyable>(v)); EXPECT_EQ(1, counter); } TEST(VariantTest, TestMoveSemantics) { typedef variant<std::unique_ptr<int>, std::unique_ptr<std::string>> Variant; Variant v(absl::WrapUnique(new int(10))); EXPECT_TRUE(absl::holds_alternative<std::unique_ptr<int>>(v)); Variant v2(std::move(v)); ASSERT_TRUE(absl::holds_alternative<std::unique_ptr<int>>(v2)); ASSERT_NE(nullptr, absl::get<std::unique_ptr<int>>(v2)); EXPECT_EQ(10, *absl::get<std::unique_ptr<int>>(v2)); EXPECT_TRUE(absl::holds_alternative<std::unique_ptr<int>>(v)); ASSERT_NE(nullptr, absl::get_if<std::unique_ptr<int>>(&v)); EXPECT_EQ(nullptr, absl::get<std::unique_ptr<int>>(v)); v = absl::make_unique<std::string>("foo"); ASSERT_TRUE(absl::holds_alternative<std::unique_ptr<std::string>>(v)); EXPECT_EQ("foo", *absl::get<std::unique_ptr<std::string>>(v)); v2 = std::move(v); ASSERT_TRUE(absl::holds_alternative<std::unique_ptr<std::string>>(v2)); EXPECT_EQ("foo", *absl::get<std::unique_ptr<std::string>>(v2)); EXPECT_TRUE(absl::holds_alternative<std::unique_ptr<std::string>>(v)); } variant<int, std::string> PassThrough(const variant<int, std::string>& arg) { return arg; } TEST(VariantTest, TestImplicitConversion) { EXPECT_TRUE(absl::holds_alternative<int>(PassThrough(0))); EXPECT_TRUE( absl::holds_alternative<std::string>(PassThrough(std::string("foo")))); } struct Convertible2; struct Convertible1 { Convertible1() {} Convertible1(const Convertible1&) {} Convertible1& operator=(const Convertible1&) { return *this; } Convertible1(const Convertible2&) {} }; struct Convertible2 { Convertible2() {} Convertible2(const Convertible2&) {} Convertible2& operator=(const Convertible2&) { return *this; } Convertible2(const Convertible1&) {} }; TEST(VariantTest, TestRvalueConversion) { #if !defined(ABSL_USES_STD_VARIANT) variant<double, std::string> var( ConvertVariantTo<variant<double, std::string>>( variant<std::string, int>(0))); ASSERT_TRUE(absl::holds_alternative<double>(var)); EXPECT_EQ(0.0, absl::get<double>(var)); var = ConvertVariantTo<variant<double, std::string>>( variant<const char*, float>("foo")); ASSERT_TRUE(absl::holds_alternative<std::string>(var)); EXPECT_EQ("foo", absl::get<std::string>(var)); variant<double> singleton( ConvertVariantTo<variant<double>>(variant<int, float>(42))); ASSERT_TRUE(absl::holds_alternative<double>(singleton)); EXPECT_EQ(42.0, absl::get<double>(singleton)); singleton = ConvertVariantTo<variant<double>>(variant<int, float>(3.14f)); ASSERT_TRUE(absl::holds_alternative<double>(singleton)); EXPECT_FLOAT_EQ(3.14f, static_cast<float>(absl::get<double>(singleton))); singleton = ConvertVariantTo<variant<double>>(variant<int>(0)); ASSERT_TRUE(absl::holds_alternative<double>(singleton)); EXPECT_EQ(0.0, absl::get<double>(singleton)); variant<int32_t, uint32_t> variant2( ConvertVariantTo<variant<int32_t, uint32_t>>(variant<int32_t>(42))); ASSERT_TRUE(absl::holds_alternative<int32_t>(variant2)); EXPECT_EQ(42, absl::get<int32_t>(variant2)); variant2 = ConvertVariantTo<variant<int32_t, uint32_t>>(variant<uint32_t>(42u)); ASSERT_TRUE(absl::holds_alternative<uint32_t>(variant2)); EXPECT_EQ(42u, absl::get<uint32_t>(variant2)); #endif variant<Convertible1, Convertible2> variant3( ConvertVariantTo<variant<Convertible1, Convertible2>>( (variant<Convertible2, Convertible1>(Convertible1())))); ASSERT_TRUE(absl::holds_alternative<Convertible1>(variant3)); variant3 = ConvertVariantTo<variant<Convertible1, Convertible2>>( variant<Convertible2, Convertible1>(Convertible2())); ASSERT_TRUE(absl::holds_alternative<Convertible2>(variant3)); } TEST(VariantTest, TestLvalueConversion) { #if !defined(ABSL_USES_STD_VARIANT) variant<std::string, int> source1 = 0; variant<double, std::string> destination( ConvertVariantTo<variant<double, std::string>>(source1)); ASSERT_TRUE(absl::holds_alternative<double>(destination)); EXPECT_EQ(0.0, absl::get<double>(destination)); variant<const char*, float> source2 = "foo"; destination = ConvertVariantTo<variant<double, std::string>>(source2); ASSERT_TRUE(absl::holds_alternative<std::string>(destination)); EXPECT_EQ("foo", absl::get<std::string>(destination)); variant<int, float> source3(42); variant<double> singleton(ConvertVariantTo<variant<double>>(source3)); ASSERT_TRUE(absl::holds_alternative<double>(singleton)); EXPECT_EQ(42.0, absl::get<double>(singleton)); source3 = 3.14f; singleton = ConvertVariantTo<variant<double>>(source3); ASSERT_TRUE(absl::holds_alternative<double>(singleton)); EXPECT_FLOAT_EQ(3.14f, static_cast<float>(absl::get<double>(singleton))); variant<int> source4(0); singleton = ConvertVariantTo<variant<double>>(source4); ASSERT_TRUE(absl::holds_alternative<double>(singleton)); EXPECT_EQ(0.0, absl::get<double>(singleton)); variant<int32_t> source5(42); variant<int32_t, uint32_t> variant2( ConvertVariantTo<variant<int32_t, uint32_t>>(source5)); ASSERT_TRUE(absl::holds_alternative<int32_t>(variant2)); EXPECT_EQ(42, absl::get<int32_t>(variant2)); variant<uint32_t> source6(42u); variant2 = ConvertVariantTo<variant<int32_t, uint32_t>>(source6); ASSERT_TRUE(absl::holds_alternative<uint32_t>(variant2)); EXPECT_EQ(42u, absl::get<uint32_t>(variant2)); #endif variant<Convertible2, Convertible1> source7((Convertible1())); variant<Convertible1, Convertible2> variant3( ConvertVariantTo<variant<Convertible1, Convertible2>>(source7)); ASSERT_TRUE(absl::holds_alternative<Convertible1>(variant3)); source7 = Convertible2(); variant3 = ConvertVariantTo<variant<Convertible1, Convertible2>>(source7); ASSERT_TRUE(absl::holds_alternative<Convertible2>(variant3)); } TEST(VariantTest, TestMoveConversion) { using Variant = variant<std::unique_ptr<const int>, std::unique_ptr<const std::string>>; using OtherVariant = variant<std::unique_ptr<int>, std::unique_ptr<std::string>>; Variant var( ConvertVariantTo<Variant>(OtherVariant{absl::make_unique<int>(0)})); ASSERT_TRUE(absl::holds_alternative<std::unique_ptr<const int>>(var)); ASSERT_NE(absl::get<std::unique_ptr<const int>>(var), nullptr); EXPECT_EQ(0, *absl::get<std::unique_ptr<const int>>(var)); var = ConvertVariantTo<Variant>( OtherVariant(absl::make_unique<std::string>("foo"))); ASSERT_TRUE(absl::holds_alternative<std::unique_ptr<const std::string>>(var)); EXPECT_EQ("foo", *absl::get<std::unique_ptr<const std::string>>(var)); } TEST(VariantTest, DoesNotMoveFromLvalues) { using Variant = variant<std::shared_ptr<const int>, std::shared_ptr<const std::string>>; using OtherVariant = variant<std::shared_ptr<int>, std::shared_ptr<std::string>>; Variant v1(std::make_shared<const int>(0)); Variant v2(v1); EXPECT_EQ(absl::get<std::shared_ptr<const int>>(v1), absl::get<std::shared_ptr<const int>>(v2)); v1 = std::make_shared<const std::string>("foo"); v2 = v1; EXPECT_EQ(absl::get<std::shared_ptr<const std::string>>(v1), absl::get<std::shared_ptr<const std::string>>(v2)); OtherVariant other(std::make_shared<int>(0)); Variant v3(ConvertVariantTo<Variant>(other)); EXPECT_EQ(absl::get<std::shared_ptr<int>>(other), absl::get<std::shared_ptr<const int>>(v3)); other = std::make_shared<std::string>("foo"); v3 = ConvertVariantTo<Variant>(other); EXPECT_EQ(absl::get<std::shared_ptr<std::string>>(other), absl::get<std::shared_ptr<const std::string>>(v3)); } TEST(VariantTest, TestRvalueConversionViaConvertVariantTo) { #if !defined(ABSL_USES_STD_VARIANT) variant<double, std::string> var( ConvertVariantTo<variant<double, std::string>>( variant<std::string, int>(3))); EXPECT_THAT(absl::get_if<double>(&var), Pointee(3.0)); var = ConvertVariantTo<variant<double, std::string>>( variant<const char*, float>("foo")); EXPECT_THAT(absl::get_if<std::string>(&var), Pointee(std::string("foo"))); variant<double> singleton( ConvertVariantTo<variant<double>>(variant<int, float>(42))); EXPECT_THAT(absl::get_if<double>(&singleton), Pointee(42.0)); singleton = ConvertVariantTo<variant<double>>(variant<int, float>(3.14f)); EXPECT_THAT(absl::get_if<double>(&singleton), Pointee(DoubleEq(3.14f))); singleton = ConvertVariantTo<variant<double>>(variant<int>(3)); EXPECT_THAT(absl::get_if<double>(&singleton), Pointee(3.0)); variant<int32_t, uint32_t> variant2( ConvertVariantTo<variant<int32_t, uint32_t>>(variant<int32_t>(42))); EXPECT_THAT(absl::get_if<int32_t>(&variant2), Pointee(42)); variant2 = ConvertVariantTo<variant<int32_t, uint32_t>>(variant<uint32_t>(42u)); EXPECT_THAT(absl::get_if<uint32_t>(&variant2), Pointee(42u)); #endif variant<Convertible1, Convertible2> variant3( ConvertVariantTo<variant<Convertible1, Convertible2>>( (variant<Convertible2, Convertible1>(Convertible1())))); ASSERT_TRUE(absl::holds_alternative<Convertible1>(variant3)); variant3 = ConvertVariantTo<variant<Convertible1, Convertible2>>( variant<Convertible2, Convertible1>(Convertible2())); ASSERT_TRUE(absl::holds_alternative<Convertible2>(variant3)); } TEST(VariantTest, TestLvalueConversionViaConvertVariantTo) { #if !defined(ABSL_USES_STD_VARIANT) variant<std::string, int> source1 = 3; variant<double, std::string> destination( ConvertVariantTo<variant<double, std::string>>(source1)); EXPECT_THAT(absl::get_if<double>(&destination), Pointee(3.0)); variant<const char*, float> source2 = "foo"; destination = ConvertVariantTo<variant<double, std::string>>(source2); EXPECT_THAT(absl::get_if<std::string>(&destination), Pointee(std::string("foo"))); variant<int, float> source3(42); variant<double> singleton(ConvertVariantTo<variant<double>>(source3)); EXPECT_THAT(absl::get_if<double>(&singleton), Pointee(42.0)); source3 = 3.14f; singleton = ConvertVariantTo<variant<double>>(source3); EXPECT_FLOAT_EQ(3.14f, static_cast<float>(absl::get<double>(singleton))); EXPECT_THAT(absl::get_if<double>(&singleton), Pointee(DoubleEq(3.14f))); variant<int> source4(3); singleton = ConvertVariantTo<variant<double>>(source4); EXPECT_THAT(absl::get_if<double>(&singleton), Pointee(3.0)); variant<int32_t> source5(42); variant<int32_t, uint32_t> variant2( ConvertVariantTo<variant<int32_t, uint32_t>>(source5)); EXPECT_THAT(absl::get_if<int32_t>(&variant2), Pointee(42)); variant<uint32_t> source6(42u); variant2 = ConvertVariantTo<variant<int32_t, uint32_t>>(source6); EXPECT_THAT(absl::get_if<uint32_t>(&variant2), Pointee(42u)); #endif variant<Convertible2, Convertible1> source7((Convertible1())); variant<Convertible1, Convertible2> variant3( ConvertVariantTo<variant<Convertible1, Convertible2>>(source7)); ASSERT_TRUE(absl::holds_alternative<Convertible1>(variant3)); source7 = Convertible2(); variant3 = ConvertVariantTo<variant<Convertible1, Convertible2>>(source7); ASSERT_TRUE(absl::holds_alternative<Convertible2>(variant3)); } TEST(VariantTest, TestMoveConversionViaConvertVariantTo) { using Variant = variant<std::unique_ptr<const int>, std::unique_ptr<const std::string>>; using OtherVariant = variant<std::unique_ptr<int>, std::unique_ptr<std::string>>; Variant var( ConvertVariantTo<Variant>(OtherVariant{absl::make_unique<int>(3)})); EXPECT_THAT(absl::get_if<std::unique_ptr<const int>>(&var), Pointee(Pointee(3))); var = ConvertVariantTo<Variant>( OtherVariant(absl::make_unique<std::string>("foo"))); EXPECT_THAT(absl::get_if<std::unique_ptr<const std::string>>(&var), Pointee(Pointee(std::string("foo")))); } #if !(defined(ABSL_USES_STD_VARIANT) && defined(__GLIBCXX__)) #define ABSL_VARIANT_PROPAGATE_COPY_MOVE_TRIVIALITY 1 #endif TEST(VariantTest, TestCopyAndMoveTypeTraits) { EXPECT_TRUE(std::is_copy_constructible<variant<std::string>>::value); EXPECT_TRUE(absl::is_copy_assignable<variant<std::string>>::value); EXPECT_TRUE(std::is_move_constructible<variant<std::string>>::value); EXPECT_TRUE(absl::is_move_assignable<variant<std::string>>::value); EXPECT_TRUE(std::is_move_constructible<variant<std::unique_ptr<int>>>::value); EXPECT_TRUE(absl::is_move_assignable<variant<std::unique_ptr<int>>>::value); EXPECT_FALSE( std::is_copy_constructible<variant<std::unique_ptr<int>>>::value); EXPECT_FALSE(absl::is_copy_assignable<variant<std::unique_ptr<int>>>::value); EXPECT_FALSE( absl::is_trivially_copy_constructible<variant<std::string>>::value); EXPECT_FALSE(absl::is_trivially_copy_assignable<variant<std::string>>::value); #if ABSL_VARIANT_PROPAGATE_COPY_MOVE_TRIVIALITY EXPECT_TRUE(absl::is_trivially_copy_constructible<variant<int>>::value); EXPECT_TRUE(absl::is_trivially_copy_assignable<variant<int>>::value); EXPECT_TRUE(is_trivially_move_constructible<variant<int>>::value); EXPECT_TRUE(is_trivially_move_assignable<variant<int>>::value); #endif } TEST(VariantTest, TestVectorOfMoveonlyVariant) { std::vector<variant<std::unique_ptr<int>, std::string>> vec; vec.push_back(absl::make_unique<int>(42)); vec.emplace_back("Hello"); vec.reserve(3); auto another_vec = std::move(vec); ASSERT_EQ(2u, another_vec.size()); EXPECT_EQ(42, *absl::get<std::unique_ptr<int>>(another_vec[0])); EXPECT_EQ("Hello", absl::get<std::string>(another_vec[1])); } TEST(VariantTest, NestedVariant) { #if ABSL_VARIANT_PROPAGATE_COPY_MOVE_TRIVIALITY static_assert(absl::is_trivially_copy_constructible<variant<int>>(), ""); static_assert(absl::is_trivially_copy_assignable<variant<int>>(), ""); static_assert(is_trivially_move_constructible<variant<int>>(), ""); static_assert(is_trivially_move_assignable<variant<int>>(), ""); static_assert(absl::is_trivially_copy_constructible<variant<variant<int>>>(), ""); static_assert(absl::is_trivially_copy_assignable<variant<variant<int>>>(), ""); static_assert(is_trivially_move_constructible<variant<variant<int>>>(), ""); static_assert(is_trivially_move_assignable<variant<variant<int>>>(), ""); #endif variant<int> x(42); variant<variant<int>> y(x); variant<variant<int>> z(y); EXPECT_TRUE(absl::holds_alternative<variant<int>>(z)); EXPECT_EQ(x, absl::get<variant<int>>(z)); } struct TriviallyDestructible { TriviallyDestructible(TriviallyDestructible&&) {} TriviallyDestructible(const TriviallyDestructible&) {} TriviallyDestructible& operator=(TriviallyDestructible&&) { return *this; } TriviallyDestructible& operator=(const TriviallyDestructible&) { return *this; } }; struct TriviallyMovable { TriviallyMovable(TriviallyMovable&&) = default; TriviallyMovable(TriviallyMovable const&) {} TriviallyMovable& operator=(const TriviallyMovable&) { return *this; } }; struct TriviallyCopyable { TriviallyCopyable(const TriviallyCopyable&) = default; TriviallyCopyable& operator=(const TriviallyCopyable&) { return *this; } }; struct TriviallyMoveAssignable { TriviallyMoveAssignable(TriviallyMoveAssignable&&) = default; TriviallyMoveAssignable(const TriviallyMoveAssignable&) {} TriviallyMoveAssignable& operator=(TriviallyMoveAssignable&&) = default; TriviallyMoveAssignable& operator=(const TriviallyMoveAssignable&) { return *this; } }; struct TriviallyCopyAssignable {}; #if ABSL_VARIANT_PROPAGATE_COPY_MOVE_TRIVIALITY TEST(VariantTest, TestTriviality) { { using TrivDestVar = absl::variant<TriviallyDestructible>; EXPECT_FALSE(is_trivially_move_constructible<TrivDestVar>::value); EXPECT_FALSE(absl::is_trivially_copy_constructible<TrivDestVar>::value); EXPECT_FALSE(is_trivially_move_assignable<TrivDestVar>::value); EXPECT_FALSE(absl::is_trivially_copy_assignable<TrivDestVar>::value); EXPECT_TRUE(absl::is_trivially_destructible<TrivDestVar>::value); } { using TrivMoveVar = absl::variant<TriviallyMovable>; EXPECT_TRUE(is_trivially_move_constructible<TrivMoveVar>::value); EXPECT_FALSE(absl::is_trivially_copy_constructible<TrivMoveVar>::value); EXPECT_FALSE(is_trivially_move_assignable<TrivMoveVar>::value); EXPECT_FALSE(absl::is_trivially_copy_assignable<TrivMoveVar>::value); EXPECT_TRUE(absl::is_trivially_destructible<TrivMoveVar>::value); } { using TrivCopyVar = absl::variant<TriviallyCopyable>; EXPECT_TRUE(is_trivially_move_constructible<TrivCopyVar>::value); EXPECT_TRUE(absl::is_trivially_copy_constructible<TrivCopyVar>::value); EXPECT_FALSE(is_trivially_move_assignable<TrivCopyVar>::value); EXPECT_FALSE(absl::is_trivially_copy_assignable<TrivCopyVar>::value); EXPECT_TRUE(absl::is_trivially_destructible<TrivCopyVar>::value); } { using TrivMoveAssignVar = absl::variant<TriviallyMoveAssignable>; EXPECT_TRUE(is_trivially_move_constructible<TrivMoveAssignVar>::value); EXPECT_FALSE( absl::is_trivially_copy_constructible<TrivMoveAssignVar>::value); EXPECT_TRUE(is_trivially_move_assignable<TrivMoveAssignVar>::value); EXPECT_FALSE(absl::is_trivially_copy_assignable<TrivMoveAssignVar>::value); EXPECT_TRUE(absl::is_trivially_destructible<TrivMoveAssignVar>::value); } { using TrivCopyAssignVar = absl::variant<TriviallyCopyAssignable>; EXPECT_TRUE(is_trivially_move_constructible<TrivCopyAssignVar>::value); EXPECT_TRUE( absl::is_trivially_copy_constructible<TrivCopyAssignVar>::value); EXPECT_TRUE(is_trivially_move_assignable<TrivCopyAssignVar>::value); EXPECT_TRUE(absl::is_trivially_copy_assignable<TrivCopyAssignVar>::value); EXPECT_TRUE(absl::is_trivially_destructible<TrivCopyAssignVar>::value); } } #endif TEST(VariantTest, MoveCtorBug) { struct TrivialCopyNontrivialMove { TrivialCopyNontrivialMove() = default; TrivialCopyNontrivialMove(const TrivialCopyNontrivialMove&) = default; TrivialCopyNontrivialMove(TrivialCopyNontrivialMove&&) { called = true; } bool called = false; }; { using V = absl::variant<TrivialCopyNontrivialMove, int>; V v1(absl::in_place_index<0>); V v2(std::move(v1)); EXPECT_TRUE(absl::get<0>(v2).called); } { using V = absl::variant<int, TrivialCopyNontrivialMove>; V v1(absl::in_place_index<1>); V v2(std::move(v1)); EXPECT_TRUE(absl::get<1>(v2).called); } } } ABSL_NAMESPACE_END } #endif
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/types/internal/variant.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/types/variant_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
17031416-18ad-44b1-bf16-d59ef841a76f
cpp
abseil/abseil-cpp
config
absl/base/config.h
absl/base/config_test.cc
#ifndef ABSL_BASE_CONFIG_H_ #define ABSL_BASE_CONFIG_H_ #include <limits.h> #ifdef __cplusplus #include <cstddef> #endif #if defined(_MSVC_LANG) #define ABSL_INTERNAL_CPLUSPLUS_LANG _MSVC_LANG #elif defined(__cplusplus) #define ABSL_INTERNAL_CPLUSPLUS_LANG __cplusplus #endif #if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L #include <version> #endif #if defined(__APPLE__) #include <Availability.h> #include <TargetConditionals.h> #endif #include "absl/base/options.h" #include "absl/base/policy_checks.h" #undef ABSL_LTS_RELEASE_VERSION #undef ABSL_LTS_RELEASE_PATCH_LEVEL #define ABSL_INTERNAL_DO_TOKEN_STR(x) #x #define ABSL_INTERNAL_TOKEN_STR(x) ABSL_INTERNAL_DO_TOKEN_STR(x) #if !defined(ABSL_OPTION_USE_INLINE_NAMESPACE) || \ !defined(ABSL_OPTION_INLINE_NAMESPACE_NAME) #error options.h is misconfigured. #endif #if defined(__cplusplus) && ABSL_OPTION_USE_INLINE_NAMESPACE == 1 #define ABSL_INTERNAL_INLINE_NAMESPACE_STR \ ABSL_INTERNAL_TOKEN_STR(ABSL_OPTION_INLINE_NAMESPACE_NAME) static_assert(ABSL_INTERNAL_INLINE_NAMESPACE_STR[0] != '\0', "options.h misconfigured: ABSL_OPTION_INLINE_NAMESPACE_NAME must " "not be empty."); static_assert(ABSL_INTERNAL_INLINE_NAMESPACE_STR[0] != 'h' || ABSL_INTERNAL_INLINE_NAMESPACE_STR[1] != 'e' || ABSL_INTERNAL_INLINE_NAMESPACE_STR[2] != 'a' || ABSL_INTERNAL_INLINE_NAMESPACE_STR[3] != 'd' || ABSL_INTERNAL_INLINE_NAMESPACE_STR[4] != '\0', "options.h misconfigured: ABSL_OPTION_INLINE_NAMESPACE_NAME must " "be changed to a new, unique identifier name."); #endif #if ABSL_OPTION_USE_INLINE_NAMESPACE == 0 #define ABSL_NAMESPACE_BEGIN #define ABSL_NAMESPACE_END #define ABSL_INTERNAL_C_SYMBOL(x) x #elif ABSL_OPTION_USE_INLINE_NAMESPACE == 1 #define ABSL_NAMESPACE_BEGIN \ inline namespace ABSL_OPTION_INLINE_NAMESPACE_NAME { #define ABSL_NAMESPACE_END } #define ABSL_INTERNAL_C_SYMBOL_HELPER_2(x, v) x##_##v #define ABSL_INTERNAL_C_SYMBOL_HELPER_1(x, v) \ ABSL_INTERNAL_C_SYMBOL_HELPER_2(x, v) #define ABSL_INTERNAL_C_SYMBOL(x) \ ABSL_INTERNAL_C_SYMBOL_HELPER_1(x, ABSL_OPTION_INLINE_NAMESPACE_NAME) #else #error options.h is misconfigured. #endif #ifdef __has_builtin #define ABSL_HAVE_BUILTIN(x) __has_builtin(x) #else #define ABSL_HAVE_BUILTIN(x) 0 #endif #ifdef __has_feature #define ABSL_HAVE_FEATURE(f) __has_feature(f) #else #define ABSL_HAVE_FEATURE(f) 0 #endif #if defined(__GNUC__) && defined(__GNUC_MINOR__) #define ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(x, y) \ (__GNUC__ > (x) || __GNUC__ == (x) && __GNUC_MINOR__ >= (y)) #else #define ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(x, y) 0 #endif #if defined(__clang__) && defined(__clang_major__) && defined(__clang_minor__) #define ABSL_INTERNAL_HAVE_MIN_CLANG_VERSION(x, y) \ (__clang_major__ > (x) || __clang_major__ == (x) && __clang_minor__ >= (y)) #else #define ABSL_INTERNAL_HAVE_MIN_CLANG_VERSION(x, y) 0 #endif #ifdef ABSL_HAVE_TLS #error ABSL_HAVE_TLS cannot be directly set #elif (defined(__linux__)) && (defined(__clang__) || defined(_GLIBCXX_HAVE_TLS)) #define ABSL_HAVE_TLS 1 #endif #ifdef ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE #error ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE cannot be directly set #define ABSL_HAVE_STD_IS_TRIVIALLY_DESTRUCTIBLE 1 #endif #ifdef ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE #error ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE cannot be directly set #else #define ABSL_HAVE_STD_IS_TRIVIALLY_CONSTRUCTIBLE 1 #endif #ifdef ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE #error ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE cannot be directly set #else #define ABSL_HAVE_STD_IS_TRIVIALLY_ASSIGNABLE 1 #endif #ifdef ABSL_HAVE_STD_IS_TRIVIALLY_COPYABLE #error ABSL_HAVE_STD_IS_TRIVIALLY_COPYABLE cannot be directly set #define ABSL_HAVE_STD_IS_TRIVIALLY_COPYABLE 1 #endif #ifdef ABSL_HAVE_THREAD_LOCAL #error ABSL_HAVE_THREAD_LOCAL cannot be directly set #else #define ABSL_HAVE_THREAD_LOCAL 1 #endif #ifdef ABSL_HAVE_INTRINSIC_INT128 #error ABSL_HAVE_INTRINSIC_INT128 cannot be directly set #elif defined(__SIZEOF_INT128__) #if (defined(__clang__) && !defined(_WIN32)) || \ (defined(__CUDACC__) && __CUDACC_VER_MAJOR__ >= 9) || \ (defined(__GNUC__) && !defined(__clang__) && !defined(__CUDACC__)) #define ABSL_HAVE_INTRINSIC_INT128 1 #elif defined(__CUDACC__) #if __CUDACC_VER__ >= 70000 #define ABSL_HAVE_INTRINSIC_INT128 1 #endif #endif #endif #ifdef ABSL_HAVE_EXCEPTIONS #error ABSL_HAVE_EXCEPTIONS cannot be directly set. #elif ABSL_INTERNAL_HAVE_MIN_CLANG_VERSION(3, 6) #if ABSL_HAVE_FEATURE(cxx_exceptions) #define ABSL_HAVE_EXCEPTIONS 1 #endif #elif defined(__clang__) #if defined(__EXCEPTIONS) && ABSL_HAVE_FEATURE(cxx_exceptions) #define ABSL_HAVE_EXCEPTIONS 1 #endif #elif !(defined(__GNUC__) && !defined(__cpp_exceptions)) && \ !(defined(_MSC_VER) && !defined(_CPPUNWIND)) #define ABSL_HAVE_EXCEPTIONS 1 #endif #ifdef ABSL_HAVE_MMAP #error ABSL_HAVE_MMAP cannot be directly set #elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \ defined(_AIX) || defined(__ros__) || defined(__native_client__) || \ defined(__asmjs__) || defined(__EMSCRIPTEN__) || defined(__Fuchsia__) || \ defined(__sun) || defined(__myriad2__) || defined(__HAIKU__) || \ defined(__OpenBSD__) || defined(__NetBSD__) || defined(__QNX__) || \ defined(__VXWORKS__) || defined(__hexagon__) #define ABSL_HAVE_MMAP 1 #endif #ifdef ABSL_HAVE_PTHREAD_GETSCHEDPARAM #error ABSL_HAVE_PTHREAD_GETSCHEDPARAM cannot be directly set #elif defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || \ defined(_AIX) || defined(__ros__) || defined(__OpenBSD__) || \ defined(__NetBSD__) || defined(__VXWORKS__) #define ABSL_HAVE_PTHREAD_GETSCHEDPARAM 1 #endif #ifdef ABSL_HAVE_SCHED_GETCPU #error ABSL_HAVE_SCHED_GETCPU cannot be directly set #elif defined(__linux__) #define ABSL_HAVE_SCHED_GETCPU 1 #endif #ifdef ABSL_HAVE_SCHED_YIELD #error ABSL_HAVE_SCHED_YIELD cannot be directly set #elif defined(__linux__) || defined(__ros__) || defined(__native_client__) || \ defined(__VXWORKS__) #define ABSL_HAVE_SCHED_YIELD 1 #endif #ifdef ABSL_HAVE_SEMAPHORE_H #error ABSL_HAVE_SEMAPHORE_H cannot be directly set #elif defined(__linux__) || defined(__ros__) || defined(__VXWORKS__) #define ABSL_HAVE_SEMAPHORE_H 1 #endif #ifdef ABSL_HAVE_ALARM #error ABSL_HAVE_ALARM cannot be directly set #elif defined(__GOOGLE_GRTE_VERSION__) #define ABSL_HAVE_ALARM 1 #elif defined(__GLIBC__) #define ABSL_HAVE_ALARM 1 #elif defined(_MSC_VER) #elif defined(__MINGW32__) #elif defined(__EMSCRIPTEN__) #elif defined(__wasi__) #elif defined(__Fuchsia__) #elif defined(__native_client__) #elif defined(__hexagon__) #else #define ABSL_HAVE_ALARM 1 #endif #if defined(ABSL_IS_BIG_ENDIAN) #error "ABSL_IS_BIG_ENDIAN cannot be directly set." #endif #if defined(ABSL_IS_LITTLE_ENDIAN) #error "ABSL_IS_LITTLE_ENDIAN cannot be directly set." #endif #if (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) #define ABSL_IS_LITTLE_ENDIAN 1 #elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \ __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ #define ABSL_IS_BIG_ENDIAN 1 #elif defined(_WIN32) #define ABSL_IS_LITTLE_ENDIAN 1 #else #error "absl endian detection needs to be set up for your compiler" #endif #if defined(__APPLE__) && \ ((defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && \ __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 101300) || \ (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && \ __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 120000) || \ (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && \ __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ < 50000) || \ (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && \ __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ < 120000)) #define ABSL_INTERNAL_APPLE_CXX17_TYPES_UNAVAILABLE 1 #else #define ABSL_INTERNAL_APPLE_CXX17_TYPES_UNAVAILABLE 0 #endif #ifdef ABSL_HAVE_STD_ANY #error "ABSL_HAVE_STD_ANY cannot be directly set." #elif defined(__cpp_lib_any) && __cpp_lib_any >= 201606L #define ABSL_HAVE_STD_ANY 1 #elif defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L && \ !ABSL_INTERNAL_APPLE_CXX17_TYPES_UNAVAILABLE #define ABSL_HAVE_STD_ANY 1 #endif #ifdef ABSL_HAVE_STD_OPTIONAL #error "ABSL_HAVE_STD_OPTIONAL cannot be directly set." #elif defined(__cpp_lib_optional) && __cpp_lib_optional >= 202106L #define ABSL_HAVE_STD_OPTIONAL 1 #elif defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L && \ !ABSL_INTERNAL_APPLE_CXX17_TYPES_UNAVAILABLE #define ABSL_HAVE_STD_OPTIONAL 1 #endif #ifdef ABSL_HAVE_STD_VARIANT #error "ABSL_HAVE_STD_VARIANT cannot be directly set." #elif defined(__cpp_lib_variant) && __cpp_lib_variant >= 201606L #define ABSL_HAVE_STD_VARIANT 1 #elif defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L && \ !ABSL_INTERNAL_APPLE_CXX17_TYPES_UNAVAILABLE #define ABSL_HAVE_STD_VARIANT 1 #endif #ifdef ABSL_HAVE_STD_STRING_VIEW #error "ABSL_HAVE_STD_STRING_VIEW cannot be directly set." #elif defined(__cpp_lib_string_view) && __cpp_lib_string_view >= 201606L #define ABSL_HAVE_STD_STRING_VIEW 1 #elif defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L #define ABSL_HAVE_STD_STRING_VIEW 1 #endif #ifdef ABSL_HAVE_STD_ORDERING #error "ABSL_HAVE_STD_ORDERING cannot be directly set." #elif (defined(__cpp_lib_three_way_comparison) && \ __cpp_lib_three_way_comparison >= 201907L) || \ (defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L) #define ABSL_HAVE_STD_ORDERING 1 #endif #if !defined(ABSL_OPTION_USE_STD_ANY) #error options.h is misconfigured. #elif ABSL_OPTION_USE_STD_ANY == 0 || \ (ABSL_OPTION_USE_STD_ANY == 2 && !defined(ABSL_HAVE_STD_ANY)) #undef ABSL_USES_STD_ANY #elif ABSL_OPTION_USE_STD_ANY == 1 || \ (ABSL_OPTION_USE_STD_ANY == 2 && defined(ABSL_HAVE_STD_ANY)) #define ABSL_USES_STD_ANY 1 #else #error options.h is misconfigured. #endif #if !defined(ABSL_OPTION_USE_STD_OPTIONAL) #error options.h is misconfigured. #elif ABSL_OPTION_USE_STD_OPTIONAL == 0 || \ (ABSL_OPTION_USE_STD_OPTIONAL == 2 && !defined(ABSL_HAVE_STD_OPTIONAL)) #undef ABSL_USES_STD_OPTIONAL #elif ABSL_OPTION_USE_STD_OPTIONAL == 1 || \ (ABSL_OPTION_USE_STD_OPTIONAL == 2 && defined(ABSL_HAVE_STD_OPTIONAL)) #define ABSL_USES_STD_OPTIONAL 1 #else #error options.h is misconfigured. #endif #if !defined(ABSL_OPTION_USE_STD_VARIANT) #error options.h is misconfigured. #elif ABSL_OPTION_USE_STD_VARIANT == 0 || \ (ABSL_OPTION_USE_STD_VARIANT == 2 && !defined(ABSL_HAVE_STD_VARIANT)) #undef ABSL_USES_STD_VARIANT #elif ABSL_OPTION_USE_STD_VARIANT == 1 || \ (ABSL_OPTION_USE_STD_VARIANT == 2 && defined(ABSL_HAVE_STD_VARIANT)) #define ABSL_USES_STD_VARIANT 1 #else #error options.h is misconfigured. #endif #if !defined(ABSL_OPTION_USE_STD_STRING_VIEW) #error options.h is misconfigured. #elif ABSL_OPTION_USE_STD_STRING_VIEW == 0 || \ (ABSL_OPTION_USE_STD_STRING_VIEW == 2 && \ !defined(ABSL_HAVE_STD_STRING_VIEW)) #undef ABSL_USES_STD_STRING_VIEW #elif ABSL_OPTION_USE_STD_STRING_VIEW == 1 || \ (ABSL_OPTION_USE_STD_STRING_VIEW == 2 && \ defined(ABSL_HAVE_STD_STRING_VIEW)) #define ABSL_USES_STD_STRING_VIEW 1 #else #error options.h is misconfigured. #endif #if !defined(ABSL_OPTION_USE_STD_ORDERING) #error options.h is misconfigured. #elif ABSL_OPTION_USE_STD_ORDERING == 0 || \ (ABSL_OPTION_USE_STD_ORDERING == 2 && !defined(ABSL_HAVE_STD_ORDERING)) #undef ABSL_USES_STD_ORDERING #elif ABSL_OPTION_USE_STD_ORDERING == 1 || \ (ABSL_OPTION_USE_STD_ORDERING == 2 && defined(ABSL_HAVE_STD_ORDERING)) #define ABSL_USES_STD_ORDERING 1 #else #error options.h is misconfigured. #endif #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_DEBUG) #define ABSL_INTERNAL_MSVC_2017_DBG_MODE #endif #if defined(_MSC_VER) #if ABSL_OPTION_USE_INLINE_NAMESPACE == 0 #define ABSL_INTERNAL_MANGLED_NS "absl" #define ABSL_INTERNAL_MANGLED_BACKREFERENCE "5" #else #define ABSL_INTERNAL_MANGLED_NS \ ABSL_INTERNAL_TOKEN_STR(ABSL_OPTION_INLINE_NAMESPACE_NAME) "@absl" #define ABSL_INTERNAL_MANGLED_BACKREFERENCE "6" #endif #endif #if defined(_MSC_VER) #if defined(ABSL_BUILD_DLL) #define ABSL_DLL __declspec(dllexport) #elif defined(ABSL_CONSUME_DLL) #define ABSL_DLL __declspec(dllimport) #else #define ABSL_DLL #endif #else #define ABSL_DLL #endif #if defined(_MSC_VER) #if defined(ABSL_BUILD_TEST_DLL) #define ABSL_TEST_DLL __declspec(dllexport) #elif defined(ABSL_CONSUME_TEST_DLL) #define ABSL_TEST_DLL __declspec(dllimport) #else #define ABSL_TEST_DLL #endif #else #define ABSL_TEST_DLL #endif #ifdef ABSL_HAVE_MEMORY_SANITIZER #error "ABSL_HAVE_MEMORY_SANITIZER cannot be directly set." #elif !defined(__native_client__) && ABSL_HAVE_FEATURE(memory_sanitizer) #define ABSL_HAVE_MEMORY_SANITIZER 1 #endif #ifdef ABSL_HAVE_THREAD_SANITIZER #error "ABSL_HAVE_THREAD_SANITIZER cannot be directly set." #elif defined(__SANITIZE_THREAD__) #define ABSL_HAVE_THREAD_SANITIZER 1 #elif ABSL_HAVE_FEATURE(thread_sanitizer) #define ABSL_HAVE_THREAD_SANITIZER 1 #endif #ifdef ABSL_HAVE_ADDRESS_SANITIZER #error "ABSL_HAVE_ADDRESS_SANITIZER cannot be directly set." #elif defined(__SANITIZE_ADDRESS__) #define ABSL_HAVE_ADDRESS_SANITIZER 1 #elif ABSL_HAVE_FEATURE(address_sanitizer) #define ABSL_HAVE_ADDRESS_SANITIZER 1 #endif #ifdef ABSL_HAVE_HWADDRESS_SANITIZER #error "ABSL_HAVE_HWADDRESS_SANITIZER cannot be directly set." #elif defined(__SANITIZE_HWADDRESS__) #define ABSL_HAVE_HWADDRESS_SANITIZER 1 #elif ABSL_HAVE_FEATURE(hwaddress_sanitizer) #define ABSL_HAVE_HWADDRESS_SANITIZER 1 #endif #ifdef ABSL_HAVE_DATAFLOW_SANITIZER #error "ABSL_HAVE_DATAFLOW_SANITIZER cannot be directly set." #elif defined(DATAFLOW_SANITIZER) #define ABSL_HAVE_DATAFLOW_SANITIZER 1 #elif ABSL_HAVE_FEATURE(dataflow_sanitizer) #define ABSL_HAVE_DATAFLOW_SANITIZER 1 #endif #ifdef ABSL_HAVE_LEAK_SANITIZER #error "ABSL_HAVE_LEAK_SANITIZER cannot be directly set." #elif defined(LEAK_SANITIZER) #define ABSL_HAVE_LEAK_SANITIZER 1 #elif ABSL_HAVE_FEATURE(leak_sanitizer) #define ABSL_HAVE_LEAK_SANITIZER 1 #elif defined(ABSL_HAVE_ADDRESS_SANITIZER) #define ABSL_HAVE_LEAK_SANITIZER 1 #endif #ifdef ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION #error "ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION cannot be directly set." #elif defined(__cpp_deduction_guides) #define ABSL_HAVE_CLASS_TEMPLATE_ARGUMENT_DEDUCTION 1 #endif #if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG < 201703L #define ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL 1 #endif #ifdef ABSL_INTERNAL_HAS_RTTI #error ABSL_INTERNAL_HAS_RTTI cannot be directly set #elif ABSL_HAVE_FEATURE(cxx_rtti) #define ABSL_INTERNAL_HAS_RTTI 1 #elif defined(__GNUC__) && defined(__GXX_RTTI) #define ABSL_INTERNAL_HAS_RTTI 1 #elif defined(_MSC_VER) && defined(_CPPRTTI) #define ABSL_INTERNAL_HAS_RTTI 1 #elif !defined(__GNUC__) && !defined(_MSC_VER) #define ABSL_INTERNAL_HAS_RTTI 1 #endif #ifdef ABSL_INTERNAL_HAS_CXA_DEMANGLE #error ABSL_INTERNAL_HAS_CXA_DEMANGLE cannot be directly set #elif defined(OS_ANDROID) && (defined(__i386__) || defined(__x86_64__)) #define ABSL_INTERNAL_HAS_CXA_DEMANGLE 0 #elif defined(__GNUC__) #define ABSL_INTERNAL_HAS_CXA_DEMANGLE 1 #elif defined(__clang__) && !defined(_MSC_VER) #define ABSL_INTERNAL_HAS_CXA_DEMANGLE 1 #endif #ifdef ABSL_INTERNAL_HAVE_SSE #error ABSL_INTERNAL_HAVE_SSE cannot be directly set #elif defined(__SSE__) #define ABSL_INTERNAL_HAVE_SSE 1 #elif (defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 1)) && \ !defined(_M_ARM64EC) #define ABSL_INTERNAL_HAVE_SSE 1 #endif #ifdef ABSL_INTERNAL_HAVE_SSE2 #error ABSL_INTERNAL_HAVE_SSE2 cannot be directly set #elif defined(__SSE2__) #define ABSL_INTERNAL_HAVE_SSE2 1 #elif (defined(_M_X64) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2)) && \ !defined(_M_ARM64EC) #define ABSL_INTERNAL_HAVE_SSE2 1 #endif #ifdef ABSL_INTERNAL_HAVE_SSSE3 #error ABSL_INTERNAL_HAVE_SSSE3 cannot be directly set #elif defined(__SSSE3__) #define ABSL_INTERNAL_HAVE_SSSE3 1 #endif #ifdef ABSL_INTERNAL_HAVE_ARM_NEON #error ABSL_INTERNAL_HAVE_ARM_NEON cannot be directly set #elif defined(__ARM_NEON) && !(defined(__NVCC__) && defined(__CUDACC__)) #define ABSL_INTERNAL_HAVE_ARM_NEON 1 #endif #ifdef ABSL_HAVE_CONSTANT_EVALUATED #error ABSL_HAVE_CONSTANT_EVALUATED cannot be directly set #endif #ifdef __cpp_lib_is_constant_evaluated #define ABSL_HAVE_CONSTANT_EVALUATED 1 #elif ABSL_HAVE_BUILTIN(__builtin_is_constant_evaluated) #define ABSL_HAVE_CONSTANT_EVALUATED 1 #endif #if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L #define ABSL_INTERNAL_CONSTEXPR_SINCE_CXX17 constexpr #else #define ABSL_INTERNAL_CONSTEXPR_SINCE_CXX17 #endif #if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L #define ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 constexpr #else #define ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 #endif #ifdef ABSL_INTERNAL_EMSCRIPTEN_VERSION #error ABSL_INTERNAL_EMSCRIPTEN_VERSION cannot be directly set #endif #ifdef __EMSCRIPTEN__ #include <emscripten/version.h> #ifdef __EMSCRIPTEN_major__ #if __EMSCRIPTEN_minor__ >= 1000 #error __EMSCRIPTEN_minor__ is too big to fit in ABSL_INTERNAL_EMSCRIPTEN_VERSION #endif #if __EMSCRIPTEN_tiny__ >= 1000 #error __EMSCRIPTEN_tiny__ is too big to fit in ABSL_INTERNAL_EMSCRIPTEN_VERSION #endif #define ABSL_INTERNAL_EMSCRIPTEN_VERSION \ ((__EMSCRIPTEN_major__) * 1000000 + (__EMSCRIPTEN_minor__) * 1000 + \ (__EMSCRIPTEN_tiny__)) #endif #endif #endif
#include "absl/base/config.h" #include <cstdint> #include "gtest/gtest.h" #include "absl/synchronization/internal/thread_pool.h" namespace { TEST(ConfigTest, Endianness) { union { uint32_t value; uint8_t data[sizeof(uint32_t)]; } number; number.data[0] = 0x00; number.data[1] = 0x01; number.data[2] = 0x02; number.data[3] = 0x03; #if defined(ABSL_IS_LITTLE_ENDIAN) && defined(ABSL_IS_BIG_ENDIAN) #error Both ABSL_IS_LITTLE_ENDIAN and ABSL_IS_BIG_ENDIAN are defined #elif defined(ABSL_IS_LITTLE_ENDIAN) EXPECT_EQ(UINT32_C(0x03020100), number.value); #elif defined(ABSL_IS_BIG_ENDIAN) EXPECT_EQ(UINT32_C(0x00010203), number.value); #else #error Unknown endianness #endif } #if defined(ABSL_HAVE_THREAD_LOCAL) TEST(ConfigTest, ThreadLocal) { static thread_local int mine_mine_mine = 16; EXPECT_EQ(16, mine_mine_mine); { absl::synchronization_internal::ThreadPool pool(1); pool.Schedule([&] { EXPECT_EQ(16, mine_mine_mine); mine_mine_mine = 32; EXPECT_EQ(32, mine_mine_mine); }); } EXPECT_EQ(16, mine_mine_mine); } #endif }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/config.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/base/config_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
75b1a335-02f3-4b27-ade6-73c68ae3eab2
cpp
abseil/abseil-cpp
path_util
absl/flags/internal/path_util.h
absl/flags/internal/path_util_test.cc
#ifndef ABSL_FLAGS_INTERNAL_PATH_UTIL_H_ #define ABSL_FLAGS_INTERNAL_PATH_UTIL_H_ #include "absl/base/config.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { inline absl::string_view Basename(absl::string_view filename) { auto last_slash_pos = filename.find_last_of("/\\"); return last_slash_pos == absl::string_view::npos ? filename : filename.substr(last_slash_pos + 1); } inline absl::string_view Package(absl::string_view filename) { auto last_slash_pos = filename.find_last_of("/\\"); return last_slash_pos == absl::string_view::npos ? absl::string_view() : filename.substr(0, last_slash_pos + 1); } } ABSL_NAMESPACE_END } #endif
#include "absl/flags/internal/path_util.h" #include "gtest/gtest.h" namespace { namespace flags = absl::flags_internal; TEST(FlagsPathUtilTest, TestBasename) { EXPECT_EQ(flags::Basename(""), ""); EXPECT_EQ(flags::Basename("a.cc"), "a.cc"); EXPECT_EQ(flags::Basename("dir/a.cc"), "a.cc"); EXPECT_EQ(flags::Basename("dir1/dir2/a.cc"), "a.cc"); EXPECT_EQ(flags::Basename("../dir1/dir2/a.cc"), "a.cc"); EXPECT_EQ(flags::Basename("/dir1/dir2/a.cc"), "a.cc"); EXPECT_EQ(flags::Basename("/dir1/dir2/../dir3/a.cc"), "a.cc"); } TEST(FlagsPathUtilTest, TestPackage) { EXPECT_EQ(flags::Package(""), ""); EXPECT_EQ(flags::Package("a.cc"), ""); EXPECT_EQ(flags::Package("dir/a.cc"), "dir/"); EXPECT_EQ(flags::Package("dir1/dir2/a.cc"), "dir1/dir2/"); EXPECT_EQ(flags::Package("../dir1/dir2/a.cc"), "../dir1/dir2/"); EXPECT_EQ(flags::Package("/dir1/dir2/a.cc"), "/dir1/dir2/"); EXPECT_EQ(flags::Package("/dir1/dir2/../dir3/a.cc"), "/dir1/dir2/../dir3/"); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/internal/path_util.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/internal/path_util_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
b22227d5-e006-494b-ba20-d41d0438b437
cpp
abseil/abseil-cpp
sequence_lock
absl/flags/internal/sequence_lock.h
absl/flags/internal/sequence_lock_test.cc
#ifndef ABSL_FLAGS_INTERNAL_SEQUENCE_LOCK_H_ #define ABSL_FLAGS_INTERNAL_SEQUENCE_LOCK_H_ #include <stddef.h> #include <stdint.h> #include <atomic> #include <cassert> #include <cstring> #include "absl/base/optimization.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace flags_internal { inline constexpr size_t AlignUp(size_t x, size_t align) { return align * ((x + align - 1) / align); } class SequenceLock { public: constexpr SequenceLock() : lock_(kUninitialized) {} void MarkInitialized() { assert(lock_.load(std::memory_order_relaxed) == kUninitialized); lock_.store(0, std::memory_order_release); } bool TryRead(void* dst, const std::atomic<uint64_t>* src, size_t size) const { int64_t seq_before = lock_.load(std::memory_order_acquire); if (ABSL_PREDICT_FALSE(seq_before & 1) == 1) return false; RelaxedCopyFromAtomic(dst, src, size); std::atomic_thread_fence(std::memory_order_acquire); int64_t seq_after = lock_.load(std::memory_order_relaxed); return ABSL_PREDICT_TRUE(seq_before == seq_after); } void Write(std::atomic<uint64_t>* dst, const void* src, size_t size) { int64_t orig_seq = lock_.load(std::memory_order_relaxed); assert((orig_seq & 1) == 0); lock_.store(orig_seq + 1, std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_release); RelaxedCopyToAtomic(dst, src, size); lock_.store(orig_seq + 2, std::memory_order_release); } int64_t ModificationCount() const { int64_t val = lock_.load(std::memory_order_relaxed); assert(val != kUninitialized && (val & 1) == 0); return val / 2; } void IncrementModificationCount() { int64_t val = lock_.load(std::memory_order_relaxed); assert(val != kUninitialized); lock_.store(val + 2, std::memory_order_relaxed); } private: static void RelaxedCopyFromAtomic(void* dst, const std::atomic<uint64_t>* src, size_t size) { char* dst_byte = static_cast<char*>(dst); while (size >= sizeof(uint64_t)) { uint64_t word = src->load(std::memory_order_relaxed); std::memcpy(dst_byte, &word, sizeof(word)); dst_byte += sizeof(word); src++; size -= sizeof(word); } if (size > 0) { uint64_t word = src->load(std::memory_order_relaxed); std::memcpy(dst_byte, &word, size); } } static void RelaxedCopyToAtomic(std::atomic<uint64_t>* dst, const void* src, size_t size) { const char* src_byte = static_cast<const char*>(src); while (size >= sizeof(uint64_t)) { uint64_t word; std::memcpy(&word, src_byte, sizeof(word)); dst->store(word, std::memory_order_relaxed); src_byte += sizeof(word); dst++; size -= sizeof(word); } if (size > 0) { uint64_t word = 0; std::memcpy(&word, src_byte, size); dst->store(word, std::memory_order_relaxed); } } static constexpr int64_t kUninitialized = -1; std::atomic<int64_t> lock_; }; } ABSL_NAMESPACE_END } #endif
#include "absl/flags/internal/sequence_lock.h" #include <algorithm> #include <atomic> #include <thread> #include <tuple> #include <vector> #include "gtest/gtest.h" #include "absl/base/internal/sysinfo.h" #include "absl/container/fixed_array.h" #include "absl/time/clock.h" namespace { namespace flags = absl::flags_internal; class ConcurrentSequenceLockTest : public testing::TestWithParam<std::tuple<int, int>> { public: ConcurrentSequenceLockTest() : buf_bytes_(std::get<0>(GetParam())), num_threads_(std::get<1>(GetParam())) {} protected: const int buf_bytes_; const int num_threads_; }; TEST_P(ConcurrentSequenceLockTest, ReadAndWrite) { const int buf_words = flags::AlignUp(buf_bytes_, sizeof(uint64_t)) / sizeof(uint64_t); absl::FixedArray<std::atomic<uint64_t>> protected_buf(buf_words); for (auto& v : protected_buf) v = -1; flags::SequenceLock seq_lock; std::atomic<bool> stop{false}; std::atomic<int64_t> bad_reads{0}; std::atomic<int64_t> good_reads{0}; std::atomic<int64_t> unsuccessful_reads{0}; std::vector<std::thread> threads; for (int i = 0; i < num_threads_; i++) { threads.emplace_back([&]() { absl::FixedArray<char> local_buf(buf_bytes_); while (!stop.load(std::memory_order_relaxed)) { if (seq_lock.TryRead(local_buf.data(), protected_buf.data(), buf_bytes_)) { bool good = true; for (const auto& v : local_buf) { if (v != local_buf[0]) good = false; } if (good) { good_reads.fetch_add(1, std::memory_order_relaxed); } else { bad_reads.fetch_add(1, std::memory_order_relaxed); } } else { unsuccessful_reads.fetch_add(1, std::memory_order_relaxed); } } }); } while (unsuccessful_reads.load(std::memory_order_relaxed) < num_threads_) { absl::SleepFor(absl::Milliseconds(1)); } seq_lock.MarkInitialized(); absl::Time deadline = absl::Now() + absl::Seconds(5); for (int i = 0; i < 100 && absl::Now() < deadline; i++) { absl::FixedArray<char> writer_buf(buf_bytes_); for (auto& v : writer_buf) v = i; seq_lock.Write(protected_buf.data(), writer_buf.data(), buf_bytes_); absl::SleepFor(absl::Microseconds(10)); } stop.store(true, std::memory_order_relaxed); for (auto& t : threads) t.join(); ASSERT_GE(good_reads, 0); ASSERT_EQ(bad_reads, 0); } std::vector<int> MultiplicativeRange(int low, int high, int scale) { std::vector<int> result; for (int current = low; current < high; current *= scale) { result.push_back(current); } result.push_back(high); return result; } #ifndef ABSL_HAVE_THREAD_SANITIZER const int kMaxThreads = absl::base_internal::NumCPUs(); #else const int kMaxThreads = std::min(absl::base_internal::NumCPUs(), 4); #endif std::vector<int> InterestingBufferSizes() { std::vector<int> ret; for (int v : MultiplicativeRange(1, 128, 2)) { ret.push_back(v); if (v > 1) { ret.push_back(v - 1); } ret.push_back(v + 1); } return ret; } INSTANTIATE_TEST_SUITE_P( TestManyByteSizes, ConcurrentSequenceLockTest, testing::Combine( testing::ValuesIn(InterestingBufferSizes()), testing::ValuesIn(MultiplicativeRange(1, kMaxThreads, 2)))); class SequenceLockTest : public testing::TestWithParam<int> {}; TEST_P(SequenceLockTest, SingleThreaded) { const int size = GetParam(); absl::FixedArray<std::atomic<uint64_t>> protected_buf( flags::AlignUp(size, sizeof(uint64_t)) / sizeof(uint64_t)); flags::SequenceLock seq_lock; seq_lock.MarkInitialized(); std::vector<char> src_buf(size, 'x'); seq_lock.Write(protected_buf.data(), src_buf.data(), size); std::vector<char> dst_buf(size, '0'); ASSERT_TRUE(seq_lock.TryRead(dst_buf.data(), protected_buf.data(), size)); ASSERT_EQ(src_buf, dst_buf); } INSTANTIATE_TEST_SUITE_P(TestManyByteSizes, SequenceLockTest, testing::Range(1, 128)); }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/internal/sequence_lock.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/flags/internal/sequence_lock_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
6fe4dcda-4ff4-4489-95e2-6a94fa8eb7a6
cpp
abseil/abseil-cpp
memory
absl/memory/memory.h
absl/memory/memory_test.cc
#ifndef ABSL_MEMORY_MEMORY_H_ #define ABSL_MEMORY_MEMORY_H_ #include <cstddef> #include <limits> #include <memory> #include <new> #include <type_traits> #include <utility> #include "absl/base/macros.h" #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN template <typename T> std::unique_ptr<T> WrapUnique(T* ptr) { static_assert(!std::is_array<T>::value, "array types are unsupported"); static_assert(std::is_object<T>::value, "non-object types are unsupported"); return std::unique_ptr<T>(ptr); } using std::make_unique; template <typename T> auto RawPtr(T&& ptr) -> decltype(std::addressof(*ptr)) { return (ptr != nullptr) ? std::addressof(*ptr) : nullptr; } inline std::nullptr_t RawPtr(std::nullptr_t) { return nullptr; } template <typename T, typename D> std::shared_ptr<T> ShareUniquePtr(std::unique_ptr<T, D>&& ptr) { return ptr ? std::shared_ptr<T>(std::move(ptr)) : std::shared_ptr<T>(); } template <typename T> std::weak_ptr<T> WeakenPtr(const std::shared_ptr<T>& ptr) { return std::weak_ptr<T>(ptr); } using std::pointer_traits; using std::allocator_traits; namespace memory_internal { template <template <typename> class Extract, typename Obj, typename Default, typename> struct ExtractOr { using type = Default; }; template <template <typename> class Extract, typename Obj, typename Default> struct ExtractOr<Extract, Obj, Default, void_t<Extract<Obj>>> { using type = Extract<Obj>; }; template <template <typename> class Extract, typename Obj, typename Default> using ExtractOrT = typename ExtractOr<Extract, Obj, Default, void>::type; template <typename Alloc> using GetIsNothrow = typename Alloc::is_nothrow; } template <typename Alloc> struct allocator_is_nothrow : memory_internal::ExtractOrT<memory_internal::GetIsNothrow, Alloc, std::false_type> {}; #if defined(ABSL_ALLOCATOR_NOTHROW) && ABSL_ALLOCATOR_NOTHROW template <typename T> struct allocator_is_nothrow<std::allocator<T>> : std::true_type {}; struct default_allocator_is_nothrow : std::true_type {}; #else struct default_allocator_is_nothrow : std::false_type {}; #endif namespace memory_internal { template <typename Allocator, typename Iterator, typename... Args> void ConstructRange(Allocator& alloc, Iterator first, Iterator last, const Args&... args) { for (Iterator cur = first; cur != last; ++cur) { ABSL_INTERNAL_TRY { std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur), args...); } ABSL_INTERNAL_CATCH_ANY { while (cur != first) { --cur; std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur)); } ABSL_INTERNAL_RETHROW; } } } template <typename Allocator, typename Iterator, typename InputIterator> void CopyRange(Allocator& alloc, Iterator destination, InputIterator first, InputIterator last) { for (Iterator cur = destination; first != last; static_cast<void>(++cur), static_cast<void>(++first)) { ABSL_INTERNAL_TRY { std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur), *first); } ABSL_INTERNAL_CATCH_ANY { while (cur != destination) { --cur; std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur)); } ABSL_INTERNAL_RETHROW; } } } } ABSL_NAMESPACE_END } #endif
#include "absl/memory/memory.h" #include <sys/types.h> #include <cstddef> #include <memory> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" namespace { using ::testing::ElementsAre; using ::testing::Return; class DestructorVerifier { public: DestructorVerifier() { ++instance_count_; } DestructorVerifier(const DestructorVerifier&) = delete; DestructorVerifier& operator=(const DestructorVerifier&) = delete; ~DestructorVerifier() { --instance_count_; } static int instance_count() { return instance_count_; } private: static int instance_count_; }; int DestructorVerifier::instance_count_ = 0; TEST(WrapUniqueTest, WrapUnique) { { auto dv = new DestructorVerifier; EXPECT_EQ(1, DestructorVerifier::instance_count()); std::unique_ptr<DestructorVerifier> ptr = absl::WrapUnique(dv); EXPECT_EQ(1, DestructorVerifier::instance_count()); } EXPECT_EQ(0, DestructorVerifier::instance_count()); } struct InitializationVerifier { static constexpr int kDefaultScalar = 0x43; static constexpr int kDefaultArray = 0x4B; static void* operator new(size_t n) { void* ret = ::operator new(n); memset(ret, kDefaultScalar, n); return ret; } static void* operator new[](size_t n) { void* ret = ::operator new[](n); memset(ret, kDefaultArray, n); return ret; } int a; int b; }; struct ArrayWatch { void* operator new[](size_t n) { allocs().push_back(n); return ::operator new[](n); } void operator delete[](void* p) { return ::operator delete[](p); } static std::vector<size_t>& allocs() { static auto& v = *new std::vector<size_t>; return v; } }; TEST(RawPtrTest, RawPointer) { int i = 5; EXPECT_EQ(&i, absl::RawPtr(&i)); } TEST(RawPtrTest, SmartPointer) { int* o = new int(5); std::unique_ptr<int> p(o); EXPECT_EQ(o, absl::RawPtr(p)); } class IntPointerNonConstDeref { public: explicit IntPointerNonConstDeref(int* p) : p_(p) {} friend bool operator!=(const IntPointerNonConstDeref& a, std::nullptr_t) { return a.p_ != nullptr; } int& operator*() { return *p_; } private: std::unique_ptr<int> p_; }; TEST(RawPtrTest, SmartPointerNonConstDereference) { int* o = new int(5); IntPointerNonConstDeref p(o); EXPECT_EQ(o, absl::RawPtr(p)); } TEST(RawPtrTest, NullValuedRawPointer) { int* p = nullptr; EXPECT_EQ(nullptr, absl::RawPtr(p)); } TEST(RawPtrTest, NullValuedSmartPointer) { std::unique_ptr<int> p; EXPECT_EQ(nullptr, absl::RawPtr(p)); } TEST(RawPtrTest, Nullptr) { auto p = absl::RawPtr(nullptr); EXPECT_TRUE((std::is_same<std::nullptr_t, decltype(p)>::value)); EXPECT_EQ(nullptr, p); } TEST(RawPtrTest, Null) { auto p = absl::RawPtr(nullptr); EXPECT_TRUE((std::is_same<std::nullptr_t, decltype(p)>::value)); EXPECT_EQ(nullptr, p); } TEST(RawPtrTest, Zero) { auto p = absl::RawPtr(nullptr); EXPECT_TRUE((std::is_same<std::nullptr_t, decltype(p)>::value)); EXPECT_EQ(nullptr, p); } TEST(ShareUniquePtrTest, Share) { auto up = absl::make_unique<int>(); int* rp = up.get(); auto sp = absl::ShareUniquePtr(std::move(up)); EXPECT_EQ(sp.get(), rp); } TEST(ShareUniquePtrTest, ShareNull) { struct NeverDie { using pointer = void*; void operator()(pointer) { ASSERT_TRUE(false) << "Deleter should not have been called."; } }; std::unique_ptr<void, NeverDie> up; auto sp = absl::ShareUniquePtr(std::move(up)); } TEST(WeakenPtrTest, Weak) { auto sp = std::make_shared<int>(); auto wp = absl::WeakenPtr(sp); EXPECT_EQ(sp.get(), wp.lock().get()); sp.reset(); EXPECT_TRUE(wp.expired()); } TEST(AllocatorNoThrowTest, DefaultAllocator) { #if defined(ABSL_ALLOCATOR_NOTHROW) && ABSL_ALLOCATOR_NOTHROW EXPECT_TRUE(absl::default_allocator_is_nothrow::value); #else EXPECT_FALSE(absl::default_allocator_is_nothrow::value); #endif } TEST(AllocatorNoThrowTest, StdAllocator) { #if defined(ABSL_ALLOCATOR_NOTHROW) && ABSL_ALLOCATOR_NOTHROW EXPECT_TRUE(absl::allocator_is_nothrow<std::allocator<int>>::value); #else EXPECT_FALSE(absl::allocator_is_nothrow<std::allocator<int>>::value); #endif } TEST(AllocatorNoThrowTest, CustomAllocator) { struct NoThrowAllocator { using is_nothrow = std::true_type; }; struct CanThrowAllocator { using is_nothrow = std::false_type; }; struct UnspecifiedAllocator {}; EXPECT_TRUE(absl::allocator_is_nothrow<NoThrowAllocator>::value); EXPECT_FALSE(absl::allocator_is_nothrow<CanThrowAllocator>::value); EXPECT_FALSE(absl::allocator_is_nothrow<UnspecifiedAllocator>::value); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/memory/memory.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/memory/memory_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
fd35989a-07fe-4260-a846-5a2bd037b427
cpp
abseil/abseil-cpp
waiter
absl/synchronization/internal/waiter.h
absl/synchronization/internal/waiter_test.cc
#ifndef ABSL_SYNCHRONIZATION_INTERNAL_WAITER_H_ #define ABSL_SYNCHRONIZATION_INTERNAL_WAITER_H_ #include "absl/base/config.h" #include "absl/synchronization/internal/futex_waiter.h" #include "absl/synchronization/internal/pthread_waiter.h" #include "absl/synchronization/internal/sem_waiter.h" #include "absl/synchronization/internal/stdcpp_waiter.h" #include "absl/synchronization/internal/win32_waiter.h" #define ABSL_WAITER_MODE_FUTEX 0 #define ABSL_WAITER_MODE_SEM 1 #define ABSL_WAITER_MODE_CONDVAR 2 #define ABSL_WAITER_MODE_WIN32 3 #define ABSL_WAITER_MODE_STDCPP 4 #if defined(ABSL_FORCE_WAITER_MODE) #define ABSL_WAITER_MODE ABSL_FORCE_WAITER_MODE #elif defined(ABSL_INTERNAL_HAVE_WIN32_WAITER) #define ABSL_WAITER_MODE ABSL_WAITER_MODE_WIN32 #elif defined(ABSL_INTERNAL_HAVE_FUTEX_WAITER) #define ABSL_WAITER_MODE ABSL_WAITER_MODE_FUTEX #elif defined(ABSL_INTERNAL_HAVE_SEM_WAITER) #define ABSL_WAITER_MODE ABSL_WAITER_MODE_SEM #elif defined(ABSL_INTERNAL_HAVE_PTHREAD_WAITER) #define ABSL_WAITER_MODE ABSL_WAITER_MODE_CONDVAR #elif defined(ABSL_INTERNAL_HAVE_STDCPP_WAITER) #define ABSL_WAITER_MODE ABSL_WAITER_MODE_STDCPP #else #error ABSL_WAITER_MODE is undefined #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace synchronization_internal { #if ABSL_WAITER_MODE == ABSL_WAITER_MODE_FUTEX using Waiter = FutexWaiter; #elif ABSL_WAITER_MODE == ABSL_WAITER_MODE_SEM using Waiter = SemWaiter; #elif ABSL_WAITER_MODE == ABSL_WAITER_MODE_CONDVAR using Waiter = PthreadWaiter; #elif ABSL_WAITER_MODE == ABSL_WAITER_MODE_WIN32 using Waiter = Win32Waiter; #elif ABSL_WAITER_MODE == ABSL_WAITER_MODE_STDCPP using Waiter = StdcppWaiter; #endif } ABSL_NAMESPACE_END } #endif
#include "absl/synchronization/internal/waiter.h" #include <ctime> #include <iostream> #include <ostream> #include "absl/base/config.h" #include "absl/random/random.h" #include "absl/synchronization/internal/create_thread_identity.h" #include "absl/synchronization/internal/futex_waiter.h" #include "absl/synchronization/internal/kernel_timeout.h" #include "absl/synchronization/internal/pthread_waiter.h" #include "absl/synchronization/internal/sem_waiter.h" #include "absl/synchronization/internal/stdcpp_waiter.h" #include "absl/synchronization/internal/thread_pool.h" #include "absl/synchronization/internal/win32_waiter.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "gtest/gtest.h" #if defined(__GOOGLE_GRTE_VERSION__) && \ !defined(ABSL_HAVE_ADDRESS_SANITIZER) && \ !defined(ABSL_HAVE_MEMORY_SANITIZER) && \ !defined(ABSL_HAVE_THREAD_SANITIZER) extern "C" int __clock_gettime(clockid_t c, struct timespec* ts); extern "C" int clock_gettime(clockid_t c, struct timespec* ts) { if (c == CLOCK_MONOTONIC && !absl::synchronization_internal::KernelTimeout::SupportsSteadyClock()) { thread_local absl::BitGen gen; ts->tv_sec = absl::Uniform(gen, 0, 1'000'000'000); ts->tv_nsec = absl::Uniform(gen, 0, 1'000'000'000); return 0; } return __clock_gettime(c, ts); } #endif namespace { TEST(Waiter, PrintPlatformImplementation) { std::cout << absl::synchronization_internal::Waiter::kName << std::endl; } template <typename T> class WaiterTest : public ::testing::Test { public: WaiterTest() { absl::synchronization_internal::GetOrCreateCurrentThreadIdentity(); } }; TYPED_TEST_SUITE_P(WaiterTest); absl::Duration WithTolerance(absl::Duration d) { return d * 0.95; } TYPED_TEST_P(WaiterTest, WaitNoTimeout) { absl::synchronization_internal::ThreadPool tp(1); TypeParam waiter; tp.Schedule([&]() { waiter.Poke(); absl::SleepFor(absl::Seconds(1)); waiter.Poke(); absl::SleepFor(absl::Seconds(1)); waiter.Post(); }); absl::Time start = absl::Now(); EXPECT_TRUE( waiter.Wait(absl::synchronization_internal::KernelTimeout::Never())); absl::Duration waited = absl::Now() - start; EXPECT_GE(waited, WithTolerance(absl::Seconds(2))); } TYPED_TEST_P(WaiterTest, WaitDurationWoken) { absl::synchronization_internal::ThreadPool tp(1); TypeParam waiter; tp.Schedule([&]() { waiter.Poke(); absl::SleepFor(absl::Milliseconds(500)); waiter.Post(); }); absl::Time start = absl::Now(); EXPECT_TRUE(waiter.Wait( absl::synchronization_internal::KernelTimeout(absl::Seconds(10)))); absl::Duration waited = absl::Now() - start; EXPECT_GE(waited, WithTolerance(absl::Milliseconds(500))); EXPECT_LT(waited, absl::Seconds(2)); } TYPED_TEST_P(WaiterTest, WaitTimeWoken) { absl::synchronization_internal::ThreadPool tp(1); TypeParam waiter; tp.Schedule([&]() { waiter.Poke(); absl::SleepFor(absl::Milliseconds(500)); waiter.Post(); }); absl::Time start = absl::Now(); EXPECT_TRUE(waiter.Wait(absl::synchronization_internal::KernelTimeout( start + absl::Seconds(10)))); absl::Duration waited = absl::Now() - start; EXPECT_GE(waited, WithTolerance(absl::Milliseconds(500))); EXPECT_LT(waited, absl::Seconds(2)); } TYPED_TEST_P(WaiterTest, WaitDurationReached) { TypeParam waiter; absl::Time start = absl::Now(); EXPECT_FALSE(waiter.Wait( absl::synchronization_internal::KernelTimeout(absl::Milliseconds(500)))); absl::Duration waited = absl::Now() - start; EXPECT_GE(waited, WithTolerance(absl::Milliseconds(500))); EXPECT_LT(waited, absl::Seconds(1)); } TYPED_TEST_P(WaiterTest, WaitTimeReached) { TypeParam waiter; absl::Time start = absl::Now(); EXPECT_FALSE(waiter.Wait(absl::synchronization_internal::KernelTimeout( start + absl::Milliseconds(500)))); absl::Duration waited = absl::Now() - start; EXPECT_GE(waited, WithTolerance(absl::Milliseconds(500))); EXPECT_LT(waited, absl::Seconds(1)); } REGISTER_TYPED_TEST_SUITE_P(WaiterTest, WaitNoTimeout, WaitDurationWoken, WaitTimeWoken, WaitDurationReached, WaitTimeReached); #ifdef ABSL_INTERNAL_HAVE_FUTEX_WAITER INSTANTIATE_TYPED_TEST_SUITE_P(Futex, WaiterTest, absl::synchronization_internal::FutexWaiter); #endif #ifdef ABSL_INTERNAL_HAVE_PTHREAD_WAITER INSTANTIATE_TYPED_TEST_SUITE_P(Pthread, WaiterTest, absl::synchronization_internal::PthreadWaiter); #endif #ifdef ABSL_INTERNAL_HAVE_SEM_WAITER INSTANTIATE_TYPED_TEST_SUITE_P(Sem, WaiterTest, absl::synchronization_internal::SemWaiter); #endif #ifdef ABSL_INTERNAL_HAVE_WIN32_WAITER INSTANTIATE_TYPED_TEST_SUITE_P(Win32, WaiterTest, absl::synchronization_internal::Win32Waiter); #endif #ifdef ABSL_INTERNAL_HAVE_STDCPP_WAITER INSTANTIATE_TYPED_TEST_SUITE_P(Stdcpp, WaiterTest, absl::synchronization_internal::StdcppWaiter); #endif }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/internal/waiter.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/synchronization/internal/waiter_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
2332d521-390d-487b-a49c-f328427eabe2
cpp
abseil/abseil-cpp
bounded_utf8_length_sequence
absl/debugging/internal/bounded_utf8_length_sequence.h
absl/debugging/internal/bounded_utf8_length_sequence_test.cc
#ifndef ABSL_DEBUGGING_INTERNAL_BOUNDED_UTF8_LENGTH_SEQUENCE_H_ #define ABSL_DEBUGGING_INTERNAL_BOUNDED_UTF8_LENGTH_SEQUENCE_H_ #include <cstdint> #include "absl/base/config.h" #include "absl/numeric/bits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { template <uint32_t max_elements> class BoundedUtf8LengthSequence { public: BoundedUtf8LengthSequence() = default; uint32_t InsertAndReturnSumOfPredecessors( uint32_t index, uint32_t utf8_length) { if (index >= max_elements) index = max_elements - 1; if (utf8_length == 0 || utf8_length > 4) utf8_length = 1; const uint32_t word_index = index/32; const uint32_t bit_index = 2 * (index % 32); const uint64_t ones_bit = uint64_t{1} << bit_index; const uint64_t odd_bits_mask = 0xaaaaaaaaaaaaaaaa; const uint64_t lower_seminibbles_mask = ones_bit - 1; const uint64_t higher_seminibbles_mask = ~lower_seminibbles_mask; const uint64_t same_word_bits_below_insertion = rep_[word_index] & lower_seminibbles_mask; int full_popcount = absl::popcount(same_word_bits_below_insertion); int odd_popcount = absl::popcount(same_word_bits_below_insertion & odd_bits_mask); for (uint32_t j = word_index; j > 0; --j) { const uint64_t word_below_insertion = rep_[j - 1]; full_popcount += absl::popcount(word_below_insertion); odd_popcount += absl::popcount(word_below_insertion & odd_bits_mask); } const uint32_t sum_of_predecessors = index + static_cast<uint32_t>(full_popcount + odd_popcount); for (uint32_t j = max_elements/32 - 1; j > word_index; --j) { rep_[j] = (rep_[j] << 2) | (rep_[j - 1] >> 62); } rep_[word_index] = (rep_[word_index] & lower_seminibbles_mask) | (uint64_t{utf8_length - 1} << bit_index) | ((rep_[word_index] & higher_seminibbles_mask) << 2); return sum_of_predecessors; } private: static_assert(max_elements > 0 && max_elements % 32 == 0, "max_elements must be a positive multiple of 32"); uint64_t rep_[max_elements/32] = {}; }; } ABSL_NAMESPACE_END } #endif
#include "absl/debugging/internal/bounded_utf8_length_sequence.h" #include <cstdint> #include "gtest/gtest.h" #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace debugging_internal { namespace { TEST(BoundedUtf8LengthSequenceTest, RemembersAValueOfOneCorrectly) { BoundedUtf8LengthSequence<32> seq; ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 1), 0); EXPECT_EQ(seq.InsertAndReturnSumOfPredecessors(1, 1), 1); } TEST(BoundedUtf8LengthSequenceTest, RemembersAValueOfTwoCorrectly) { BoundedUtf8LengthSequence<32> seq; ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 2), 0); EXPECT_EQ(seq.InsertAndReturnSumOfPredecessors(1, 1), 2); } TEST(BoundedUtf8LengthSequenceTest, RemembersAValueOfThreeCorrectly) { BoundedUtf8LengthSequence<32> seq; ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 3), 0); EXPECT_EQ(seq.InsertAndReturnSumOfPredecessors(1, 1), 3); } TEST(BoundedUtf8LengthSequenceTest, RemembersAValueOfFourCorrectly) { BoundedUtf8LengthSequence<32> seq; ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 4), 0); EXPECT_EQ(seq.InsertAndReturnSumOfPredecessors(1, 1), 4); } TEST(BoundedUtf8LengthSequenceTest, RemembersSeveralAppendedValues) { BoundedUtf8LengthSequence<32> seq; ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 1), 0); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(1, 4), 1); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(2, 2), 5); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(3, 3), 7); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(4, 1), 10); } TEST(BoundedUtf8LengthSequenceTest, RemembersSeveralPrependedValues) { BoundedUtf8LengthSequence<32> seq; ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 4), 0); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 3), 0); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 2), 0); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 1), 0); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(4, 1), 10); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(3, 1), 6); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(2, 1), 3); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(1, 1), 1); } TEST(BoundedUtf8LengthSequenceTest, RepeatedInsertsShiftValuesOutTheRightEnd) { BoundedUtf8LengthSequence<32> seq; ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 2), 0); for (uint32_t i = 1; i < 31; ++i) { ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 1), 0) << "while moving the 2 into position " << i; ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(31, 1), 32) << "after moving the 2 into position " << i; } ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 1), 0) << "while moving the 2 into position 31"; EXPECT_EQ(seq.InsertAndReturnSumOfPredecessors(31, 1), 31) << "after moving the 2 into position 31"; } TEST(BoundedUtf8LengthSequenceTest, InsertsIntoWord1LeaveWord0Untouched) { BoundedUtf8LengthSequence<64> seq; for (uint32_t i = 0; i < 32; ++i) { ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(i, 2), 2 * i) << "at index " << i; } EXPECT_EQ(seq.InsertAndReturnSumOfPredecessors(32, 1), 64); EXPECT_EQ(seq.InsertAndReturnSumOfPredecessors(32, 1), 64); } TEST(BoundedUtf8LengthSequenceTest, InsertsIntoWord0ShiftValuesIntoWord1) { BoundedUtf8LengthSequence<64> seq; ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(29, 2), 29); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(30, 3), 31); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(31, 4), 34); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 1), 0); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 1), 0); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(34, 1), 31 + 2 + 3 + 4); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(32, 1), 31 + 2); } TEST(BoundedUtf8LengthSequenceTest, ValuesAreShiftedCorrectlyAmongThreeWords) { BoundedUtf8LengthSequence<96> seq; ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(31, 3), 31); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(63, 4), 62 + 3); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(0, 1), 0); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(65, 1), 63 + 3 + 4); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(64, 1), 63 + 3); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(33, 1), 32 + 3); ASSERT_EQ(seq.InsertAndReturnSumOfPredecessors(32, 1), 32); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/internal/bounded_utf8_length_sequence.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/debugging/internal/bounded_utf8_length_sequence_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
42319aa6-f217-4379-886a-a36337e2685c
cpp
abseil/abseil-cpp
non_temporal_memcpy
absl/crc/internal/non_temporal_memcpy.h
absl/crc/internal/non_temporal_memcpy_test.cc
#ifndef ABSL_CRC_INTERNAL_NON_TEMPORAL_MEMCPY_H_ #define ABSL_CRC_INTERNAL_NON_TEMPORAL_MEMCPY_H_ #ifdef _MSC_VER #include <intrin.h> #endif #if defined(__SSE__) || defined(__AVX__) #include <immintrin.h> #endif #ifdef __aarch64__ #include "absl/crc/internal/non_temporal_arm_intrinsics.h" #endif #include <algorithm> #include <cassert> #include <cstdint> #include <cstring> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/optimization.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace crc_internal { constexpr size_t kCacheLineSize = ABSL_CACHELINE_SIZE; inline void *non_temporal_store_memcpy(void *__restrict dst, const void *__restrict src, size_t len) { #if defined(__SSE3__) || defined(__aarch64__) || \ (defined(_MSC_VER) && defined(__AVX__)) uint8_t *d = reinterpret_cast<uint8_t *>(dst); const uint8_t *s = reinterpret_cast<const uint8_t *>(src); if (reinterpret_cast<uintptr_t>(d) & (kCacheLineSize - 1)) { uintptr_t bytes_before_alignment_boundary = kCacheLineSize - (reinterpret_cast<uintptr_t>(d) & (kCacheLineSize - 1)); size_t header_len = (std::min)(bytes_before_alignment_boundary, len); assert(bytes_before_alignment_boundary < kCacheLineSize); memcpy(d, s, header_len); d += header_len; s += header_len; len -= header_len; } if (len >= kCacheLineSize) { _mm_sfence(); __m128i *dst_cacheline = reinterpret_cast<__m128i *>(d); const __m128i *src_cacheline = reinterpret_cast<const __m128i *>(s); constexpr int kOpsPerCacheLine = kCacheLineSize / sizeof(__m128i); size_t loops = len / kCacheLineSize; while (len >= kCacheLineSize) { __m128i temp1, temp2, temp3, temp4; temp1 = _mm_lddqu_si128(src_cacheline + 0); temp2 = _mm_lddqu_si128(src_cacheline + 1); temp3 = _mm_lddqu_si128(src_cacheline + 2); temp4 = _mm_lddqu_si128(src_cacheline + 3); _mm_stream_si128(dst_cacheline + 0, temp1); _mm_stream_si128(dst_cacheline + 1, temp2); _mm_stream_si128(dst_cacheline + 2, temp3); _mm_stream_si128(dst_cacheline + 3, temp4); src_cacheline += kOpsPerCacheLine; dst_cacheline += kOpsPerCacheLine; len -= kCacheLineSize; } d += loops * kCacheLineSize; s += loops * kCacheLineSize; _mm_sfence(); } if (len) { memcpy(d, s, len); } return dst; #else return memcpy(dst, src, len); #endif } #if ABSL_HAVE_CPP_ATTRIBUTE(gnu::target) && !defined(_MSC_VER) && \ (defined(__x86_64__) || defined(__i386__)) #define ABSL_INTERNAL_CAN_FORCE_AVX 1 #endif #ifdef ABSL_INTERNAL_CAN_FORCE_AVX [[gnu::target("avx")]] #endif inline void *non_temporal_store_memcpy_avx(void *__restrict dst, const void *__restrict src, size_t len) { #if ((defined(__AVX__) || defined(ABSL_INTERNAL_CAN_FORCE_AVX)) && \ defined(__SSE3__)) || \ (defined(_MSC_VER) && defined(__AVX__)) uint8_t *d = reinterpret_cast<uint8_t *>(dst); const uint8_t *s = reinterpret_cast<const uint8_t *>(src); if (reinterpret_cast<uintptr_t>(d) & (kCacheLineSize - 1)) { uintptr_t bytes_before_alignment_boundary = kCacheLineSize - (reinterpret_cast<uintptr_t>(d) & (kCacheLineSize - 1)); size_t header_len = (std::min)(bytes_before_alignment_boundary, len); assert(bytes_before_alignment_boundary < kCacheLineSize); memcpy(d, s, header_len); d += header_len; s += header_len; len -= header_len; } if (len >= kCacheLineSize) { _mm_sfence(); __m256i *dst_cacheline = reinterpret_cast<__m256i *>(d); const __m256i *src_cacheline = reinterpret_cast<const __m256i *>(s); constexpr int kOpsPerCacheLine = kCacheLineSize / sizeof(__m256i); size_t loops = len / kCacheLineSize; while (len >= kCacheLineSize) { __m256i temp1, temp2; temp1 = _mm256_lddqu_si256(src_cacheline + 0); temp2 = _mm256_lddqu_si256(src_cacheline + 1); _mm256_stream_si256(dst_cacheline + 0, temp1); _mm256_stream_si256(dst_cacheline + 1, temp2); src_cacheline += kOpsPerCacheLine; dst_cacheline += kOpsPerCacheLine; len -= kCacheLineSize; } d += loops * kCacheLineSize; s += loops * kCacheLineSize; _mm_sfence(); } if (len) { memcpy(d, s, len); } return dst; #else return memcpy(dst, src, len); #endif } #undef ABSL_INTERNAL_CAN_FORCE_AVX } ABSL_NAMESPACE_END } #endif
#include "absl/crc/internal/non_temporal_memcpy.h" #include <algorithm> #include <cstdint> #include <iostream> #include <vector> #include "gtest/gtest.h" namespace { struct TestParam { size_t copy_size; uint32_t src_offset; uint32_t dst_offset; }; class NonTemporalMemcpyTest : public testing::TestWithParam<TestParam> { protected: void SetUp() override { size_t buf_size = ((std::max(GetParam().src_offset, GetParam().dst_offset) + GetParam().copy_size) + 15) / 16 * 16; a_.resize(buf_size); b_.resize(buf_size); for (size_t i = 0; i < buf_size; i++) { a_[i] = static_cast<uint8_t>(i % 256); b_[i] = ~a_[i]; } } std::vector<uint8_t> a_, b_; }; TEST_P(NonTemporalMemcpyTest, SSEEquality) { uint8_t *src = a_.data() + GetParam().src_offset; uint8_t *dst = b_.data() + GetParam().dst_offset; absl::crc_internal::non_temporal_store_memcpy(dst, src, GetParam().copy_size); for (size_t i = 0; i < GetParam().copy_size; i++) { EXPECT_EQ(src[i], dst[i]); } } TEST_P(NonTemporalMemcpyTest, AVXEquality) { uint8_t* src = a_.data() + GetParam().src_offset; uint8_t* dst = b_.data() + GetParam().dst_offset; absl::crc_internal::non_temporal_store_memcpy_avx(dst, src, GetParam().copy_size); for (size_t i = 0; i < GetParam().copy_size; i++) { EXPECT_EQ(src[i], dst[i]); } } constexpr TestParam params[] = { {63, 0, 0}, {58, 5, 5}, {61, 2, 0}, {61, 0, 2}, {58, 5, 2}, {4096, 0, 0}, {4096, 0, 1}, {4096, 0, 2}, {4096, 0, 3}, {4096, 0, 4}, {4096, 0, 5}, {4096, 0, 6}, {4096, 0, 7}, {4096, 0, 8}, {4096, 0, 9}, {4096, 0, 10}, {4096, 0, 11}, {4096, 0, 12}, {4096, 0, 13}, {4096, 0, 14}, {4096, 0, 15}, {4096, 7, 7}, {4096, 3, 0}, {4096, 1, 0}, {4096, 9, 3}, {4096, 9, 11}, {8192, 0, 0}, {8192, 5, 2}, {1024768, 7, 11}, {1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}}; INSTANTIATE_TEST_SUITE_P(ParameterizedNonTemporalMemcpyTest, NonTemporalMemcpyTest, testing::ValuesIn(params)); }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/crc/internal/non_temporal_memcpy.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/crc/internal/non_temporal_memcpy_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
cf22b863-770e-44ee-9819-8cef360eb2f4
cpp
abseil/abseil-cpp
crc_memcpy
absl/crc/internal/crc_memcpy.h
absl/crc/internal/crc_memcpy_test.cc
#ifndef ABSL_CRC_INTERNAL_CRC_MEMCPY_H_ #define ABSL_CRC_INTERNAL_CRC_MEMCPY_H_ #include <cstddef> #include <memory> #include "absl/base/config.h" #include "absl/crc/crc32c.h" #include "absl/crc/internal/crc32_x86_arm_combined_simd.h" #if defined(ABSL_CRC_INTERNAL_HAVE_X86_SIMD) #define ABSL_INTERNAL_HAVE_X86_64_ACCELERATED_CRC_MEMCPY_ENGINE 1 #elif defined(ABSL_CRC_INTERNAL_HAVE_ARM_SIMD) #define ABSL_INTERNAL_HAVE_ARM_ACCELERATED_CRC_MEMCPY_ENGINE 1 #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace crc_internal { class CrcMemcpyEngine { public: virtual ~CrcMemcpyEngine() = default; virtual crc32c_t Compute(void* __restrict dst, const void* __restrict src, std::size_t length, crc32c_t initial_crc) const = 0; protected: CrcMemcpyEngine() = default; }; class CrcMemcpy { public: static crc32c_t CrcAndCopy(void* __restrict dst, const void* __restrict src, std::size_t length, crc32c_t initial_crc = crc32c_t{0}, bool non_temporal = false) { static const ArchSpecificEngines engines = GetArchSpecificEngines(); auto* engine = non_temporal ? engines.non_temporal : engines.temporal; return engine->Compute(dst, src, length, initial_crc); } static std::unique_ptr<CrcMemcpyEngine> GetTestEngine(int vector, int integer); private: struct ArchSpecificEngines { CrcMemcpyEngine* temporal; CrcMemcpyEngine* non_temporal; }; static ArchSpecificEngines GetArchSpecificEngines(); }; class FallbackCrcMemcpyEngine : public CrcMemcpyEngine { public: FallbackCrcMemcpyEngine() = default; FallbackCrcMemcpyEngine(const FallbackCrcMemcpyEngine&) = delete; FallbackCrcMemcpyEngine operator=(const FallbackCrcMemcpyEngine&) = delete; crc32c_t Compute(void* __restrict dst, const void* __restrict src, std::size_t length, crc32c_t initial_crc) const override; }; class CrcNonTemporalMemcpyEngine : public CrcMemcpyEngine { public: CrcNonTemporalMemcpyEngine() = default; CrcNonTemporalMemcpyEngine(const CrcNonTemporalMemcpyEngine&) = delete; CrcNonTemporalMemcpyEngine operator=(const CrcNonTemporalMemcpyEngine&) = delete; crc32c_t Compute(void* __restrict dst, const void* __restrict src, std::size_t length, crc32c_t initial_crc) const override; }; class CrcNonTemporalMemcpyAVXEngine : public CrcMemcpyEngine { public: CrcNonTemporalMemcpyAVXEngine() = default; CrcNonTemporalMemcpyAVXEngine(const CrcNonTemporalMemcpyAVXEngine&) = delete; CrcNonTemporalMemcpyAVXEngine operator=( const CrcNonTemporalMemcpyAVXEngine&) = delete; crc32c_t Compute(void* __restrict dst, const void* __restrict src, std::size_t length, crc32c_t initial_crc) const override; }; inline crc32c_t Crc32CAndCopy(void* __restrict dst, const void* __restrict src, std::size_t length, crc32c_t initial_crc = crc32c_t{0}, bool non_temporal = false) { return CrcMemcpy::CrcAndCopy(dst, src, length, initial_crc, non_temporal); } } ABSL_NAMESPACE_END } #endif
#include "absl/crc/internal/crc_memcpy.h" #include <cstddef> #include <cstdint> #include <cstring> #include <limits> #include <memory> #include <string> #include <utility> #include "gtest/gtest.h" #include "absl/crc/crc32c.h" #include "absl/memory/memory.h" #include "absl/random/distributions.h" #include "absl/random/random.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace { enum CrcEngine { ACCELERATED = 0, NONTEMPORAL = 1, FALLBACK = 2, }; template <size_t max_size> class CrcMemcpyTest : public testing::Test { protected: CrcMemcpyTest() { source_ = std::make_unique<char[]>(kSize); destination_ = std::make_unique<char[]>(kSize); } static constexpr size_t kAlignment = 16; static constexpr size_t kMaxCopySize = max_size; static constexpr size_t kSize = kAlignment + kMaxCopySize; std::unique_ptr<char[]> source_; std::unique_ptr<char[]> destination_; absl::BitGen gen_; }; typedef CrcMemcpyTest<4500> CrcSmallTest; typedef CrcMemcpyTest<(1 << 24)> CrcLargeTest; template <typename ParamsT> class EngineParamTestTemplate : public CrcSmallTest, public ::testing::WithParamInterface<ParamsT> { protected: EngineParamTestTemplate() { if (GetParam().crc_engine_selector == FALLBACK) { engine_ = std::make_unique<absl::crc_internal::FallbackCrcMemcpyEngine>(); } else if (GetParam().crc_engine_selector == NONTEMPORAL) { engine_ = std::make_unique<absl::crc_internal::CrcNonTemporalMemcpyEngine>(); } else { engine_ = absl::crc_internal::CrcMemcpy::GetTestEngine( GetParam().vector_lanes, GetParam().integer_lanes); } } ParamsT GetParam() const { return ::testing::WithParamInterface<ParamsT>::GetParam(); } std::unique_ptr<absl::crc_internal::CrcMemcpyEngine> engine_; }; struct TestParams { CrcEngine crc_engine_selector = ACCELERATED; int vector_lanes = 0; int integer_lanes = 0; }; using EngineParamTest = EngineParamTestTemplate<TestParams>; TEST_P(EngineParamTest, SmallCorrectnessCheckSourceAlignment) { constexpr size_t kTestSizes[] = {0, 100, 255, 512, 1024, 4000, kMaxCopySize}; for (size_t source_alignment = 0; source_alignment < kAlignment; source_alignment++) { for (auto size : kTestSizes) { char* base_data = static_cast<char*>(source_.get()) + source_alignment; for (size_t i = 0; i < size; i++) { *(base_data + i) = static_cast<char>(absl::Uniform<unsigned char>(gen_)); } SCOPED_TRACE(absl::StrCat("engine=<", GetParam().vector_lanes, ",", GetParam().integer_lanes, ">, ", "size=", size, ", source_alignment=", source_alignment)); absl::crc32c_t initial_crc = absl::crc32c_t{absl::Uniform<uint32_t>(gen_)}; absl::crc32c_t experiment_crc = engine_->Compute(destination_.get(), source_.get() + source_alignment, size, initial_crc); int mem_comparison = memcmp(destination_.get(), source_.get() + source_alignment, size); SCOPED_TRACE(absl::StrCat("Error in memcpy of size: ", size, " with source alignment: ", source_alignment)); ASSERT_EQ(mem_comparison, 0); absl::crc32c_t baseline_crc = absl::ExtendCrc32c( initial_crc, absl::string_view( static_cast<char*>(source_.get()) + source_alignment, size)); ASSERT_EQ(baseline_crc, experiment_crc); } } } TEST_P(EngineParamTest, SmallCorrectnessCheckDestAlignment) { constexpr size_t kTestSizes[] = {0, 100, 255, 512, 1024, 4000, kMaxCopySize}; for (size_t dest_alignment = 0; dest_alignment < kAlignment; dest_alignment++) { for (auto size : kTestSizes) { char* base_data = static_cast<char*>(source_.get()); for (size_t i = 0; i < size; i++) { *(base_data + i) = static_cast<char>(absl::Uniform<unsigned char>(gen_)); } SCOPED_TRACE(absl::StrCat("engine=<", GetParam().vector_lanes, ",", GetParam().integer_lanes, ">, ", "size=", size, ", destination_alignment=", dest_alignment)); absl::crc32c_t initial_crc = absl::crc32c_t{absl::Uniform<uint32_t>(gen_)}; absl::crc32c_t experiment_crc = engine_->Compute(destination_.get() + dest_alignment, source_.get(), size, initial_crc); int mem_comparison = memcmp(destination_.get() + dest_alignment, source_.get(), size); SCOPED_TRACE(absl::StrCat("Error in memcpy of size: ", size, " with dest alignment: ", dest_alignment)); ASSERT_EQ(mem_comparison, 0); absl::crc32c_t baseline_crc = absl::ExtendCrc32c( initial_crc, absl::string_view(static_cast<char*>(source_.get()), size)); ASSERT_EQ(baseline_crc, experiment_crc); } } } INSTANTIATE_TEST_SUITE_P(EngineParamTest, EngineParamTest, ::testing::Values( TestParams{ACCELERATED, 3, 0}, TestParams{ACCELERATED, 1, 2}, TestParams{ACCELERATED, 1, 0}, TestParams{FALLBACK, 0, 0}, TestParams{NONTEMPORAL, 0, 0})); }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/crc/internal/crc_memcpy.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/crc/internal/crc_memcpy_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
e87940a3-3087-4512-85f9-cd3fc3a7d4f1
cpp
abseil/abseil-cpp
type_traits
absl/meta/type_traits.h
absl/meta/type_traits_test.cc
#ifndef ABSL_META_TYPE_TRAITS_H_ #define ABSL_META_TYPE_TRAITS_H_ #include <cstddef> #include <functional> #include <string> #include <type_traits> #include <vector> #include "absl/base/attributes.h" #include "absl/base/config.h" #ifdef __cpp_lib_span #include <span> #endif #ifdef ABSL_HAVE_STD_STRING_VIEW #include <string_view> #endif #if defined(__STDCPP_DEFAULT_NEW_ALIGNMENT__) #define ABSL_INTERNAL_DEFAULT_NEW_ALIGNMENT __STDCPP_DEFAULT_NEW_ALIGNMENT__ #else #define ABSL_INTERNAL_DEFAULT_NEW_ALIGNMENT alignof(std::max_align_t) #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace type_traits_internal { template <typename... Ts> struct VoidTImpl { using type = void; }; template <class Enabler, template <class...> class Op, class... Args> struct is_detected_impl { using type = std::false_type; }; template <template <class...> class Op, class... Args> struct is_detected_impl<typename VoidTImpl<Op<Args...>>::type, Op, Args...> { using type = std::true_type; }; template <template <class...> class Op, class... Args> struct is_detected : is_detected_impl<void, Op, Args...>::type {}; template <class Enabler, class To, template <class...> class Op, class... Args> struct is_detected_convertible_impl { using type = std::false_type; }; template <class To, template <class...> class Op, class... Args> struct is_detected_convertible_impl< typename std::enable_if<std::is_convertible<Op<Args...>, To>::value>::type, To, Op, Args...> { using type = std::true_type; }; template <class To, template <class...> class Op, class... Args> struct is_detected_convertible : is_detected_convertible_impl<void, To, Op, Args...>::type {}; } template <typename... Ts> using void_t = typename type_traits_internal::VoidTImpl<Ts...>::type; template <typename... Ts> struct conjunction : std::true_type {}; template <typename T, typename... Ts> struct conjunction<T, Ts...> : std::conditional<T::value, conjunction<Ts...>, T>::type {}; template <typename T> struct conjunction<T> : T {}; template <typename... Ts> struct disjunction : std::false_type {}; template <typename T, typename... Ts> struct disjunction<T, Ts...> : std::conditional<T::value, T, disjunction<Ts...>>::type {}; template <typename T> struct disjunction<T> : T {}; template <typename T> struct negation : std::integral_constant<bool, !T::value> {}; template <typename T> struct is_function : std::integral_constant< bool, !(std::is_reference<T>::value || std::is_const<typename std::add_const<T>::type>::value)> {}; using std::is_copy_assignable; using std::is_move_assignable; using std::is_trivially_copy_assignable; using std::is_trivially_copy_constructible; using std::is_trivially_default_constructible; using std::is_trivially_destructible; using std::is_trivially_move_assignable; using std::is_trivially_move_constructible; #if defined(__cpp_lib_remove_cvref) && __cpp_lib_remove_cvref >= 201711L template <typename T> using remove_cvref = std::remove_cvref<T>; template <typename T> using remove_cvref_t = typename std::remove_cvref<T>::type; #else template <typename T> struct remove_cvref { using type = typename std::remove_cv<typename std::remove_reference<T>::type>::type; }; template <typename T> using remove_cvref_t = typename remove_cvref<T>::type; #endif template <typename T> using remove_cv_t = typename std::remove_cv<T>::type; template <typename T> using remove_const_t = typename std::remove_const<T>::type; template <typename T> using remove_volatile_t = typename std::remove_volatile<T>::type; template <typename T> using add_cv_t = typename std::add_cv<T>::type; template <typename T> using add_const_t = typename std::add_const<T>::type; template <typename T> using add_volatile_t = typename std::add_volatile<T>::type; template <typename T> using remove_reference_t = typename std::remove_reference<T>::type; template <typename T> using add_lvalue_reference_t = typename std::add_lvalue_reference<T>::type; template <typename T> using add_rvalue_reference_t = typename std::add_rvalue_reference<T>::type; template <typename T> using remove_pointer_t = typename std::remove_pointer<T>::type; template <typename T> using add_pointer_t = typename std::add_pointer<T>::type; template <typename T> using make_signed_t = typename std::make_signed<T>::type; template <typename T> using make_unsigned_t = typename std::make_unsigned<T>::type; template <typename T> using remove_extent_t = typename std::remove_extent<T>::type; template <typename T> using remove_all_extents_t = typename std::remove_all_extents<T>::type; template <typename T> using decay_t = typename std::decay<T>::type; template <bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type; template <bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type; template <typename... T> using common_type_t = typename std::common_type<T...>::type; template <typename T> using underlying_type_t = typename std::underlying_type<T>::type; namespace type_traits_internal { #if (defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703L) || \ (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) template <typename> struct result_of; template <typename F, typename... Args> struct result_of<F(Args...)> : std::invoke_result<F, Args...> {}; #else template <typename F> using result_of = std::result_of<F>; #endif } template <typename F> using result_of_t = typename type_traits_internal::result_of<F>::type; namespace type_traits_internal { #if defined(_MSC_VER) || (defined(_LIBCPP_VERSION) && \ _LIBCPP_VERSION < 4000 && _LIBCPP_STD_VER > 11) #define ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ 0 #else #define ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ 1 #endif #if !ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ template <typename Key, typename = size_t> struct IsHashable : std::true_type {}; #else template <typename Key, typename = void> struct IsHashable : std::false_type {}; template <typename Key> struct IsHashable< Key, absl::enable_if_t<std::is_convertible< decltype(std::declval<std::hash<Key>&>()(std::declval<Key const&>())), std::size_t>::value>> : std::true_type {}; #endif struct AssertHashEnabledHelper { private: static void Sink(...) {} struct NAT {}; template <class Key> static auto GetReturnType(int) -> decltype(std::declval<std::hash<Key>>()(std::declval<Key const&>())); template <class Key> static NAT GetReturnType(...); template <class Key> static std::nullptr_t DoIt() { static_assert(IsHashable<Key>::value, "std::hash<Key> does not provide a call operator"); static_assert( std::is_default_constructible<std::hash<Key>>::value, "std::hash<Key> must be default constructible when it is enabled"); static_assert( std::is_copy_constructible<std::hash<Key>>::value, "std::hash<Key> must be copy constructible when it is enabled"); static_assert(absl::is_copy_assignable<std::hash<Key>>::value, "std::hash<Key> must be copy assignable when it is enabled"); using ReturnType = decltype(GetReturnType<Key>(0)); static_assert(std::is_same<ReturnType, NAT>::value || std::is_same<ReturnType, size_t>::value, "std::hash<Key> must return size_t"); return nullptr; } template <class... Ts> friend void AssertHashEnabled(); }; template <class... Ts> inline void AssertHashEnabled() { using Helper = AssertHashEnabledHelper; Helper::Sink(Helper::DoIt<Ts>()...); } } namespace swap_internal { using std::swap; void swap(); template <class T> using IsSwappableImpl = decltype(swap(std::declval<T&>(), std::declval<T&>())); template <class T, class IsNoexcept = std::integral_constant< bool, noexcept(swap(std::declval<T&>(), std::declval<T&>()))>> using IsNothrowSwappableImpl = typename std::enable_if<IsNoexcept::value>::type; template <class T> struct IsSwappable : absl::type_traits_internal::is_detected<IsSwappableImpl, T> {}; template <class T> struct IsNothrowSwappable : absl::type_traits_internal::is_detected<IsNothrowSwappableImpl, T> {}; template <class T, absl::enable_if_t<IsSwappable<T>::value, int> = 0> void Swap(T& lhs, T& rhs) noexcept(IsNothrowSwappable<T>::value) { swap(lhs, rhs); } using StdSwapIsUnconstrained = IsSwappable<void()>; } namespace type_traits_internal { using swap_internal::IsNothrowSwappable; using swap_internal::IsSwappable; using swap_internal::StdSwapIsUnconstrained; using swap_internal::Swap; } #if ABSL_HAVE_BUILTIN(__is_trivially_relocatable) && \ (defined(__cpp_impl_trivially_relocatable) || \ (!defined(__clang__) && !defined(__APPLE__) && !defined(__NVCC__))) template <class T> struct is_trivially_relocatable : std::integral_constant<bool, __is_trivially_relocatable(T)> {}; #else template <class T> struct is_trivially_relocatable : std::is_trivially_copyable<T> {}; #endif #if defined(ABSL_HAVE_CONSTANT_EVALUATED) constexpr bool is_constant_evaluated() noexcept { #ifdef __cpp_lib_is_constant_evaluated return std::is_constant_evaluated(); #elif ABSL_HAVE_BUILTIN(__builtin_is_constant_evaluated) return __builtin_is_constant_evaluated(); #endif } #endif namespace type_traits_internal { template <typename T, typename = void> struct IsOwnerImpl : std::false_type { static_assert(std::is_same<T, absl::remove_cvref_t<T>>::value, "type must lack qualifiers"); }; template <typename T> struct IsOwnerImpl< T, std::enable_if_t<std::is_class<typename T::absl_internal_is_view>::value>> : absl::negation<typename T::absl_internal_is_view> {}; template <typename T> struct IsOwner : IsOwnerImpl<T> {}; template <typename T, typename Traits, typename Alloc> struct IsOwner<std::basic_string<T, Traits, Alloc>> : std::true_type {}; template <typename T, typename Alloc> struct IsOwner<std::vector<T, Alloc>> : std::true_type {}; template <typename T, typename = void> struct IsViewImpl : std::false_type { static_assert(std::is_same<T, absl::remove_cvref_t<T>>::value, "type must lack qualifiers"); }; template <typename T> struct IsViewImpl< T, std::enable_if_t<std::is_class<typename T::absl_internal_is_view>::value>> : T::absl_internal_is_view {}; template <typename T> struct IsView : std::integral_constant<bool, std::is_pointer<T>::value || IsViewImpl<T>::value> {}; #ifdef ABSL_HAVE_STD_STRING_VIEW template <typename Char, typename Traits> struct IsView<std::basic_string_view<Char, Traits>> : std::true_type {}; #endif #ifdef __cpp_lib_span template <typename T> struct IsView<std::span<T>> : std::true_type {}; #endif template <typename T, typename U> using IsLifetimeBoundAssignment = std::integral_constant<bool, IsView<absl::remove_cvref_t<T>>::value && IsOwner<absl::remove_cvref_t<U>>::value>; } ABSL_NAMESPACE_END } #endif
#include "absl/meta/type_traits.h" #include <cstdint> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/time/clock.h" #include "absl/time/time.h" #ifdef ABSL_HAVE_STD_STRING_VIEW #include <string_view> #endif namespace { using ::testing::StaticAssertTypeEq; template <typename T> using IsOwnerAndNotView = absl::conjunction<absl::type_traits_internal::IsOwner<T>, absl::negation<absl::type_traits_internal::IsView<T>>>; static_assert(IsOwnerAndNotView<std::vector<int>>::value, "vector is an owner, not a view"); static_assert(IsOwnerAndNotView<std::string>::value, "string is an owner, not a view"); static_assert(IsOwnerAndNotView<std::wstring>::value, "wstring is an owner, not a view"); #ifdef ABSL_HAVE_STD_STRING_VIEW static_assert(!IsOwnerAndNotView<std::string_view>::value, "string_view is a view, not an owner"); static_assert(!IsOwnerAndNotView<std::wstring_view>::value, "wstring_view is a view, not an owner"); #endif template <class T, class U> struct simple_pair { T first; U second; }; struct Dummy {}; struct ReturnType {}; struct ConvertibleToReturnType { operator ReturnType() const; }; struct StructA {}; struct StructB {}; struct StructC {}; struct TypeWithBarFunction { template <class T, absl::enable_if_t<std::is_same<T&&, StructA&>::value, int> = 0> ReturnType bar(T&&, const StructB&, StructC&&) &&; }; struct TypeWithBarFunctionAndConvertibleReturnType { template <class T, absl::enable_if_t<std::is_same<T&&, StructA&>::value, int> = 0> ConvertibleToReturnType bar(T&&, const StructB&, StructC&&) &&; }; template <class Class, class... Ts> using BarIsCallableImpl = decltype(std::declval<Class>().bar(std::declval<Ts>()...)); template <class Class, class... T> using BarIsCallable = absl::type_traits_internal::is_detected<BarIsCallableImpl, Class, T...>; template <class Class, class... T> using BarIsCallableConv = absl::type_traits_internal::is_detected_convertible< ReturnType, BarIsCallableImpl, Class, T...>; TEST(IsDetectedTest, BasicUsage) { EXPECT_TRUE((BarIsCallable<TypeWithBarFunction, StructA&, const StructB&, StructC>::value)); EXPECT_TRUE( (BarIsCallable<TypeWithBarFunction, StructA&, StructB&, StructC>::value)); EXPECT_TRUE( (BarIsCallable<TypeWithBarFunction, StructA&, StructB, StructC>::value)); EXPECT_FALSE((BarIsCallable<int, StructA&, const StructB&, StructC>::value)); EXPECT_FALSE((BarIsCallable<TypeWithBarFunction&, StructA&, const StructB&, StructC>::value)); EXPECT_FALSE((BarIsCallable<TypeWithBarFunction, StructA, const StructB&, StructC>::value)); } TEST(IsDetectedConvertibleTest, BasicUsage) { EXPECT_TRUE((BarIsCallableConv<TypeWithBarFunction, StructA&, const StructB&, StructC>::value)); EXPECT_TRUE((BarIsCallableConv<TypeWithBarFunction, StructA&, StructB&, StructC>::value)); EXPECT_TRUE((BarIsCallableConv<TypeWithBarFunction, StructA&, StructB, StructC>::value)); EXPECT_TRUE((BarIsCallableConv<TypeWithBarFunctionAndConvertibleReturnType, StructA&, const StructB&, StructC>::value)); EXPECT_TRUE((BarIsCallableConv<TypeWithBarFunctionAndConvertibleReturnType, StructA&, StructB&, StructC>::value)); EXPECT_TRUE((BarIsCallableConv<TypeWithBarFunctionAndConvertibleReturnType, StructA&, StructB, StructC>::value)); EXPECT_FALSE( (BarIsCallableConv<int, StructA&, const StructB&, StructC>::value)); EXPECT_FALSE((BarIsCallableConv<TypeWithBarFunction&, StructA&, const StructB&, StructC>::value)); EXPECT_FALSE((BarIsCallableConv<TypeWithBarFunction, StructA, const StructB&, StructC>::value)); EXPECT_FALSE((BarIsCallableConv<TypeWithBarFunctionAndConvertibleReturnType&, StructA&, const StructB&, StructC>::value)); EXPECT_FALSE((BarIsCallableConv<TypeWithBarFunctionAndConvertibleReturnType, StructA, const StructB&, StructC>::value)); } TEST(VoidTTest, BasicUsage) { StaticAssertTypeEq<void, absl::void_t<Dummy>>(); StaticAssertTypeEq<void, absl::void_t<Dummy, Dummy, Dummy>>(); } TEST(ConjunctionTest, BasicBooleanLogic) { EXPECT_TRUE(absl::conjunction<>::value); EXPECT_TRUE(absl::conjunction<std::true_type>::value); EXPECT_TRUE((absl::conjunction<std::true_type, std::true_type>::value)); EXPECT_FALSE((absl::conjunction<std::true_type, std::false_type>::value)); EXPECT_FALSE((absl::conjunction<std::false_type, std::true_type>::value)); EXPECT_FALSE((absl::conjunction<std::false_type, std::false_type>::value)); } struct MyTrueType { static constexpr bool value = true; }; struct MyFalseType { static constexpr bool value = false; }; TEST(ConjunctionTest, ShortCircuiting) { EXPECT_FALSE( (absl::conjunction<std::true_type, std::false_type, Dummy>::value)); EXPECT_TRUE((std::is_base_of<MyFalseType, absl::conjunction<std::true_type, MyFalseType, std::false_type>>::value)); EXPECT_TRUE( (std::is_base_of<MyTrueType, absl::conjunction<std::true_type, MyTrueType>>::value)); } TEST(DisjunctionTest, BasicBooleanLogic) { EXPECT_FALSE(absl::disjunction<>::value); EXPECT_FALSE(absl::disjunction<std::false_type>::value); EXPECT_TRUE((absl::disjunction<std::true_type, std::true_type>::value)); EXPECT_TRUE((absl::disjunction<std::true_type, std::false_type>::value)); EXPECT_TRUE((absl::disjunction<std::false_type, std::true_type>::value)); EXPECT_FALSE((absl::disjunction<std::false_type, std::false_type>::value)); } TEST(DisjunctionTest, ShortCircuiting) { EXPECT_TRUE( (absl::disjunction<std::false_type, std::true_type, Dummy>::value)); EXPECT_TRUE(( std::is_base_of<MyTrueType, absl::disjunction<std::false_type, MyTrueType, std::true_type>>::value)); EXPECT_TRUE(( std::is_base_of<MyFalseType, absl::disjunction<std::false_type, MyFalseType>>::value)); } TEST(NegationTest, BasicBooleanLogic) { EXPECT_FALSE(absl::negation<std::true_type>::value); EXPECT_FALSE(absl::negation<MyTrueType>::value); EXPECT_TRUE(absl::negation<std::false_type>::value); EXPECT_TRUE(absl::negation<MyFalseType>::value); } class Trivial { int n_; }; struct TrivialDestructor { ~TrivialDestructor() = default; }; struct NontrivialDestructor { ~NontrivialDestructor() {} }; struct DeletedDestructor { ~DeletedDestructor() = delete; }; class TrivialDefaultCtor { public: TrivialDefaultCtor() = default; explicit TrivialDefaultCtor(int n) : n_(n) {} private: int n_; }; class NontrivialDefaultCtor { public: NontrivialDefaultCtor() : n_(1) {} private: int n_; }; class DeletedDefaultCtor { public: DeletedDefaultCtor() = delete; explicit DeletedDefaultCtor(int n) : n_(n) {} private: int n_; }; class TrivialMoveCtor { public: explicit TrivialMoveCtor(int n) : n_(n) {} TrivialMoveCtor(TrivialMoveCtor&&) = default; TrivialMoveCtor& operator=(const TrivialMoveCtor& t) { n_ = t.n_; return *this; } private: int n_; }; class NontrivialMoveCtor { public: explicit NontrivialMoveCtor(int n) : n_(n) {} NontrivialMoveCtor(NontrivialMoveCtor&& t) noexcept : n_(t.n_) {} NontrivialMoveCtor& operator=(const NontrivialMoveCtor&) = default; private: int n_; }; class TrivialCopyCtor { public: explicit TrivialCopyCtor(int n) : n_(n) {} TrivialCopyCtor(const TrivialCopyCtor&) = default; TrivialCopyCtor& operator=(const TrivialCopyCtor& t) { n_ = t.n_; return *this; } private: int n_; }; class NontrivialCopyCtor { public: explicit NontrivialCopyCtor(int n) : n_(n) {} NontrivialCopyCtor(const NontrivialCopyCtor& t) : n_(t.n_) {} NontrivialCopyCtor& operator=(const NontrivialCopyCtor&) = default; private: int n_; }; class DeletedCopyCtor { public: explicit DeletedCopyCtor(int n) : n_(n) {} DeletedCopyCtor(const DeletedCopyCtor&) = delete; DeletedCopyCtor& operator=(const DeletedCopyCtor&) = default; private: int n_; }; class TrivialMoveAssign { public: explicit TrivialMoveAssign(int n) : n_(n) {} TrivialMoveAssign(const TrivialMoveAssign& t) : n_(t.n_) {} TrivialMoveAssign& operator=(TrivialMoveAssign&&) = default; ~TrivialMoveAssign() {} private: int n_; }; class NontrivialMoveAssign { public: explicit NontrivialMoveAssign(int n) : n_(n) {} NontrivialMoveAssign(const NontrivialMoveAssign&) = default; NontrivialMoveAssign& operator=(NontrivialMoveAssign&& t) noexcept { n_ = t.n_; return *this; } private: int n_; }; class TrivialCopyAssign { public: explicit TrivialCopyAssign(int n) : n_(n) {} TrivialCopyAssign(const TrivialCopyAssign& t) : n_(t.n_) {} TrivialCopyAssign& operator=(const TrivialCopyAssign& t) = default; ~TrivialCopyAssign() {} private: int n_; }; class NontrivialCopyAssign { public: explicit NontrivialCopyAssign(int n) : n_(n) {} NontrivialCopyAssign(const NontrivialCopyAssign&) = default; NontrivialCopyAssign& operator=(const NontrivialCopyAssign& t) { n_ = t.n_; return *this; } private: int n_; }; class DeletedCopyAssign { public: explicit DeletedCopyAssign(int n) : n_(n) {} DeletedCopyAssign(const DeletedCopyAssign&) = default; DeletedCopyAssign& operator=(const DeletedCopyAssign&) = delete; private: int n_; }; struct MovableNonCopyable { MovableNonCopyable() = default; MovableNonCopyable(const MovableNonCopyable&) = delete; MovableNonCopyable(MovableNonCopyable&&) = default; MovableNonCopyable& operator=(const MovableNonCopyable&) = delete; MovableNonCopyable& operator=(MovableNonCopyable&&) = default; }; struct NonCopyableOrMovable { NonCopyableOrMovable() = default; virtual ~NonCopyableOrMovable() = default; NonCopyableOrMovable(const NonCopyableOrMovable&) = delete; NonCopyableOrMovable(NonCopyableOrMovable&&) = delete; NonCopyableOrMovable& operator=(const NonCopyableOrMovable&) = delete; NonCopyableOrMovable& operator=(NonCopyableOrMovable&&) = delete; }; class Base { public: virtual ~Base() {} }; TEST(TypeTraitsTest, TestIsFunction) { struct Callable { void operator()() {} }; EXPECT_TRUE(absl::is_function<void()>::value); EXPECT_TRUE(absl::is_function<void()&>::value); EXPECT_TRUE(absl::is_function<void() const>::value); EXPECT_TRUE(absl::is_function<void() noexcept>::value); EXPECT_TRUE(absl::is_function<void(...) noexcept>::value); EXPECT_FALSE(absl::is_function<void (*)()>::value); EXPECT_FALSE(absl::is_function<void (&)()>::value); EXPECT_FALSE(absl::is_function<int>::value); EXPECT_FALSE(absl::is_function<Callable>::value); } TEST(TypeTraitsTest, TestRemoveCVRef) { EXPECT_TRUE( (std::is_same<typename absl::remove_cvref<int>::type, int>::value)); EXPECT_TRUE( (std::is_same<typename absl::remove_cvref<int&>::type, int>::value)); EXPECT_TRUE( (std::is_same<typename absl::remove_cvref<int&&>::type, int>::value)); EXPECT_TRUE(( std::is_same<typename absl::remove_cvref<const int&>::type, int>::value)); EXPECT_TRUE( (std::is_same<typename absl::remove_cvref<int*>::type, int*>::value)); EXPECT_TRUE((std::is_same<typename absl::remove_cvref<const int*>::type, const int*>::value)); EXPECT_TRUE( (std::is_same<typename absl::remove_cvref<int[2]>::type, int[2]>::value)); EXPECT_TRUE((std::is_same<typename absl::remove_cvref<int(&)[2]>::type, int[2]>::value)); EXPECT_TRUE((std::is_same<typename absl::remove_cvref<int(&&)[2]>::type, int[2]>::value)); EXPECT_TRUE((std::is_same<typename absl::remove_cvref<const int[2]>::type, int[2]>::value)); EXPECT_TRUE((std::is_same<typename absl::remove_cvref<const int(&)[2]>::type, int[2]>::value)); EXPECT_TRUE((std::is_same<typename absl::remove_cvref<const int(&&)[2]>::type, int[2]>::value)); } #define ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(trait_name, ...) \ EXPECT_TRUE((std::is_same<typename std::trait_name<__VA_ARGS__>::type, \ absl::trait_name##_t<__VA_ARGS__>>::value)) TEST(TypeTraitsTest, TestRemoveCVAliases) { ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_cv, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_cv, const int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_cv, volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_cv, const volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_const, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_const, const int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_const, volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_const, const volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_volatile, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_volatile, const int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_volatile, volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_volatile, const volatile int); } TEST(TypeTraitsTest, TestAddCVAliases) { ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_cv, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_cv, const int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_cv, volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_cv, const volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_const, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_const, const int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_const, volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_const, const volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_volatile, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_volatile, const int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_volatile, volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_volatile, const volatile int); } TEST(TypeTraitsTest, TestReferenceAliases) { ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_reference, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_reference, volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_reference, int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_reference, volatile int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_reference, int&&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_reference, volatile int&&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_lvalue_reference, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_lvalue_reference, volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_lvalue_reference, int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_lvalue_reference, volatile int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_lvalue_reference, int&&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_lvalue_reference, volatile int&&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_rvalue_reference, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_rvalue_reference, volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_rvalue_reference, int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_rvalue_reference, volatile int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_rvalue_reference, int&&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_rvalue_reference, volatile int&&); } TEST(TypeTraitsTest, TestPointerAliases) { ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_pointer, int*); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_pointer, volatile int*); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_pointer, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(add_pointer, volatile int); } TEST(TypeTraitsTest, TestSignednessAliases) { ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(make_signed, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(make_signed, volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(make_signed, unsigned); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(make_signed, volatile unsigned); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(make_unsigned, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(make_unsigned, volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(make_unsigned, unsigned); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(make_unsigned, volatile unsigned); } TEST(TypeTraitsTest, TestExtentAliases) { ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_extent, int[]); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_extent, int[1]); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_extent, int[1][1]); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_extent, int[][1]); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_all_extents, int[]); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_all_extents, int[1]); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_all_extents, int[1][1]); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(remove_all_extents, int[][1]); } TEST(TypeTraitsTest, TestDecay) { ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, const int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, const volatile int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, const int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, volatile int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, const volatile int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, const int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, volatile int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, const volatile int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, int[1]); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, int[1][1]); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, int[][1]); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, int()); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, int(float)); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(decay, int(char, ...)); } struct TypeA {}; struct TypeB {}; struct TypeC {}; struct TypeD {}; template <typename T> struct Wrap {}; enum class TypeEnum { A, B, C, D }; struct GetTypeT { template <typename T, absl::enable_if_t<std::is_same<T, TypeA>::value, int> = 0> TypeEnum operator()(Wrap<T>) const { return TypeEnum::A; } template <typename T, absl::enable_if_t<std::is_same<T, TypeB>::value, int> = 0> TypeEnum operator()(Wrap<T>) const { return TypeEnum::B; } template <typename T, absl::enable_if_t<std::is_same<T, TypeC>::value, int> = 0> TypeEnum operator()(Wrap<T>) const { return TypeEnum::C; } } constexpr GetType = {}; TEST(TypeTraitsTest, TestEnableIf) { EXPECT_EQ(TypeEnum::A, GetType(Wrap<TypeA>())); EXPECT_EQ(TypeEnum::B, GetType(Wrap<TypeB>())); EXPECT_EQ(TypeEnum::C, GetType(Wrap<TypeC>())); } TEST(TypeTraitsTest, TestConditional) { ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(conditional, true, int, char); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(conditional, false, int, char); } TEST(TypeTraitsTest, TestCommonType) { ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(common_type, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(common_type, int, char); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(common_type, int, char, int); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(common_type, int&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(common_type, int, char&); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(common_type, int, char, int&); } TEST(TypeTraitsTest, TestUnderlyingType) { enum class enum_char : char {}; enum class enum_long_long : long long {}; ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(underlying_type, enum_char); ABSL_INTERNAL_EXPECT_ALIAS_EQUIVALENCE(underlying_type, enum_long_long); } struct GetTypeExtT { template <typename T> absl::result_of_t<const GetTypeT&(T)> operator()(T&& arg) const { return GetType(std::forward<T>(arg)); } TypeEnum operator()(Wrap<TypeD>) const { return TypeEnum::D; } } constexpr GetTypeExt = {}; TEST(TypeTraitsTest, TestResultOf) { EXPECT_EQ(TypeEnum::A, GetTypeExt(Wrap<TypeA>())); EXPECT_EQ(TypeEnum::B, GetTypeExt(Wrap<TypeB>())); EXPECT_EQ(TypeEnum::C, GetTypeExt(Wrap<TypeC>())); EXPECT_EQ(TypeEnum::D, GetTypeExt(Wrap<TypeD>())); } namespace adl_namespace { struct DeletedSwap {}; void swap(DeletedSwap&, DeletedSwap&) = delete; struct SpecialNoexceptSwap { SpecialNoexceptSwap(SpecialNoexceptSwap&&) {} SpecialNoexceptSwap& operator=(SpecialNoexceptSwap&&) { return *this; } ~SpecialNoexceptSwap() = default; }; void swap(SpecialNoexceptSwap&, SpecialNoexceptSwap&) noexcept {} } TEST(TypeTraitsTest, IsSwappable) { using absl::type_traits_internal::IsSwappable; using absl::type_traits_internal::StdSwapIsUnconstrained; EXPECT_TRUE(IsSwappable<int>::value); struct S {}; EXPECT_TRUE(IsSwappable<S>::value); struct NoConstruct { NoConstruct(NoConstruct&&) = delete; NoConstruct& operator=(NoConstruct&&) { return *this; } ~NoConstruct() = default; }; EXPECT_EQ(IsSwappable<NoConstruct>::value, StdSwapIsUnconstrained::value); struct NoAssign { NoAssign(NoAssign&&) {} NoAssign& operator=(NoAssign&&) = delete; ~NoAssign() = default; }; EXPECT_EQ(IsSwappable<NoAssign>::value, StdSwapIsUnconstrained::value); EXPECT_FALSE(IsSwappable<adl_namespace::DeletedSwap>::value); EXPECT_TRUE(IsSwappable<adl_namespace::SpecialNoexceptSwap>::value); } TEST(TypeTraitsTest, IsNothrowSwappable) { using absl::type_traits_internal::IsNothrowSwappable; using absl::type_traits_internal::StdSwapIsUnconstrained; EXPECT_TRUE(IsNothrowSwappable<int>::value); struct NonNoexceptMoves { NonNoexceptMoves(NonNoexceptMoves&&) {} NonNoexceptMoves& operator=(NonNoexceptMoves&&) { return *this; } ~NonNoexceptMoves() = default; }; EXPECT_FALSE(IsNothrowSwappable<NonNoexceptMoves>::value); struct NoConstruct { NoConstruct(NoConstruct&&) = delete; NoConstruct& operator=(NoConstruct&&) { return *this; } ~NoConstruct() = default; }; EXPECT_FALSE(IsNothrowSwappable<NoConstruct>::value); struct NoAssign { NoAssign(NoAssign&&) {} NoAssign& operator=(NoAssign&&) = delete; ~NoAssign() = default; }; EXPECT_FALSE(IsNothrowSwappable<NoAssign>::value); EXPECT_FALSE(IsNothrowSwappable<adl_namespace::DeletedSwap>::value); EXPECT_TRUE(IsNothrowSwappable<adl_namespace::SpecialNoexceptSwap>::value); } TEST(TriviallyRelocatable, PrimitiveTypes) { static_assert(absl::is_trivially_relocatable<int>::value, ""); static_assert(absl::is_trivially_relocatable<char>::value, ""); static_assert(absl::is_trivially_relocatable<void*>::value, ""); } TEST(TriviallyRelocatable, UserDefinedTriviallyRelocatable) { struct S { int x; int y; }; static_assert(absl::is_trivially_relocatable<S>::value, ""); } TEST(TriviallyRelocatable, UserProvidedMoveConstructor) { struct S { S(S&&) {} }; static_assert(!absl::is_trivially_relocatable<S>::value, ""); } TEST(TriviallyRelocatable, UserProvidedCopyConstructor) { struct S { S(const S&) {} }; static_assert(!absl::is_trivially_relocatable<S>::value, ""); } TEST(TriviallyRelocatable, UserProvidedCopyAssignment) { struct S { S(const S&) = default; S& operator=(const S&) { return *this; } }; static_assert(!absl::is_trivially_relocatable<S>::value, ""); } TEST(TriviallyRelocatable, UserProvidedMoveAssignment) { struct S { S(S&&) = default; S& operator=(S&&) { return *this; } }; static_assert(!absl::is_trivially_relocatable<S>::value, ""); } TEST(TriviallyRelocatable, UserProvidedDestructor) { struct S { ~S() {} }; static_assert(!absl::is_trivially_relocatable<S>::value, ""); } #if defined(ABSL_HAVE_ATTRIBUTE_TRIVIAL_ABI) && \ ABSL_HAVE_BUILTIN(__is_trivially_relocatable) && \ (defined(__cpp_impl_trivially_relocatable) || \ (!defined(__clang__) && !defined(__APPLE__) && !defined(__NVCC__))) TEST(TriviallyRelocatable, TrivialAbi) { struct ABSL_ATTRIBUTE_TRIVIAL_ABI S { S(S&&) {} S(const S&) {} void operator=(S&&) {} void operator=(const S&) {} ~S() {} }; static_assert(absl::is_trivially_relocatable<S>::value, ""); } #endif #ifdef ABSL_HAVE_CONSTANT_EVALUATED constexpr int64_t NegateIfConstantEvaluated(int64_t i) { if (absl::is_constant_evaluated()) { return -i; } else { return i; } } #endif TEST(IsConstantEvaluated, is_constant_evaluated) { #ifdef ABSL_HAVE_CONSTANT_EVALUATED constexpr int64_t constant = NegateIfConstantEvaluated(42); EXPECT_EQ(constant, -42); int64_t now = absl::ToUnixSeconds(absl::Now()); int64_t not_constant = NegateIfConstantEvaluated(now); EXPECT_EQ(not_constant, now); static int64_t const_init = NegateIfConstantEvaluated(42); EXPECT_EQ(const_init, -42); #else GTEST_SKIP() << "absl::is_constant_evaluated is not defined"; #endif } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/meta/type_traits.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/meta/type_traits_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
e0ef1394-ad72-454a-8904-8a48b9b75687
cpp
abseil/abseil-cpp
algorithm
absl/algorithm/algorithm.h
absl/algorithm/algorithm_test.cc
#ifndef ABSL_ALGORITHM_ALGORITHM_H_ #define ABSL_ALGORITHM_ALGORITHM_H_ #include <algorithm> #include <iterator> #include <type_traits> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN using std::equal; using std::rotate; template <typename InputIterator, typename EqualityComparable> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool linear_search( InputIterator first, InputIterator last, const EqualityComparable& value) { return std::find(first, last, value) != last; } ABSL_NAMESPACE_END } #endif
#include "absl/algorithm/algorithm.h" #include <array> #include <vector> #include "gtest/gtest.h" #include "absl/base/config.h" namespace { class LinearSearchTest : public testing::Test { protected: LinearSearchTest() : container_{1, 2, 3} {} static bool Is3(int n) { return n == 3; } static bool Is4(int n) { return n == 4; } std::vector<int> container_; }; TEST_F(LinearSearchTest, linear_search) { EXPECT_TRUE(absl::linear_search(container_.begin(), container_.end(), 3)); EXPECT_FALSE(absl::linear_search(container_.begin(), container_.end(), 4)); } TEST_F(LinearSearchTest, linear_searchConst) { const std::vector<int> *const const_container = &container_; EXPECT_TRUE( absl::linear_search(const_container->begin(), const_container->end(), 3)); EXPECT_FALSE( absl::linear_search(const_container->begin(), const_container->end(), 4)); } #if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L TEST_F(LinearSearchTest, Constexpr) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(absl::linear_search(kArray.begin(), kArray.end(), 3)); static_assert(!absl::linear_search(kArray.begin(), kArray.end(), 4)); } #endif }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/algorithm/algorithm.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/algorithm/algorithm_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
f82ffd9e-8b2e-4ecd-b255-4dcf792fe58e
cpp
abseil/abseil-cpp
container
absl/algorithm/container.h
absl/algorithm/container_test.cc
#ifndef ABSL_ALGORITHM_CONTAINER_H_ #define ABSL_ALGORITHM_CONTAINER_H_ #include <algorithm> #include <cassert> #include <iterator> #include <numeric> #include <random> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "absl/algorithm/algorithm.h" #include "absl/base/config.h" #include "absl/base/macros.h" #include "absl/base/nullability.h" #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_algorithm_internal { using std::begin; using std::end; template <typename C> using ContainerIter = decltype(begin(std::declval<C&>())); template <typename C1, typename C2> using ContainerIterPairType = decltype(std::make_pair(ContainerIter<C1>(), ContainerIter<C2>())); template <typename C> using ContainerDifferenceType = decltype(std::distance( std::declval<ContainerIter<C>>(), std::declval<ContainerIter<C>>())); template <typename C> using ContainerPointerType = typename std::iterator_traits<ContainerIter<C>>::pointer; template <typename C> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX17 ContainerIter<C> c_begin(C& c) { return begin(c); } template <typename C> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX17 ContainerIter<C> c_end(C& c) { return end(c); } template <typename T> struct IsUnorderedContainer : std::false_type {}; template <class Key, class T, class Hash, class KeyEqual, class Allocator> struct IsUnorderedContainer< std::unordered_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {}; template <class Key, class Hash, class KeyEqual, class Allocator> struct IsUnorderedContainer<std::unordered_set<Key, Hash, KeyEqual, Allocator>> : std::true_type {}; } template <typename C, typename EqualityComparable> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool c_linear_search( const C& c, EqualityComparable&& value) { return absl::linear_search(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<EqualityComparable>(value)); } template <typename C> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX17 container_algorithm_internal::ContainerDifferenceType<const C> c_distance(const C& c) { return std::distance(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c)); } template <typename C, typename Pred> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool c_all_of(const C& c, Pred&& pred) { return std::all_of(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Pred>(pred)); } template <typename C, typename Pred> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool c_any_of(const C& c, Pred&& pred) { return std::any_of(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Pred>(pred)); } template <typename C, typename Pred> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool c_none_of(const C& c, Pred&& pred) { return std::none_of(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Pred>(pred)); } template <typename C, typename Function> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 decay_t<Function> c_for_each(C&& c, Function&& f) { return std::for_each(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Function>(f)); } template <typename C, typename T> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<C> c_find(C& c, T&& value) { return std::find(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<T>(value)); } template <typename Sequence, typename T> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool c_contains(const Sequence& sequence, T&& value) { return absl::c_find(sequence, std::forward<T>(value)) != container_algorithm_internal::c_end(sequence); } template <typename C, typename Pred> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<C> c_find_if(C& c, Pred&& pred) { return std::find_if(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Pred>(pred)); } template <typename C, typename Pred> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<C> c_find_if_not(C& c, Pred&& pred) { return std::find_if_not(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Pred>(pred)); } template <typename Sequence1, typename Sequence2> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<Sequence1> c_find_end(Sequence1& sequence, Sequence2& subsequence) { return std::find_end(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), container_algorithm_internal::c_begin(subsequence), container_algorithm_internal::c_end(subsequence)); } template <typename Sequence1, typename Sequence2, typename BinaryPredicate> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<Sequence1> c_find_end(Sequence1& sequence, Sequence2& subsequence, BinaryPredicate&& pred) { return std::find_end(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), container_algorithm_internal::c_begin(subsequence), container_algorithm_internal::c_end(subsequence), std::forward<BinaryPredicate>(pred)); } template <typename C1, typename C2> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<C1> c_find_first_of(C1& container, C2& options) { return std::find_first_of(container_algorithm_internal::c_begin(container), container_algorithm_internal::c_end(container), container_algorithm_internal::c_begin(options), container_algorithm_internal::c_end(options)); } template <typename C1, typename C2, typename BinaryPredicate> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<C1> c_find_first_of(C1& container, C2& options, BinaryPredicate&& pred) { return std::find_first_of(container_algorithm_internal::c_begin(container), container_algorithm_internal::c_end(container), container_algorithm_internal::c_begin(options), container_algorithm_internal::c_end(options), std::forward<BinaryPredicate>(pred)); } template <typename Sequence> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<Sequence> c_adjacent_find(Sequence& sequence) { return std::adjacent_find(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence)); } template <typename Sequence, typename BinaryPredicate> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<Sequence> c_adjacent_find(Sequence& sequence, BinaryPredicate&& pred) { return std::adjacent_find(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), std::forward<BinaryPredicate>(pred)); } template <typename C, typename T> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerDifferenceType<const C> c_count(const C& c, T&& value) { return std::count(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<T>(value)); } template <typename C, typename Pred> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerDifferenceType<const C> c_count_if(const C& c, Pred&& pred) { return std::count_if(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Pred>(pred)); } template <typename C1, typename C2> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIterPairType<C1, C2> c_mismatch(C1& c1, C2& c2) { return std::mismatch(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2)); } template <typename C1, typename C2, typename BinaryPredicate> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIterPairType<C1, C2> c_mismatch(C1& c1, C2& c2, BinaryPredicate pred) { return std::mismatch(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), pred); } template <typename C1, typename C2> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool c_equal(const C1& c1, const C2& c2) { return std::equal(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2)); } template <typename C1, typename C2, typename BinaryPredicate> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool c_equal(const C1& c1, const C2& c2, BinaryPredicate&& pred) { return std::equal(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), std::forward<BinaryPredicate>(pred)); } template <typename C1, typename C2> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool c_is_permutation(const C1& c1, const C2& c2) { return std::is_permutation(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2)); } template <typename C1, typename C2, typename BinaryPredicate> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool c_is_permutation( const C1& c1, const C2& c2, BinaryPredicate&& pred) { return std::is_permutation(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), std::forward<BinaryPredicate>(pred)); } template <typename Sequence1, typename Sequence2> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<Sequence1> c_search(Sequence1& sequence, Sequence2& subsequence) { return std::search(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), container_algorithm_internal::c_begin(subsequence), container_algorithm_internal::c_end(subsequence)); } template <typename Sequence1, typename Sequence2, typename BinaryPredicate> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<Sequence1> c_search(Sequence1& sequence, Sequence2& subsequence, BinaryPredicate&& pred) { return std::search(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), container_algorithm_internal::c_begin(subsequence), container_algorithm_internal::c_end(subsequence), std::forward<BinaryPredicate>(pred)); } template <typename Sequence1, typename Sequence2> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool c_contains_subrange( Sequence1& sequence, Sequence2& subsequence) { return absl::c_search(sequence, subsequence) != container_algorithm_internal::c_end(sequence); } template <typename Sequence1, typename Sequence2, typename BinaryPredicate> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool c_contains_subrange( Sequence1& sequence, Sequence2& subsequence, BinaryPredicate&& pred) { return absl::c_search(sequence, subsequence, std::forward<BinaryPredicate>(pred)) != container_algorithm_internal::c_end(sequence); } template <typename Sequence, typename Size, typename T> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<Sequence> c_search_n(Sequence& sequence, Size count, T&& value) { return std::search_n(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), count, std::forward<T>(value)); } template <typename Sequence, typename Size, typename T, typename BinaryPredicate> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 container_algorithm_internal::ContainerIter<Sequence> c_search_n(Sequence& sequence, Size count, T&& value, BinaryPredicate&& pred) { return std::search_n(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), count, std::forward<T>(value), std::forward<BinaryPredicate>(pred)); } template <typename InputSequence, typename OutputIterator> OutputIterator c_copy(const InputSequence& input, OutputIterator output) { return std::copy(container_algorithm_internal::c_begin(input), container_algorithm_internal::c_end(input), output); } template <typename C, typename Size, typename OutputIterator> OutputIterator c_copy_n(const C& input, Size n, OutputIterator output) { return std::copy_n(container_algorithm_internal::c_begin(input), n, output); } template <typename InputSequence, typename OutputIterator, typename Pred> OutputIterator c_copy_if(const InputSequence& input, OutputIterator output, Pred&& pred) { return std::copy_if(container_algorithm_internal::c_begin(input), container_algorithm_internal::c_end(input), output, std::forward<Pred>(pred)); } template <typename C, typename BidirectionalIterator> BidirectionalIterator c_copy_backward(const C& src, BidirectionalIterator dest) { return std::copy_backward(container_algorithm_internal::c_begin(src), container_algorithm_internal::c_end(src), dest); } template <typename C, typename OutputIterator> OutputIterator c_move(C&& src, OutputIterator dest) { return std::move(container_algorithm_internal::c_begin(src), container_algorithm_internal::c_end(src), dest); } template <typename C, typename BidirectionalIterator> BidirectionalIterator c_move_backward(C&& src, BidirectionalIterator dest) { return std::move_backward(container_algorithm_internal::c_begin(src), container_algorithm_internal::c_end(src), dest); } template <typename C1, typename C2> container_algorithm_internal::ContainerIter<C2> c_swap_ranges(C1& c1, C2& c2) { auto first1 = container_algorithm_internal::c_begin(c1); auto last1 = container_algorithm_internal::c_end(c1); auto first2 = container_algorithm_internal::c_begin(c2); auto last2 = container_algorithm_internal::c_end(c2); using std::swap; for (; first1 != last1 && first2 != last2; ++first1, (void)++first2) { swap(*first1, *first2); } return first2; } template <typename InputSequence, typename OutputIterator, typename UnaryOp> OutputIterator c_transform(const InputSequence& input, OutputIterator output, UnaryOp&& unary_op) { return std::transform(container_algorithm_internal::c_begin(input), container_algorithm_internal::c_end(input), output, std::forward<UnaryOp>(unary_op)); } template <typename InputSequence1, typename InputSequence2, typename OutputIterator, typename BinaryOp> OutputIterator c_transform(const InputSequence1& input1, const InputSequence2& input2, OutputIterator output, BinaryOp&& binary_op) { auto first1 = container_algorithm_internal::c_begin(input1); auto last1 = container_algorithm_internal::c_end(input1); auto first2 = container_algorithm_internal::c_begin(input2); auto last2 = container_algorithm_internal::c_end(input2); for (; first1 != last1 && first2 != last2; ++first1, (void)++first2, ++output) { *output = binary_op(*first1, *first2); } return output; } template <typename Sequence, typename T> void c_replace(Sequence& sequence, const T& old_value, const T& new_value) { std::replace(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), old_value, new_value); } template <typename C, typename Pred, typename T> void c_replace_if(C& c, Pred&& pred, T&& new_value) { std::replace_if(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Pred>(pred), std::forward<T>(new_value)); } template <typename C, typename OutputIterator, typename T> OutputIterator c_replace_copy(const C& c, OutputIterator result, T&& old_value, T&& new_value) { return std::replace_copy(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), result, std::forward<T>(old_value), std::forward<T>(new_value)); } template <typename C, typename OutputIterator, typename Pred, typename T> OutputIterator c_replace_copy_if(const C& c, OutputIterator result, Pred&& pred, const T& new_value) { return std::replace_copy_if(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), result, std::forward<Pred>(pred), new_value); } template <typename C, typename T> void c_fill(C& c, const T& value) { std::fill(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), value); } template <typename C, typename Size, typename T> void c_fill_n(C& c, Size n, const T& value) { std::fill_n(container_algorithm_internal::c_begin(c), n, value); } template <typename C, typename Generator> void c_generate(C& c, Generator&& gen) { std::generate(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Generator>(gen)); } template <typename C, typename Size, typename Generator> container_algorithm_internal::ContainerIter<C> c_generate_n(C& c, Size n, Generator&& gen) { return std::generate_n(container_algorithm_internal::c_begin(c), n, std::forward<Generator>(gen)); } template <typename C, typename OutputIterator, typename T> OutputIterator c_remove_copy(const C& c, OutputIterator result, const T& value) { return std::remove_copy(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), result, value); } template <typename C, typename OutputIterator, typename Pred> OutputIterator c_remove_copy_if(const C& c, OutputIterator result, Pred&& pred) { return std::remove_copy_if(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), result, std::forward<Pred>(pred)); } template <typename C, typename OutputIterator> OutputIterator c_unique_copy(const C& c, OutputIterator result) { return std::unique_copy(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), result); } template <typename C, typename OutputIterator, typename BinaryPredicate> OutputIterator c_unique_copy(const C& c, OutputIterator result, BinaryPredicate&& pred) { return std::unique_copy(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), result, std::forward<BinaryPredicate>(pred)); } template <typename Sequence> void c_reverse(Sequence& sequence) { std::reverse(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence)); } template <typename C, typename OutputIterator> OutputIterator c_reverse_copy(const C& sequence, OutputIterator result) { return std::reverse_copy(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), result); } template <typename C, typename Iterator = container_algorithm_internal::ContainerIter<C>> Iterator c_rotate(C& sequence, Iterator middle) { return absl::rotate(container_algorithm_internal::c_begin(sequence), middle, container_algorithm_internal::c_end(sequence)); } template <typename C, typename OutputIterator> OutputIterator c_rotate_copy( const C& sequence, container_algorithm_internal::ContainerIter<const C> middle, OutputIterator result) { return std::rotate_copy(container_algorithm_internal::c_begin(sequence), middle, container_algorithm_internal::c_end(sequence), result); } template <typename RandomAccessContainer, typename UniformRandomBitGenerator> void c_shuffle(RandomAccessContainer& c, UniformRandomBitGenerator&& gen) { std::shuffle(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<UniformRandomBitGenerator>(gen)); } template <typename C, typename OutputIterator, typename Distance, typename UniformRandomBitGenerator> OutputIterator c_sample(const C& c, OutputIterator result, Distance n, UniformRandomBitGenerator&& gen) { #if defined(__cpp_lib_sample) && __cpp_lib_sample >= 201603L return std::sample(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), result, n, std::forward<UniformRandomBitGenerator>(gen)); #else auto first = container_algorithm_internal::c_begin(c); Distance unsampled_elements = c_distance(c); n = (std::min)(n, unsampled_elements); for (; n != 0; ++first) { Distance r = std::uniform_int_distribution<Distance>(0, --unsampled_elements)(gen); if (r < n) { *result++ = *first; --n; } } return result; #endif } template <typename C, typename Pred> bool c_is_partitioned(const C& c, Pred&& pred) { return std::is_partitioned(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Pred>(pred)); } template <typename C, typename Pred> container_algorithm_internal::ContainerIter<C> c_partition(C& c, Pred&& pred) { return std::partition(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Pred>(pred)); } template <typename C, typename Pred> container_algorithm_internal::ContainerIter<C> c_stable_partition(C& c, Pred&& pred) { return std::stable_partition(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Pred>(pred)); } template <typename C, typename OutputIterator1, typename OutputIterator2, typename Pred> std::pair<OutputIterator1, OutputIterator2> c_partition_copy( const C& c, OutputIterator1 out_true, OutputIterator2 out_false, Pred&& pred) { return std::partition_copy(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), out_true, out_false, std::forward<Pred>(pred)); } template <typename C, typename Pred> container_algorithm_internal::ContainerIter<C> c_partition_point(C& c, Pred&& pred) { return std::partition_point(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<Pred>(pred)); } template <typename C> void c_sort(C& c) { std::sort(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c)); } template <typename C, typename LessThan> void c_sort(C& c, LessThan&& comp) { std::sort(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<LessThan>(comp)); } template <typename C> void c_stable_sort(C& c) { std::stable_sort(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c)); } template <typename C, typename LessThan> void c_stable_sort(C& c, LessThan&& comp) { std::stable_sort(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<LessThan>(comp)); } template <typename C> bool c_is_sorted(const C& c) { return std::is_sorted(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c)); } template <typename C, typename LessThan> bool c_is_sorted(const C& c, LessThan&& comp) { return std::is_sorted(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<LessThan>(comp)); } template <typename RandomAccessContainer> void c_partial_sort( RandomAccessContainer& sequence, container_algorithm_internal::ContainerIter<RandomAccessContainer> middle) { std::partial_sort(container_algorithm_internal::c_begin(sequence), middle, container_algorithm_internal::c_end(sequence)); } template <typename RandomAccessContainer, typename LessThan> void c_partial_sort( RandomAccessContainer& sequence, container_algorithm_internal::ContainerIter<RandomAccessContainer> middle, LessThan&& comp) { std::partial_sort(container_algorithm_internal::c_begin(sequence), middle, container_algorithm_internal::c_end(sequence), std::forward<LessThan>(comp)); } template <typename C, typename RandomAccessContainer> container_algorithm_internal::ContainerIter<RandomAccessContainer> c_partial_sort_copy(const C& sequence, RandomAccessContainer& result) { return std::partial_sort_copy(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), container_algorithm_internal::c_begin(result), container_algorithm_internal::c_end(result)); } template <typename C, typename RandomAccessContainer, typename LessThan> container_algorithm_internal::ContainerIter<RandomAccessContainer> c_partial_sort_copy(const C& sequence, RandomAccessContainer& result, LessThan&& comp) { return std::partial_sort_copy(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), container_algorithm_internal::c_begin(result), container_algorithm_internal::c_end(result), std::forward<LessThan>(comp)); } template <typename C> container_algorithm_internal::ContainerIter<C> c_is_sorted_until(C& c) { return std::is_sorted_until(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c)); } template <typename C, typename LessThan> container_algorithm_internal::ContainerIter<C> c_is_sorted_until( C& c, LessThan&& comp) { return std::is_sorted_until(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<LessThan>(comp)); } template <typename RandomAccessContainer> void c_nth_element( RandomAccessContainer& sequence, container_algorithm_internal::ContainerIter<RandomAccessContainer> nth) { std::nth_element(container_algorithm_internal::c_begin(sequence), nth, container_algorithm_internal::c_end(sequence)); } template <typename RandomAccessContainer, typename LessThan> void c_nth_element( RandomAccessContainer& sequence, container_algorithm_internal::ContainerIter<RandomAccessContainer> nth, LessThan&& comp) { std::nth_element(container_algorithm_internal::c_begin(sequence), nth, container_algorithm_internal::c_end(sequence), std::forward<LessThan>(comp)); } template <typename Sequence, typename T> container_algorithm_internal::ContainerIter<Sequence> c_lower_bound( Sequence& sequence, const T& value) { return std::lower_bound(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), value); } template <typename Sequence, typename T, typename LessThan> container_algorithm_internal::ContainerIter<Sequence> c_lower_bound( Sequence& sequence, const T& value, LessThan&& comp) { return std::lower_bound(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), value, std::forward<LessThan>(comp)); } template <typename Sequence, typename T> container_algorithm_internal::ContainerIter<Sequence> c_upper_bound( Sequence& sequence, const T& value) { return std::upper_bound(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), value); } template <typename Sequence, typename T, typename LessThan> container_algorithm_internal::ContainerIter<Sequence> c_upper_bound( Sequence& sequence, const T& value, LessThan&& comp) { return std::upper_bound(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), value, std::forward<LessThan>(comp)); } template <typename Sequence, typename T> container_algorithm_internal::ContainerIterPairType<Sequence, Sequence> c_equal_range(Sequence& sequence, const T& value) { return std::equal_range(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), value); } template <typename Sequence, typename T, typename LessThan> container_algorithm_internal::ContainerIterPairType<Sequence, Sequence> c_equal_range(Sequence& sequence, const T& value, LessThan&& comp) { return std::equal_range(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), value, std::forward<LessThan>(comp)); } template <typename Sequence, typename T> bool c_binary_search(const Sequence& sequence, const T& value) { return std::binary_search(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), value); } template <typename Sequence, typename T, typename LessThan> bool c_binary_search(const Sequence& sequence, const T& value, LessThan&& comp) { return std::binary_search(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), value, std::forward<LessThan>(comp)); } template <typename C1, typename C2, typename OutputIterator> OutputIterator c_merge(const C1& c1, const C2& c2, OutputIterator result) { return std::merge(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), result); } template <typename C1, typename C2, typename OutputIterator, typename LessThan> OutputIterator c_merge(const C1& c1, const C2& c2, OutputIterator result, LessThan&& comp) { return std::merge(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), result, std::forward<LessThan>(comp)); } template <typename C> void c_inplace_merge(C& c, container_algorithm_internal::ContainerIter<C> middle) { std::inplace_merge(container_algorithm_internal::c_begin(c), middle, container_algorithm_internal::c_end(c)); } template <typename C, typename LessThan> void c_inplace_merge(C& c, container_algorithm_internal::ContainerIter<C> middle, LessThan&& comp) { std::inplace_merge(container_algorithm_internal::c_begin(c), middle, container_algorithm_internal::c_end(c), std::forward<LessThan>(comp)); } template <typename C1, typename C2> bool c_includes(const C1& c1, const C2& c2) { return std::includes(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2)); } template <typename C1, typename C2, typename LessThan> bool c_includes(const C1& c1, const C2& c2, LessThan&& comp) { return std::includes(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), std::forward<LessThan>(comp)); } template <typename C1, typename C2, typename OutputIterator, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C1>::value, void>::type, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C2>::value, void>::type> OutputIterator c_set_union(const C1& c1, const C2& c2, OutputIterator output) { return std::set_union(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), output); } template <typename C1, typename C2, typename OutputIterator, typename LessThan, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C1>::value, void>::type, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C2>::value, void>::type> OutputIterator c_set_union(const C1& c1, const C2& c2, OutputIterator output, LessThan&& comp) { return std::set_union(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), output, std::forward<LessThan>(comp)); } template <typename C1, typename C2, typename OutputIterator, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C1>::value, void>::type, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C2>::value, void>::type> OutputIterator c_set_intersection(const C1& c1, const C2& c2, OutputIterator output) { assert(absl::c_is_sorted(c1)); assert(absl::c_is_sorted(c2)); return std::set_intersection(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), output); } template <typename C1, typename C2, typename OutputIterator, typename LessThan, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C1>::value, void>::type, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C2>::value, void>::type> OutputIterator c_set_intersection(const C1& c1, const C2& c2, OutputIterator output, LessThan&& comp) { assert(absl::c_is_sorted(c1, comp)); assert(absl::c_is_sorted(c2, comp)); return std::set_intersection(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), output, std::forward<LessThan>(comp)); } template <typename C1, typename C2, typename OutputIterator, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C1>::value, void>::type, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C2>::value, void>::type> OutputIterator c_set_difference(const C1& c1, const C2& c2, OutputIterator output) { return std::set_difference(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), output); } template <typename C1, typename C2, typename OutputIterator, typename LessThan, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C1>::value, void>::type, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C2>::value, void>::type> OutputIterator c_set_difference(const C1& c1, const C2& c2, OutputIterator output, LessThan&& comp) { return std::set_difference(container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), output, std::forward<LessThan>(comp)); } template <typename C1, typename C2, typename OutputIterator, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C1>::value, void>::type, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C2>::value, void>::type> OutputIterator c_set_symmetric_difference(const C1& c1, const C2& c2, OutputIterator output) { return std::set_symmetric_difference( container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), output); } template <typename C1, typename C2, typename OutputIterator, typename LessThan, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C1>::value, void>::type, typename = typename std::enable_if< !container_algorithm_internal::IsUnorderedContainer<C2>::value, void>::type> OutputIterator c_set_symmetric_difference(const C1& c1, const C2& c2, OutputIterator output, LessThan&& comp) { return std::set_symmetric_difference( container_algorithm_internal::c_begin(c1), container_algorithm_internal::c_end(c1), container_algorithm_internal::c_begin(c2), container_algorithm_internal::c_end(c2), output, std::forward<LessThan>(comp)); } template <typename RandomAccessContainer> void c_push_heap(RandomAccessContainer& sequence) { std::push_heap(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence)); } template <typename RandomAccessContainer, typename LessThan> void c_push_heap(RandomAccessContainer& sequence, LessThan&& comp) { std::push_heap(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), std::forward<LessThan>(comp)); } template <typename RandomAccessContainer> void c_pop_heap(RandomAccessContainer& sequence) { std::pop_heap(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence)); } template <typename RandomAccessContainer, typename LessThan> void c_pop_heap(RandomAccessContainer& sequence, LessThan&& comp) { std::pop_heap(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), std::forward<LessThan>(comp)); } template <typename RandomAccessContainer> void c_make_heap(RandomAccessContainer& sequence) { std::make_heap(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence)); } template <typename RandomAccessContainer, typename LessThan> void c_make_heap(RandomAccessContainer& sequence, LessThan&& comp) { std::make_heap(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), std::forward<LessThan>(comp)); } template <typename RandomAccessContainer> void c_sort_heap(RandomAccessContainer& sequence) { std::sort_heap(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence)); } template <typename RandomAccessContainer, typename LessThan> void c_sort_heap(RandomAccessContainer& sequence, LessThan&& comp) { std::sort_heap(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), std::forward<LessThan>(comp)); } template <typename RandomAccessContainer> bool c_is_heap(const RandomAccessContainer& sequence) { return std::is_heap(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence)); } template <typename RandomAccessContainer, typename LessThan> bool c_is_heap(const RandomAccessContainer& sequence, LessThan&& comp) { return std::is_heap(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), std::forward<LessThan>(comp)); } template <typename RandomAccessContainer> container_algorithm_internal::ContainerIter<RandomAccessContainer> c_is_heap_until(RandomAccessContainer& sequence) { return std::is_heap_until(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence)); } template <typename RandomAccessContainer, typename LessThan> container_algorithm_internal::ContainerIter<RandomAccessContainer> c_is_heap_until(RandomAccessContainer& sequence, LessThan&& comp) { return std::is_heap_until(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), std::forward<LessThan>(comp)); } template <typename Sequence> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX17 container_algorithm_internal::ContainerIter<Sequence> c_min_element(Sequence& sequence) { return std::min_element(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence)); } template <typename Sequence, typename LessThan> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX17 container_algorithm_internal::ContainerIter<Sequence> c_min_element(Sequence& sequence, LessThan&& comp) { return std::min_element(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), std::forward<LessThan>(comp)); } template <typename Sequence> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX17 container_algorithm_internal::ContainerIter<Sequence> c_max_element(Sequence& sequence) { return std::max_element(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence)); } template <typename Sequence, typename LessThan> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX17 container_algorithm_internal::ContainerIter<Sequence> c_max_element(Sequence& sequence, LessThan&& comp) { return std::max_element(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), std::forward<LessThan>(comp)); } template <typename C> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX17 container_algorithm_internal::ContainerIterPairType<C, C> c_minmax_element(C& c) { return std::minmax_element(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c)); } template <typename C, typename LessThan> ABSL_INTERNAL_CONSTEXPR_SINCE_CXX17 container_algorithm_internal::ContainerIterPairType<C, C> c_minmax_element(C& c, LessThan&& comp) { return std::minmax_element(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<LessThan>(comp)); } template <typename Sequence1, typename Sequence2> bool c_lexicographical_compare(const Sequence1& sequence1, const Sequence2& sequence2) { return std::lexicographical_compare( container_algorithm_internal::c_begin(sequence1), container_algorithm_internal::c_end(sequence1), container_algorithm_internal::c_begin(sequence2), container_algorithm_internal::c_end(sequence2)); } template <typename Sequence1, typename Sequence2, typename LessThan> bool c_lexicographical_compare(const Sequence1& sequence1, const Sequence2& sequence2, LessThan&& comp) { return std::lexicographical_compare( container_algorithm_internal::c_begin(sequence1), container_algorithm_internal::c_end(sequence1), container_algorithm_internal::c_begin(sequence2), container_algorithm_internal::c_end(sequence2), std::forward<LessThan>(comp)); } template <typename C> bool c_next_permutation(C& c) { return std::next_permutation(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c)); } template <typename C, typename LessThan> bool c_next_permutation(C& c, LessThan&& comp) { return std::next_permutation(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<LessThan>(comp)); } template <typename C> bool c_prev_permutation(C& c) { return std::prev_permutation(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c)); } template <typename C, typename LessThan> bool c_prev_permutation(C& c, LessThan&& comp) { return std::prev_permutation(container_algorithm_internal::c_begin(c), container_algorithm_internal::c_end(c), std::forward<LessThan>(comp)); } template <typename Sequence, typename T> void c_iota(Sequence& sequence, const T& value) { std::iota(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), value); } template <typename Sequence, typename T> decay_t<T> c_accumulate(const Sequence& sequence, T&& init) { return std::accumulate(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), std::forward<T>(init)); } template <typename Sequence, typename T, typename BinaryOp> decay_t<T> c_accumulate(const Sequence& sequence, T&& init, BinaryOp&& binary_op) { return std::accumulate(container_algorithm_internal::c_begin(sequence), container_algorithm_internal::c_end(sequence), std::forward<T>(init), std::forward<BinaryOp>(binary_op)); } template <typename Sequence1, typename Sequence2, typename T> decay_t<T> c_inner_product(const Sequence1& factors1, const Sequence2& factors2, T&& sum) { return std::inner_product(container_algorithm_internal::c_begin(factors1), container_algorithm_internal::c_end(factors1), container_algorithm_internal::c_begin(factors2), std::forward<T>(sum)); } template <typename Sequence1, typename Sequence2, typename T, typename BinaryOp1, typename BinaryOp2> decay_t<T> c_inner_product(const Sequence1& factors1, const Sequence2& factors2, T&& sum, BinaryOp1&& op1, BinaryOp2&& op2) { return std::inner_product(container_algorithm_internal::c_begin(factors1), container_algorithm_internal::c_end(factors1), container_algorithm_internal::c_begin(factors2), std::forward<T>(sum), std::forward<BinaryOp1>(op1), std::forward<BinaryOp2>(op2)); } template <typename InputSequence, typename OutputIt> OutputIt c_adjacent_difference(const InputSequence& input, OutputIt output_first) { return std::adjacent_difference(container_algorithm_internal::c_begin(input), container_algorithm_internal::c_end(input), output_first); } template <typename InputSequence, typename OutputIt, typename BinaryOp> OutputIt c_adjacent_difference(const InputSequence& input, OutputIt output_first, BinaryOp&& op) { return std::adjacent_difference(container_algorithm_internal::c_begin(input), container_algorithm_internal::c_end(input), output_first, std::forward<BinaryOp>(op)); } template <typename InputSequence, typename OutputIt> OutputIt c_partial_sum(const InputSequence& input, OutputIt output_first) { return std::partial_sum(container_algorithm_internal::c_begin(input), container_algorithm_internal::c_end(input), output_first); } template <typename InputSequence, typename OutputIt, typename BinaryOp> OutputIt c_partial_sum(const InputSequence& input, OutputIt output_first, BinaryOp&& op) { return std::partial_sum(container_algorithm_internal::c_begin(input), container_algorithm_internal::c_end(input), output_first, std::forward<BinaryOp>(op)); } ABSL_NAMESPACE_END } #endif
#include "absl/algorithm/container.h" #include <algorithm> #include <array> #include <functional> #include <initializer_list> #include <iterator> #include <list> #include <memory> #include <ostream> #include <random> #include <set> #include <unordered_set> #include <utility> #include <valarray> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/casts.h" #include "absl/base/config.h" #include "absl/base/macros.h" #include "absl/memory/memory.h" #include "absl/types/span.h" namespace { using ::testing::Each; using ::testing::ElementsAre; using ::testing::Gt; using ::testing::IsNull; using ::testing::IsSubsetOf; using ::testing::Lt; using ::testing::Pointee; using ::testing::SizeIs; using ::testing::Truly; using ::testing::UnorderedElementsAre; class NonMutatingTest : public testing::Test { protected: std::unordered_set<int> container_ = {1, 2, 3}; std::list<int> sequence_ = {1, 2, 3}; std::vector<int> vector_ = {1, 2, 3}; int array_[3] = {1, 2, 3}; }; struct AccumulateCalls { void operator()(int value) { calls.push_back(value); } std::vector<int> calls; }; bool Predicate(int value) { return value < 3; } bool BinPredicate(int v1, int v2) { return v1 < v2; } bool Equals(int v1, int v2) { return v1 == v2; } bool IsOdd(int x) { return x % 2 != 0; } TEST_F(NonMutatingTest, Distance) { EXPECT_EQ(container_.size(), static_cast<size_t>(absl::c_distance(container_))); EXPECT_EQ(sequence_.size(), static_cast<size_t>(absl::c_distance(sequence_))); EXPECT_EQ(vector_.size(), static_cast<size_t>(absl::c_distance(vector_))); EXPECT_EQ(ABSL_ARRAYSIZE(array_), static_cast<size_t>(absl::c_distance(array_))); EXPECT_EQ(vector_.size(), static_cast<size_t>(absl::c_distance(std::vector<int>(vector_)))); } TEST_F(NonMutatingTest, Distance_OverloadedBeginEnd) { std::initializer_list<int> a = {1, 2, 3}; std::valarray<int> b = {1, 2, 3}; EXPECT_EQ(3, absl::c_distance(a)); EXPECT_EQ(3, absl::c_distance(b)); } TEST_F(NonMutatingTest, ForEach) { AccumulateCalls c = absl::c_for_each(container_, AccumulateCalls()); std::sort(c.calls.begin(), c.calls.end()); EXPECT_EQ(vector_, c.calls); AccumulateCalls c2 = absl::c_for_each(std::unordered_set<int>(container_), AccumulateCalls()); std::sort(c2.calls.begin(), c2.calls.end()); EXPECT_EQ(vector_, c2.calls); } TEST_F(NonMutatingTest, FindReturnsCorrectType) { auto it = absl::c_find(container_, 3); EXPECT_EQ(3, *it); absl::c_find(absl::implicit_cast<const std::list<int>&>(sequence_), 3); } TEST_F(NonMutatingTest, Contains) { EXPECT_TRUE(absl::c_contains(container_, 3)); EXPECT_FALSE(absl::c_contains(container_, 4)); } TEST_F(NonMutatingTest, FindIf) { absl::c_find_if(container_, Predicate); } TEST_F(NonMutatingTest, FindIfNot) { absl::c_find_if_not(container_, Predicate); } TEST_F(NonMutatingTest, FindEnd) { absl::c_find_end(sequence_, vector_); absl::c_find_end(vector_, sequence_); } TEST_F(NonMutatingTest, FindEndWithPredicate) { absl::c_find_end(sequence_, vector_, BinPredicate); absl::c_find_end(vector_, sequence_, BinPredicate); } TEST_F(NonMutatingTest, FindFirstOf) { absl::c_find_first_of(container_, sequence_); absl::c_find_first_of(sequence_, container_); } TEST_F(NonMutatingTest, FindFirstOfWithPredicate) { absl::c_find_first_of(container_, sequence_, BinPredicate); absl::c_find_first_of(sequence_, container_, BinPredicate); } TEST_F(NonMutatingTest, AdjacentFind) { absl::c_adjacent_find(sequence_); } TEST_F(NonMutatingTest, AdjacentFindWithPredicate) { absl::c_adjacent_find(sequence_, BinPredicate); } TEST_F(NonMutatingTest, Count) { EXPECT_EQ(1, absl::c_count(container_, 3)); } TEST_F(NonMutatingTest, CountIf) { EXPECT_EQ(2, absl::c_count_if(container_, Predicate)); const std::unordered_set<int>& const_container = container_; EXPECT_EQ(2, absl::c_count_if(const_container, Predicate)); } TEST_F(NonMutatingTest, Mismatch) { { auto result = absl::c_mismatch(vector_, sequence_); EXPECT_EQ(result.first, vector_.end()); EXPECT_EQ(result.second, sequence_.end()); } { auto result = absl::c_mismatch(sequence_, vector_); EXPECT_EQ(result.first, sequence_.end()); EXPECT_EQ(result.second, vector_.end()); } sequence_.back() = 5; { auto result = absl::c_mismatch(vector_, sequence_); EXPECT_EQ(result.first, std::prev(vector_.end())); EXPECT_EQ(result.second, std::prev(sequence_.end())); } { auto result = absl::c_mismatch(sequence_, vector_); EXPECT_EQ(result.first, std::prev(sequence_.end())); EXPECT_EQ(result.second, std::prev(vector_.end())); } sequence_.pop_back(); { auto result = absl::c_mismatch(vector_, sequence_); EXPECT_EQ(result.first, std::prev(vector_.end())); EXPECT_EQ(result.second, sequence_.end()); } { auto result = absl::c_mismatch(sequence_, vector_); EXPECT_EQ(result.first, sequence_.end()); EXPECT_EQ(result.second, std::prev(vector_.end())); } { struct NoNotEquals { constexpr bool operator==(NoNotEquals) const { return true; } constexpr bool operator!=(NoNotEquals) const = delete; }; std::vector<NoNotEquals> first; std::list<NoNotEquals> second; absl::c_mismatch(first, second); } } TEST_F(NonMutatingTest, MismatchWithPredicate) { { auto result = absl::c_mismatch(vector_, sequence_, BinPredicate); EXPECT_EQ(result.first, vector_.begin()); EXPECT_EQ(result.second, sequence_.begin()); } { auto result = absl::c_mismatch(sequence_, vector_, BinPredicate); EXPECT_EQ(result.first, sequence_.begin()); EXPECT_EQ(result.second, vector_.begin()); } sequence_.front() = 0; { auto result = absl::c_mismatch(vector_, sequence_, BinPredicate); EXPECT_EQ(result.first, vector_.begin()); EXPECT_EQ(result.second, sequence_.begin()); } { auto result = absl::c_mismatch(sequence_, vector_, BinPredicate); EXPECT_EQ(result.first, std::next(sequence_.begin())); EXPECT_EQ(result.second, std::next(vector_.begin())); } sequence_.clear(); { auto result = absl::c_mismatch(vector_, sequence_, BinPredicate); EXPECT_EQ(result.first, vector_.begin()); EXPECT_EQ(result.second, sequence_.end()); } { auto result = absl::c_mismatch(sequence_, vector_, BinPredicate); EXPECT_EQ(result.first, sequence_.end()); EXPECT_EQ(result.second, vector_.begin()); } } TEST_F(NonMutatingTest, Equal) { EXPECT_TRUE(absl::c_equal(vector_, sequence_)); EXPECT_TRUE(absl::c_equal(sequence_, vector_)); EXPECT_TRUE(absl::c_equal(sequence_, array_)); EXPECT_TRUE(absl::c_equal(array_, vector_)); std::vector<int> vector_plus = {1, 2, 3}; vector_plus.push_back(4); EXPECT_FALSE(absl::c_equal(vector_plus, sequence_)); EXPECT_FALSE(absl::c_equal(sequence_, vector_plus)); EXPECT_FALSE(absl::c_equal(array_, vector_plus)); } TEST_F(NonMutatingTest, EqualWithPredicate) { EXPECT_TRUE(absl::c_equal(vector_, sequence_, Equals)); EXPECT_TRUE(absl::c_equal(sequence_, vector_, Equals)); EXPECT_TRUE(absl::c_equal(array_, sequence_, Equals)); EXPECT_TRUE(absl::c_equal(vector_, array_, Equals)); std::vector<int> vector_plus = {1, 2, 3}; vector_plus.push_back(4); EXPECT_FALSE(absl::c_equal(vector_plus, sequence_, Equals)); EXPECT_FALSE(absl::c_equal(sequence_, vector_plus, Equals)); EXPECT_FALSE(absl::c_equal(vector_plus, array_, Equals)); } TEST_F(NonMutatingTest, IsPermutation) { auto vector_permut_ = vector_; std::next_permutation(vector_permut_.begin(), vector_permut_.end()); EXPECT_TRUE(absl::c_is_permutation(vector_permut_, sequence_)); EXPECT_TRUE(absl::c_is_permutation(sequence_, vector_permut_)); std::vector<int> vector_plus = {1, 2, 3}; vector_plus.push_back(4); EXPECT_FALSE(absl::c_is_permutation(vector_plus, sequence_)); EXPECT_FALSE(absl::c_is_permutation(sequence_, vector_plus)); } TEST_F(NonMutatingTest, IsPermutationWithPredicate) { auto vector_permut_ = vector_; std::next_permutation(vector_permut_.begin(), vector_permut_.end()); EXPECT_TRUE(absl::c_is_permutation(vector_permut_, sequence_, Equals)); EXPECT_TRUE(absl::c_is_permutation(sequence_, vector_permut_, Equals)); std::vector<int> vector_plus = {1, 2, 3}; vector_plus.push_back(4); EXPECT_FALSE(absl::c_is_permutation(vector_plus, sequence_, Equals)); EXPECT_FALSE(absl::c_is_permutation(sequence_, vector_plus, Equals)); } TEST_F(NonMutatingTest, Search) { absl::c_search(sequence_, vector_); absl::c_search(vector_, sequence_); absl::c_search(array_, sequence_); } TEST_F(NonMutatingTest, SearchWithPredicate) { absl::c_search(sequence_, vector_, BinPredicate); absl::c_search(vector_, sequence_, BinPredicate); } TEST_F(NonMutatingTest, ContainsSubrange) { EXPECT_TRUE(absl::c_contains_subrange(sequence_, vector_)); EXPECT_TRUE(absl::c_contains_subrange(vector_, sequence_)); EXPECT_TRUE(absl::c_contains_subrange(array_, sequence_)); } TEST_F(NonMutatingTest, ContainsSubrangeWithPredicate) { EXPECT_TRUE(absl::c_contains_subrange(sequence_, vector_, Equals)); EXPECT_TRUE(absl::c_contains_subrange(vector_, sequence_, Equals)); } TEST_F(NonMutatingTest, SearchN) { absl::c_search_n(sequence_, 3, 1); } TEST_F(NonMutatingTest, SearchNWithPredicate) { absl::c_search_n(sequence_, 3, 1, BinPredicate); } TEST_F(NonMutatingTest, LowerBound) { std::list<int>::iterator i = absl::c_lower_bound(sequence_, 3); ASSERT_TRUE(i != sequence_.end()); EXPECT_EQ(2, std::distance(sequence_.begin(), i)); EXPECT_EQ(3, *i); } TEST_F(NonMutatingTest, LowerBoundWithPredicate) { std::vector<int> v(vector_); std::sort(v.begin(), v.end(), std::greater<int>()); std::vector<int>::iterator i = absl::c_lower_bound(v, 3, std::greater<int>()); EXPECT_TRUE(i == v.begin()); EXPECT_EQ(3, *i); } TEST_F(NonMutatingTest, UpperBound) { std::list<int>::iterator i = absl::c_upper_bound(sequence_, 1); ASSERT_TRUE(i != sequence_.end()); EXPECT_EQ(1, std::distance(sequence_.begin(), i)); EXPECT_EQ(2, *i); } TEST_F(NonMutatingTest, UpperBoundWithPredicate) { std::vector<int> v(vector_); std::sort(v.begin(), v.end(), std::greater<int>()); std::vector<int>::iterator i = absl::c_upper_bound(v, 1, std::greater<int>()); EXPECT_EQ(3, i - v.begin()); EXPECT_TRUE(i == v.end()); } TEST_F(NonMutatingTest, EqualRange) { std::pair<std::list<int>::iterator, std::list<int>::iterator> p = absl::c_equal_range(sequence_, 2); EXPECT_EQ(1, std::distance(sequence_.begin(), p.first)); EXPECT_EQ(2, std::distance(sequence_.begin(), p.second)); } TEST_F(NonMutatingTest, EqualRangeArray) { auto p = absl::c_equal_range(array_, 2); EXPECT_EQ(1, std::distance(std::begin(array_), p.first)); EXPECT_EQ(2, std::distance(std::begin(array_), p.second)); } TEST_F(NonMutatingTest, EqualRangeWithPredicate) { std::vector<int> v(vector_); std::sort(v.begin(), v.end(), std::greater<int>()); std::pair<std::vector<int>::iterator, std::vector<int>::iterator> p = absl::c_equal_range(v, 2, std::greater<int>()); EXPECT_EQ(1, std::distance(v.begin(), p.first)); EXPECT_EQ(2, std::distance(v.begin(), p.second)); } TEST_F(NonMutatingTest, BinarySearch) { EXPECT_TRUE(absl::c_binary_search(vector_, 2)); EXPECT_TRUE(absl::c_binary_search(std::vector<int>(vector_), 2)); } TEST_F(NonMutatingTest, BinarySearchWithPredicate) { std::vector<int> v(vector_); std::sort(v.begin(), v.end(), std::greater<int>()); EXPECT_TRUE(absl::c_binary_search(v, 2, std::greater<int>())); EXPECT_TRUE( absl::c_binary_search(std::vector<int>(v), 2, std::greater<int>())); } TEST_F(NonMutatingTest, MinElement) { std::list<int>::iterator i = absl::c_min_element(sequence_); ASSERT_TRUE(i != sequence_.end()); EXPECT_EQ(*i, 1); } TEST_F(NonMutatingTest, MinElementWithPredicate) { std::list<int>::iterator i = absl::c_min_element(sequence_, std::greater<int>()); ASSERT_TRUE(i != sequence_.end()); EXPECT_EQ(*i, 3); } TEST_F(NonMutatingTest, MaxElement) { std::list<int>::iterator i = absl::c_max_element(sequence_); ASSERT_TRUE(i != sequence_.end()); EXPECT_EQ(*i, 3); } TEST_F(NonMutatingTest, MaxElementWithPredicate) { std::list<int>::iterator i = absl::c_max_element(sequence_, std::greater<int>()); ASSERT_TRUE(i != sequence_.end()); EXPECT_EQ(*i, 1); } TEST_F(NonMutatingTest, LexicographicalCompare) { EXPECT_FALSE(absl::c_lexicographical_compare(sequence_, sequence_)); std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(4); EXPECT_TRUE(absl::c_lexicographical_compare(sequence_, v)); EXPECT_TRUE(absl::c_lexicographical_compare(std::list<int>(sequence_), v)); } TEST_F(NonMutatingTest, LexicographicalCopmareWithPredicate) { EXPECT_FALSE(absl::c_lexicographical_compare(sequence_, sequence_, std::greater<int>())); std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(4); EXPECT_TRUE( absl::c_lexicographical_compare(v, sequence_, std::greater<int>())); EXPECT_TRUE(absl::c_lexicographical_compare( std::vector<int>(v), std::list<int>(sequence_), std::greater<int>())); } TEST_F(NonMutatingTest, Includes) { std::set<int> s(vector_.begin(), vector_.end()); s.insert(4); EXPECT_TRUE(absl::c_includes(s, vector_)); } TEST_F(NonMutatingTest, IncludesWithPredicate) { std::vector<int> v = {3, 2, 1}; std::set<int, std::greater<int>> s(v.begin(), v.end()); s.insert(4); EXPECT_TRUE(absl::c_includes(s, v, std::greater<int>())); } class NumericMutatingTest : public testing::Test { protected: std::list<int> list_ = {1, 2, 3}; std::vector<int> output_; }; TEST_F(NumericMutatingTest, Iota) { absl::c_iota(list_, 5); std::list<int> expected{5, 6, 7}; EXPECT_EQ(list_, expected); } TEST_F(NonMutatingTest, Accumulate) { EXPECT_EQ(absl::c_accumulate(sequence_, 4), 1 + 2 + 3 + 4); } TEST_F(NonMutatingTest, AccumulateWithBinaryOp) { EXPECT_EQ(absl::c_accumulate(sequence_, 4, std::multiplies<int>()), 1 * 2 * 3 * 4); } TEST_F(NonMutatingTest, AccumulateLvalueInit) { int lvalue = 4; EXPECT_EQ(absl::c_accumulate(sequence_, lvalue), 1 + 2 + 3 + 4); } TEST_F(NonMutatingTest, AccumulateWithBinaryOpLvalueInit) { int lvalue = 4; EXPECT_EQ(absl::c_accumulate(sequence_, lvalue, std::multiplies<int>()), 1 * 2 * 3 * 4); } TEST_F(NonMutatingTest, InnerProduct) { EXPECT_EQ(absl::c_inner_product(sequence_, vector_, 1000), 1000 + 1 * 1 + 2 * 2 + 3 * 3); } TEST_F(NonMutatingTest, InnerProductWithBinaryOps) { EXPECT_EQ(absl::c_inner_product(sequence_, vector_, 10, std::multiplies<int>(), std::plus<int>()), 10 * (1 + 1) * (2 + 2) * (3 + 3)); } TEST_F(NonMutatingTest, InnerProductLvalueInit) { int lvalue = 1000; EXPECT_EQ(absl::c_inner_product(sequence_, vector_, lvalue), 1000 + 1 * 1 + 2 * 2 + 3 * 3); } TEST_F(NonMutatingTest, InnerProductWithBinaryOpsLvalueInit) { int lvalue = 10; EXPECT_EQ(absl::c_inner_product(sequence_, vector_, lvalue, std::multiplies<int>(), std::plus<int>()), 10 * (1 + 1) * (2 + 2) * (3 + 3)); } TEST_F(NumericMutatingTest, AdjacentDifference) { auto last = absl::c_adjacent_difference(list_, std::back_inserter(output_)); *last = 1000; std::vector<int> expected{1, 2 - 1, 3 - 2, 1000}; EXPECT_EQ(output_, expected); } TEST_F(NumericMutatingTest, AdjacentDifferenceWithBinaryOp) { auto last = absl::c_adjacent_difference(list_, std::back_inserter(output_), std::multiplies<int>()); *last = 1000; std::vector<int> expected{1, 2 * 1, 3 * 2, 1000}; EXPECT_EQ(output_, expected); } TEST_F(NumericMutatingTest, PartialSum) { auto last = absl::c_partial_sum(list_, std::back_inserter(output_)); *last = 1000; std::vector<int> expected{1, 1 + 2, 1 + 2 + 3, 1000}; EXPECT_EQ(output_, expected); } TEST_F(NumericMutatingTest, PartialSumWithBinaryOp) { auto last = absl::c_partial_sum(list_, std::back_inserter(output_), std::multiplies<int>()); *last = 1000; std::vector<int> expected{1, 1 * 2, 1 * 2 * 3, 1000}; EXPECT_EQ(output_, expected); } TEST_F(NonMutatingTest, LinearSearch) { EXPECT_TRUE(absl::c_linear_search(container_, 3)); EXPECT_FALSE(absl::c_linear_search(container_, 4)); } TEST_F(NonMutatingTest, AllOf) { const std::vector<int>& v = vector_; EXPECT_FALSE(absl::c_all_of(v, [](int x) { return x > 1; })); EXPECT_TRUE(absl::c_all_of(v, [](int x) { return x > 0; })); } TEST_F(NonMutatingTest, AnyOf) { const std::vector<int>& v = vector_; EXPECT_TRUE(absl::c_any_of(v, [](int x) { return x > 2; })); EXPECT_FALSE(absl::c_any_of(v, [](int x) { return x > 5; })); } TEST_F(NonMutatingTest, NoneOf) { const std::vector<int>& v = vector_; EXPECT_FALSE(absl::c_none_of(v, [](int x) { return x > 2; })); EXPECT_TRUE(absl::c_none_of(v, [](int x) { return x > 5; })); } TEST_F(NonMutatingTest, MinMaxElementLess) { std::pair<std::vector<int>::const_iterator, std::vector<int>::const_iterator> p = absl::c_minmax_element(vector_, std::less<int>()); EXPECT_TRUE(p.first == vector_.begin()); EXPECT_TRUE(p.second == vector_.begin() + 2); } TEST_F(NonMutatingTest, MinMaxElementGreater) { std::pair<std::vector<int>::const_iterator, std::vector<int>::const_iterator> p = absl::c_minmax_element(vector_, std::greater<int>()); EXPECT_TRUE(p.first == vector_.begin() + 2); EXPECT_TRUE(p.second == vector_.begin()); } TEST_F(NonMutatingTest, MinMaxElementNoPredicate) { std::pair<std::vector<int>::const_iterator, std::vector<int>::const_iterator> p = absl::c_minmax_element(vector_); EXPECT_TRUE(p.first == vector_.begin()); EXPECT_TRUE(p.second == vector_.begin() + 2); } class SortingTest : public testing::Test { protected: std::list<int> sorted_ = {1, 2, 3, 4}; std::list<int> unsorted_ = {2, 4, 1, 3}; std::list<int> reversed_ = {4, 3, 2, 1}; }; TEST_F(SortingTest, IsSorted) { EXPECT_TRUE(absl::c_is_sorted(sorted_)); EXPECT_FALSE(absl::c_is_sorted(unsorted_)); EXPECT_FALSE(absl::c_is_sorted(reversed_)); } TEST_F(SortingTest, IsSortedWithPredicate) { EXPECT_FALSE(absl::c_is_sorted(sorted_, std::greater<int>())); EXPECT_FALSE(absl::c_is_sorted(unsorted_, std::greater<int>())); EXPECT_TRUE(absl::c_is_sorted(reversed_, std::greater<int>())); } TEST_F(SortingTest, IsSortedUntil) { EXPECT_EQ(1, *absl::c_is_sorted_until(unsorted_)); EXPECT_EQ(4, *absl::c_is_sorted_until(unsorted_, std::greater<int>())); } TEST_F(SortingTest, NthElement) { std::vector<int> unsorted = {2, 4, 1, 3}; absl::c_nth_element(unsorted, unsorted.begin() + 2); EXPECT_THAT(unsorted, ElementsAre(Lt(3), Lt(3), 3, Gt(3))); absl::c_nth_element(unsorted, unsorted.begin() + 2, std::greater<int>()); EXPECT_THAT(unsorted, ElementsAre(Gt(2), Gt(2), 2, Lt(2))); } TEST(MutatingTest, IsPartitioned) { EXPECT_TRUE( absl::c_is_partitioned(std::vector<int>{1, 3, 5, 2, 4, 6}, IsOdd)); EXPECT_FALSE( absl::c_is_partitioned(std::vector<int>{1, 2, 3, 4, 5, 6}, IsOdd)); EXPECT_FALSE( absl::c_is_partitioned(std::vector<int>{2, 4, 6, 1, 3, 5}, IsOdd)); } TEST(MutatingTest, Partition) { std::vector<int> actual = {1, 2, 3, 4, 5}; absl::c_partition(actual, IsOdd); EXPECT_THAT(actual, Truly([](const std::vector<int>& c) { return absl::c_is_partitioned(c, IsOdd); })); } TEST(MutatingTest, StablePartition) { std::vector<int> actual = {1, 2, 3, 4, 5}; absl::c_stable_partition(actual, IsOdd); EXPECT_THAT(actual, ElementsAre(1, 3, 5, 2, 4)); } TEST(MutatingTest, PartitionCopy) { const std::vector<int> initial = {1, 2, 3, 4, 5}; std::vector<int> odds, evens; auto ends = absl::c_partition_copy(initial, back_inserter(odds), back_inserter(evens), IsOdd); *ends.first = 7; *ends.second = 6; EXPECT_THAT(odds, ElementsAre(1, 3, 5, 7)); EXPECT_THAT(evens, ElementsAre(2, 4, 6)); } TEST(MutatingTest, PartitionPoint) { const std::vector<int> initial = {1, 3, 5, 2, 4}; auto middle = absl::c_partition_point(initial, IsOdd); EXPECT_EQ(2, *middle); } TEST(MutatingTest, CopyMiddle) { const std::vector<int> initial = {4, -1, -2, -3, 5}; const std::list<int> input = {1, 2, 3}; const std::vector<int> expected = {4, 1, 2, 3, 5}; std::list<int> test_list(initial.begin(), initial.end()); absl::c_copy(input, ++test_list.begin()); EXPECT_EQ(std::list<int>(expected.begin(), expected.end()), test_list); std::vector<int> test_vector = initial; absl::c_copy(input, test_vector.begin() + 1); EXPECT_EQ(expected, test_vector); } TEST(MutatingTest, CopyFrontInserter) { const std::list<int> initial = {4, 5}; const std::list<int> input = {1, 2, 3}; const std::list<int> expected = {3, 2, 1, 4, 5}; std::list<int> test_list = initial; absl::c_copy(input, std::front_inserter(test_list)); EXPECT_EQ(expected, test_list); } TEST(MutatingTest, CopyBackInserter) { const std::vector<int> initial = {4, 5}; const std::list<int> input = {1, 2, 3}; const std::vector<int> expected = {4, 5, 1, 2, 3}; std::list<int> test_list(initial.begin(), initial.end()); absl::c_copy(input, std::back_inserter(test_list)); EXPECT_EQ(std::list<int>(expected.begin(), expected.end()), test_list); std::vector<int> test_vector = initial; absl::c_copy(input, std::back_inserter(test_vector)); EXPECT_EQ(expected, test_vector); } TEST(MutatingTest, CopyN) { const std::vector<int> initial = {1, 2, 3, 4, 5}; const std::vector<int> expected = {1, 2}; std::vector<int> actual; absl::c_copy_n(initial, 2, back_inserter(actual)); EXPECT_EQ(expected, actual); } TEST(MutatingTest, CopyIf) { const std::list<int> input = {1, 2, 3}; std::vector<int> output; absl::c_copy_if(input, std::back_inserter(output), [](int i) { return i != 2; }); EXPECT_THAT(output, ElementsAre(1, 3)); } TEST(MutatingTest, CopyBackward) { std::vector<int> actual = {1, 2, 3, 4, 5}; std::vector<int> expected = {1, 2, 1, 2, 3}; absl::c_copy_backward(absl::MakeSpan(actual.data(), 3), actual.end()); EXPECT_EQ(expected, actual); } TEST(MutatingTest, Move) { std::vector<std::unique_ptr<int>> src; src.emplace_back(absl::make_unique<int>(1)); src.emplace_back(absl::make_unique<int>(2)); src.emplace_back(absl::make_unique<int>(3)); src.emplace_back(absl::make_unique<int>(4)); src.emplace_back(absl::make_unique<int>(5)); std::vector<std::unique_ptr<int>> dest = {}; absl::c_move(src, std::back_inserter(dest)); EXPECT_THAT(src, Each(IsNull())); EXPECT_THAT(dest, ElementsAre(Pointee(1), Pointee(2), Pointee(3), Pointee(4), Pointee(5))); } TEST(MutatingTest, MoveBackward) { std::vector<std::unique_ptr<int>> actual; actual.emplace_back(absl::make_unique<int>(1)); actual.emplace_back(absl::make_unique<int>(2)); actual.emplace_back(absl::make_unique<int>(3)); actual.emplace_back(absl::make_unique<int>(4)); actual.emplace_back(absl::make_unique<int>(5)); auto subrange = absl::MakeSpan(actual.data(), 3); absl::c_move_backward(subrange, actual.end()); EXPECT_THAT(actual, ElementsAre(IsNull(), IsNull(), Pointee(1), Pointee(2), Pointee(3))); } TEST(MutatingTest, MoveWithRvalue) { auto MakeRValueSrc = [] { std::vector<std::unique_ptr<int>> src; src.emplace_back(absl::make_unique<int>(1)); src.emplace_back(absl::make_unique<int>(2)); src.emplace_back(absl::make_unique<int>(3)); return src; }; std::vector<std::unique_ptr<int>> dest = MakeRValueSrc(); absl::c_move(MakeRValueSrc(), std::back_inserter(dest)); EXPECT_THAT(dest, ElementsAre(Pointee(1), Pointee(2), Pointee(3), Pointee(1), Pointee(2), Pointee(3))); } TEST(MutatingTest, SwapRanges) { std::vector<int> odds = {2, 4, 6}; std::vector<int> evens = {1, 3, 5}; absl::c_swap_ranges(odds, evens); EXPECT_THAT(odds, ElementsAre(1, 3, 5)); EXPECT_THAT(evens, ElementsAre(2, 4, 6)); odds.pop_back(); absl::c_swap_ranges(odds, evens); EXPECT_THAT(odds, ElementsAre(2, 4)); EXPECT_THAT(evens, ElementsAre(1, 3, 6)); absl::c_swap_ranges(evens, odds); EXPECT_THAT(odds, ElementsAre(1, 3)); EXPECT_THAT(evens, ElementsAre(2, 4, 6)); } TEST_F(NonMutatingTest, Transform) { std::vector<int> x{0, 2, 4}, y, z; auto end = absl::c_transform(x, back_inserter(y), std::negate<int>()); EXPECT_EQ(std::vector<int>({0, -2, -4}), y); *end = 7; EXPECT_EQ(std::vector<int>({0, -2, -4, 7}), y); y = {1, 3, 0}; end = absl::c_transform(x, y, back_inserter(z), std::plus<int>()); EXPECT_EQ(std::vector<int>({1, 5, 4}), z); *end = 7; EXPECT_EQ(std::vector<int>({1, 5, 4, 7}), z); z.clear(); y.pop_back(); end = absl::c_transform(x, y, std::back_inserter(z), std::plus<int>()); EXPECT_EQ(std::vector<int>({1, 5}), z); *end = 7; EXPECT_EQ(std::vector<int>({1, 5, 7}), z); z.clear(); std::swap(x, y); end = absl::c_transform(x, y, std::back_inserter(z), std::plus<int>()); EXPECT_EQ(std::vector<int>({1, 5}), z); *end = 7; EXPECT_EQ(std::vector<int>({1, 5, 7}), z); } TEST(MutatingTest, Replace) { const std::vector<int> initial = {1, 2, 3, 1, 4, 5}; const std::vector<int> expected = {4, 2, 3, 4, 4, 5}; std::vector<int> test_vector = initial; absl::c_replace(test_vector, 1, 4); EXPECT_EQ(expected, test_vector); std::list<int> test_list(initial.begin(), initial.end()); absl::c_replace(test_list, 1, 4); EXPECT_EQ(std::list<int>(expected.begin(), expected.end()), test_list); } TEST(MutatingTest, ReplaceIf) { std::vector<int> actual = {1, 2, 3, 4, 5}; const std::vector<int> expected = {0, 2, 0, 4, 0}; absl::c_replace_if(actual, IsOdd, 0); EXPECT_EQ(expected, actual); } TEST(MutatingTest, ReplaceCopy) { const std::vector<int> initial = {1, 2, 3, 1, 4, 5}; const std::vector<int> expected = {4, 2, 3, 4, 4, 5}; std::vector<int> actual; absl::c_replace_copy(initial, back_inserter(actual), 1, 4); EXPECT_EQ(expected, actual); } TEST(MutatingTest, Sort) { std::vector<int> test_vector = {2, 3, 1, 4}; absl::c_sort(test_vector); EXPECT_THAT(test_vector, ElementsAre(1, 2, 3, 4)); } TEST(MutatingTest, SortWithPredicate) { std::vector<int> test_vector = {2, 3, 1, 4}; absl::c_sort(test_vector, std::greater<int>()); EXPECT_THAT(test_vector, ElementsAre(4, 3, 2, 1)); } struct Element { int key; int value; friend bool operator<(const Element& e1, const Element& e2) { return e1.key < e2.key; } friend std::ostream& operator<<(std::ostream& o, const Element& e) { return o << "{" << e.key << ", " << e.value << "}"; } }; MATCHER_P2(IsElement, key, value, "") { return arg.key == key && arg.value == value; } TEST(MutatingTest, StableSort) { std::vector<Element> test_vector = {{1, 1}, {2, 1}, {2, 0}, {1, 0}, {2, 2}}; absl::c_stable_sort(test_vector); EXPECT_THAT(test_vector, ElementsAre(IsElement(1, 1), IsElement(1, 0), IsElement(2, 1), IsElement(2, 0), IsElement(2, 2))); } TEST(MutatingTest, StableSortWithPredicate) { std::vector<Element> test_vector = {{1, 1}, {2, 1}, {2, 0}, {1, 0}, {2, 2}}; absl::c_stable_sort(test_vector, [](const Element& e1, const Element& e2) { return e2 < e1; }); EXPECT_THAT(test_vector, ElementsAre(IsElement(2, 1), IsElement(2, 0), IsElement(2, 2), IsElement(1, 1), IsElement(1, 0))); } TEST(MutatingTest, ReplaceCopyIf) { const std::vector<int> initial = {1, 2, 3, 4, 5}; const std::vector<int> expected = {0, 2, 0, 4, 0}; std::vector<int> actual; absl::c_replace_copy_if(initial, back_inserter(actual), IsOdd, 0); EXPECT_EQ(expected, actual); } TEST(MutatingTest, Fill) { std::vector<int> actual(5); absl::c_fill(actual, 1); EXPECT_THAT(actual, ElementsAre(1, 1, 1, 1, 1)); } TEST(MutatingTest, FillN) { std::vector<int> actual(5, 0); absl::c_fill_n(actual, 2, 1); EXPECT_THAT(actual, ElementsAre(1, 1, 0, 0, 0)); } TEST(MutatingTest, Generate) { std::vector<int> actual(5); int x = 0; absl::c_generate(actual, [&x]() { return ++x; }); EXPECT_THAT(actual, ElementsAre(1, 2, 3, 4, 5)); } TEST(MutatingTest, GenerateN) { std::vector<int> actual(5, 0); int x = 0; absl::c_generate_n(actual, 3, [&x]() { return ++x; }); EXPECT_THAT(actual, ElementsAre(1, 2, 3, 0, 0)); } TEST(MutatingTest, RemoveCopy) { std::vector<int> actual; absl::c_remove_copy(std::vector<int>{1, 2, 3}, back_inserter(actual), 2); EXPECT_THAT(actual, ElementsAre(1, 3)); } TEST(MutatingTest, RemoveCopyIf) { std::vector<int> actual; absl::c_remove_copy_if(std::vector<int>{1, 2, 3}, back_inserter(actual), IsOdd); EXPECT_THAT(actual, ElementsAre(2)); } TEST(MutatingTest, UniqueCopy) { std::vector<int> actual; absl::c_unique_copy(std::vector<int>{1, 2, 2, 2, 3, 3, 2}, back_inserter(actual)); EXPECT_THAT(actual, ElementsAre(1, 2, 3, 2)); } TEST(MutatingTest, UniqueCopyWithPredicate) { std::vector<int> actual; absl::c_unique_copy(std::vector<int>{1, 2, 3, -1, -2, -3, 1}, back_inserter(actual), [](int x, int y) { return (x < 0) == (y < 0); }); EXPECT_THAT(actual, ElementsAre(1, -1, 1)); } TEST(MutatingTest, Reverse) { std::vector<int> test_vector = {1, 2, 3, 4}; absl::c_reverse(test_vector); EXPECT_THAT(test_vector, ElementsAre(4, 3, 2, 1)); std::list<int> test_list = {1, 2, 3, 4}; absl::c_reverse(test_list); EXPECT_THAT(test_list, ElementsAre(4, 3, 2, 1)); } TEST(MutatingTest, ReverseCopy) { std::vector<int> actual; absl::c_reverse_copy(std::vector<int>{1, 2, 3, 4}, back_inserter(actual)); EXPECT_THAT(actual, ElementsAre(4, 3, 2, 1)); } TEST(MutatingTest, Rotate) { std::vector<int> actual = {1, 2, 3, 4}; auto it = absl::c_rotate(actual, actual.begin() + 2); EXPECT_THAT(actual, testing::ElementsAreArray({3, 4, 1, 2})); EXPECT_EQ(*it, 1); } TEST(MutatingTest, RotateCopy) { std::vector<int> initial = {1, 2, 3, 4}; std::vector<int> actual; auto end = absl::c_rotate_copy(initial, initial.begin() + 2, back_inserter(actual)); *end = 5; EXPECT_THAT(actual, ElementsAre(3, 4, 1, 2, 5)); } template <typename T> T RandomlySeededPrng() { std::random_device rdev; std::seed_seq::result_type data[T::state_size]; std::generate_n(data, T::state_size, std::ref(rdev)); std::seed_seq prng_seed(data, data + T::state_size); return T(prng_seed); } TEST(MutatingTest, Shuffle) { std::vector<int> actual = {1, 2, 3, 4, 5}; absl::c_shuffle(actual, RandomlySeededPrng<std::mt19937_64>()); EXPECT_THAT(actual, UnorderedElementsAre(1, 2, 3, 4, 5)); } TEST(MutatingTest, Sample) { std::vector<int> actual; absl::c_sample(std::vector<int>{1, 2, 3, 4, 5}, std::back_inserter(actual), 3, RandomlySeededPrng<std::mt19937_64>()); EXPECT_THAT(actual, IsSubsetOf({1, 2, 3, 4, 5})); EXPECT_THAT(actual, SizeIs(3)); } TEST(MutatingTest, PartialSort) { std::vector<int> sequence{5, 3, 42, 0}; absl::c_partial_sort(sequence, sequence.begin() + 2); EXPECT_THAT(absl::MakeSpan(sequence.data(), 2), ElementsAre(0, 3)); absl::c_partial_sort(sequence, sequence.begin() + 2, std::greater<int>()); EXPECT_THAT(absl::MakeSpan(sequence.data(), 2), ElementsAre(42, 5)); } TEST(MutatingTest, PartialSortCopy) { const std::vector<int> initial = {5, 3, 42, 0}; std::vector<int> actual(2); absl::c_partial_sort_copy(initial, actual); EXPECT_THAT(actual, ElementsAre(0, 3)); absl::c_partial_sort_copy(initial, actual, std::greater<int>()); EXPECT_THAT(actual, ElementsAre(42, 5)); } TEST(MutatingTest, Merge) { std::vector<int> actual; absl::c_merge(std::vector<int>{1, 3, 5}, std::vector<int>{2, 4}, back_inserter(actual)); EXPECT_THAT(actual, ElementsAre(1, 2, 3, 4, 5)); } TEST(MutatingTest, MergeWithComparator) { std::vector<int> actual; absl::c_merge(std::vector<int>{5, 3, 1}, std::vector<int>{4, 2}, back_inserter(actual), std::greater<int>()); EXPECT_THAT(actual, ElementsAre(5, 4, 3, 2, 1)); } TEST(MutatingTest, InplaceMerge) { std::vector<int> actual = {1, 3, 5, 2, 4}; absl::c_inplace_merge(actual, actual.begin() + 3); EXPECT_THAT(actual, ElementsAre(1, 2, 3, 4, 5)); } TEST(MutatingTest, InplaceMergeWithComparator) { std::vector<int> actual = {5, 3, 1, 4, 2}; absl::c_inplace_merge(actual, actual.begin() + 3, std::greater<int>()); EXPECT_THAT(actual, ElementsAre(5, 4, 3, 2, 1)); } class SetOperationsTest : public testing::Test { protected: std::vector<int> a_ = {1, 2, 3}; std::vector<int> b_ = {1, 3, 5}; std::vector<int> a_reversed_ = {3, 2, 1}; std::vector<int> b_reversed_ = {5, 3, 1}; }; TEST_F(SetOperationsTest, SetUnion) { std::vector<int> actual; absl::c_set_union(a_, b_, back_inserter(actual)); EXPECT_THAT(actual, ElementsAre(1, 2, 3, 5)); } TEST_F(SetOperationsTest, SetUnionWithComparator) { std::vector<int> actual; absl::c_set_union(a_reversed_, b_reversed_, back_inserter(actual), std::greater<int>()); EXPECT_THAT(actual, ElementsAre(5, 3, 2, 1)); } TEST_F(SetOperationsTest, SetIntersection) { std::vector<int> actual; absl::c_set_intersection(a_, b_, back_inserter(actual)); EXPECT_THAT(actual, ElementsAre(1, 3)); } TEST_F(SetOperationsTest, SetIntersectionWithComparator) { std::vector<int> actual; absl::c_set_intersection(a_reversed_, b_reversed_, back_inserter(actual), std::greater<int>()); EXPECT_THAT(actual, ElementsAre(3, 1)); } TEST_F(SetOperationsTest, SetDifference) { std::vector<int> actual; absl::c_set_difference(a_, b_, back_inserter(actual)); EXPECT_THAT(actual, ElementsAre(2)); } TEST_F(SetOperationsTest, SetDifferenceWithComparator) { std::vector<int> actual; absl::c_set_difference(a_reversed_, b_reversed_, back_inserter(actual), std::greater<int>()); EXPECT_THAT(actual, ElementsAre(2)); } TEST_F(SetOperationsTest, SetSymmetricDifference) { std::vector<int> actual; absl::c_set_symmetric_difference(a_, b_, back_inserter(actual)); EXPECT_THAT(actual, ElementsAre(2, 5)); } TEST_F(SetOperationsTest, SetSymmetricDifferenceWithComparator) { std::vector<int> actual; absl::c_set_symmetric_difference(a_reversed_, b_reversed_, back_inserter(actual), std::greater<int>()); EXPECT_THAT(actual, ElementsAre(5, 2)); } TEST(HeapOperationsTest, WithoutComparator) { std::vector<int> heap = {1, 2, 3}; EXPECT_FALSE(absl::c_is_heap(heap)); absl::c_make_heap(heap); EXPECT_TRUE(absl::c_is_heap(heap)); heap.push_back(4); EXPECT_EQ(3, absl::c_is_heap_until(heap) - heap.begin()); absl::c_push_heap(heap); EXPECT_EQ(4, heap[0]); absl::c_pop_heap(heap); EXPECT_EQ(4, heap[3]); absl::c_make_heap(heap); absl::c_sort_heap(heap); EXPECT_THAT(heap, ElementsAre(1, 2, 3, 4)); EXPECT_FALSE(absl::c_is_heap(heap)); } TEST(HeapOperationsTest, WithComparator) { using greater = std::greater<int>; std::vector<int> heap = {3, 2, 1}; EXPECT_FALSE(absl::c_is_heap(heap, greater())); absl::c_make_heap(heap, greater()); EXPECT_TRUE(absl::c_is_heap(heap, greater())); heap.push_back(0); EXPECT_EQ(3, absl::c_is_heap_until(heap, greater()) - heap.begin()); absl::c_push_heap(heap, greater()); EXPECT_EQ(0, heap[0]); absl::c_pop_heap(heap, greater()); EXPECT_EQ(0, heap[3]); absl::c_make_heap(heap, greater()); absl::c_sort_heap(heap, greater()); EXPECT_THAT(heap, ElementsAre(3, 2, 1, 0)); EXPECT_FALSE(absl::c_is_heap(heap, greater())); } TEST(MutatingTest, PermutationOperations) { std::vector<int> initial = {1, 2, 3, 4}; std::vector<int> permuted = initial; absl::c_next_permutation(permuted); EXPECT_TRUE(absl::c_is_permutation(initial, permuted)); EXPECT_TRUE(absl::c_is_permutation(initial, permuted, std::equal_to<int>())); std::vector<int> permuted2 = initial; absl::c_prev_permutation(permuted2, std::greater<int>()); EXPECT_EQ(permuted, permuted2); absl::c_prev_permutation(permuted); EXPECT_EQ(initial, permuted); } #if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 201703L TEST(ConstexprTest, Distance) { static_assert(absl::c_distance(std::array<int, 3>()) == 3); } TEST(ConstexprTest, MinElement) { constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(*absl::c_min_element(kArray) == 1); } TEST(ConstexprTest, MinElementWithPredicate) { constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(*absl::c_min_element(kArray, std::greater<int>()) == 3); } TEST(ConstexprTest, MaxElement) { constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(*absl::c_max_element(kArray) == 3); } TEST(ConstexprTest, MaxElementWithPredicate) { constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(*absl::c_max_element(kArray, std::greater<int>()) == 1); } TEST(ConstexprTest, MinMaxElement) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; constexpr auto kMinMaxPair = absl::c_minmax_element(kArray); static_assert(*kMinMaxPair.first == 1); static_assert(*kMinMaxPair.second == 3); } TEST(ConstexprTest, MinMaxElementWithPredicate) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; constexpr auto kMinMaxPair = absl::c_minmax_element(kArray, std::greater<int>()); static_assert(*kMinMaxPair.first == 3); static_assert(*kMinMaxPair.second == 1); } #endif #if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \ ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L TEST(ConstexprTest, LinearSearch) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(absl::c_linear_search(kArray, 3)); static_assert(!absl::c_linear_search(kArray, 4)); } TEST(ConstexprTest, AllOf) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(!absl::c_all_of(kArray, [](int x) { return x > 1; })); static_assert(absl::c_all_of(kArray, [](int x) { return x > 0; })); } TEST(ConstexprTest, AnyOf) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(absl::c_any_of(kArray, [](int x) { return x > 2; })); static_assert(!absl::c_any_of(kArray, [](int x) { return x > 5; })); } TEST(ConstexprTest, NoneOf) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(!absl::c_none_of(kArray, [](int x) { return x > 2; })); static_assert(absl::c_none_of(kArray, [](int x) { return x > 5; })); } TEST(ConstexprTest, ForEach) { static constexpr std::array<int, 3> kArray = [] { std::array<int, 3> array = {1, 2, 3}; absl::c_for_each(array, [](int& x) { x += 1; }); return array; }(); static_assert(kArray == std::array{2, 3, 4}); } TEST(ConstexprTest, Find) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(absl::c_find(kArray, 1) == kArray.begin()); static_assert(absl::c_find(kArray, 4) == kArray.end()); } TEST(ConstexprTest, Contains) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(absl::c_contains(kArray, 1)); static_assert(!absl::c_contains(kArray, 4)); } TEST(ConstexprTest, FindIf) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(absl::c_find_if(kArray, [](int x) { return x > 2; }) == kArray.begin() + 2); static_assert(absl::c_find_if(kArray, [](int x) { return x > 5; }) == kArray.end()); } TEST(ConstexprTest, FindIfNot) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(absl::c_find_if_not(kArray, [](int x) { return x > 1; }) == kArray.begin()); static_assert(absl::c_find_if_not(kArray, [](int x) { return x > 0; }) == kArray.end()); } TEST(ConstexprTest, FindEnd) { static constexpr std::array<int, 5> kHaystack = {1, 2, 3, 2, 3}; static constexpr std::array<int, 2> kNeedle = {2, 3}; static_assert(absl::c_find_end(kHaystack, kNeedle) == kHaystack.begin() + 3); } TEST(ConstexprTest, FindFirstOf) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(absl::c_find_first_of(kArray, kArray) == kArray.begin()); } TEST(ConstexprTest, AdjacentFind) { static constexpr std::array<int, 4> kArray = {1, 2, 2, 3}; static_assert(absl::c_adjacent_find(kArray) == kArray.begin() + 1); } TEST(ConstexprTest, AdjacentFindWithPredicate) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(absl::c_adjacent_find(kArray, std::less<int>()) == kArray.begin()); } TEST(ConstexprTest, Count) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(absl::c_count(kArray, 1) == 1); static_assert(absl::c_count(kArray, 2) == 1); static_assert(absl::c_count(kArray, 3) == 1); static_assert(absl::c_count(kArray, 4) == 0); } TEST(ConstexprTest, CountIf) { static constexpr std::array<int, 3> kArray = {1, 2, 3}; static_assert(absl::c_count_if(kArray, [](int x) { return x > 0; }) == 3); static_assert(absl::c_count_if(kArray, [](int x) { return x > 1; }) == 2); } TEST(ConstexprTest, Mismatch) { static constexpr std::array<int, 3> kArray1 = {1, 2, 3}; static constexpr std::array<int, 3> kArray2 = {1, 2, 3}; static constexpr std::array<int, 3> kArray3 = {2, 3, 4}; static_assert(absl::c_mismatch(kArray1, kArray2) == std::pair{kArray1.end(), kArray2.end()}); static_assert(absl::c_mismatch(kArray1, kArray3) == std::pair{kArray1.begin(), kArray3.begin()}); } TEST(ConstexprTest, MismatchWithPredicate) { static constexpr std::array<int, 3> kArray1 = {1, 2, 3}; static constexpr std::array<int, 3> kArray2 = {1, 2, 3}; static constexpr std::array<int, 3> kArray3 = {2, 3, 4}; static_assert(absl::c_mismatch(kArray1, kArray2, std::not_equal_to<int>()) == std::pair{kArray1.begin(), kArray2.begin()}); static_assert(absl::c_mismatch(kArray1, kArray3, std::not_equal_to<int>()) == std::pair{kArray1.end(), kArray3.end()}); } TEST(ConstexprTest, Equal) { static constexpr std::array<int, 3> kArray1 = {1, 2, 3}; static constexpr std::array<int, 3> kArray2 = {1, 2, 3}; static constexpr std::array<int, 3> kArray3 = {2, 3, 4}; static_assert(absl::c_equal(kArray1, kArray2)); static_assert(!absl::c_equal(kArray1, kArray3)); } TEST(ConstexprTest, EqualWithPredicate) { static constexpr std::array<int, 3> kArray1 = {1, 2, 3}; static constexpr std::array<int, 3> kArray2 = {1, 2, 3}; static constexpr std::array<int, 3> kArray3 = {2, 3, 4}; static_assert(!absl::c_equal(kArray1, kArray2, std::not_equal_to<int>())); static_assert(absl::c_equal(kArray1, kArray3, std::not_equal_to<int>())); } TEST(ConstexprTest, IsPermutation) { static constexpr std::array<int, 3> kArray1 = {1, 2, 3}; static constexpr std::array<int, 3> kArray2 = {3, 2, 1}; static constexpr std::array<int, 3> kArray3 = {2, 3, 4}; static_assert(absl::c_is_permutation(kArray1, kArray2)); static_assert(!absl::c_is_permutation(kArray1, kArray3)); } TEST(ConstexprTest, IsPermutationWithPredicate) { static constexpr std::array<int, 3> kArray1 = {1, 2, 3}; static constexpr std::array<int, 3> kArray2 = {3, 2, 1}; static constexpr std::array<int, 3> kArray3 = {2, 3, 4}; static_assert(absl::c_is_permutation(kArray1, kArray2, std::equal_to<int>())); static_assert( !absl::c_is_permutation(kArray1, kArray3, std::equal_to<int>())); } TEST(ConstexprTest, Search) { static constexpr std::array<int, 3> kArray1 = {1, 2, 3}; static constexpr std::array<int, 3> kArray2 = {1, 2, 3}; static constexpr std::array<int, 3> kArray3 = {2, 3, 4}; static_assert(absl::c_search(kArray1, kArray2) == kArray1.begin()); static_assert(absl::c_search(kArray1, kArray3) == kArray1.end()); } TEST(ConstexprTest, SearchWithPredicate) { static constexpr std::array<int, 3> kArray1 = {1, 2, 3}; static constexpr std::array<int, 3> kArray2 = {1, 2, 3}; static constexpr std::array<int, 3> kArray3 = {2, 3, 4}; static_assert(absl::c_search(kArray1, kArray2, std::not_equal_to<int>()) == kArray1.end()); static_assert(absl::c_search(kArray1, kArray3, std::not_equal_to<int>()) == kArray1.begin()); } TEST(ConstexprTest, ContainsSubrange) { static constexpr std::array<int, 3> kArray1 = {1, 2, 3}; static constexpr std::array<int, 3> kArray2 = {1, 2, 3}; static constexpr std::array<int, 3> kArray3 = {2, 3, 4}; static_assert(absl::c_contains_subrange(kArray1, kArray2)); static_assert(!absl::c_contains_subrange(kArray1, kArray3)); } TEST(ConstexprTest, ContainsSubrangeWithPredicate) { static constexpr std::array<int, 3> kArray1 = {1, 2, 3}; static constexpr std::array<int, 3> kArray2 = {1, 2, 3}; static constexpr std::array<int, 3> kArray3 = {2, 3, 4}; static_assert( !absl::c_contains_subrange(kArray1, kArray2, std::not_equal_to<>())); static_assert( absl::c_contains_subrange(kArray1, kArray3, std::not_equal_to<>())); } TEST(ConstexprTest, SearchN) { static constexpr std::array<int, 4> kArray = {1, 2, 2, 3}; static_assert(absl::c_search_n(kArray, 1, 1) == kArray.begin()); static_assert(absl::c_search_n(kArray, 2, 2) == kArray.begin() + 1); static_assert(absl::c_search_n(kArray, 1, 4) == kArray.end()); } TEST(ConstexprTest, SearchNWithPredicate) { static constexpr std::array<int, 4> kArray = {1, 2, 2, 3}; static_assert(absl::c_search_n(kArray, 1, 1, std::not_equal_to<int>()) == kArray.begin() + 1); static_assert(absl::c_search_n(kArray, 2, 2, std::not_equal_to<int>()) == kArray.end()); static_assert(absl::c_search_n(kArray, 1, 4, std::not_equal_to<int>()) == kArray.begin()); } #endif }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/algorithm/container.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/algorithm/container_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
7293ea99-22f7-461c-95a5-f309d55d0574
cpp
abseil/abseil-cpp
time_zone
absl/time/internal/cctz/include/cctz/time_zone.h
absl/time/time_zone_test.cc
#ifndef ABSL_TIME_INTERNAL_CCTZ_TIME_ZONE_H_ #define ABSL_TIME_INTERNAL_CCTZ_TIME_ZONE_H_ #include <chrono> #include <cstdint> #include <limits> #include <ratio> #include <string> #include <utility> #include "absl/base/config.h" #include "absl/time/internal/cctz/include/cctz/civil_time.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace time_internal { namespace cctz { template <typename D> using time_point = std::chrono::time_point<std::chrono::system_clock, D>; using seconds = std::chrono::duration<std::int_fast64_t>; using sys_seconds = seconds; namespace detail { template <typename D> std::pair<time_point<seconds>, D> split_seconds(const time_point<D>& tp); std::pair<time_point<seconds>, seconds> split_seconds( const time_point<seconds>& tp); } class time_zone { public: time_zone() : time_zone(nullptr) {} time_zone(const time_zone&) = default; time_zone& operator=(const time_zone&) = default; std::string name() const; struct absolute_lookup { civil_second cs; int offset; bool is_dst; const char* abbr; }; absolute_lookup lookup(const time_point<seconds>& tp) const; template <typename D> absolute_lookup lookup(const time_point<D>& tp) const { return lookup(detail::split_seconds(tp).first); } struct civil_lookup { enum civil_kind { UNIQUE, SKIPPED, REPEATED, } kind; time_point<seconds> pre; time_point<seconds> trans; time_point<seconds> post; }; civil_lookup lookup(const civil_second& cs) const; struct civil_transition { civil_second from; civil_second to; }; bool next_transition(const time_point<seconds>& tp, civil_transition* trans) const; template <typename D> bool next_transition(const time_point<D>& tp, civil_transition* trans) const { return next_transition(detail::split_seconds(tp).first, trans); } bool prev_transition(const time_point<seconds>& tp, civil_transition* trans) const; template <typename D> bool prev_transition(const time_point<D>& tp, civil_transition* trans) const { return prev_transition(detail::split_seconds(tp).first, trans); } std::string version() const; std::string description() const; friend bool operator==(time_zone lhs, time_zone rhs) { return &lhs.effective_impl() == &rhs.effective_impl(); } friend bool operator!=(time_zone lhs, time_zone rhs) { return !(lhs == rhs); } template <typename H> friend H AbslHashValue(H h, time_zone tz) { return H::combine(std::move(h), &tz.effective_impl()); } class Impl; private: explicit time_zone(const Impl* impl) : impl_(impl) {} const Impl& effective_impl() const; const Impl* impl_; }; bool load_time_zone(const std::string& name, time_zone* tz); time_zone utc_time_zone(); time_zone fixed_time_zone(const seconds& offset); time_zone local_time_zone(); template <typename D> inline civil_second convert(const time_point<D>& tp, const time_zone& tz) { return tz.lookup(tp).cs; } inline time_point<seconds> convert(const civil_second& cs, const time_zone& tz) { const time_zone::civil_lookup cl = tz.lookup(cs); if (cl.kind == time_zone::civil_lookup::SKIPPED) return cl.trans; return cl.pre; } namespace detail { using femtoseconds = std::chrono::duration<std::int_fast64_t, std::femto>; std::string format(const std::string&, const time_point<seconds>&, const femtoseconds&, const time_zone&); bool parse(const std::string&, const std::string&, const time_zone&, time_point<seconds>*, femtoseconds*, std::string* err = nullptr); template <typename Rep, std::intmax_t Denom> bool join_seconds( const time_point<seconds>& sec, const femtoseconds& fs, time_point<std::chrono::duration<Rep, std::ratio<1, Denom>>>* tpp); template <typename Rep, std::intmax_t Num> bool join_seconds( const time_point<seconds>& sec, const femtoseconds& fs, time_point<std::chrono::duration<Rep, std::ratio<Num, 1>>>* tpp); template <typename Rep> bool join_seconds( const time_point<seconds>& sec, const femtoseconds& fs, time_point<std::chrono::duration<Rep, std::ratio<1, 1>>>* tpp); bool join_seconds(const time_point<seconds>& sec, const femtoseconds&, time_point<seconds>* tpp); } template <typename D> inline std::string format(const std::string& fmt, const time_point<D>& tp, const time_zone& tz) { const auto p = detail::split_seconds(tp); const auto n = std::chrono::duration_cast<detail::femtoseconds>(p.second); return detail::format(fmt, p.first, n, tz); } template <typename D> inline bool parse(const std::string& fmt, const std::string& input, const time_zone& tz, time_point<D>* tpp) { time_point<seconds> sec; detail::femtoseconds fs; return detail::parse(fmt, input, tz, &sec, &fs) && detail::join_seconds(sec, fs, tpp); } namespace detail { template <typename D> std::pair<time_point<seconds>, D> split_seconds(const time_point<D>& tp) { auto sec = std::chrono::time_point_cast<seconds>(tp); auto sub = tp - sec; if (sub.count() < 0) { sec -= seconds(1); sub += seconds(1); } return {sec, std::chrono::duration_cast<D>(sub)}; } inline std::pair<time_point<seconds>, seconds> split_seconds( const time_point<seconds>& tp) { return {tp, seconds::zero()}; } template <typename Rep, std::intmax_t Denom> bool join_seconds( const time_point<seconds>& sec, const femtoseconds& fs, time_point<std::chrono::duration<Rep, std::ratio<1, Denom>>>* tpp) { using D = std::chrono::duration<Rep, std::ratio<1, Denom>>; *tpp = std::chrono::time_point_cast<D>(sec); *tpp += std::chrono::duration_cast<D>(fs); return true; } template <typename Rep, std::intmax_t Num> bool join_seconds( const time_point<seconds>& sec, const femtoseconds&, time_point<std::chrono::duration<Rep, std::ratio<Num, 1>>>* tpp) { using D = std::chrono::duration<Rep, std::ratio<Num, 1>>; auto count = sec.time_since_epoch().count(); if (count >= 0 || count % Num == 0) { count /= Num; } else { count /= Num; count -= 1; } if (count > (std::numeric_limits<Rep>::max)()) return false; if (count < (std::numeric_limits<Rep>::min)()) return false; *tpp = time_point<D>() + D{static_cast<Rep>(count)}; return true; } template <typename Rep> bool join_seconds( const time_point<seconds>& sec, const femtoseconds&, time_point<std::chrono::duration<Rep, std::ratio<1, 1>>>* tpp) { using D = std::chrono::duration<Rep, std::ratio<1, 1>>; auto count = sec.time_since_epoch().count(); if (count > (std::numeric_limits<Rep>::max)()) return false; if (count < (std::numeric_limits<Rep>::min)()) return false; *tpp = time_point<D>() + D{static_cast<Rep>(count)}; return true; } inline bool join_seconds(const time_point<seconds>& sec, const femtoseconds&, time_point<seconds>* tpp) { *tpp = sec; return true; } } } } ABSL_NAMESPACE_END } #endif
#include "absl/time/internal/cctz/include/cctz/time_zone.h" #include "gtest/gtest.h" #include "absl/time/internal/test_util.h" #include "absl/time/time.h" namespace cctz = absl::time_internal::cctz; namespace { TEST(TimeZone, ValueSemantics) { absl::TimeZone tz; absl::TimeZone tz2 = tz; EXPECT_EQ(tz, tz2); tz2 = tz; EXPECT_EQ(tz, tz2); } TEST(TimeZone, Equality) { absl::TimeZone a, b; EXPECT_EQ(a, b); EXPECT_EQ(a.name(), b.name()); absl::TimeZone implicit_utc; absl::TimeZone explicit_utc = absl::UTCTimeZone(); EXPECT_EQ(implicit_utc, explicit_utc); EXPECT_EQ(implicit_utc.name(), explicit_utc.name()); absl::TimeZone la = absl::time_internal::LoadTimeZone("America/Los_Angeles"); absl::TimeZone nyc = absl::time_internal::LoadTimeZone("America/New_York"); EXPECT_NE(la, nyc); } TEST(TimeZone, CCTZConversion) { const cctz::time_zone cz = cctz::utc_time_zone(); const absl::TimeZone tz(cz); EXPECT_EQ(cz, cctz::time_zone(tz)); } TEST(TimeZone, DefaultTimeZones) { absl::TimeZone tz; EXPECT_EQ("UTC", absl::TimeZone().name()); EXPECT_EQ("UTC", absl::UTCTimeZone().name()); } TEST(TimeZone, FixedTimeZone) { const absl::TimeZone tz = absl::FixedTimeZone(123); const cctz::time_zone cz = cctz::fixed_time_zone(cctz::seconds(123)); EXPECT_EQ(tz, absl::TimeZone(cz)); } TEST(TimeZone, LocalTimeZone) { const absl::TimeZone local_tz = absl::LocalTimeZone(); absl::TimeZone tz = absl::time_internal::LoadTimeZone("localtime"); EXPECT_EQ(tz, local_tz); } TEST(TimeZone, NamedTimeZones) { absl::TimeZone nyc = absl::time_internal::LoadTimeZone("America/New_York"); EXPECT_EQ("America/New_York", nyc.name()); absl::TimeZone syd = absl::time_internal::LoadTimeZone("Australia/Sydney"); EXPECT_EQ("Australia/Sydney", syd.name()); absl::TimeZone fixed = absl::FixedTimeZone((((3 * 60) + 25) * 60) + 45); EXPECT_EQ("Fixed/UTC+03:25:45", fixed.name()); } TEST(TimeZone, Failures) { absl::TimeZone tz = absl::time_internal::LoadTimeZone("America/Los_Angeles"); EXPECT_FALSE(LoadTimeZone("Invalid/TimeZone", &tz)); EXPECT_EQ(absl::UTCTimeZone(), tz); tz = absl::time_internal::LoadTimeZone("America/Los_Angeles"); EXPECT_FALSE(LoadTimeZone("Invalid/TimeZone", &tz)); EXPECT_EQ(absl::UTCTimeZone(), tz); tz = absl::time_internal::LoadTimeZone("America/Los_Angeles"); EXPECT_FALSE(LoadTimeZone("", &tz)); EXPECT_EQ(absl::UTCTimeZone(), tz); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/internal/cctz/include/cctz/time_zone.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/time/time_zone_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
8e5fed20-1d82-45b2-a25a-4ceb840b9908
cpp
abseil/abseil-cpp
node_hash_map
absl/container/node_hash_map.h
absl/container/node_hash_map_test.cc
#ifndef ABSL_CONTAINER_NODE_HASH_MAP_H_ #define ABSL_CONTAINER_NODE_HASH_MAP_H_ #include <cstddef> #include <memory> #include <type_traits> #include <utility> #include "absl/algorithm/container.h" #include "absl/base/attributes.h" #include "absl/container/hash_container_defaults.h" #include "absl/container/internal/container_memory.h" #include "absl/container/internal/node_slot_policy.h" #include "absl/container/internal/raw_hash_map.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { template <class Key, class Value> class NodeHashMapPolicy; } template <class Key, class Value, class Hash = DefaultHashContainerHash<Key>, class Eq = DefaultHashContainerEq<Key>, class Alloc = std::allocator<std::pair<const Key, Value>>> class ABSL_ATTRIBUTE_OWNER node_hash_map : public absl::container_internal::raw_hash_map< absl::container_internal::NodeHashMapPolicy<Key, Value>, Hash, Eq, Alloc> { using Base = typename node_hash_map::raw_hash_map; public: node_hash_map() {} using Base::Base; using Base::begin; using Base::cbegin; using Base::cend; using Base::end; using Base::capacity; using Base::empty; using Base::max_size; using Base::size; using Base::clear; using Base::erase; using Base::insert; using Base::insert_or_assign; using Base::emplace; using Base::emplace_hint; using Base::try_emplace; using Base::extract; using Base::merge; using Base::swap; using Base::rehash; using Base::reserve; using Base::at; using Base::contains; using Base::count; using Base::equal_range; using Base::find; using Base::operator[]; using Base::bucket_count; using Base::load_factor; using Base::max_load_factor; using Base::get_allocator; using Base::hash_function; using Base::key_eq; }; template <typename K, typename V, typename H, typename E, typename A, typename Predicate> typename node_hash_map<K, V, H, E, A>::size_type erase_if( node_hash_map<K, V, H, E, A>& c, Predicate pred) { return container_internal::EraseIf(pred, &c); } template <typename K, typename V, typename H, typename E, typename A> void swap(node_hash_map<K, V, H, E, A>& x, node_hash_map<K, V, H, E, A>& y) noexcept(noexcept(x.swap(y))) { return x.swap(y); } namespace container_internal { template <typename K, typename V, typename H, typename E, typename A, typename Function> decay_t<Function> c_for_each_fast(const node_hash_map<K, V, H, E, A>& c, Function&& f) { container_internal::ForEach(f, &c); return f; } template <typename K, typename V, typename H, typename E, typename A, typename Function> decay_t<Function> c_for_each_fast(node_hash_map<K, V, H, E, A>& c, Function&& f) { container_internal::ForEach(f, &c); return f; } template <typename K, typename V, typename H, typename E, typename A, typename Function> decay_t<Function> c_for_each_fast(node_hash_map<K, V, H, E, A>&& c, Function&& f) { container_internal::ForEach(f, &c); return f; } } namespace container_internal { template <class Key, class Value> class NodeHashMapPolicy : public absl::container_internal::node_slot_policy< std::pair<const Key, Value>&, NodeHashMapPolicy<Key, Value>> { using value_type = std::pair<const Key, Value>; public: using key_type = Key; using mapped_type = Value; using init_type = std::pair< key_type, mapped_type>; template <class Allocator, class... Args> static value_type* new_element(Allocator* alloc, Args&&... args) { using PairAlloc = typename absl::allocator_traits< Allocator>::template rebind_alloc<value_type>; PairAlloc pair_alloc(*alloc); value_type* res = absl::allocator_traits<PairAlloc>::allocate(pair_alloc, 1); absl::allocator_traits<PairAlloc>::construct(pair_alloc, res, std::forward<Args>(args)...); return res; } template <class Allocator> static void delete_element(Allocator* alloc, value_type* pair) { using PairAlloc = typename absl::allocator_traits< Allocator>::template rebind_alloc<value_type>; PairAlloc pair_alloc(*alloc); absl::allocator_traits<PairAlloc>::destroy(pair_alloc, pair); absl::allocator_traits<PairAlloc>::deallocate(pair_alloc, pair, 1); } template <class F, class... Args> static decltype(absl::container_internal::DecomposePair( std::declval<F>(), std::declval<Args>()...)) apply(F&& f, Args&&... args) { return absl::container_internal::DecomposePair(std::forward<F>(f), std::forward<Args>(args)...); } static size_t element_space_used(const value_type*) { return sizeof(value_type); } static Value& value(value_type* elem) { return elem->second; } static const Value& value(const value_type* elem) { return elem->second; } template <class Hash> static constexpr HashSlotFn get_hash_slot_fn() { return memory_internal::IsLayoutCompatible<Key, Value>::value ? &TypeErasedDerefAndApplyToSlotFn<Hash, Key> : nullptr; } }; } namespace container_algorithm_internal { template <class Key, class T, class Hash, class KeyEqual, class Allocator> struct IsUnorderedContainer< absl::node_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {}; } ABSL_NAMESPACE_END } #endif
#include "absl/container/node_hash_map.h" #include <cstddef> #include <new> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/container/internal/hash_policy_testing.h" #include "absl/container/internal/tracked.h" #include "absl/container/internal/unordered_map_constructor_test.h" #include "absl/container/internal/unordered_map_lookup_test.h" #include "absl/container/internal/unordered_map_members_test.h" #include "absl/container/internal/unordered_map_modifiers_test.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { using ::testing::Field; using ::testing::IsEmpty; using ::testing::Pair; using ::testing::UnorderedElementsAre; using ::testing::UnorderedElementsAreArray; using MapTypes = ::testing::Types< absl::node_hash_map<int, int, StatefulTestingHash, StatefulTestingEqual, Alloc<std::pair<const int, int>>>, absl::node_hash_map<std::string, std::string, StatefulTestingHash, StatefulTestingEqual, Alloc<std::pair<const std::string, std::string>>>>; INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashMap, ConstructorTest, MapTypes); INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashMap, LookupTest, MapTypes); INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashMap, MembersTest, MapTypes); INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashMap, ModifiersTest, MapTypes); using M = absl::node_hash_map<std::string, Tracked<int>>; TEST(NodeHashMap, Emplace) { M m; Tracked<int> t(53); m.emplace("a", t); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(1, t.num_copies()); m.emplace(std::string("a"), t); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(1, t.num_copies()); std::string a("a"); m.emplace(a, t); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(1, t.num_copies()); const std::string ca("a"); m.emplace(a, t); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(1, t.num_copies()); m.emplace(std::make_pair("a", t)); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(2, t.num_copies()); m.emplace(std::make_pair(std::string("a"), t)); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(3, t.num_copies()); std::pair<std::string, Tracked<int>> p("a", t); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(4, t.num_copies()); m.emplace(p); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(4, t.num_copies()); const std::pair<std::string, Tracked<int>> cp("a", t); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(5, t.num_copies()); m.emplace(cp); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(5, t.num_copies()); std::pair<const std::string, Tracked<int>> pc("a", t); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(6, t.num_copies()); m.emplace(pc); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(6, t.num_copies()); const std::pair<const std::string, Tracked<int>> cpc("a", t); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(7, t.num_copies()); m.emplace(cpc); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(7, t.num_copies()); m.emplace(std::piecewise_construct, std::forward_as_tuple("a"), std::forward_as_tuple(t)); 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)); ASSERT_EQ(0, t.num_moves()); ASSERT_EQ(7, t.num_copies()); } TEST(NodeHashMap, AssignRecursive) { struct Tree { absl::node_hash_map<int, Tree> children; }; Tree root; const Tree& child = root.children.emplace().first->second; root = child; } TEST(FlatHashMap, MoveOnlyKey) { struct Key { Key() = default; Key(Key&&) = default; Key& operator=(Key&&) = default; }; struct Eq { bool operator()(const Key&, const Key&) const { return true; } }; struct Hash { size_t operator()(const Key&) const { return 0; } }; absl::node_hash_map<Key, int, Hash, Eq> m; m[Key()]; } struct NonMovableKey { explicit NonMovableKey(int i) : i(i) {} NonMovableKey(NonMovableKey&&) = delete; int i; }; 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 { 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(NodeHashMap, MergeExtractInsert) { absl::node_hash_map<NonMovableKey, int, NonMovableKeyHash, NonMovableKeyEq> 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)); set2.emplace(std::piecewise_construct, std::make_tuple(7), std::make_tuple(-70)); set2.emplace(std::piecewise_construct, std::make_tuple(19), std::make_tuple(-190)); auto Elem = [](int key, int value) { return Pair(Field(&NonMovableKey::i, key), value); }; EXPECT_THAT(set1, UnorderedElementsAre(Elem(7, -7), Elem(17, -17))); EXPECT_THAT(set2, UnorderedElementsAre(Elem(7, -70), Elem(19, -190))); static_assert(!std::is_move_constructible<NonMovableKey>::value, ""); set1.merge(set2); EXPECT_THAT(set1, UnorderedElementsAre(Elem(7, -7), Elem(17, -17), Elem(19, -190))); EXPECT_THAT(set2, UnorderedElementsAre(Elem(7, -70))); auto node = set1.extract(7); EXPECT_TRUE(node); EXPECT_EQ(node.key().i, 7); EXPECT_EQ(node.mapped(), -7); EXPECT_THAT(set1, UnorderedElementsAre(Elem(17, -17), Elem(19, -190))); auto insert_result = set2.insert(std::move(node)); EXPECT_FALSE(node); EXPECT_FALSE(insert_result.inserted); EXPECT_TRUE(insert_result.node); EXPECT_EQ(insert_result.node.key().i, 7); EXPECT_EQ(insert_result.node.mapped(), -7); EXPECT_THAT(*insert_result.position, Elem(7, -70)); EXPECT_THAT(set2, UnorderedElementsAre(Elem(7, -70))); node = set1.extract(17); EXPECT_TRUE(node); EXPECT_EQ(node.key().i, 17); EXPECT_EQ(node.mapped(), -17); EXPECT_THAT(set1, UnorderedElementsAre(Elem(19, -190))); node.mapped() = 23; insert_result = set2.insert(std::move(node)); EXPECT_FALSE(node); EXPECT_TRUE(insert_result.inserted); EXPECT_FALSE(insert_result.node); EXPECT_THAT(*insert_result.position, Elem(17, 23)); EXPECT_THAT(set2, UnorderedElementsAre(Elem(7, -70), Elem(17, 23))); } bool FirstIsEven(std::pair<const int, int> p) { return p.first % 2 == 0; } TEST(NodeHashMap, EraseIf) { { node_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_EQ(erase_if(s, [](std::pair<const int, int>) { return true; }), 5); EXPECT_THAT(s, IsEmpty()); } { node_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_EQ(erase_if(s, [](std::pair<const int, int>) { return false; }), 0); EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3), Pair(4, 4), Pair(5, 5))); } { node_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_EQ(erase_if(s, [](std::pair<const int, int> kvp) { return kvp.first % 2 == 1; }), 3); EXPECT_THAT(s, UnorderedElementsAre(Pair(2, 2), Pair(4, 4))); } { node_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_EQ(erase_if(s, FirstIsEven), 2); EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(3, 3), Pair(5, 5))); } { node_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_EQ(erase_if(s, &FirstIsEven), 2); EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(3, 3), Pair(5, 5))); } } TEST(NodeHashMap, CForEach) { node_hash_map<int, int> m; std::vector<std::pair<int, int>> expected; for (int i = 0; i < 100; ++i) { { SCOPED_TRACE("mutable object iteration"); std::vector<std::pair<int, int>> v; absl::container_internal::c_for_each_fast( m, [&v](std::pair<const int, int>& p) { v.push_back(p); }); EXPECT_THAT(v, UnorderedElementsAreArray(expected)); } { SCOPED_TRACE("const object iteration"); std::vector<std::pair<int, int>> v; const node_hash_map<int, int>& cm = m; absl::container_internal::c_for_each_fast( cm, [&v](const std::pair<const int, int>& p) { v.push_back(p); }); EXPECT_THAT(v, UnorderedElementsAreArray(expected)); } { SCOPED_TRACE("const object iteration"); std::vector<std::pair<int, int>> v; absl::container_internal::c_for_each_fast( node_hash_map<int, int>(m), [&v](std::pair<const int, int>& p) { v.push_back(p); }); EXPECT_THAT(v, UnorderedElementsAreArray(expected)); } m[i] = i; expected.emplace_back(i, i); } } TEST(NodeHashMap, CForEachMutate) { node_hash_map<int, int> s; std::vector<std::pair<int, int>> expected; for (int i = 0; i < 100; ++i) { std::vector<std::pair<int, int>> v; absl::container_internal::c_for_each_fast( s, [&v](std::pair<const int, int>& p) { v.push_back(p); p.second++; }); EXPECT_THAT(v, UnorderedElementsAreArray(expected)); for (auto& p : expected) { p.second++; } EXPECT_THAT(s, UnorderedElementsAreArray(expected)); s[i] = i; expected.emplace_back(i, i); } } #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606 TEST(NodeHashMap, NodeHandleMutableKeyAccess) { node_hash_map<std::string, std::string> map; map["key1"] = "mapped"; auto nh = map.extract(map.begin()); nh.key().resize(3); map.insert(std::move(nh)); EXPECT_THAT(map, testing::ElementsAre(Pair("key", "mapped"))); } #endif TEST(NodeHashMap, RecursiveTypeCompiles) { struct RecursiveType { node_hash_map<int, RecursiveType> m; }; RecursiveType t; t.m[0] = RecursiveType{}; } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/node_hash_map.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/node_hash_map_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
a05555de-5346-431f-bb36-c663f7b184e5
cpp
abseil/abseil-cpp
flat_hash_map
absl/container/flat_hash_map.h
absl/container/flat_hash_map_test.cc
#ifndef ABSL_CONTAINER_FLAT_HASH_MAP_H_ #define ABSL_CONTAINER_FLAT_HASH_MAP_H_ #include <cstddef> #include <memory> #include <type_traits> #include <utility> #include "absl/algorithm/container.h" #include "absl/base/attributes.h" #include "absl/base/macros.h" #include "absl/container/hash_container_defaults.h" #include "absl/container/internal/container_memory.h" #include "absl/container/internal/raw_hash_map.h" #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { template <class K, class V> struct FlatHashMapPolicy; } template <class K, class V, class Hash = DefaultHashContainerHash<K>, class Eq = DefaultHashContainerEq<K>, class Allocator = std::allocator<std::pair<const K, V>>> class ABSL_ATTRIBUTE_OWNER flat_hash_map : public absl::container_internal::raw_hash_map< absl::container_internal::FlatHashMapPolicy<K, V>, Hash, Eq, Allocator> { using Base = typename flat_hash_map::raw_hash_map; public: flat_hash_map() {} using Base::Base; using Base::begin; using Base::cbegin; using Base::cend; using Base::end; using Base::capacity; using Base::empty; using Base::max_size; using Base::size; using Base::clear; using Base::erase; using Base::insert; using Base::insert_or_assign; using Base::emplace; using Base::emplace_hint; using Base::try_emplace; using Base::extract; using Base::merge; using Base::swap; using Base::rehash; using Base::reserve; using Base::at; using Base::contains; using Base::count; using Base::equal_range; using Base::find; using Base::operator[]; using Base::bucket_count; using Base::load_factor; using Base::max_load_factor; using Base::get_allocator; using Base::hash_function; using Base::key_eq; }; template <typename K, typename V, typename H, typename E, typename A, typename Predicate> typename flat_hash_map<K, V, H, E, A>::size_type erase_if( flat_hash_map<K, V, H, E, A>& c, Predicate pred) { return container_internal::EraseIf(pred, &c); } template <typename K, typename V, typename H, typename E, typename A> void swap(flat_hash_map<K, V, H, E, A>& x, flat_hash_map<K, V, H, E, A>& y) noexcept(noexcept(x.swap(y))) { x.swap(y); } namespace container_internal { template <typename K, typename V, typename H, typename E, typename A, typename Function> decay_t<Function> c_for_each_fast(const flat_hash_map<K, V, H, E, A>& c, Function&& f) { container_internal::ForEach(f, &c); return f; } template <typename K, typename V, typename H, typename E, typename A, typename Function> decay_t<Function> c_for_each_fast(flat_hash_map<K, V, H, E, A>& c, Function&& f) { container_internal::ForEach(f, &c); return f; } template <typename K, typename V, typename H, typename E, typename A, typename Function> decay_t<Function> c_for_each_fast(flat_hash_map<K, V, H, E, A>&& c, Function&& f) { container_internal::ForEach(f, &c); return f; } } namespace container_internal { template <class K, class V> struct FlatHashMapPolicy { using slot_policy = container_internal::map_slot_policy<K, V>; using slot_type = typename slot_policy::slot_type; using key_type = K; using mapped_type = V; using init_type = std::pair< key_type, mapped_type>; template <class Allocator, class... Args> static void construct(Allocator* alloc, slot_type* slot, Args&&... args) { slot_policy::construct(alloc, slot, std::forward<Args>(args)...); } template <class Allocator> static auto destroy(Allocator* alloc, slot_type* slot) { return slot_policy::destroy(alloc, slot); } template <class Allocator> static auto transfer(Allocator* alloc, slot_type* new_slot, slot_type* old_slot) { return slot_policy::transfer(alloc, new_slot, old_slot); } template <class F, class... Args> static decltype(absl::container_internal::DecomposePair( std::declval<F>(), std::declval<Args>()...)) apply(F&& f, Args&&... args) { return absl::container_internal::DecomposePair(std::forward<F>(f), std::forward<Args>(args)...); } template <class Hash> static constexpr HashSlotFn get_hash_slot_fn() { return memory_internal::IsLayoutCompatible<K, V>::value ? &TypeErasedApplyToSlotFn<Hash, K> : nullptr; } static size_t space_used(const slot_type*) { return 0; } static std::pair<const K, V>& element(slot_type* slot) { return slot->value; } static V& value(std::pair<const K, V>* kv) { return kv->second; } static const V& value(const std::pair<const K, V>* kv) { return kv->second; } }; } namespace container_algorithm_internal { template <class Key, class T, class Hash, class KeyEqual, class Allocator> struct IsUnorderedContainer< absl::flat_hash_map<Key, T, Hash, KeyEqual, Allocator>> : std::true_type {}; } ABSL_NAMESPACE_END } #endif
#include "absl/container/flat_hash_map.h" #include <cstddef> #include <memory> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/container/internal/hash_generator_testing.h" #include "absl/container/internal/hash_policy_testing.h" #include "absl/container/internal/test_allocator.h" #include "absl/container/internal/unordered_map_constructor_test.h" #include "absl/container/internal/unordered_map_lookup_test.h" #include "absl/container/internal/unordered_map_members_test.h" #include "absl/container/internal/unordered_map_modifiers_test.h" #include "absl/log/check.h" #include "absl/meta/type_traits.h" #include "absl/types/any.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { using ::absl::container_internal::hash_internal::Enum; using ::absl::container_internal::hash_internal::EnumClass; using ::testing::_; using ::testing::IsEmpty; using ::testing::Pair; using ::testing::UnorderedElementsAre; using ::testing::UnorderedElementsAreArray; struct BeforeMain { BeforeMain() { absl::flat_hash_map<int, int> x; x.insert({1, 1}); CHECK(x.find(0) == x.end()) << "x should not contain 0"; auto it = x.find(1); CHECK(it != x.end()) << "x should contain 1"; CHECK(it->second) << "1 should map to 1"; } }; const BeforeMain before_main; template <class K, class V> using Map = flat_hash_map<K, V, StatefulTestingHash, StatefulTestingEqual, Alloc<std::pair<const K, V>>>; static_assert(!std::is_standard_layout<NonStandardLayout>(), ""); using MapTypes = ::testing::Types<Map<int, int>, Map<std::string, int>, Map<Enum, std::string>, Map<EnumClass, int>, Map<int, NonStandardLayout>, Map<NonStandardLayout, int>>; INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, ConstructorTest, MapTypes); INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, LookupTest, MapTypes); INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, MembersTest, MapTypes); INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, ModifiersTest, MapTypes); using UniquePtrMapTypes = ::testing::Types<Map<int, std::unique_ptr<int>>>; INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashMap, UniquePtrModifiersTest, UniquePtrMapTypes); TEST(FlatHashMap, StandardLayout) { struct Int { explicit Int(size_t value) : value(value) {} Int() : value(0) { ADD_FAILURE(); } Int(const Int& other) : value(other.value) { ADD_FAILURE(); } Int(Int&&) = default; bool operator==(const Int& other) const { return value == other.value; } size_t value; }; static_assert(std::is_standard_layout<Int>(), ""); struct Hash { size_t operator()(const Int& obj) const { return obj.value; } }; { flat_hash_map<Int, Int, Hash> m; m.try_emplace(Int(1), Int(2)); m.try_emplace(Int(3), Int(4)); m.erase(Int(1)); m.rehash(2 * m.bucket_count()); } { flat_hash_map<Int, Int, Hash> m; m.try_emplace(Int(1), Int(2)); m.try_emplace(Int(3), Int(4)); m.erase(Int(1)); m.clear(); } } TEST(FlatHashMap, Relocatability) { static_assert(absl::is_trivially_relocatable<int>::value, ""); static_assert( absl::is_trivially_relocatable<std::pair<const int, int>>::value, ""); static_assert( std::is_same<decltype(absl::container_internal::FlatHashMapPolicy< int, int>::transfer<std::allocator<char>>(nullptr, nullptr, nullptr)), std::true_type>::value, ""); struct NonRelocatable { NonRelocatable() = default; NonRelocatable(NonRelocatable&&) {} NonRelocatable& operator=(NonRelocatable&&) { return *this; } void* self = nullptr; }; EXPECT_FALSE(absl::is_trivially_relocatable<NonRelocatable>::value); EXPECT_TRUE( (std::is_same<decltype(absl::container_internal::FlatHashMapPolicy< int, NonRelocatable>:: transfer<std::allocator<char>>(nullptr, nullptr, nullptr)), std::false_type>::value)); } struct balast {}; TEST(FlatHashMap, IteratesMsan) { std::vector<absl::flat_hash_map<int, balast>> garbage; for (int i = 0; i < 100; ++i) { absl::flat_hash_map<int, balast> t; for (int j = 0; j < 100; ++j) { t[j]; for (const auto& p : t) EXPECT_THAT(p, Pair(_, _)); } garbage.push_back(std::move(t)); } } struct LazyInt { explicit LazyInt(size_t value, int* tracker) : value(value), tracker(tracker) {} explicit operator size_t() const { ++*tracker; return value; } size_t value; int* tracker; }; struct Hash { using is_transparent = void; int* tracker; size_t operator()(size_t obj) const { ++*tracker; return obj; } size_t operator()(const LazyInt& obj) const { ++*tracker; return obj.value; } }; 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(FlatHashMap, LazyKeyPattern) { int conversions = 0; int hashes = 0; flat_hash_map<size_t, size_t, Hash, Eq> m(0, Hash{&hashes}); m.reserve(3); m[LazyInt(1, &conversions)] = 1; EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 1))); EXPECT_EQ(conversions, 1); #ifdef NDEBUG EXPECT_EQ(hashes, 1); #endif m[LazyInt(1, &conversions)] = 2; EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 2))); EXPECT_EQ(conversions, 1); #ifdef NDEBUG EXPECT_EQ(hashes, 2); #endif m.try_emplace(LazyInt(2, &conversions), 3); EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 2), Pair(2, 3))); EXPECT_EQ(conversions, 2); #ifdef NDEBUG EXPECT_EQ(hashes, 3); #endif m.try_emplace(LazyInt(2, &conversions), 4); EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 2), Pair(2, 3))); EXPECT_EQ(conversions, 2); #ifdef NDEBUG EXPECT_EQ(hashes, 4); #endif } TEST(FlatHashMap, BitfieldArgument) { union { int n : 1; }; n = 0; flat_hash_map<int, int> m; m.erase(n); m.count(n); m.prefetch(n); m.find(n); m.contains(n); m.equal_range(n); m.insert_or_assign(n, n); m.insert_or_assign(m.end(), n, n); m.try_emplace(n); m.try_emplace(m.end(), n); m.at(n); m[n]; } TEST(FlatHashMap, MergeExtractInsert) { absl::flat_hash_map<int, int> m = {{1, 7}, {2, 9}}; auto node = m.extract(1); EXPECT_TRUE(node); EXPECT_EQ(node.key(), 1); EXPECT_EQ(node.mapped(), 7); EXPECT_THAT(m, UnorderedElementsAre(Pair(2, 9))); node.mapped() = 17; m.insert(std::move(node)); EXPECT_THAT(m, UnorderedElementsAre(Pair(1, 17), Pair(2, 9))); } bool FirstIsEven(std::pair<const int, int> p) { return p.first % 2 == 0; } TEST(FlatHashMap, EraseIf) { { flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_EQ(erase_if(s, [](std::pair<const int, int>) { return true; }), 5); EXPECT_THAT(s, IsEmpty()); } { flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_EQ(erase_if(s, [](std::pair<const int, int>) { return false; }), 0); EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3), Pair(4, 4), Pair(5, 5))); } { flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_EQ(erase_if(s, [](std::pair<const int, int> kvp) { return kvp.first % 2 == 1; }), 3); EXPECT_THAT(s, UnorderedElementsAre(Pair(2, 2), Pair(4, 4))); } { flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_EQ(erase_if(s, FirstIsEven), 2); EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(3, 3), Pair(5, 5))); } { flat_hash_map<int, int> s = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_EQ(erase_if(s, &FirstIsEven), 2); EXPECT_THAT(s, UnorderedElementsAre(Pair(1, 1), Pair(3, 3), Pair(5, 5))); } } TEST(FlatHashMap, CForEach) { flat_hash_map<int, int> m; std::vector<std::pair<int, int>> expected; for (int i = 0; i < 100; ++i) { { SCOPED_TRACE("mutable object iteration"); std::vector<std::pair<int, int>> v; absl::container_internal::c_for_each_fast( m, [&v](std::pair<const int, int>& p) { v.push_back(p); }); EXPECT_THAT(v, UnorderedElementsAreArray(expected)); } { SCOPED_TRACE("const object iteration"); std::vector<std::pair<int, int>> v; const flat_hash_map<int, int>& cm = m; absl::container_internal::c_for_each_fast( cm, [&v](const std::pair<const int, int>& p) { v.push_back(p); }); EXPECT_THAT(v, UnorderedElementsAreArray(expected)); } { SCOPED_TRACE("const object iteration"); std::vector<std::pair<int, int>> v; absl::container_internal::c_for_each_fast( flat_hash_map<int, int>(m), [&v](std::pair<const int, int>& p) { v.push_back(p); }); EXPECT_THAT(v, UnorderedElementsAreArray(expected)); } m[i] = i; expected.emplace_back(i, i); } } TEST(FlatHashMap, CForEachMutate) { flat_hash_map<int, int> s; std::vector<std::pair<int, int>> expected; for (int i = 0; i < 100; ++i) { std::vector<std::pair<int, int>> v; absl::container_internal::c_for_each_fast( s, [&v](std::pair<const int, int>& p) { v.push_back(p); p.second++; }); EXPECT_THAT(v, UnorderedElementsAreArray(expected)); for (auto& p : expected) { p.second++; } EXPECT_THAT(s, UnorderedElementsAreArray(expected)); s[i] = i; expected.emplace_back(i, i); } } #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606 TEST(FlatHashMap, NodeHandleMutableKeyAccess) { flat_hash_map<std::string, std::string> map; map["key1"] = "mapped"; auto nh = map.extract(map.begin()); nh.key().resize(3); map.insert(std::move(nh)); EXPECT_THAT(map, testing::ElementsAre(Pair("key", "mapped"))); } #endif TEST(FlatHashMap, Reserve) { for (size_t trial = 0; trial < 20; ++trial) { for (size_t initial = 3; initial < 100; ++initial) { flat_hash_map<size_t, size_t> map; for (size_t i = 0; i < initial; ++i) { map[i] = i; } map.erase(0); map.erase(1); map.reserve(map.size() + 2); size_t& a2 = map[2]; map[initial] = a2; map[initial + 1] = a2; size_t& a2new = map[2]; EXPECT_EQ(&a2, &a2new); } } } TEST(FlatHashMap, RecursiveTypeCompiles) { struct RecursiveType { flat_hash_map<int, RecursiveType> m; }; RecursiveType t; t.m[0] = RecursiveType{}; } TEST(FlatHashMap, FlatHashMapPolicyDestroyReturnsTrue) { EXPECT_TRUE( (decltype(FlatHashMapPolicy<int, char>::destroy<std::allocator<char>>( nullptr, nullptr))())); EXPECT_FALSE( (decltype(FlatHashMapPolicy<int, char>::destroy<CountingAllocator<char>>( nullptr, nullptr))())); EXPECT_FALSE((decltype(FlatHashMapPolicy<int, std::unique_ptr<int>>::destroy< std::allocator<char>>(nullptr, nullptr))())); } struct InconsistentHashEqType { InconsistentHashEqType(int v1, int v2) : v1(v1), v2(v2) {} template <typename H> friend H AbslHashValue(H h, InconsistentHashEqType t) { return H::combine(std::move(h), t.v1); } bool operator==(InconsistentHashEqType t) const { return v2 == t.v2; } int v1, v2; }; TEST(Iterator, InconsistentHashEqFunctorsValidation) { if (!IsAssertEnabled()) GTEST_SKIP() << "Assertions not enabled."; absl::flat_hash_map<InconsistentHashEqType, int> m; for (int i = 0; i < 10; ++i) m[{i, i}] = 1; auto insert_conflicting_elems = [&] { for (int i = 100; i < 20000; ++i) { EXPECT_EQ((m[{i, 0}]), 1); } }; const char* crash_message = "hash/eq functors are inconsistent."; #if defined(__arm__) || defined(__aarch64__) crash_message = ""; #endif EXPECT_DEATH_IF_SUPPORTED(insert_conflicting_elems(), crash_message); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/flat_hash_map.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/flat_hash_map_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
0ef82f61-2c0d-4c8e-ac35-17fce5a47c6e
cpp
abseil/abseil-cpp
fixed_array
absl/container/fixed_array.h
absl/container/fixed_array_test.cc
#ifndef ABSL_CONTAINER_FIXED_ARRAY_H_ #define ABSL_CONTAINER_FIXED_ARRAY_H_ #include <algorithm> #include <cassert> #include <cstddef> #include <initializer_list> #include <iterator> #include <limits> #include <memory> #include <new> #include <type_traits> #include "absl/algorithm/algorithm.h" #include "absl/base/config.h" #include "absl/base/dynamic_annotations.h" #include "absl/base/internal/throw_delegate.h" #include "absl/base/macros.h" #include "absl/base/optimization.h" #include "absl/base/port.h" #include "absl/container/internal/compressed_tuple.h" #include "absl/memory/memory.h" namespace absl { ABSL_NAMESPACE_BEGIN constexpr static auto kFixedArrayUseDefault = static_cast<size_t>(-1); template <typename T, size_t N = kFixedArrayUseDefault, typename A = std::allocator<T>> class FixedArray { static_assert(!std::is_array<T>::value || std::extent<T>::value > 0, "Arrays with unknown bounds cannot be used with FixedArray."); static constexpr size_t kInlineBytesDefault = 256; using AllocatorTraits = std::allocator_traits<A>; template <typename Iterator> using EnableIfForwardIterator = absl::enable_if_t<std::is_convertible< typename std::iterator_traits<Iterator>::iterator_category, std::forward_iterator_tag>::value>; static constexpr bool NoexceptCopyable() { return std::is_nothrow_copy_constructible<StorageElement>::value && absl::allocator_is_nothrow<allocator_type>::value; } static constexpr bool NoexceptMovable() { return std::is_nothrow_move_constructible<StorageElement>::value && absl::allocator_is_nothrow<allocator_type>::value; } static constexpr bool DefaultConstructorIsNonTrivial() { return !absl::is_trivially_default_constructible<StorageElement>::value; } public: using allocator_type = typename AllocatorTraits::allocator_type; using value_type = typename AllocatorTraits::value_type; using pointer = typename AllocatorTraits::pointer; using const_pointer = typename AllocatorTraits::const_pointer; using reference = value_type&; using const_reference = const value_type&; using size_type = typename AllocatorTraits::size_type; using difference_type = typename AllocatorTraits::difference_type; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; static constexpr size_type inline_elements = (N == kFixedArrayUseDefault ? kInlineBytesDefault / sizeof(value_type) : static_cast<size_type>(N)); FixedArray(const FixedArray& other) noexcept(NoexceptCopyable()) : FixedArray(other, AllocatorTraits::select_on_container_copy_construction( other.storage_.alloc())) {} FixedArray(const FixedArray& other, const allocator_type& a) noexcept(NoexceptCopyable()) : FixedArray(other.begin(), other.end(), a) {} FixedArray(FixedArray&& other) noexcept(NoexceptMovable()) : FixedArray(std::move(other), other.storage_.alloc()) {} FixedArray(FixedArray&& other, const allocator_type& a) noexcept(NoexceptMovable()) : FixedArray(std::make_move_iterator(other.begin()), std::make_move_iterator(other.end()), a) {} explicit FixedArray(size_type n, const allocator_type& a = allocator_type()) : storage_(n, a) { if (DefaultConstructorIsNonTrivial()) { memory_internal::ConstructRange(storage_.alloc(), storage_.begin(), storage_.end()); } } FixedArray(size_type n, const value_type& val, const allocator_type& a = allocator_type()) : storage_(n, a) { memory_internal::ConstructRange(storage_.alloc(), storage_.begin(), storage_.end(), val); } FixedArray(std::initializer_list<value_type> init_list, const allocator_type& a = allocator_type()) : FixedArray(init_list.begin(), init_list.end(), a) {} template <typename Iterator, EnableIfForwardIterator<Iterator>* = nullptr> FixedArray(Iterator first, Iterator last, const allocator_type& a = allocator_type()) : storage_(std::distance(first, last), a) { memory_internal::CopyRange(storage_.alloc(), storage_.begin(), first, last); } ~FixedArray() noexcept { for (auto* cur = storage_.begin(); cur != storage_.end(); ++cur) { AllocatorTraits::destroy(storage_.alloc(), cur); } } void operator=(FixedArray&&) = delete; void operator=(const FixedArray&) = delete; size_type size() const { return storage_.size(); } constexpr size_type max_size() const { return (std::numeric_limits<difference_type>::max)() / sizeof(value_type); } bool empty() const { return size() == 0; } size_t memsize() const { return size() * sizeof(value_type); } const_pointer data() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return AsValueType(storage_.begin()); } pointer data() ABSL_ATTRIBUTE_LIFETIME_BOUND { return AsValueType(storage_.begin()); } reference operator[](size_type i) ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_HARDENING_ASSERT(i < size()); return data()[i]; } const_reference operator[](size_type i) const ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_HARDENING_ASSERT(i < size()); return data()[i]; } reference at(size_type i) ABSL_ATTRIBUTE_LIFETIME_BOUND { if (ABSL_PREDICT_FALSE(i >= size())) { base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check"); } return data()[i]; } const_reference at(size_type i) const ABSL_ATTRIBUTE_LIFETIME_BOUND { if (ABSL_PREDICT_FALSE(i >= size())) { base_internal::ThrowStdOutOfRange("FixedArray::at failed bounds check"); } return data()[i]; } reference front() ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_HARDENING_ASSERT(!empty()); return data()[0]; } const_reference front() const ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_HARDENING_ASSERT(!empty()); return data()[0]; } reference back() ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_HARDENING_ASSERT(!empty()); return data()[size() - 1]; } const_reference back() const ABSL_ATTRIBUTE_LIFETIME_BOUND { ABSL_HARDENING_ASSERT(!empty()); return data()[size() - 1]; } iterator begin() ABSL_ATTRIBUTE_LIFETIME_BOUND { return data(); } const_iterator begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return data(); } const_iterator cbegin() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return begin(); } iterator end() ABSL_ATTRIBUTE_LIFETIME_BOUND { return data() + size(); } const_iterator end() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return data() + size(); } const_iterator cend() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return end(); } reverse_iterator rbegin() ABSL_ATTRIBUTE_LIFETIME_BOUND { return reverse_iterator(end()); } const_reverse_iterator rbegin() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return const_reverse_iterator(end()); } const_reverse_iterator crbegin() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return rbegin(); } reverse_iterator rend() ABSL_ATTRIBUTE_LIFETIME_BOUND { return reverse_iterator(begin()); } const_reverse_iterator rend() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return const_reverse_iterator(begin()); } const_reverse_iterator crend() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return rend(); } void fill(const value_type& val) { std::fill(begin(), end(), val); } friend bool operator==(const FixedArray& lhs, const FixedArray& rhs) { return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } friend bool operator!=(const FixedArray& lhs, const FixedArray& rhs) { return !(lhs == rhs); } friend bool operator<(const FixedArray& lhs, const FixedArray& rhs) { return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } friend bool operator>(const FixedArray& lhs, const FixedArray& rhs) { return rhs < lhs; } friend bool operator<=(const FixedArray& lhs, const FixedArray& rhs) { return !(rhs < lhs); } friend bool operator>=(const FixedArray& lhs, const FixedArray& rhs) { return !(lhs < rhs); } template <typename H> friend H AbslHashValue(H h, const FixedArray& v) { return H::combine(H::combine_contiguous(std::move(h), v.data(), v.size()), v.size()); } private: template <typename OuterT, typename InnerT = absl::remove_extent_t<OuterT>, size_t InnerN = std::extent<OuterT>::value> struct StorageElementWrapper { InnerT array[InnerN]; }; using StorageElement = absl::conditional_t<std::is_array<value_type>::value, StorageElementWrapper<value_type>, value_type>; static pointer AsValueType(pointer ptr) { return ptr; } static pointer AsValueType(StorageElementWrapper<value_type>* ptr) { return std::addressof(ptr->array); } static_assert(sizeof(StorageElement) == sizeof(value_type), ""); static_assert(alignof(StorageElement) == alignof(value_type), ""); class NonEmptyInlinedStorage { public: StorageElement* data() { return reinterpret_cast<StorageElement*>(buff_); } void AnnotateConstruct(size_type n); void AnnotateDestruct(size_type n); #ifdef ABSL_HAVE_ADDRESS_SANITIZER void* RedzoneBegin() { return &redzone_begin_; } void* RedzoneEnd() { return &redzone_end_ + 1; } #endif private: ABSL_ADDRESS_SANITIZER_REDZONE(redzone_begin_); alignas(StorageElement) char buff_[sizeof(StorageElement[inline_elements])]; ABSL_ADDRESS_SANITIZER_REDZONE(redzone_end_); }; class EmptyInlinedStorage { public: StorageElement* data() { return nullptr; } void AnnotateConstruct(size_type) {} void AnnotateDestruct(size_type) {} }; using InlinedStorage = absl::conditional_t<inline_elements == 0, EmptyInlinedStorage, NonEmptyInlinedStorage>; class Storage : public InlinedStorage { public: Storage(size_type n, const allocator_type& a) : size_alloc_(n, a), data_(InitializeData()) {} ~Storage() noexcept { if (UsingInlinedStorage(size())) { InlinedStorage::AnnotateDestruct(size()); } else { AllocatorTraits::deallocate(alloc(), AsValueType(begin()), size()); } } size_type size() const { return size_alloc_.template get<0>(); } StorageElement* begin() const { return data_; } StorageElement* end() const { return begin() + size(); } allocator_type& alloc() { return size_alloc_.template get<1>(); } const allocator_type& alloc() const { return size_alloc_.template get<1>(); } private: static bool UsingInlinedStorage(size_type n) { return n <= inline_elements; } #ifdef ABSL_HAVE_ADDRESS_SANITIZER ABSL_ATTRIBUTE_NOINLINE #endif StorageElement* InitializeData() { if (UsingInlinedStorage(size())) { InlinedStorage::AnnotateConstruct(size()); return InlinedStorage::data(); } else { return reinterpret_cast<StorageElement*>( AllocatorTraits::allocate(alloc(), size())); } } container_internal::CompressedTuple<size_type, allocator_type> size_alloc_; StorageElement* data_; }; Storage storage_; }; #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL template <typename T, size_t N, typename A> constexpr size_t FixedArray<T, N, A>::kInlineBytesDefault; template <typename T, size_t N, typename A> constexpr typename FixedArray<T, N, A>::size_type FixedArray<T, N, A>::inline_elements; #endif template <typename T, size_t N, typename A> void FixedArray<T, N, A>::NonEmptyInlinedStorage::AnnotateConstruct( typename FixedArray<T, N, A>::size_type n) { #ifdef ABSL_HAVE_ADDRESS_SANITIZER if (!n) return; ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(data(), RedzoneEnd(), RedzoneEnd(), data() + n); ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(RedzoneBegin(), data(), data(), RedzoneBegin()); #endif static_cast<void>(n); } template <typename T, size_t N, typename A> void FixedArray<T, N, A>::NonEmptyInlinedStorage::AnnotateDestruct( typename FixedArray<T, N, A>::size_type n) { #ifdef ABSL_HAVE_ADDRESS_SANITIZER if (!n) return; ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(data(), RedzoneEnd(), data() + n, RedzoneEnd()); ABSL_ANNOTATE_CONTIGUOUS_CONTAINER(RedzoneBegin(), data(), RedzoneBegin(), data()); #endif static_cast<void>(n); } ABSL_NAMESPACE_END } #endif
#include "absl/container/fixed_array.h" #include <stdio.h> #include <cstring> #include <list> #include <memory> #include <numeric> #include <scoped_allocator> #include <stdexcept> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/base/internal/exception_testing.h" #include "absl/base/options.h" #include "absl/container/internal/test_allocator.h" #include "absl/hash/hash_testing.h" #include "absl/memory/memory.h" using ::testing::ElementsAreArray; namespace { template <typename ArrayType> static bool IsOnStack(const ArrayType& a) { return a.size() <= ArrayType::inline_elements; } class ConstructionTester { public: ConstructionTester() : self_ptr_(this), value_(0) { constructions++; } ~ConstructionTester() { assert(self_ptr_ == this); self_ptr_ = nullptr; destructions++; } static int constructions; static int destructions; void CheckConstructed() { assert(self_ptr_ == this); } void set(int value) { value_ = value; } int get() { return value_; } private: ConstructionTester* self_ptr_; int value_; }; int ConstructionTester::constructions = 0; int ConstructionTester::destructions = 0; class ThreeInts { public: ThreeInts() { x_ = counter; y_ = counter; z_ = counter; ++counter; } static int counter; int x_, y_, z_; }; int ThreeInts::counter = 0; TEST(FixedArrayTest, CopyCtor) { absl::FixedArray<int, 10> on_stack(5); std::iota(on_stack.begin(), on_stack.end(), 0); absl::FixedArray<int, 10> stack_copy = on_stack; EXPECT_THAT(stack_copy, ElementsAreArray(on_stack)); EXPECT_TRUE(IsOnStack(stack_copy)); absl::FixedArray<int, 10> allocated(15); std::iota(allocated.begin(), allocated.end(), 0); absl::FixedArray<int, 10> alloced_copy = allocated; EXPECT_THAT(alloced_copy, ElementsAreArray(allocated)); EXPECT_FALSE(IsOnStack(alloced_copy)); } TEST(FixedArrayTest, MoveCtor) { absl::FixedArray<std::unique_ptr<int>, 10> on_stack(5); for (int i = 0; i < 5; ++i) { on_stack[i] = absl::make_unique<int>(i); } absl::FixedArray<std::unique_ptr<int>, 10> stack_copy = std::move(on_stack); for (int i = 0; i < 5; ++i) EXPECT_EQ(*(stack_copy[i]), i); EXPECT_EQ(stack_copy.size(), on_stack.size()); absl::FixedArray<std::unique_ptr<int>, 10> allocated(15); for (int i = 0; i < 15; ++i) { allocated[i] = absl::make_unique<int>(i); } absl::FixedArray<std::unique_ptr<int>, 10> alloced_copy = std::move(allocated); for (int i = 0; i < 15; ++i) EXPECT_EQ(*(alloced_copy[i]), i); EXPECT_EQ(allocated.size(), alloced_copy.size()); } TEST(FixedArrayTest, SmallObjects) { { absl::FixedArray<int> array(4); EXPECT_TRUE(IsOnStack(array)); } { absl::FixedArray<int> array(1048576); EXPECT_FALSE(IsOnStack(array)); } { absl::FixedArray<int, 100> array(100); EXPECT_TRUE(IsOnStack(array)); } { absl::FixedArray<int, 100> array(101); EXPECT_FALSE(IsOnStack(array)); } { absl::FixedArray<int> array1(0); absl::FixedArray<char> array2(0); EXPECT_LE(sizeof(array1), sizeof(array2) + 100); EXPECT_LE(sizeof(array2), sizeof(array1) + 100); } { absl::FixedArray<std::vector<int>> array(2); EXPECT_EQ(0, array[0].size()); EXPECT_EQ(0, array[1].size()); } { ThreeInts::counter = 1; absl::FixedArray<ThreeInts> array(2); EXPECT_EQ(1, array[0].x_); EXPECT_EQ(1, array[0].y_); EXPECT_EQ(1, array[0].z_); EXPECT_EQ(2, array[1].x_); EXPECT_EQ(2, array[1].y_); EXPECT_EQ(2, array[1].z_); } } TEST(FixedArrayTest, AtThrows) { absl::FixedArray<int> a = {1, 2, 3}; EXPECT_EQ(a.at(2), 3); ABSL_BASE_INTERNAL_EXPECT_FAIL(a.at(3), std::out_of_range, "failed bounds check"); } TEST(FixedArrayTest, Hardened) { #if !defined(NDEBUG) || ABSL_OPTION_HARDENED absl::FixedArray<int> a = {1, 2, 3}; EXPECT_EQ(a[2], 3); EXPECT_DEATH_IF_SUPPORTED(a[3], ""); EXPECT_DEATH_IF_SUPPORTED(a[-1], ""); absl::FixedArray<int> empty(0); EXPECT_DEATH_IF_SUPPORTED(empty[0], ""); EXPECT_DEATH_IF_SUPPORTED(empty[-1], ""); EXPECT_DEATH_IF_SUPPORTED(empty.front(), ""); EXPECT_DEATH_IF_SUPPORTED(empty.back(), ""); #endif } TEST(FixedArrayRelationalsTest, EqualArrays) { for (int i = 0; i < 10; ++i) { absl::FixedArray<int, 5> a1(i); std::iota(a1.begin(), a1.end(), 0); absl::FixedArray<int, 5> a2(a1.begin(), a1.end()); EXPECT_TRUE(a1 == a2); EXPECT_FALSE(a1 != a2); EXPECT_TRUE(a2 == a1); EXPECT_FALSE(a2 != a1); EXPECT_FALSE(a1 < a2); EXPECT_FALSE(a1 > a2); EXPECT_FALSE(a2 < a1); EXPECT_FALSE(a2 > a1); EXPECT_TRUE(a1 <= a2); EXPECT_TRUE(a1 >= a2); EXPECT_TRUE(a2 <= a1); EXPECT_TRUE(a2 >= a1); } } TEST(FixedArrayRelationalsTest, UnequalArrays) { for (int i = 1; i < 10; ++i) { absl::FixedArray<int, 5> a1(i); std::iota(a1.begin(), a1.end(), 0); absl::FixedArray<int, 5> a2(a1.begin(), a1.end()); --a2[i / 2]; EXPECT_FALSE(a1 == a2); EXPECT_TRUE(a1 != a2); EXPECT_FALSE(a2 == a1); EXPECT_TRUE(a2 != a1); EXPECT_FALSE(a1 < a2); EXPECT_TRUE(a1 > a2); EXPECT_TRUE(a2 < a1); EXPECT_FALSE(a2 > a1); EXPECT_FALSE(a1 <= a2); EXPECT_TRUE(a1 >= a2); EXPECT_TRUE(a2 <= a1); EXPECT_FALSE(a2 >= a1); } } template <int stack_elements> static void TestArray(int n) { SCOPED_TRACE(n); SCOPED_TRACE(stack_elements); ConstructionTester::constructions = 0; ConstructionTester::destructions = 0; { absl::FixedArray<ConstructionTester, stack_elements> array(n); EXPECT_THAT(array.size(), n); EXPECT_THAT(array.memsize(), sizeof(ConstructionTester) * n); EXPECT_THAT(array.begin() + n, array.end()); for (int i = 0; i < n; i++) { array[i].CheckConstructed(); } EXPECT_THAT(ConstructionTester::constructions, n); for (int i = 0; i < n; i++) { array[i].set(i); } for (int i = 0; i < n; i++) { EXPECT_THAT(array[i].get(), i); EXPECT_THAT(array.data()[i].get(), i); } for (int i = 0; i < n; i++) { array.data()[i].set(i + 1); } for (int i = 0; i < n; i++) { EXPECT_THAT(array[i].get(), i + 1); EXPECT_THAT(array.data()[i].get(), i + 1); } } EXPECT_EQ(ConstructionTester::constructions, ConstructionTester::destructions); } template <int elements_per_inner_array, int inline_elements> static void TestArrayOfArrays(int n) { SCOPED_TRACE(n); SCOPED_TRACE(inline_elements); SCOPED_TRACE(elements_per_inner_array); ConstructionTester::constructions = 0; ConstructionTester::destructions = 0; { using InnerArray = ConstructionTester[elements_per_inner_array]; auto array_ptr = absl::make_unique<absl::FixedArray<InnerArray, inline_elements>>(n); auto& array = *array_ptr; ASSERT_EQ(array.size(), n); ASSERT_EQ(array.memsize(), sizeof(ConstructionTester) * elements_per_inner_array * n); ASSERT_EQ(array.begin() + n, array.end()); for (int i = 0; i < n; i++) { for (int j = 0; j < elements_per_inner_array; j++) { (array[i])[j].CheckConstructed(); } } ASSERT_EQ(ConstructionTester::constructions, n * elements_per_inner_array); for (int i = 0; i < n; i++) { for (int j = 0; j < elements_per_inner_array; j++) { (array[i])[j].set(i * elements_per_inner_array + j); } } for (int i = 0; i < n; i++) { for (int j = 0; j < elements_per_inner_array; j++) { ASSERT_EQ((array[i])[j].get(), i * elements_per_inner_array + j); ASSERT_EQ((array.data()[i])[j].get(), i * elements_per_inner_array + j); } } for (int i = 0; i < n; i++) { for (int j = 0; j < elements_per_inner_array; j++) { (array.data()[i])[j].set((i + 1) * elements_per_inner_array + j); } } for (int i = 0; i < n; i++) { for (int j = 0; j < elements_per_inner_array; j++) { ASSERT_EQ((array[i])[j].get(), (i + 1) * elements_per_inner_array + j); ASSERT_EQ((array.data()[i])[j].get(), (i + 1) * elements_per_inner_array + j); } } } EXPECT_EQ(ConstructionTester::constructions, ConstructionTester::destructions); } TEST(IteratorConstructorTest, NonInline) { int const kInput[] = {2, 3, 5, 7, 11, 13, 17}; absl::FixedArray<int, ABSL_ARRAYSIZE(kInput) - 1> const fixed( kInput, kInput + ABSL_ARRAYSIZE(kInput)); ASSERT_EQ(ABSL_ARRAYSIZE(kInput), fixed.size()); for (size_t i = 0; i < ABSL_ARRAYSIZE(kInput); ++i) { ASSERT_EQ(kInput[i], fixed[i]); } } TEST(IteratorConstructorTest, Inline) { int const kInput[] = {2, 3, 5, 7, 11, 13, 17}; absl::FixedArray<int, ABSL_ARRAYSIZE(kInput)> const fixed( kInput, kInput + ABSL_ARRAYSIZE(kInput)); ASSERT_EQ(ABSL_ARRAYSIZE(kInput), fixed.size()); for (size_t i = 0; i < ABSL_ARRAYSIZE(kInput); ++i) { ASSERT_EQ(kInput[i], fixed[i]); } } TEST(IteratorConstructorTest, NonPod) { char const* kInput[] = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"}; absl::FixedArray<std::string> const fixed(kInput, kInput + ABSL_ARRAYSIZE(kInput)); ASSERT_EQ(ABSL_ARRAYSIZE(kInput), fixed.size()); for (size_t i = 0; i < ABSL_ARRAYSIZE(kInput); ++i) { ASSERT_EQ(kInput[i], fixed[i]); } } TEST(IteratorConstructorTest, FromEmptyVector) { std::vector<int> const empty; absl::FixedArray<int> const fixed(empty.begin(), empty.end()); EXPECT_EQ(0, fixed.size()); EXPECT_EQ(empty.size(), fixed.size()); } TEST(IteratorConstructorTest, FromNonEmptyVector) { int const kInput[] = {2, 3, 5, 7, 11, 13, 17}; std::vector<int> const items(kInput, kInput + ABSL_ARRAYSIZE(kInput)); absl::FixedArray<int> const fixed(items.begin(), items.end()); ASSERT_EQ(items.size(), fixed.size()); for (size_t i = 0; i < items.size(); ++i) { ASSERT_EQ(items[i], fixed[i]); } } TEST(IteratorConstructorTest, FromBidirectionalIteratorRange) { int const kInput[] = {2, 3, 5, 7, 11, 13, 17}; std::list<int> const items(kInput, kInput + ABSL_ARRAYSIZE(kInput)); absl::FixedArray<int> const fixed(items.begin(), items.end()); EXPECT_THAT(fixed, testing::ElementsAreArray(kInput)); } TEST(InitListConstructorTest, InitListConstruction) { absl::FixedArray<int> fixed = {1, 2, 3}; EXPECT_THAT(fixed, testing::ElementsAreArray({1, 2, 3})); } TEST(FillConstructorTest, NonEmptyArrays) { absl::FixedArray<int> stack_array(4, 1); EXPECT_THAT(stack_array, testing::ElementsAreArray({1, 1, 1, 1})); absl::FixedArray<int, 0> heap_array(4, 1); EXPECT_THAT(stack_array, testing::ElementsAreArray({1, 1, 1, 1})); } TEST(FillConstructorTest, EmptyArray) { absl::FixedArray<int> empty_fill(0, 1); absl::FixedArray<int> empty_size(0); EXPECT_EQ(empty_fill, empty_size); } TEST(FillConstructorTest, NotTriviallyCopyable) { std::string str = "abcd"; absl::FixedArray<std::string> strings = {str, str, str, str}; absl::FixedArray<std::string> array(4, str); EXPECT_EQ(array, strings); } TEST(FillConstructorTest, Disambiguation) { absl::FixedArray<size_t> a(1, 2); EXPECT_THAT(a, testing::ElementsAre(2)); } TEST(FixedArrayTest, ManySizedArrays) { std::vector<int> sizes; for (int i = 1; i < 100; i++) sizes.push_back(i); for (int i = 100; i <= 1000; i += 100) sizes.push_back(i); for (int n : sizes) { TestArray<0>(n); TestArray<1>(n); TestArray<64>(n); TestArray<1000>(n); } } TEST(FixedArrayTest, ManySizedArraysOfArraysOf1) { for (int n = 1; n < 1000; n++) { ASSERT_NO_FATAL_FAILURE((TestArrayOfArrays<1, 0>(n))); ASSERT_NO_FATAL_FAILURE((TestArrayOfArrays<1, 1>(n))); ASSERT_NO_FATAL_FAILURE((TestArrayOfArrays<1, 64>(n))); ASSERT_NO_FATAL_FAILURE((TestArrayOfArrays<1, 1000>(n))); } } TEST(FixedArrayTest, ManySizedArraysOfArraysOf2) { for (int n = 1; n < 1000; n++) { TestArrayOfArrays<2, 0>(n); TestArrayOfArrays<2, 1>(n); TestArrayOfArrays<2, 64>(n); TestArrayOfArrays<2, 1000>(n); } } TEST(FixedArrayTest, AvoidParanoidDiagnostics) { absl::FixedArray<char, 32> buf(32); sprintf(buf.data(), "foo"); } TEST(FixedArrayTest, TooBigInlinedSpace) { struct TooBig { char c[1 << 20]; }; struct Data { TooBig* p; size_t size; }; static_assert(sizeof(absl::FixedArray<TooBig, 0>) == sizeof(Data), "0-sized absl::FixedArray should have same size as Data."); static_assert(alignof(absl::FixedArray<TooBig, 0>) == alignof(Data), "0-sized absl::FixedArray should have same alignment as Data."); static_assert(sizeof(absl::FixedArray<TooBig>) == sizeof(Data), "default-sized absl::FixedArray should have same size as Data"); static_assert( alignof(absl::FixedArray<TooBig>) == alignof(Data), "default-sized absl::FixedArray should have same alignment as Data."); } struct PickyDelete { PickyDelete() {} ~PickyDelete() {} void operator delete(void* p) { EXPECT_TRUE(false) << __FUNCTION__; ::operator delete(p); } void operator delete[](void* p) { EXPECT_TRUE(false) << __FUNCTION__; ::operator delete[](p); } }; TEST(FixedArrayTest, UsesGlobalAlloc) { absl::FixedArray<PickyDelete, 0> a(5); } TEST(FixedArrayTest, Data) { static const int kInput[] = {2, 3, 5, 7, 11, 13, 17}; absl::FixedArray<int> fa(std::begin(kInput), std::end(kInput)); EXPECT_EQ(fa.data(), &*fa.begin()); EXPECT_EQ(fa.data(), &fa[0]); const absl::FixedArray<int>& cfa = fa; EXPECT_EQ(cfa.data(), &*cfa.begin()); EXPECT_EQ(cfa.data(), &cfa[0]); } TEST(FixedArrayTest, Empty) { absl::FixedArray<int> empty(0); absl::FixedArray<int> inline_filled(1); absl::FixedArray<int, 0> heap_filled(1); EXPECT_TRUE(empty.empty()); EXPECT_FALSE(inline_filled.empty()); EXPECT_FALSE(heap_filled.empty()); } TEST(FixedArrayTest, FrontAndBack) { absl::FixedArray<int, 3 * sizeof(int)> inlined = {1, 2, 3}; EXPECT_EQ(inlined.front(), 1); EXPECT_EQ(inlined.back(), 3); absl::FixedArray<int, 0> allocated = {1, 2, 3}; EXPECT_EQ(allocated.front(), 1); EXPECT_EQ(allocated.back(), 3); absl::FixedArray<int> one_element = {1}; EXPECT_EQ(one_element.front(), one_element.back()); } TEST(FixedArrayTest, ReverseIteratorInlined) { absl::FixedArray<int, 5 * sizeof(int)> a = {0, 1, 2, 3, 4}; int counter = 5; for (absl::FixedArray<int>::reverse_iterator iter = a.rbegin(); iter != a.rend(); ++iter) { counter--; EXPECT_EQ(counter, *iter); } EXPECT_EQ(counter, 0); counter = 5; for (absl::FixedArray<int>::const_reverse_iterator iter = a.rbegin(); iter != a.rend(); ++iter) { counter--; EXPECT_EQ(counter, *iter); } EXPECT_EQ(counter, 0); counter = 5; for (auto iter = a.crbegin(); iter != a.crend(); ++iter) { counter--; EXPECT_EQ(counter, *iter); } EXPECT_EQ(counter, 0); } TEST(FixedArrayTest, ReverseIteratorAllocated) { absl::FixedArray<int, 0> a = {0, 1, 2, 3, 4}; int counter = 5; for (absl::FixedArray<int>::reverse_iterator iter = a.rbegin(); iter != a.rend(); ++iter) { counter--; EXPECT_EQ(counter, *iter); } EXPECT_EQ(counter, 0); counter = 5; for (absl::FixedArray<int>::const_reverse_iterator iter = a.rbegin(); iter != a.rend(); ++iter) { counter--; EXPECT_EQ(counter, *iter); } EXPECT_EQ(counter, 0); counter = 5; for (auto iter = a.crbegin(); iter != a.crend(); ++iter) { counter--; EXPECT_EQ(counter, *iter); } EXPECT_EQ(counter, 0); } TEST(FixedArrayTest, Fill) { absl::FixedArray<int, 5 * sizeof(int)> inlined(5); int fill_val = 42; inlined.fill(fill_val); for (int i : inlined) EXPECT_EQ(i, fill_val); absl::FixedArray<int, 0> allocated(5); allocated.fill(fill_val); for (int i : allocated) EXPECT_EQ(i, fill_val); absl::FixedArray<int> empty(0); empty.fill(fill_val); } #ifndef __GNUC__ TEST(FixedArrayTest, DefaultCtorDoesNotValueInit) { using T = char; constexpr auto capacity = 10; using FixedArrType = absl::FixedArray<T, capacity>; constexpr auto scrubbed_bits = 0x95; constexpr auto length = capacity / 2; alignas(FixedArrType) unsigned char buff[sizeof(FixedArrType)]; std::memset(std::addressof(buff), scrubbed_bits, sizeof(FixedArrType)); FixedArrType* arr = ::new (static_cast<void*>(std::addressof(buff))) FixedArrType(length); EXPECT_THAT(*arr, testing::Each(scrubbed_bits)); arr->~FixedArrType(); } #endif TEST(AllocatorSupportTest, CountInlineAllocations) { constexpr size_t inlined_size = 4; using Alloc = absl::container_internal::CountingAllocator<int>; using AllocFxdArr = absl::FixedArray<int, inlined_size, Alloc>; int64_t allocated = 0; int64_t active_instances = 0; { const int ia[] = {0, 1, 2, 3, 4, 5, 6, 7}; Alloc alloc(&allocated, &active_instances); AllocFxdArr arr(ia, ia + inlined_size, alloc); static_cast<void>(arr); } EXPECT_EQ(allocated, 0); EXPECT_EQ(active_instances, 0); } TEST(AllocatorSupportTest, CountOutoflineAllocations) { constexpr size_t inlined_size = 4; using Alloc = absl::container_internal::CountingAllocator<int>; using AllocFxdArr = absl::FixedArray<int, inlined_size, Alloc>; int64_t allocated = 0; int64_t active_instances = 0; { const int ia[] = {0, 1, 2, 3, 4, 5, 6, 7}; Alloc alloc(&allocated, &active_instances); AllocFxdArr arr(ia, ia + ABSL_ARRAYSIZE(ia), alloc); EXPECT_EQ(allocated, arr.size() * sizeof(int)); static_cast<void>(arr); } EXPECT_EQ(active_instances, 0); } TEST(AllocatorSupportTest, CountCopyInlineAllocations) { constexpr size_t inlined_size = 4; using Alloc = absl::container_internal::CountingAllocator<int>; using AllocFxdArr = absl::FixedArray<int, inlined_size, Alloc>; int64_t allocated1 = 0; int64_t allocated2 = 0; int64_t active_instances = 0; Alloc alloc(&allocated1, &active_instances); Alloc alloc2(&allocated2, &active_instances); { int initial_value = 1; AllocFxdArr arr1(inlined_size / 2, initial_value, alloc); EXPECT_EQ(allocated1, 0); AllocFxdArr arr2(arr1, alloc2); EXPECT_EQ(allocated2, 0); static_cast<void>(arr1); static_cast<void>(arr2); } EXPECT_EQ(active_instances, 0); } TEST(AllocatorSupportTest, CountCopyOutoflineAllocations) { constexpr size_t inlined_size = 4; using Alloc = absl::container_internal::CountingAllocator<int>; using AllocFxdArr = absl::FixedArray<int, inlined_size, Alloc>; int64_t allocated1 = 0; int64_t allocated2 = 0; int64_t active_instances = 0; Alloc alloc(&allocated1, &active_instances); Alloc alloc2(&allocated2, &active_instances); { int initial_value = 1; AllocFxdArr arr1(inlined_size * 2, initial_value, alloc); EXPECT_EQ(allocated1, arr1.size() * sizeof(int)); AllocFxdArr arr2(arr1, alloc2); EXPECT_EQ(allocated2, inlined_size * 2 * sizeof(int)); static_cast<void>(arr1); static_cast<void>(arr2); } EXPECT_EQ(active_instances, 0); } TEST(AllocatorSupportTest, SizeValAllocConstructor) { using testing::AllOf; using testing::Each; using testing::SizeIs; constexpr size_t inlined_size = 4; using Alloc = absl::container_internal::CountingAllocator<int>; using AllocFxdArr = absl::FixedArray<int, inlined_size, Alloc>; { auto len = inlined_size / 2; auto val = 0; int64_t allocated = 0; AllocFxdArr arr(len, val, Alloc(&allocated)); EXPECT_EQ(allocated, 0); EXPECT_THAT(arr, AllOf(SizeIs(len), Each(0))); } { auto len = inlined_size * 2; auto val = 0; int64_t allocated = 0; AllocFxdArr arr(len, val, Alloc(&allocated)); EXPECT_EQ(allocated, len * sizeof(int)); EXPECT_THAT(arr, AllOf(SizeIs(len), Each(0))); } } TEST(AllocatorSupportTest, PropagatesStatefulAllocator) { constexpr size_t inlined_size = 4; using Alloc = absl::container_internal::CountingAllocator<int>; using AllocFxdArr = absl::FixedArray<int, inlined_size, Alloc>; auto len = inlined_size * 2; auto val = 0; int64_t allocated = 0; AllocFxdArr arr(len, val, Alloc(&allocated)); EXPECT_EQ(allocated, len * sizeof(int)); AllocFxdArr copy = arr; EXPECT_EQ(allocated, len * sizeof(int) * 2); } #ifdef ABSL_HAVE_ADDRESS_SANITIZER TEST(FixedArrayTest, AddressSanitizerAnnotations1) { absl::FixedArray<int, 32> a(10); int* raw = a.data(); raw[0] = 0; raw[9] = 0; EXPECT_DEATH_IF_SUPPORTED(raw[-2] = 0, "container-overflow"); EXPECT_DEATH_IF_SUPPORTED(raw[-1] = 0, "container-overflow"); EXPECT_DEATH_IF_SUPPORTED(raw[10] = 0, "container-overflow"); EXPECT_DEATH_IF_SUPPORTED(raw[31] = 0, "container-overflow"); } TEST(FixedArrayTest, AddressSanitizerAnnotations2) { absl::FixedArray<char, 17> a(12); char* raw = a.data(); raw[0] = 0; raw[11] = 0; EXPECT_DEATH_IF_SUPPORTED(raw[-7] = 0, "container-overflow"); EXPECT_DEATH_IF_SUPPORTED(raw[-1] = 0, "container-overflow"); EXPECT_DEATH_IF_SUPPORTED(raw[12] = 0, "container-overflow"); EXPECT_DEATH_IF_SUPPORTED(raw[17] = 0, "container-overflow"); } TEST(FixedArrayTest, AddressSanitizerAnnotations3) { absl::FixedArray<uint64_t, 20> a(20); uint64_t* raw = a.data(); raw[0] = 0; raw[19] = 0; EXPECT_DEATH_IF_SUPPORTED(raw[-1] = 0, "container-overflow"); EXPECT_DEATH_IF_SUPPORTED(raw[20] = 0, "container-overflow"); } TEST(FixedArrayTest, AddressSanitizerAnnotations4) { absl::FixedArray<ThreeInts> a(10); ThreeInts* raw = a.data(); raw[0] = ThreeInts(); raw[9] = ThreeInts(); EXPECT_DEATH_IF_SUPPORTED(raw[-1].z_ = 0, "container-overflow"); EXPECT_DEATH_IF_SUPPORTED(raw[10] = ThreeInts(), "container-overflow"); EXPECT_DEATH_IF_SUPPORTED(raw[21] = ThreeInts(), "container-overflow"); } #endif TEST(FixedArrayTest, AbslHashValueWorks) { using V = absl::FixedArray<int>; std::vector<V> cases; for (int i = 0; i < 10; ++i) { V v(i); for (int j = 0; j < i; ++j) { v[j] = j; } cases.push_back(v); } EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(cases)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/fixed_array.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/fixed_array_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
1d8752e4-7dbe-4dac-8754-ecd8df904db3
cpp
abseil/abseil-cpp
inlined_vector
absl/container/internal/inlined_vector.h
absl/container/inlined_vector_test.cc
#ifndef ABSL_CONTAINER_INTERNAL_INLINED_VECTOR_H_ #define ABSL_CONTAINER_INTERNAL_INLINED_VECTOR_H_ #include <algorithm> #include <cstddef> #include <cstring> #include <iterator> #include <limits> #include <memory> #include <new> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/base/internal/identity.h" #include "absl/base/macros.h" #include "absl/container/internal/compressed_tuple.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/types/span.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace inlined_vector_internal { #if !defined(__clang__) && defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Warray-bounds" #endif template <typename A> using AllocatorTraits = std::allocator_traits<A>; template <typename A> using ValueType = typename AllocatorTraits<A>::value_type; template <typename A> using SizeType = typename AllocatorTraits<A>::size_type; template <typename A> using Pointer = typename AllocatorTraits<A>::pointer; template <typename A> using ConstPointer = typename AllocatorTraits<A>::const_pointer; template <typename A> using SizeType = typename AllocatorTraits<A>::size_type; template <typename A> using DifferenceType = typename AllocatorTraits<A>::difference_type; template <typename A> using Reference = ValueType<A>&; template <typename A> using ConstReference = const ValueType<A>&; template <typename A> using Iterator = Pointer<A>; template <typename A> using ConstIterator = ConstPointer<A>; template <typename A> using ReverseIterator = typename std::reverse_iterator<Iterator<A>>; template <typename A> using ConstReverseIterator = typename std::reverse_iterator<ConstIterator<A>>; template <typename A> using MoveIterator = typename std::move_iterator<Iterator<A>>; template <typename Iterator> using IsAtLeastForwardIterator = std::is_convertible< typename std::iterator_traits<Iterator>::iterator_category, std::forward_iterator_tag>; template <typename A> using IsMoveAssignOk = std::is_move_assignable<ValueType<A>>; template <typename A> using IsSwapOk = absl::type_traits_internal::IsSwappable<ValueType<A>>; template <typename A, bool IsTriviallyDestructible = absl::is_trivially_destructible<ValueType<A>>::value> struct DestroyAdapter; template <typename A> struct DestroyAdapter<A, false> { static void DestroyElements(A& allocator, Pointer<A> destroy_first, SizeType<A> destroy_size) { for (SizeType<A> i = destroy_size; i != 0;) { --i; AllocatorTraits<A>::destroy(allocator, destroy_first + i); } } }; template <typename A> struct DestroyAdapter<A, true> { static void DestroyElements(A& allocator, Pointer<A> destroy_first, SizeType<A> destroy_size) { static_cast<void>(allocator); static_cast<void>(destroy_first); static_cast<void>(destroy_size); } }; template <typename A> struct Allocation { Pointer<A> data = nullptr; SizeType<A> capacity = 0; }; template <typename A, bool IsOverAligned = (alignof(ValueType<A>) > ABSL_INTERNAL_DEFAULT_NEW_ALIGNMENT)> struct MallocAdapter { static Allocation<A> Allocate(A& allocator, SizeType<A> requested_capacity) { return {AllocatorTraits<A>::allocate(allocator, requested_capacity), requested_capacity}; } static void Deallocate(A& allocator, Pointer<A> pointer, SizeType<A> capacity) { AllocatorTraits<A>::deallocate(allocator, pointer, capacity); } }; template <typename A, typename ValueAdapter> void ConstructElements(absl::internal::type_identity_t<A>& allocator, Pointer<A> construct_first, ValueAdapter& values, SizeType<A> construct_size) { for (SizeType<A> i = 0; i < construct_size; ++i) { ABSL_INTERNAL_TRY { values.ConstructNext(allocator, construct_first + i); } ABSL_INTERNAL_CATCH_ANY { DestroyAdapter<A>::DestroyElements(allocator, construct_first, i); ABSL_INTERNAL_RETHROW; } } } template <typename A, typename ValueAdapter> void AssignElements(Pointer<A> assign_first, ValueAdapter& values, SizeType<A> assign_size) { for (SizeType<A> i = 0; i < assign_size; ++i) { values.AssignNext(assign_first + i); } } template <typename A> struct StorageView { Pointer<A> data; SizeType<A> size; SizeType<A> capacity; }; template <typename A, typename Iterator> class IteratorValueAdapter { public: explicit IteratorValueAdapter(const Iterator& it) : it_(it) {} void ConstructNext(A& allocator, Pointer<A> construct_at) { AllocatorTraits<A>::construct(allocator, construct_at, *it_); ++it_; } void AssignNext(Pointer<A> assign_at) { *assign_at = *it_; ++it_; } private: Iterator it_; }; template <typename A> class CopyValueAdapter { public: explicit CopyValueAdapter(ConstPointer<A> p) : ptr_(p) {} void ConstructNext(A& allocator, Pointer<A> construct_at) { AllocatorTraits<A>::construct(allocator, construct_at, *ptr_); } void AssignNext(Pointer<A> assign_at) { *assign_at = *ptr_; } private: ConstPointer<A> ptr_; }; template <typename A> class DefaultValueAdapter { public: explicit DefaultValueAdapter() {} void ConstructNext(A& allocator, Pointer<A> construct_at) { AllocatorTraits<A>::construct(allocator, construct_at); } void AssignNext(Pointer<A> assign_at) { *assign_at = ValueType<A>(); } }; template <typename A> class AllocationTransaction { public: explicit AllocationTransaction(A& allocator) : allocator_data_(allocator, nullptr), capacity_(0) {} ~AllocationTransaction() { if (DidAllocate()) { MallocAdapter<A>::Deallocate(GetAllocator(), GetData(), GetCapacity()); } } AllocationTransaction(const AllocationTransaction&) = delete; void operator=(const AllocationTransaction&) = delete; A& GetAllocator() { return allocator_data_.template get<0>(); } Pointer<A>& GetData() { return allocator_data_.template get<1>(); } SizeType<A>& GetCapacity() { return capacity_; } bool DidAllocate() { return GetData() != nullptr; } Pointer<A> Allocate(SizeType<A> requested_capacity) { Allocation<A> result = MallocAdapter<A>::Allocate(GetAllocator(), requested_capacity); GetData() = result.data; GetCapacity() = result.capacity; return result.data; } ABSL_MUST_USE_RESULT Allocation<A> Release() && { Allocation<A> result = {GetData(), GetCapacity()}; Reset(); return result; } private: void Reset() { GetData() = nullptr; GetCapacity() = 0; } container_internal::CompressedTuple<A, Pointer<A>> allocator_data_; SizeType<A> capacity_; }; template <typename A> class ConstructionTransaction { public: explicit ConstructionTransaction(A& allocator) : allocator_data_(allocator, nullptr), size_(0) {} ~ConstructionTransaction() { if (DidConstruct()) { DestroyAdapter<A>::DestroyElements(GetAllocator(), GetData(), GetSize()); } } ConstructionTransaction(const ConstructionTransaction&) = delete; void operator=(const ConstructionTransaction&) = delete; A& GetAllocator() { return allocator_data_.template get<0>(); } Pointer<A>& GetData() { return allocator_data_.template get<1>(); } SizeType<A>& GetSize() { return size_; } bool DidConstruct() { return GetData() != nullptr; } template <typename ValueAdapter> void Construct(Pointer<A> data, ValueAdapter& values, SizeType<A> size) { ConstructElements<A>(GetAllocator(), data, values, size); GetData() = data; GetSize() = size; } void Commit() && { GetData() = nullptr; GetSize() = 0; } private: container_internal::CompressedTuple<A, Pointer<A>> allocator_data_; SizeType<A> size_; }; template <typename T, size_t N, typename A> class Storage { public: struct MemcpyPolicy {}; struct ElementwiseAssignPolicy {}; struct ElementwiseSwapPolicy {}; struct ElementwiseConstructPolicy {}; using MoveAssignmentPolicy = absl::conditional_t< absl::conjunction<absl::is_trivially_move_assignable<ValueType<A>>, absl::is_trivially_destructible<ValueType<A>>, std::is_same<A, std::allocator<ValueType<A>>>>::value, MemcpyPolicy, absl::conditional_t<IsMoveAssignOk<A>::value, ElementwiseAssignPolicy, ElementwiseConstructPolicy>>; using SwapInlinedElementsPolicy = absl::conditional_t< absl::conjunction<absl::is_trivially_relocatable<ValueType<A>>, std::is_same<A, std::allocator<ValueType<A>>>>::value, MemcpyPolicy, absl::conditional_t<IsSwapOk<A>::value, ElementwiseSwapPolicy, ElementwiseConstructPolicy>>; static SizeType<A> NextCapacity(SizeType<A> current_capacity) { return current_capacity * 2; } static SizeType<A> ComputeCapacity(SizeType<A> current_capacity, SizeType<A> requested_capacity) { return (std::max)(NextCapacity(current_capacity), requested_capacity); } Storage() : metadata_(A(), 0u) {} explicit Storage(const A& allocator) : metadata_(allocator, 0u) {} ~Storage() { if (GetSizeAndIsAllocated() == 0) { return; } if (absl::is_trivially_destructible<ValueType<A>>::value && std::is_same<A, std::allocator<ValueType<A>>>::value) { DeallocateIfAllocated(); return; } DestroyContents(); } SizeType<A>& GetSizeAndIsAllocated() { return metadata_.template get<1>(); } const SizeType<A>& GetSizeAndIsAllocated() const { return metadata_.template get<1>(); } SizeType<A> GetSize() const { return GetSizeAndIsAllocated() >> 1; } bool GetIsAllocated() const { return GetSizeAndIsAllocated() & 1; } Pointer<A> GetAllocatedData() { #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif return data_.allocated.allocated_data; #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(12, 0) #pragma GCC diagnostic pop #endif } ConstPointer<A> GetAllocatedData() const { return data_.allocated.allocated_data; } ABSL_ATTRIBUTE_NO_SANITIZE_CFI Pointer<A> GetInlinedData() { return reinterpret_cast<Pointer<A>>(data_.inlined.inlined_data); } ABSL_ATTRIBUTE_NO_SANITIZE_CFI ConstPointer<A> GetInlinedData() const { return reinterpret_cast<ConstPointer<A>>(data_.inlined.inlined_data); } SizeType<A> GetAllocatedCapacity() const { return data_.allocated.allocated_capacity; } SizeType<A> GetInlinedCapacity() const { return static_cast<SizeType<A>>(kOptimalInlinedSize); } StorageView<A> MakeStorageView() { return GetIsAllocated() ? StorageView<A>{GetAllocatedData(), GetSize(), GetAllocatedCapacity()} : StorageView<A>{GetInlinedData(), GetSize(), GetInlinedCapacity()}; } A& GetAllocator() { return metadata_.template get<0>(); } const A& GetAllocator() const { return metadata_.template get<0>(); } ABSL_ATTRIBUTE_NOINLINE void InitFrom(const Storage& other); template <typename ValueAdapter> void Initialize(ValueAdapter values, SizeType<A> new_size); template <typename ValueAdapter> void Assign(ValueAdapter values, SizeType<A> new_size); template <typename ValueAdapter> void Resize(ValueAdapter values, SizeType<A> new_size); template <typename ValueAdapter> Iterator<A> Insert(ConstIterator<A> pos, ValueAdapter values, SizeType<A> insert_count); template <typename... Args> Reference<A> EmplaceBack(Args&&... args); Iterator<A> Erase(ConstIterator<A> from, ConstIterator<A> to); void Reserve(SizeType<A> requested_capacity); void ShrinkToFit(); void Swap(Storage* other_storage_ptr); void SetIsAllocated() { GetSizeAndIsAllocated() |= static_cast<SizeType<A>>(1); } void UnsetIsAllocated() { GetSizeAndIsAllocated() &= ((std::numeric_limits<SizeType<A>>::max)() - 1); } void SetSize(SizeType<A> size) { GetSizeAndIsAllocated() = (size << 1) | static_cast<SizeType<A>>(GetIsAllocated()); } void SetAllocatedSize(SizeType<A> size) { GetSizeAndIsAllocated() = (size << 1) | static_cast<SizeType<A>>(1); } void SetInlinedSize(SizeType<A> size) { GetSizeAndIsAllocated() = size << static_cast<SizeType<A>>(1); } void AddSize(SizeType<A> count) { GetSizeAndIsAllocated() += count << static_cast<SizeType<A>>(1); } void SubtractSize(SizeType<A> count) { ABSL_HARDENING_ASSERT(count <= GetSize()); GetSizeAndIsAllocated() -= count << static_cast<SizeType<A>>(1); } void SetAllocation(Allocation<A> allocation) { data_.allocated.allocated_data = allocation.data; data_.allocated.allocated_capacity = allocation.capacity; } void MemcpyFrom(const Storage& other_storage) { { using V = ValueType<A>; ABSL_HARDENING_ASSERT( other_storage.GetIsAllocated() || (std::is_same<A, std::allocator<V>>::value && ( absl::is_trivially_relocatable<V>::value || (absl::is_trivially_move_assignable<V>::value && absl::is_trivially_destructible<V>::value) || (absl::is_trivially_copy_constructible<V>::value || absl::is_trivially_copy_assignable<V>::value)))); } GetSizeAndIsAllocated() = other_storage.GetSizeAndIsAllocated(); data_ = other_storage.data_; } void DeallocateIfAllocated() { if (GetIsAllocated()) { MallocAdapter<A>::Deallocate(GetAllocator(), GetAllocatedData(), GetAllocatedCapacity()); } } private: ABSL_ATTRIBUTE_NOINLINE void DestroyContents(); using Metadata = container_internal::CompressedTuple<A, SizeType<A>>; struct Allocated { Pointer<A> allocated_data; SizeType<A> allocated_capacity; }; static constexpr size_t kOptimalInlinedSize = (std::max)(N, sizeof(Allocated) / sizeof(ValueType<A>)); struct Inlined { alignas(ValueType<A>) char inlined_data[sizeof( ValueType<A>[kOptimalInlinedSize])]; }; union Data { Allocated allocated; Inlined inlined; }; void SwapN(ElementwiseSwapPolicy, Storage* other, SizeType<A> n); void SwapN(ElementwiseConstructPolicy, Storage* other, SizeType<A> n); void SwapInlinedElements(MemcpyPolicy, Storage* other); template <typename NotMemcpyPolicy> void SwapInlinedElements(NotMemcpyPolicy, Storage* other); template <typename... Args> ABSL_ATTRIBUTE_NOINLINE Reference<A> EmplaceBackSlow(Args&&... args); Metadata metadata_; Data data_; }; template <typename T, size_t N, typename A> void Storage<T, N, A>::DestroyContents() { Pointer<A> data = GetIsAllocated() ? GetAllocatedData() : GetInlinedData(); DestroyAdapter<A>::DestroyElements(GetAllocator(), data, GetSize()); DeallocateIfAllocated(); } template <typename T, size_t N, typename A> void Storage<T, N, A>::InitFrom(const Storage& other) { const SizeType<A> n = other.GetSize(); ABSL_HARDENING_ASSERT(n > 0); ConstPointer<A> src; Pointer<A> dst; if (!other.GetIsAllocated()) { dst = GetInlinedData(); src = other.GetInlinedData(); } else { SizeType<A> requested_capacity = ComputeCapacity(GetInlinedCapacity(), n); Allocation<A> allocation = MallocAdapter<A>::Allocate(GetAllocator(), requested_capacity); SetAllocation(allocation); dst = allocation.data; src = other.GetAllocatedData(); } if (absl::is_trivially_copy_constructible<ValueType<A>>::value && std::is_same<A, std::allocator<ValueType<A>>>::value) { std::memcpy(reinterpret_cast<char*>(dst), reinterpret_cast<const char*>(src), n * sizeof(ValueType<A>)); } else { auto values = IteratorValueAdapter<A, ConstPointer<A>>(src); ConstructElements<A>(GetAllocator(), dst, values, n); } GetSizeAndIsAllocated() = other.GetSizeAndIsAllocated(); } template <typename T, size_t N, typename A> template <typename ValueAdapter> auto Storage<T, N, A>::Initialize(ValueAdapter values, SizeType<A> new_size) -> void { ABSL_HARDENING_ASSERT(!GetIsAllocated()); ABSL_HARDENING_ASSERT(GetSize() == 0); Pointer<A> construct_data; if (new_size > GetInlinedCapacity()) { SizeType<A> requested_capacity = ComputeCapacity(GetInlinedCapacity(), new_size); Allocation<A> allocation = MallocAdapter<A>::Allocate(GetAllocator(), requested_capacity); construct_data = allocation.data; SetAllocation(allocation); SetIsAllocated(); } else { construct_data = GetInlinedData(); } ConstructElements<A>(GetAllocator(), construct_data, values, new_size); AddSize(new_size); } template <typename T, size_t N, typename A> template <typename ValueAdapter> auto Storage<T, N, A>::Assign(ValueAdapter values, SizeType<A> new_size) -> void { StorageView<A> storage_view = MakeStorageView(); AllocationTransaction<A> allocation_tx(GetAllocator()); absl::Span<ValueType<A>> assign_loop; absl::Span<ValueType<A>> construct_loop; absl::Span<ValueType<A>> destroy_loop; if (new_size > storage_view.capacity) { SizeType<A> requested_capacity = ComputeCapacity(storage_view.capacity, new_size); construct_loop = {allocation_tx.Allocate(requested_capacity), new_size}; destroy_loop = {storage_view.data, storage_view.size}; } else if (new_size > storage_view.size) { assign_loop = {storage_view.data, storage_view.size}; construct_loop = {storage_view.data + storage_view.size, new_size - storage_view.size}; } else { assign_loop = {storage_view.data, new_size}; destroy_loop = {storage_view.data + new_size, storage_view.size - new_size}; } AssignElements<A>(assign_loop.data(), values, assign_loop.size()); ConstructElements<A>(GetAllocator(), construct_loop.data(), values, construct_loop.size()); DestroyAdapter<A>::DestroyElements(GetAllocator(), destroy_loop.data(), destroy_loop.size()); if (allocation_tx.DidAllocate()) { DeallocateIfAllocated(); SetAllocation(std::move(allocation_tx).Release()); SetIsAllocated(); } SetSize(new_size); } template <typename T, size_t N, typename A> template <typename ValueAdapter> auto Storage<T, N, A>::Resize(ValueAdapter values, SizeType<A> new_size) -> void { StorageView<A> storage_view = MakeStorageView(); Pointer<A> const base = storage_view.data; const SizeType<A> size = storage_view.size; A& alloc = GetAllocator(); if (new_size <= size) { DestroyAdapter<A>::DestroyElements(alloc, base + new_size, size - new_size); } else if (new_size <= storage_view.capacity) { ConstructElements<A>(alloc, base + size, values, new_size - size); } else { AllocationTransaction<A> allocation_tx(alloc); SizeType<A> requested_capacity = ComputeCapacity(storage_view.capacity, new_size); Pointer<A> new_data = allocation_tx.Allocate(requested_capacity); ConstructionTransaction<A> construction_tx(alloc); construction_tx.Construct(new_data + size, values, new_size - size); IteratorValueAdapter<A, MoveIterator<A>> move_values( (MoveIterator<A>(base))); ConstructElements<A>(alloc, new_data, move_values, size); DestroyAdapter<A>::DestroyElements(alloc, base, size); std::move(construction_tx).Commit(); DeallocateIfAllocated(); SetAllocation(std::move(allocation_tx).Release()); SetIsAllocated(); } SetSize(new_size); } template <typename T, size_t N, typename A> template <typename ValueAdapter> auto Storage<T, N, A>::Insert(ConstIterator<A> pos, ValueAdapter values, SizeType<A> insert_count) -> Iterator<A> { StorageView<A> storage_view = MakeStorageView(); auto insert_index = static_cast<SizeType<A>>( std::distance(ConstIterator<A>(storage_view.data), pos)); SizeType<A> insert_end_index = insert_index + insert_count; SizeType<A> new_size = storage_view.size + insert_count; if (new_size > storage_view.capacity) { AllocationTransaction<A> allocation_tx(GetAllocator()); ConstructionTransaction<A> construction_tx(GetAllocator()); ConstructionTransaction<A> move_construction_tx(GetAllocator()); IteratorValueAdapter<A, MoveIterator<A>> move_values( MoveIterator<A>(storage_view.data)); SizeType<A> requested_capacity = ComputeCapacity(storage_view.capacity, new_size); Pointer<A> new_data = allocation_tx.Allocate(requested_capacity); construction_tx.Construct(new_data + insert_index, values, insert_count); move_construction_tx.Construct(new_data, move_values, insert_index); ConstructElements<A>(GetAllocator(), new_data + insert_end_index, move_values, storage_view.size - insert_index); DestroyAdapter<A>::DestroyElements(GetAllocator(), storage_view.data, storage_view.size); std::move(construction_tx).Commit(); std::move(move_construction_tx).Commit(); DeallocateIfAllocated(); SetAllocation(std::move(allocation_tx).Release()); SetAllocatedSize(new_size); return Iterator<A>(new_data + insert_index); } else { SizeType<A> move_construction_destination_index = (std::max)(insert_end_index, storage_view.size); ConstructionTransaction<A> move_construction_tx(GetAllocator()); IteratorValueAdapter<A, MoveIterator<A>> move_construction_values( MoveIterator<A>(storage_view.data + (move_construction_destination_index - insert_count))); absl::Span<ValueType<A>> move_construction = { storage_view.data + move_construction_destination_index, new_size - move_construction_destination_index}; Pointer<A> move_assignment_values = storage_view.data + insert_index; absl::Span<ValueType<A>> move_assignment = { storage_view.data + insert_end_index, move_construction_destination_index - insert_end_index}; absl::Span<ValueType<A>> insert_assignment = {move_assignment_values, move_construction.size()}; absl::Span<ValueType<A>> insert_construction = { insert_assignment.data() + insert_assignment.size(), insert_count - insert_assignment.size()}; move_construction_tx.Construct(move_construction.data(), move_construction_values, move_construction.size()); for (Pointer<A> destination = move_assignment.data() + move_assignment.size(), last_destination = move_assignment.data(), source = move_assignment_values + move_assignment.size(); ;) { --destination; --source; if (destination < last_destination) break; *destination = std::move(*source); } AssignElements<A>(insert_assignment.data(), values, insert_assignment.size()); ConstructElements<A>(GetAllocator(), insert_construction.data(), values, insert_construction.size()); std::move(move_construction_tx).Commit(); AddSize(insert_count); return Iterator<A>(storage_view.data + insert_index); } } template <typename T, size_t N, typename A> template <typename... Args> auto Storage<T, N, A>::EmplaceBack(Args&&... args) -> Reference<A> { StorageView<A> storage_view = MakeStorageView(); const SizeType<A> n = storage_view.size; if (ABSL_PREDICT_TRUE(n != storage_view.capacity)) { Pointer<A> last_ptr = storage_view.data + n; AllocatorTraits<A>::construct(GetAllocator(), last_ptr, std::forward<Args>(args)...); AddSize(1); return *last_ptr; } return EmplaceBackSlow(std::forward<Args>(args)...); } template <typename T, size_t N, typename A> template <typename... Args> auto Storage<T, N, A>::EmplaceBackSlow(Args&&... args) -> Reference<A> { StorageView<A> storage_view = MakeStorageView(); AllocationTransaction<A> allocation_tx(GetAllocator()); IteratorValueAdapter<A, MoveIterator<A>> move_values( MoveIterator<A>(storage_view.data)); SizeType<A> requested_capacity = NextCapacity(storage_view.capacity); Pointer<A> construct_data = allocation_tx.Allocate(requested_capacity); Pointer<A> last_ptr = construct_data + storage_view.size; AllocatorTraits<A>::construct(GetAllocator(), last_ptr, std::forward<Args>(args)...); ABSL_INTERNAL_TRY { ConstructElements<A>(GetAllocator(), allocation_tx.GetData(), move_values, storage_view.size); } ABSL_INTERNAL_CATCH_ANY { AllocatorTraits<A>::destroy(GetAllocator(), last_ptr); ABSL_INTERNAL_RETHROW; } DestroyAdapter<A>::DestroyElements(GetAllocator(), storage_view.data, storage_view.size); DeallocateIfAllocated(); SetAllocation(std::move(allocation_tx).Release()); SetIsAllocated(); AddSize(1); return *last_ptr; } template <typename T, size_t N, typename A> auto Storage<T, N, A>::Erase(ConstIterator<A> from, ConstIterator<A> to) -> Iterator<A> { StorageView<A> storage_view = MakeStorageView(); auto erase_size = static_cast<SizeType<A>>(std::distance(from, to)); auto erase_index = static_cast<SizeType<A>>( std::distance(ConstIterator<A>(storage_view.data), from)); SizeType<A> erase_end_index = erase_index + erase_size; if (absl::is_trivially_relocatable<ValueType<A>>::value && std::is_nothrow_destructible<ValueType<A>>::value && std::is_same<A, std::allocator<ValueType<A>>>::value) { DestroyAdapter<A>::DestroyElements( GetAllocator(), storage_view.data + erase_index, erase_size); std::memmove( reinterpret_cast<char*>(storage_view.data + erase_index), reinterpret_cast<const char*>(storage_view.data + erase_end_index), (storage_view.size - erase_end_index) * sizeof(ValueType<A>)); } else { IteratorValueAdapter<A, MoveIterator<A>> move_values( MoveIterator<A>(storage_view.data + erase_end_index)); AssignElements<A>(storage_view.data + erase_index, move_values, storage_view.size - erase_end_index); DestroyAdapter<A>::DestroyElements( GetAllocator(), storage_view.data + (storage_view.size - erase_size), erase_size); } SubtractSize(erase_size); return Iterator<A>(storage_view.data + erase_index); } template <typename T, size_t N, typename A> auto Storage<T, N, A>::Reserve(SizeType<A> requested_capacity) -> void { StorageView<A> storage_view = MakeStorageView(); if (ABSL_PREDICT_FALSE(requested_capacity <= storage_view.capacity)) return; AllocationTransaction<A> allocation_tx(GetAllocator()); IteratorValueAdapter<A, MoveIterator<A>> move_values( MoveIterator<A>(storage_view.data)); SizeType<A> new_requested_capacity = ComputeCapacity(storage_view.capacity, requested_capacity); Pointer<A> new_data = allocation_tx.Allocate(new_requested_capacity); ConstructElements<A>(GetAllocator(), new_data, move_values, storage_view.size); DestroyAdapter<A>::DestroyElements(GetAllocator(), storage_view.data, storage_view.size); DeallocateIfAllocated(); SetAllocation(std::move(allocation_tx).Release()); SetIsAllocated(); } template <typename T, size_t N, typename A> auto Storage<T, N, A>::ShrinkToFit() -> void { ABSL_HARDENING_ASSERT(GetIsAllocated()); StorageView<A> storage_view{GetAllocatedData(), GetSize(), GetAllocatedCapacity()}; if (ABSL_PREDICT_FALSE(storage_view.size == storage_view.capacity)) return; AllocationTransaction<A> allocation_tx(GetAllocator()); IteratorValueAdapter<A, MoveIterator<A>> move_values( MoveIterator<A>(storage_view.data)); Pointer<A> construct_data; if (storage_view.size > GetInlinedCapacity()) { SizeType<A> requested_capacity = storage_view.size; construct_data = allocation_tx.Allocate(requested_capacity); if (allocation_tx.GetCapacity() >= storage_view.capacity) { return; } } else { construct_data = GetInlinedData(); } ABSL_INTERNAL_TRY { ConstructElements<A>(GetAllocator(), construct_data, move_values, storage_view.size); } ABSL_INTERNAL_CATCH_ANY { SetAllocation({storage_view.data, storage_view.capacity}); ABSL_INTERNAL_RETHROW; } DestroyAdapter<A>::DestroyElements(GetAllocator(), storage_view.data, storage_view.size); MallocAdapter<A>::Deallocate(GetAllocator(), storage_view.data, storage_view.capacity); if (allocation_tx.DidAllocate()) { SetAllocation(std::move(allocation_tx).Release()); } else { UnsetIsAllocated(); } } template <typename T, size_t N, typename A> auto Storage<T, N, A>::Swap(Storage* other_storage_ptr) -> void { using std::swap; ABSL_HARDENING_ASSERT(this != other_storage_ptr); if (GetIsAllocated() && other_storage_ptr->GetIsAllocated()) { swap(data_.allocated, other_storage_ptr->data_.allocated); } else if (!GetIsAllocated() && !other_storage_ptr->GetIsAllocated()) { SwapInlinedElements(SwapInlinedElementsPolicy{}, other_storage_ptr); } else { Storage* allocated_ptr = this; Storage* inlined_ptr = other_storage_ptr; if (!allocated_ptr->GetIsAllocated()) swap(allocated_ptr, inlined_ptr); StorageView<A> allocated_storage_view{ allocated_ptr->GetAllocatedData(), allocated_ptr->GetSize(), allocated_ptr->GetAllocatedCapacity()}; IteratorValueAdapter<A, MoveIterator<A>> move_values( MoveIterator<A>(inlined_ptr->GetInlinedData())); ABSL_INTERNAL_TRY { ConstructElements<A>(inlined_ptr->GetAllocator(), allocated_ptr->GetInlinedData(), move_values, inlined_ptr->GetSize()); } ABSL_INTERNAL_CATCH_ANY { allocated_ptr->SetAllocation(Allocation<A>{ allocated_storage_view.data, allocated_storage_view.capacity}); ABSL_INTERNAL_RETHROW; } DestroyAdapter<A>::DestroyElements(inlined_ptr->GetAllocator(), inlined_ptr->GetInlinedData(), inlined_ptr->GetSize()); inlined_ptr->SetAllocation(Allocation<A>{allocated_storage_view.data, allocated_storage_view.capacity}); } swap(GetSizeAndIsAllocated(), other_storage_ptr->GetSizeAndIsAllocated()); swap(GetAllocator(), other_storage_ptr->GetAllocator()); } template <typename T, size_t N, typename A> void Storage<T, N, A>::SwapN(ElementwiseSwapPolicy, Storage* other, SizeType<A> n) { std::swap_ranges(GetInlinedData(), GetInlinedData() + n, other->GetInlinedData()); } template <typename T, size_t N, typename A> void Storage<T, N, A>::SwapN(ElementwiseConstructPolicy, Storage* other, SizeType<A> n) { Pointer<A> a = GetInlinedData(); Pointer<A> b = other->GetInlinedData(); A& allocator_a = GetAllocator(); A& allocator_b = other->GetAllocator(); for (SizeType<A> i = 0; i < n; ++i, ++a, ++b) { ValueType<A> tmp(std::move(*a)); AllocatorTraits<A>::destroy(allocator_a, a); AllocatorTraits<A>::construct(allocator_b, a, std::move(*b)); AllocatorTraits<A>::destroy(allocator_b, b); AllocatorTraits<A>::construct(allocator_a, b, std::move(tmp)); } } template <typename T, size_t N, typename A> void Storage<T, N, A>::SwapInlinedElements(MemcpyPolicy, Storage* other) { Data tmp = data_; data_ = other->data_; other->data_ = tmp; } template <typename T, size_t N, typename A> template <typename NotMemcpyPolicy> void Storage<T, N, A>::SwapInlinedElements(NotMemcpyPolicy policy, Storage* other) { Storage* small_ptr = this; Storage* large_ptr = other; if (small_ptr->GetSize() > large_ptr->GetSize()) { std::swap(small_ptr, large_ptr); } auto small_size = small_ptr->GetSize(); auto diff = large_ptr->GetSize() - small_size; SwapN(policy, other, small_size); IteratorValueAdapter<A, MoveIterator<A>> move_values( MoveIterator<A>(large_ptr->GetInlinedData() + small_size)); ConstructElements<A>(large_ptr->GetAllocator(), small_ptr->GetInlinedData() + small_size, move_values, diff); DestroyAdapter<A>::DestroyElements(large_ptr->GetAllocator(), large_ptr->GetInlinedData() + small_size, diff); } #if !defined(__clang__) && defined(__GNUC__) #pragma GCC diagnostic pop #endif } ABSL_NAMESPACE_END } #endif
#include "absl/container/inlined_vector.h" #include <algorithm> #include <cstddef> #include <forward_list> #include <iterator> #include <list> #include <memory> #include <scoped_allocator> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/attributes.h" #include "absl/base/internal/exception_testing.h" #include "absl/base/macros.h" #include "absl/base/options.h" #include "absl/container/internal/test_allocator.h" #include "absl/container/internal/test_instance_tracker.h" #include "absl/hash/hash_testing.h" #include "absl/log/check.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" namespace { using absl::container_internal::CountingAllocator; using absl::test_internal::CopyableMovableInstance; using absl::test_internal::CopyableOnlyInstance; using absl::test_internal::InstanceTracker; using testing::AllOf; using testing::Each; using testing::ElementsAre; using testing::ElementsAreArray; using testing::Eq; using testing::Gt; using testing::Pointee; using testing::Pointwise; using testing::PrintToString; using testing::SizeIs; using IntVec = absl::InlinedVector<int, 8>; MATCHER_P(CapacityIs, n, "") { return testing::ExplainMatchResult(n, arg.capacity(), result_listener); } MATCHER_P(ValueIs, e, "") { return testing::ExplainMatchResult(e, arg.value(), result_listener); } template <typename T> class InstanceTest : public ::testing::Test {}; TYPED_TEST_SUITE_P(InstanceTest); class RefCounted { public: RefCounted(int value, int* count) : value_(value), count_(count) { Ref(); } RefCounted(const RefCounted& v) : value_(v.value_), count_(v.count_) { Ref(); } ~RefCounted() { Unref(); count_ = nullptr; } friend void swap(RefCounted& a, RefCounted& b) { using std::swap; swap(a.value_, b.value_); swap(a.count_, b.count_); } RefCounted& operator=(RefCounted v) { using std::swap; swap(*this, v); return *this; } void Ref() const { CHECK_NE(count_, nullptr); ++(*count_); } void Unref() const { --(*count_); CHECK_GE(*count_, 0); } int value_; int* count_; }; using RefCountedVec = absl::InlinedVector<RefCounted, 8>; class Dynamic { public: virtual ~Dynamic() {} }; using DynamicVec = absl::InlinedVector<Dynamic, 8>; template <typename Container> static void Fill(Container* v, size_t len, int offset = 0) { for (size_t i = 0; i < len; i++) { v->push_back(static_cast<int>(i) + offset); } } static IntVec Fill(size_t len, int offset = 0) { IntVec v; Fill(&v, len, offset); return v; } TEST(IntVec, SimpleOps) { for (size_t len = 0; len < 20; len++) { IntVec v; const IntVec& cv = v; Fill(&v, len); EXPECT_EQ(len, v.size()); EXPECT_LE(len, v.capacity()); for (size_t i = 0; i < len; i++) { EXPECT_EQ(static_cast<int>(i), v[i]); EXPECT_EQ(static_cast<int>(i), v.at(i)); } EXPECT_EQ(v.begin(), v.data()); EXPECT_EQ(cv.begin(), cv.data()); size_t counter = 0; for (IntVec::iterator iter = v.begin(); iter != v.end(); ++iter) { EXPECT_EQ(static_cast<int>(counter), *iter); counter++; } EXPECT_EQ(counter, len); counter = 0; for (IntVec::const_iterator iter = v.begin(); iter != v.end(); ++iter) { EXPECT_EQ(static_cast<int>(counter), *iter); counter++; } EXPECT_EQ(counter, len); counter = 0; for (IntVec::const_iterator iter = v.cbegin(); iter != v.cend(); ++iter) { EXPECT_EQ(static_cast<int>(counter), *iter); counter++; } EXPECT_EQ(counter, len); if (len > 0) { EXPECT_EQ(0, v.front()); EXPECT_EQ(static_cast<int>(len - 1), v.back()); v.pop_back(); EXPECT_EQ(len - 1, v.size()); for (size_t i = 0; i < v.size(); ++i) { EXPECT_EQ(static_cast<int>(i), v[i]); EXPECT_EQ(static_cast<int>(i), v.at(i)); } } } } TEST(IntVec, PopBackNoOverflow) { IntVec v = {1}; v.pop_back(); EXPECT_EQ(v.size(), 0u); } TEST(IntVec, AtThrows) { IntVec v = {1, 2, 3}; EXPECT_EQ(v.at(2), 3); ABSL_BASE_INTERNAL_EXPECT_FAIL(v.at(3), std::out_of_range, "failed bounds check"); } TEST(IntVec, ReverseIterator) { for (size_t len = 0; len < 20; len++) { IntVec v; Fill(&v, len); size_t counter = len; for (IntVec::reverse_iterator iter = v.rbegin(); iter != v.rend(); ++iter) { counter--; EXPECT_EQ(static_cast<int>(counter), *iter); } EXPECT_EQ(counter, 0u); counter = len; for (IntVec::const_reverse_iterator iter = v.rbegin(); iter != v.rend(); ++iter) { counter--; EXPECT_EQ(static_cast<int>(counter), *iter); } EXPECT_EQ(counter, 0u); counter = len; for (IntVec::const_reverse_iterator iter = v.crbegin(); iter != v.crend(); ++iter) { counter--; EXPECT_EQ(static_cast<int>(counter), *iter); } EXPECT_EQ(counter, 0u); } } TEST(IntVec, Erase) { for (size_t len = 1; len < 20; len++) { for (size_t i = 0; i < len; ++i) { IntVec v; Fill(&v, len); v.erase(v.begin() + i); EXPECT_EQ(len - 1, v.size()); for (size_t j = 0; j < i; ++j) { EXPECT_EQ(static_cast<int>(j), v[j]); } for (size_t j = i; j < len - 1; ++j) { EXPECT_EQ(static_cast<int>(j + 1), v[j]); } } } } TEST(IntVec, Hardened) { IntVec v; Fill(&v, 10); EXPECT_EQ(v[9], 9); #if !defined(NDEBUG) || ABSL_OPTION_HARDENED EXPECT_DEATH_IF_SUPPORTED(v[10], ""); EXPECT_DEATH_IF_SUPPORTED(v[static_cast<size_t>(-1)], ""); EXPECT_DEATH_IF_SUPPORTED(v.resize(v.max_size() + 1), ""); #endif } TEST(UniquePtr, MoveConstruct) { for (size_t size = 0; size < 16; ++size) { SCOPED_TRACE(size); absl::InlinedVector<std::unique_ptr<size_t>, 2> a; for (size_t i = 0; i < size; ++i) { a.push_back(std::make_unique<size_t>(i)); } absl::InlinedVector<std::unique_ptr<size_t>, 2> b(std::move(a)); ASSERT_THAT(b, SizeIs(size)); for (size_t i = 0; i < size; ++i) { ASSERT_THAT(b[i], Pointee(i)); } } } TEST(UniquePtr, MoveAssign) { for (size_t size = 0; size < 16; ++size) { SCOPED_TRACE(size); absl::InlinedVector<std::unique_ptr<size_t>, 2> a; for (size_t i = 0; i < size; ++i) { a.push_back(std::make_unique<size_t>(i)); } absl::InlinedVector<std::unique_ptr<size_t>, 2> b; b = std::move(a); ASSERT_THAT(b, SizeIs(size)); for (size_t i = 0; i < size; ++i) { ASSERT_THAT(b[i], Pointee(i)); } } } TEST(UniquePtr, Swap) { for (size_t size1 = 0; size1 < 5; ++size1) { for (size_t size2 = 0; size2 < 5; ++size2) { absl::InlinedVector<std::unique_ptr<size_t>, 2> a; absl::InlinedVector<std::unique_ptr<size_t>, 2> b; for (size_t i = 0; i < size1; ++i) { a.push_back(std::make_unique<size_t>(i + 10)); } for (size_t i = 0; i < size2; ++i) { b.push_back(std::make_unique<size_t>(i + 20)); } a.swap(b); ASSERT_THAT(a, SizeIs(size2)); ASSERT_THAT(b, SizeIs(size1)); for (size_t i = 0; i < a.size(); ++i) { ASSERT_THAT(a[i], Pointee(i + 20)); } for (size_t i = 0; i < b.size(); ++i) { ASSERT_THAT(b[i], Pointee(i + 10)); } } } } TEST(UniquePtr, EraseSingle) { for (size_t size = 4; size < 16; ++size) { absl::InlinedVector<std::unique_ptr<size_t>, 8> a; for (size_t i = 0; i < size; ++i) { a.push_back(std::make_unique<size_t>(i)); } a.erase(a.begin()); ASSERT_THAT(a, SizeIs(size - 1)); for (size_t i = 0; i < size - 1; ++i) { ASSERT_THAT(a[i], Pointee(i + 1)); } a.erase(a.begin() + 2); ASSERT_THAT(a, SizeIs(size - 2)); ASSERT_THAT(a[0], Pointee(1)); ASSERT_THAT(a[1], Pointee(2)); for (size_t i = 2; i < size - 2; ++i) { ASSERT_THAT(a[i], Pointee(i + 2)); } } } TEST(UniquePtr, EraseMulti) { for (size_t size = 5; size < 16; ++size) { absl::InlinedVector<std::unique_ptr<size_t>, 8> a; for (size_t i = 0; i < size; ++i) { a.push_back(std::make_unique<size_t>(i)); } a.erase(a.begin(), a.begin() + 2); ASSERT_THAT(a, SizeIs(size - 2)); for (size_t i = 0; i < size - 2; ++i) { ASSERT_THAT(a[i], Pointee(i + 2)); } a.erase(a.begin() + 1, a.begin() + 3); ASSERT_THAT(a, SizeIs(size - 4)); ASSERT_THAT(a[0], Pointee(2)); for (size_t i = 1; i < size - 4; ++i) { ASSERT_THAT(a[i], Pointee(i + 4)); } } } TEST(RefCountedVec, EraseBeginEnd) { for (size_t len = 1; len < 20; ++len) { for (size_t erase_begin = 0; erase_begin < len; ++erase_begin) { for (size_t erase_end = erase_begin; erase_end <= len; ++erase_end) { std::vector<int> counts(len, 0); RefCountedVec v; for (size_t i = 0; i < len; ++i) { v.push_back(RefCounted(static_cast<int>(i), &counts[i])); } size_t erase_len = erase_end - erase_begin; v.erase(v.begin() + erase_begin, v.begin() + erase_end); EXPECT_EQ(len - erase_len, v.size()); for (size_t i = 0; i < erase_begin; ++i) { EXPECT_EQ(static_cast<int>(i), v[i].value_); } for (size_t i = erase_begin; i < v.size(); ++i) { EXPECT_EQ(static_cast<int>(i + erase_len), v[i].value_); } for (size_t i = 0; i < erase_begin; ++i) { EXPECT_EQ(1, counts[i]); } for (size_t i = erase_begin; i < erase_end; ++i) { EXPECT_EQ(0, counts[i]); } for (size_t i = erase_end; i < len; ++i) { EXPECT_EQ(1, counts[i]); } } } } } struct NoDefaultCtor { explicit NoDefaultCtor(int) {} }; struct NoCopy { NoCopy() {} NoCopy(const NoCopy&) = delete; }; struct NoAssign { NoAssign() {} NoAssign& operator=(const NoAssign&) = delete; }; struct MoveOnly { MoveOnly() {} MoveOnly(MoveOnly&&) = default; MoveOnly& operator=(MoveOnly&&) = default; }; TEST(InlinedVectorTest, NoDefaultCtor) { absl::InlinedVector<NoDefaultCtor, 1> v(10, NoDefaultCtor(2)); (void)v; } TEST(InlinedVectorTest, NoCopy) { absl::InlinedVector<NoCopy, 1> v(10); (void)v; } TEST(InlinedVectorTest, NoAssign) { absl::InlinedVector<NoAssign, 1> v(10); (void)v; } TEST(InlinedVectorTest, MoveOnly) { absl::InlinedVector<MoveOnly, 2> v; v.push_back(MoveOnly{}); v.push_back(MoveOnly{}); v.push_back(MoveOnly{}); v.erase(v.begin()); v.push_back(MoveOnly{}); v.erase(v.begin(), v.begin() + 1); v.insert(v.begin(), MoveOnly{}); v.emplace(v.begin()); v.emplace(v.begin(), MoveOnly{}); } TEST(InlinedVectorTest, Noexcept) { EXPECT_TRUE(std::is_nothrow_move_constructible<IntVec>::value); EXPECT_TRUE((std::is_nothrow_move_constructible< absl::InlinedVector<MoveOnly, 2>>::value)); struct MoveCanThrow { MoveCanThrow(MoveCanThrow&&) {} }; EXPECT_EQ(absl::default_allocator_is_nothrow::value, (std::is_nothrow_move_constructible< absl::InlinedVector<MoveCanThrow, 2>>::value)); } TEST(InlinedVectorTest, EmplaceBack) { absl::InlinedVector<std::pair<std::string, int>, 1> v; auto& inlined_element = v.emplace_back("answer", 42); EXPECT_EQ(&inlined_element, &v[0]); EXPECT_EQ(inlined_element.first, "answer"); EXPECT_EQ(inlined_element.second, 42); auto& allocated_element = v.emplace_back("taxicab", 1729); EXPECT_EQ(&allocated_element, &v[1]); EXPECT_EQ(allocated_element.first, "taxicab"); EXPECT_EQ(allocated_element.second, 1729); } TEST(InlinedVectorTest, ShrinkToFitGrowingVector) { absl::InlinedVector<std::pair<std::string, int>, 1> v; v.shrink_to_fit(); EXPECT_EQ(v.capacity(), 1u); v.emplace_back("answer", 42); v.shrink_to_fit(); EXPECT_EQ(v.capacity(), 1u); v.emplace_back("taxicab", 1729); EXPECT_GE(v.capacity(), 2u); v.shrink_to_fit(); EXPECT_EQ(v.capacity(), 2u); v.reserve(100); EXPECT_GE(v.capacity(), 100u); v.shrink_to_fit(); EXPECT_EQ(v.capacity(), 2u); } TEST(InlinedVectorTest, ShrinkToFitEdgeCases) { { absl::InlinedVector<std::pair<std::string, int>, 1> v; v.emplace_back("answer", 42); v.emplace_back("taxicab", 1729); EXPECT_GE(v.capacity(), 2u); v.pop_back(); v.shrink_to_fit(); EXPECT_EQ(v.capacity(), 1u); EXPECT_EQ(v[0].first, "answer"); EXPECT_EQ(v[0].second, 42); } { absl::InlinedVector<std::string, 2> v(100); v.resize(0); v.shrink_to_fit(); EXPECT_EQ(v.capacity(), 2u); } { absl::InlinedVector<std::string, 2> v(100); v.resize(1); v.shrink_to_fit(); EXPECT_EQ(v.capacity(), 2u); } { absl::InlinedVector<std::string, 2> v(100); v.resize(2); v.shrink_to_fit(); EXPECT_EQ(v.capacity(), 2u); } { absl::InlinedVector<std::string, 2> v(100); v.resize(3); v.shrink_to_fit(); EXPECT_EQ(v.capacity(), 3u); } } TEST(IntVec, Insert) { for (size_t len = 0; len < 20; len++) { for (ptrdiff_t pos = 0; pos <= static_cast<ptrdiff_t>(len); pos++) { { std::vector<int> std_v; Fill(&std_v, len); IntVec v; Fill(&v, len); std_v.insert(std_v.begin() + pos, 9999); IntVec::iterator it = v.insert(v.cbegin() + pos, 9999); EXPECT_THAT(v, ElementsAreArray(std_v)); EXPECT_EQ(it, v.cbegin() + pos); } { std::vector<int> std_v; Fill(&std_v, len); IntVec v; Fill(&v, len); IntVec::size_type n = 5; std_v.insert(std_v.begin() + pos, n, 9999); IntVec::iterator it = v.insert(v.cbegin() + pos, n, 9999); EXPECT_THAT(v, ElementsAreArray(std_v)); EXPECT_EQ(it, v.cbegin() + pos); } { std::vector<int> std_v; Fill(&std_v, len); IntVec v; Fill(&v, len); const std::vector<int> input = {9999, 8888, 7777}; std_v.insert(std_v.begin() + pos, input.cbegin(), input.cend()); IntVec::iterator it = v.insert(v.cbegin() + pos, input.cbegin(), input.cend()); EXPECT_THAT(v, ElementsAreArray(std_v)); EXPECT_EQ(it, v.cbegin() + pos); } { std::vector<int> std_v; Fill(&std_v, len); IntVec v; Fill(&v, len); const std::forward_list<int> input = {9999, 8888, 7777}; std_v.insert(std_v.begin() + pos, input.cbegin(), input.cend()); IntVec::iterator it = v.insert(v.cbegin() + pos, input.cbegin(), input.cend()); EXPECT_THAT(v, ElementsAreArray(std_v)); EXPECT_EQ(it, v.cbegin() + pos); } { std::vector<int> std_v; Fill(&std_v, len); IntVec v; Fill(&v, len); std_v.insert(std_v.begin() + pos, {9999, 8888, 7777}); std::istringstream input("9999 8888 7777"); IntVec::iterator it = v.insert(v.cbegin() + pos, std::istream_iterator<int>(input), std::istream_iterator<int>()); EXPECT_THAT(v, ElementsAreArray(std_v)); EXPECT_EQ(it, v.cbegin() + pos); } { std::vector<int> std_v; Fill(&std_v, len); IntVec v; Fill(&v, len); std_v.insert(std_v.begin() + pos, {9999, 8888}); IntVec::iterator it = v.insert(v.cbegin() + pos, {9999, 8888}); EXPECT_THAT(v, ElementsAreArray(std_v)); EXPECT_EQ(it, v.cbegin() + pos); } } } } TEST(RefCountedVec, InsertConstructorDestructor) { for (size_t len = 0; len < 20; len++) { SCOPED_TRACE(len); for (size_t pos = 0; pos <= len; pos++) { SCOPED_TRACE(pos); std::vector<int> counts(len, 0); int inserted_count = 0; RefCountedVec v; for (size_t i = 0; i < len; ++i) { SCOPED_TRACE(i); v.push_back(RefCounted(static_cast<int>(i), &counts[i])); } EXPECT_THAT(counts, Each(Eq(1))); RefCounted insert_element(9999, &inserted_count); EXPECT_EQ(1, inserted_count); v.insert(v.begin() + pos, insert_element); EXPECT_EQ(2, inserted_count); EXPECT_THAT(counts, Each(Eq(1))); EXPECT_EQ(2, inserted_count); } } } TEST(IntVec, Resize) { for (size_t len = 0; len < 20; len++) { IntVec v; Fill(&v, len); static const int kResizeElem = 1000000; for (size_t k = 0; k < 10; k++) { v.resize(len + k, kResizeElem); EXPECT_EQ(len + k, v.size()); EXPECT_LE(len + k, v.capacity()); for (size_t i = 0; i < len + k; i++) { if (i < len) { EXPECT_EQ(static_cast<int>(i), v[i]); } else { EXPECT_EQ(kResizeElem, v[i]); } } v.resize(len, kResizeElem); EXPECT_EQ(len, v.size()); EXPECT_LE(len, v.capacity()); for (size_t i = 0; i < len; i++) { EXPECT_EQ(static_cast<int>(i), v[i]); } } } } TEST(IntVec, InitWithLength) { for (size_t len = 0; len < 20; len++) { IntVec v(len, 7); EXPECT_EQ(len, v.size()); EXPECT_LE(len, v.capacity()); for (size_t i = 0; i < len; i++) { EXPECT_EQ(7, v[i]); } } } TEST(IntVec, CopyConstructorAndAssignment) { for (size_t len = 0; len < 20; len++) { IntVec v; Fill(&v, len); EXPECT_EQ(len, v.size()); EXPECT_LE(len, v.capacity()); IntVec v2(v); EXPECT_TRUE(v == v2) << PrintToString(v) << PrintToString(v2); for (size_t start_len = 0; start_len < 20; start_len++) { IntVec v3; Fill(&v3, start_len, 99); v3 = v; EXPECT_TRUE(v == v3) << PrintToString(v) << PrintToString(v3); } } } TEST(IntVec, AliasingCopyAssignment) { for (size_t len = 0; len < 20; ++len) { IntVec original; Fill(&original, len); IntVec dup = original; dup = *&dup; EXPECT_EQ(dup, original); } } TEST(IntVec, MoveConstructorAndAssignment) { for (size_t len = 0; len < 20; len++) { IntVec v_in; const size_t inlined_capacity = v_in.capacity(); Fill(&v_in, len); EXPECT_EQ(len, v_in.size()); EXPECT_LE(len, v_in.capacity()); { IntVec v_temp(v_in); auto* old_data = v_temp.data(); IntVec v_out(std::move(v_temp)); EXPECT_TRUE(v_in == v_out) << PrintToString(v_in) << PrintToString(v_out); if (v_in.size() > inlined_capacity) { EXPECT_TRUE(v_out.data() == old_data); } else { EXPECT_FALSE(v_out.data() == old_data); } } for (size_t start_len = 0; start_len < 20; start_len++) { IntVec v_out; Fill(&v_out, start_len, 99); IntVec v_temp(v_in); auto* old_data = v_temp.data(); v_out = std::move(v_temp); EXPECT_TRUE(v_in == v_out) << PrintToString(v_in) << PrintToString(v_out); if (v_in.size() > inlined_capacity) { EXPECT_TRUE(v_out.data() == old_data); } else { EXPECT_FALSE(v_out.data() == old_data); } } } } class NotTriviallyDestructible { public: NotTriviallyDestructible() : p_(new int(1)) {} explicit NotTriviallyDestructible(int i) : p_(new int(i)) {} NotTriviallyDestructible(const NotTriviallyDestructible& other) : p_(new int(*other.p_)) {} NotTriviallyDestructible& operator=(const NotTriviallyDestructible& other) { p_ = absl::make_unique<int>(*other.p_); return *this; } bool operator==(const NotTriviallyDestructible& other) const { return *p_ == *other.p_; } private: std::unique_ptr<int> p_; }; TEST(AliasingTest, Emplace) { for (size_t i = 2; i < 20; ++i) { absl::InlinedVector<NotTriviallyDestructible, 10> vec; for (size_t j = 0; j < i; ++j) { vec.push_back(NotTriviallyDestructible(static_cast<int>(j))); } vec.emplace(vec.begin(), vec[0]); EXPECT_EQ(vec[0], vec[1]); vec.emplace(vec.begin() + i / 2, vec[i / 2]); EXPECT_EQ(vec[i / 2], vec[i / 2 + 1]); vec.emplace(vec.end() - 1, vec.back()); EXPECT_EQ(vec[vec.size() - 2], vec.back()); } } TEST(AliasingTest, InsertWithCount) { for (size_t i = 1; i < 20; ++i) { absl::InlinedVector<NotTriviallyDestructible, 10> vec; for (size_t j = 0; j < i; ++j) { vec.push_back(NotTriviallyDestructible(static_cast<int>(j))); } for (size_t n = 0; n < 5; ++n) { vec.insert(vec.begin(), n, vec.back()); auto b = vec.begin(); EXPECT_TRUE( std::all_of(b, b + n, [&vec](const NotTriviallyDestructible& x) { return x == vec.back(); })); auto m_idx = vec.size() / 2; vec.insert(vec.begin() + m_idx, n, vec.back()); auto m = vec.begin() + m_idx; EXPECT_TRUE( std::all_of(m, m + n, [&vec](const NotTriviallyDestructible& x) { return x == vec.back(); })); auto old_e = vec.size() - 1; auto val = vec[old_e]; vec.insert(vec.end(), n, vec[old_e]); auto e = vec.begin() + old_e; EXPECT_TRUE(std::all_of( e, e + n, [&val](const NotTriviallyDestructible& x) { return x == val; })); } } } TEST(OverheadTest, Storage) { struct T { void* val; }; size_t expected_overhead = sizeof(T); EXPECT_EQ((2 * expected_overhead), sizeof(absl::InlinedVector<T, 1>) - sizeof(T[1])); EXPECT_EQ(expected_overhead, sizeof(absl::InlinedVector<T, 2>) - sizeof(T[2])); EXPECT_EQ(expected_overhead, sizeof(absl::InlinedVector<T, 3>) - sizeof(T[3])); EXPECT_EQ(expected_overhead, sizeof(absl::InlinedVector<T, 4>) - sizeof(T[4])); EXPECT_EQ(expected_overhead, sizeof(absl::InlinedVector<T, 5>) - sizeof(T[5])); EXPECT_EQ(expected_overhead, sizeof(absl::InlinedVector<T, 6>) - sizeof(T[6])); EXPECT_EQ(expected_overhead, sizeof(absl::InlinedVector<T, 7>) - sizeof(T[7])); EXPECT_EQ(expected_overhead, sizeof(absl::InlinedVector<T, 8>) - sizeof(T[8])); } TEST(IntVec, Clear) { for (size_t len = 0; len < 20; len++) { SCOPED_TRACE(len); IntVec v; Fill(&v, len); v.clear(); EXPECT_EQ(0u, v.size()); EXPECT_EQ(v.begin(), v.end()); } } TEST(IntVec, Reserve) { for (size_t len = 0; len < 20; len++) { IntVec v; Fill(&v, len); for (size_t newlen = 0; newlen < 100; newlen++) { const int* start_rep = v.data(); v.reserve(newlen); const int* final_rep = v.data(); if (newlen <= len) { EXPECT_EQ(start_rep, final_rep); } EXPECT_LE(newlen, v.capacity()); while (v.size() < newlen) { v.push_back(0); } EXPECT_EQ(final_rep, v.data()); } } } TEST(StringVec, SelfRefPushBack) { std::vector<std::string> std_v; absl::InlinedVector<std::string, 4> v; const std::string s = "A quite long string to ensure heap."; std_v.push_back(s); v.push_back(s); for (int i = 0; i < 20; ++i) { EXPECT_THAT(v, ElementsAreArray(std_v)); v.push_back(v.back()); std_v.push_back(std_v.back()); } EXPECT_THAT(v, ElementsAreArray(std_v)); } TEST(StringVec, SelfRefPushBackWithMove) { std::vector<std::string> std_v; absl::InlinedVector<std::string, 4> v; const std::string s = "A quite long string to ensure heap."; std_v.push_back(s); v.push_back(s); for (int i = 0; i < 20; ++i) { EXPECT_EQ(v.back(), std_v.back()); v.push_back(std::move(v.back())); std_v.push_back(std::move(std_v.back())); } EXPECT_EQ(v.back(), std_v.back()); } TEST(StringVec, SelfMove) { const std::string s = "A quite long string to ensure heap."; for (int len = 0; len < 20; len++) { SCOPED_TRACE(len); absl::InlinedVector<std::string, 8> v; for (int i = 0; i < len; ++i) { SCOPED_TRACE(i); v.push_back(s); } v = std::move(*(&v)); std::vector<std::string> copy(v.begin(), v.end()); } } TEST(IntVec, Swap) { for (size_t l1 = 0; l1 < 20; l1++) { SCOPED_TRACE(l1); for (size_t l2 = 0; l2 < 20; l2++) { SCOPED_TRACE(l2); IntVec a = Fill(l1, 0); IntVec b = Fill(l2, 100); { using std::swap; swap(a, b); } EXPECT_EQ(l1, b.size()); EXPECT_EQ(l2, a.size()); for (size_t i = 0; i < l1; i++) { SCOPED_TRACE(i); EXPECT_EQ(static_cast<int>(i), b[i]); } for (size_t i = 0; i < l2; i++) { SCOPED_TRACE(i); EXPECT_EQ(100 + static_cast<int>(i), a[i]); } } } } TYPED_TEST_P(InstanceTest, Swap) { using Instance = TypeParam; using InstanceVec = absl::InlinedVector<Instance, 8>; for (size_t l1 = 0; l1 < 20; l1++) { SCOPED_TRACE(l1); for (size_t l2 = 0; l2 < 20; l2++) { SCOPED_TRACE(l2); InstanceTracker tracker; InstanceVec a, b; const size_t inlined_capacity = a.capacity(); auto min_len = std::min(l1, l2); auto max_len = std::max(l1, l2); for (size_t i = 0; i < l1; i++) a.push_back(Instance(static_cast<int>(i))); for (size_t i = 0; i < l2; i++) b.push_back(Instance(100 + static_cast<int>(i))); EXPECT_EQ(tracker.instances(), static_cast<int>(l1 + l2)); tracker.ResetCopiesMovesSwaps(); { using std::swap; swap(a, b); } EXPECT_EQ(tracker.instances(), static_cast<int>(l1 + l2)); if (a.size() > inlined_capacity && b.size() > inlined_capacity) { EXPECT_EQ(tracker.swaps(), 0); EXPECT_EQ(tracker.moves(), 0); } else if (a.size() <= inlined_capacity && b.size() <= inlined_capacity) { EXPECT_EQ(tracker.swaps(), static_cast<int>(min_len)); EXPECT_EQ((tracker.moves() ? tracker.moves() : tracker.copies()), static_cast<int>(max_len - min_len)); } else { EXPECT_EQ(tracker.swaps(), 0); EXPECT_EQ((tracker.moves() ? tracker.moves() : tracker.copies()), static_cast<int>(min_len)); } EXPECT_EQ(l1, b.size()); EXPECT_EQ(l2, a.size()); for (size_t i = 0; i < l1; i++) { EXPECT_EQ(static_cast<int>(i), b[i].value()); } for (size_t i = 0; i < l2; i++) { EXPECT_EQ(100 + static_cast<int>(i), a[i].value()); } } } } TEST(IntVec, EqualAndNotEqual) { IntVec a, b; EXPECT_TRUE(a == b); EXPECT_FALSE(a != b); a.push_back(3); EXPECT_FALSE(a == b); EXPECT_TRUE(a != b); b.push_back(3); EXPECT_TRUE(a == b); EXPECT_FALSE(a != b); b.push_back(7); EXPECT_FALSE(a == b); EXPECT_TRUE(a != b); a.push_back(6); EXPECT_FALSE(a == b); EXPECT_TRUE(a != b); a.clear(); b.clear(); for (size_t i = 0; i < 100; i++) { a.push_back(static_cast<int>(i)); b.push_back(static_cast<int>(i)); EXPECT_TRUE(a == b); EXPECT_FALSE(a != b); b[i] = b[i] + 1; EXPECT_FALSE(a == b); EXPECT_TRUE(a != b); b[i] = b[i] - 1; EXPECT_TRUE(a == b); EXPECT_FALSE(a != b); } } TEST(IntVec, RelationalOps) { IntVec a, b; EXPECT_FALSE(a < b); EXPECT_FALSE(b < a); EXPECT_FALSE(a > b); EXPECT_FALSE(b > a); EXPECT_TRUE(a <= b); EXPECT_TRUE(b <= a); EXPECT_TRUE(a >= b); EXPECT_TRUE(b >= a); b.push_back(3); EXPECT_TRUE(a < b); EXPECT_FALSE(b < a); EXPECT_FALSE(a > b); EXPECT_TRUE(b > a); EXPECT_TRUE(a <= b); EXPECT_FALSE(b <= a); EXPECT_FALSE(a >= b); EXPECT_TRUE(b >= a); } TYPED_TEST_P(InstanceTest, CountConstructorsDestructors) { using Instance = TypeParam; using InstanceVec = absl::InlinedVector<Instance, 8>; InstanceTracker tracker; for (size_t len = 0; len < 20; len++) { SCOPED_TRACE(len); tracker.ResetCopiesMovesSwaps(); InstanceVec v; const size_t inlined_capacity = v.capacity(); for (size_t i = 0; i < len; i++) { v.push_back(Instance(static_cast<int>(i))); } EXPECT_EQ(tracker.instances(), static_cast<int>(len)); EXPECT_GE(tracker.copies() + tracker.moves(), static_cast<int>(len)); tracker.ResetCopiesMovesSwaps(); tracker.ResetCopiesMovesSwaps(); v.resize(len + 10, Instance(100)); EXPECT_EQ(tracker.instances(), static_cast<int>(len) + 10); if (len <= inlined_capacity && len + 10 > inlined_capacity) { EXPECT_EQ(tracker.copies() + tracker.moves(), 10 + static_cast<int>(len)); } else { EXPECT_GE(tracker.copies() + tracker.moves(), 10); } tracker.ResetCopiesMovesSwaps(); v.resize(len, Instance(100)); EXPECT_EQ(tracker.instances(), static_cast<int>(len)); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 0); SCOPED_TRACE("reserve"); v.reserve(len + 1000); EXPECT_EQ(tracker.instances(), static_cast<int>(len)); EXPECT_EQ(tracker.copies() + tracker.moves(), static_cast<int>(len)); if (len > 0) { tracker.ResetCopiesMovesSwaps(); v.pop_back(); EXPECT_EQ(tracker.instances(), static_cast<int>(len) - 1); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 0); if (!v.empty()) { tracker.ResetCopiesMovesSwaps(); v.erase(v.begin()); EXPECT_EQ(tracker.instances(), static_cast<int>(len) - 2); EXPECT_EQ(tracker.copies() + tracker.moves(), static_cast<int>(len) - 2); } } tracker.ResetCopiesMovesSwaps(); int instances_before_empty_erase = tracker.instances(); v.erase(v.begin(), v.begin()); EXPECT_EQ(tracker.instances(), instances_before_empty_erase); EXPECT_EQ(tracker.copies() + tracker.moves(), 0); } } TYPED_TEST_P(InstanceTest, CountConstructorsDestructorsOnCopyConstruction) { using Instance = TypeParam; using InstanceVec = absl::InlinedVector<Instance, 8>; InstanceTracker tracker; for (int len = 0; len < 20; len++) { SCOPED_TRACE(len); tracker.ResetCopiesMovesSwaps(); InstanceVec v; for (int i = 0; i < len; i++) { v.push_back(Instance(i)); } EXPECT_EQ(tracker.instances(), len); EXPECT_GE(tracker.copies() + tracker.moves(), len); tracker.ResetCopiesMovesSwaps(); { InstanceVec v_copy(v); EXPECT_EQ(tracker.instances(), len + len); EXPECT_EQ(tracker.copies(), len); EXPECT_EQ(tracker.moves(), 0); } EXPECT_EQ(tracker.instances(), len); } } TYPED_TEST_P(InstanceTest, CountConstructorsDestructorsOnMoveConstruction) { using Instance = TypeParam; using InstanceVec = absl::InlinedVector<Instance, 8>; InstanceTracker tracker; for (int len = 0; len < 20; len++) { SCOPED_TRACE(len); tracker.ResetCopiesMovesSwaps(); InstanceVec v; const size_t inlined_capacity = v.capacity(); for (int i = 0; i < len; i++) { v.push_back(Instance(i)); } EXPECT_EQ(tracker.instances(), len); EXPECT_GE(tracker.copies() + tracker.moves(), len); tracker.ResetCopiesMovesSwaps(); { InstanceVec v_copy(std::move(v)); if (static_cast<size_t>(len) > inlined_capacity) { EXPECT_EQ(tracker.instances(), len); EXPECT_EQ(tracker.live_instances(), len); EXPECT_EQ(v.size(), 0u); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 0); } else { EXPECT_EQ(tracker.instances(), len + len); if (Instance::supports_move()) { EXPECT_EQ(tracker.live_instances(), len); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), len); } else { EXPECT_EQ(tracker.live_instances(), len + len); EXPECT_EQ(tracker.copies(), len); EXPECT_EQ(tracker.moves(), 0); } } EXPECT_EQ(tracker.swaps(), 0); } } } TYPED_TEST_P(InstanceTest, CountConstructorsDestructorsOnAssignment) { using Instance = TypeParam; using InstanceVec = absl::InlinedVector<Instance, 8>; InstanceTracker tracker; for (int len = 0; len < 20; len++) { SCOPED_TRACE(len); for (int longorshort = 0; longorshort <= 1; ++longorshort) { SCOPED_TRACE(longorshort); tracker.ResetCopiesMovesSwaps(); InstanceVec longer, shorter; for (int i = 0; i < len; i++) { longer.push_back(Instance(i)); shorter.push_back(Instance(i)); } longer.push_back(Instance(len)); EXPECT_EQ(tracker.instances(), len + len + 1); EXPECT_GE(tracker.copies() + tracker.moves(), len + len + 1); tracker.ResetCopiesMovesSwaps(); if (longorshort) { shorter = longer; EXPECT_EQ(tracker.instances(), (len + 1) + (len + 1)); EXPECT_GE(tracker.copies() + tracker.moves(), len + 1); } else { longer = shorter; EXPECT_EQ(tracker.instances(), len + len); EXPECT_EQ(tracker.copies() + tracker.moves(), len); } } } } TYPED_TEST_P(InstanceTest, CountConstructorsDestructorsOnMoveAssignment) { using Instance = TypeParam; using InstanceVec = absl::InlinedVector<Instance, 8>; InstanceTracker tracker; for (int len = 0; len < 20; len++) { SCOPED_TRACE(len); for (int longorshort = 0; longorshort <= 1; ++longorshort) { SCOPED_TRACE(longorshort); tracker.ResetCopiesMovesSwaps(); InstanceVec longer, shorter; const size_t inlined_capacity = longer.capacity(); for (int i = 0; i < len; i++) { longer.push_back(Instance(i)); shorter.push_back(Instance(i)); } longer.push_back(Instance(len)); EXPECT_EQ(tracker.instances(), len + len + 1); EXPECT_GE(tracker.copies() + tracker.moves(), len + len + 1); tracker.ResetCopiesMovesSwaps(); int src_len; if (longorshort) { src_len = len + 1; shorter = std::move(longer); } else { src_len = len; longer = std::move(shorter); } if (static_cast<size_t>(src_len) > inlined_capacity) { EXPECT_EQ(tracker.instances(), src_len); EXPECT_EQ(tracker.live_instances(), src_len); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 0); } else { EXPECT_EQ(tracker.instances(), src_len + src_len); if (Instance::supports_move()) { EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), src_len); EXPECT_EQ(tracker.live_instances(), src_len); } else { EXPECT_EQ(tracker.copies(), src_len); EXPECT_EQ(tracker.moves(), 0); EXPECT_EQ(tracker.live_instances(), src_len + src_len); } } EXPECT_EQ(tracker.swaps(), 0); } } } TEST(CountElemAssign, SimpleTypeWithInlineBacking) { const size_t inlined_capacity = absl::InlinedVector<int, 2>().capacity(); for (size_t original_size = 0; original_size <= 5; ++original_size) { SCOPED_TRACE(original_size); std::vector<int> original_contents(original_size, 12345); absl::InlinedVector<int, 2> v(original_contents.begin(), original_contents.end()); v.assign(2, 123); EXPECT_THAT(v, AllOf(SizeIs(2u), ElementsAre(123, 123))); if (original_size <= inlined_capacity) { EXPECT_EQ(v.capacity(), inlined_capacity); } } } TEST(CountElemAssign, SimpleTypeWithAllocation) { for (size_t original_size = 0; original_size <= 5; ++original_size) { SCOPED_TRACE(original_size); std::vector<int> original_contents(original_size, 12345); absl::InlinedVector<int, 2> v(original_contents.begin(), original_contents.end()); v.assign(3, 123); EXPECT_THAT(v, AllOf(SizeIs(3u), ElementsAre(123, 123, 123))); EXPECT_LE(v.size(), v.capacity()); } } TYPED_TEST_P(InstanceTest, CountElemAssignInlineBacking) { using Instance = TypeParam; for (size_t original_size = 0; original_size <= 5; ++original_size) { SCOPED_TRACE(original_size); std::vector<Instance> original_contents(original_size, Instance(12345)); absl::InlinedVector<Instance, 2> v(original_contents.begin(), original_contents.end()); v.assign(2, Instance(123)); EXPECT_THAT(v, AllOf(SizeIs(2u), ElementsAre(ValueIs(123), ValueIs(123)))); if (original_size <= 2) { EXPECT_EQ(2u, v.capacity()); } } } template <typename Instance> void InstanceCountElemAssignWithAllocationTest() { for (size_t original_size = 0; original_size <= 5; ++original_size) { SCOPED_TRACE(original_size); std::vector<Instance> original_contents(original_size, Instance(12345)); absl::InlinedVector<Instance, 2> v(original_contents.begin(), original_contents.end()); v.assign(3, Instance(123)); EXPECT_THAT(v, AllOf(SizeIs(3u), ElementsAre(ValueIs(123), ValueIs(123), ValueIs(123)))); EXPECT_LE(v.size(), v.capacity()); } } TEST(CountElemAssign, WithAllocationCopyableInstance) { InstanceCountElemAssignWithAllocationTest<CopyableOnlyInstance>(); } TEST(CountElemAssign, WithAllocationCopyableMovableInstance) { InstanceCountElemAssignWithAllocationTest<CopyableMovableInstance>(); } TEST(RangedConstructor, SimpleType) { std::vector<int> source_v = {4, 5, 6}; absl::InlinedVector<int, 4> v(source_v.begin(), source_v.end()); EXPECT_EQ(3u, v.size()); EXPECT_EQ(4u, v.capacity()); EXPECT_EQ(4, v[0]); EXPECT_EQ(5, v[1]); EXPECT_EQ(6, v[2]); absl::InlinedVector<int, 2> realloc_v(source_v.begin(), source_v.end()); EXPECT_EQ(3u, realloc_v.size()); EXPECT_LT(2u, realloc_v.capacity()); EXPECT_EQ(4, realloc_v[0]); EXPECT_EQ(5, realloc_v[1]); EXPECT_EQ(6, realloc_v[2]); } template <typename Instance, typename SourceContainer, int inlined_capacity> void InstanceRangedConstructorTestForContainer() { InstanceTracker tracker; SourceContainer source_v = {Instance(0), Instance(1)}; tracker.ResetCopiesMovesSwaps(); absl::InlinedVector<Instance, inlined_capacity> v(source_v.begin(), source_v.end()); EXPECT_EQ(2u, v.size()); EXPECT_LT(1u, v.capacity()); EXPECT_EQ(0, v[0].value()); EXPECT_EQ(1, v[1].value()); EXPECT_EQ(tracker.copies(), 2); EXPECT_EQ(tracker.moves(), 0); } template <typename Instance, int inlined_capacity> void InstanceRangedConstructorTestWithCapacity() { { SCOPED_TRACE("std::list"); InstanceRangedConstructorTestForContainer<Instance, std::list<Instance>, inlined_capacity>(); { SCOPED_TRACE("const std::list"); InstanceRangedConstructorTestForContainer< Instance, const std::list<Instance>, inlined_capacity>(); } { SCOPED_TRACE("std::vector"); InstanceRangedConstructorTestForContainer<Instance, std::vector<Instance>, inlined_capacity>(); } { SCOPED_TRACE("const std::vector"); InstanceRangedConstructorTestForContainer< Instance, const std::vector<Instance>, inlined_capacity>(); } } } TYPED_TEST_P(InstanceTest, RangedConstructor) { using Instance = TypeParam; SCOPED_TRACE("capacity=1"); InstanceRangedConstructorTestWithCapacity<Instance, 1>(); SCOPED_TRACE("capacity=2"); InstanceRangedConstructorTestWithCapacity<Instance, 2>(); } TEST(RangedConstructor, ElementsAreConstructed) { std::vector<std::string> source_v = {"cat", "dog"}; absl::InlinedVector<std::string, 1> v(source_v.begin(), source_v.end()); EXPECT_EQ("cat", v[0]); EXPECT_EQ("dog", v[1]); } TEST(RangedAssign, SimpleType) { const size_t inlined_capacity = absl::InlinedVector<int, 3>().capacity(); for (size_t original_size = 0; original_size <= 5; ++original_size) { SCOPED_TRACE(original_size); std::vector<int> original_contents(original_size, 12345); for (size_t target_size = 0; target_size <= 5; ++target_size) { SCOPED_TRACE(target_size); std::vector<int> new_contents; for (size_t i = 0; i < target_size; ++i) { new_contents.push_back(static_cast<int>(i + 3)); } absl::InlinedVector<int, 3> v(original_contents.begin(), original_contents.end()); v.assign(new_contents.begin(), new_contents.end()); EXPECT_EQ(new_contents.size(), v.size()); EXPECT_LE(new_contents.size(), v.capacity()); if (target_size <= inlined_capacity && original_size <= inlined_capacity) { EXPECT_EQ(v.capacity(), inlined_capacity); } EXPECT_THAT(v, ElementsAreArray(new_contents)); } } } template <typename Instance> static bool InstanceValuesEqual(const Instance& lhs, const Instance& rhs) { return lhs.value() == rhs.value(); } template <typename Instance, typename SourceContainer> void InstanceRangedAssignTestForContainer() { for (size_t original_size = 0; original_size <= 5; ++original_size) { SCOPED_TRACE(original_size); std::vector<Instance> original_contents(original_size, Instance(12345)); for (size_t target_size = 0; target_size <= 5; ++target_size) { SCOPED_TRACE(target_size); std::vector<Instance> new_contents_in; for (size_t i = 0; i < target_size; ++i) { new_contents_in.push_back(Instance(static_cast<int>(i) + 3)); } SourceContainer new_contents(new_contents_in.begin(), new_contents_in.end()); absl::InlinedVector<Instance, 3> v(original_contents.begin(), original_contents.end()); v.assign(new_contents.begin(), new_contents.end()); EXPECT_EQ(new_contents.size(), v.size()); EXPECT_LE(new_contents.size(), v.capacity()); if (target_size <= 3 && original_size <= 3) { EXPECT_EQ(3u, v.capacity()); } EXPECT_TRUE(std::equal(v.begin(), v.end(), new_contents.begin(), InstanceValuesEqual<Instance>)); } } } TYPED_TEST_P(InstanceTest, RangedAssign) { using Instance = TypeParam; SCOPED_TRACE("std::list"); InstanceRangedAssignTestForContainer<Instance, std::list<Instance>>(); SCOPED_TRACE("const std::list"); InstanceRangedAssignTestForContainer<Instance, const std::list<Instance>>(); SCOPED_TRACE("std::vector"); InstanceRangedAssignTestForContainer<Instance, std::vector<Instance>>(); SCOPED_TRACE("const std::vector"); InstanceRangedAssignTestForContainer<Instance, const std::vector<Instance>>(); } TEST(InitializerListConstructor, SimpleTypeWithInlineBacking) { EXPECT_THAT((absl::InlinedVector<int, 4>{4, 5, 6}), AllOf(SizeIs(3u), CapacityIs(4u), ElementsAre(4, 5, 6))); } TEST(InitializerListConstructor, SimpleTypeWithReallocationRequired) { EXPECT_THAT((absl::InlinedVector<int, 2>{4, 5, 6}), AllOf(SizeIs(3u), CapacityIs(Gt(2u)), ElementsAre(4, 5, 6))); } TEST(InitializerListConstructor, DisparateTypesInList) { EXPECT_THAT((absl::InlinedVector<int, 2>{-7, 8ULL}), ElementsAre(-7, 8)); EXPECT_THAT((absl::InlinedVector<std::string, 2>{"foo", std::string("bar")}), ElementsAre("foo", "bar")); } TEST(InitializerListConstructor, ComplexTypeWithInlineBacking) { const size_t inlined_capacity = absl::InlinedVector<CopyableMovableInstance, 1>().capacity(); EXPECT_THAT( (absl::InlinedVector<CopyableMovableInstance, 1>{ CopyableMovableInstance(0)}), AllOf(SizeIs(1u), CapacityIs(inlined_capacity), ElementsAre(ValueIs(0)))); } TEST(InitializerListConstructor, ComplexTypeWithReallocationRequired) { EXPECT_THAT((absl::InlinedVector<CopyableMovableInstance, 1>{ CopyableMovableInstance(0), CopyableMovableInstance(1)}), AllOf(SizeIs(2u), CapacityIs(Gt(1u)), ElementsAre(ValueIs(0), ValueIs(1)))); } TEST(InitializerListAssign, SimpleTypeFitsInlineBacking) { for (size_t original_size = 0; original_size <= 4; ++original_size) { SCOPED_TRACE(original_size); absl::InlinedVector<int, 2> v1(original_size, 12345); const size_t original_capacity_v1 = v1.capacity(); v1.assign({3}); EXPECT_THAT(v1, AllOf(SizeIs(1u), CapacityIs(original_capacity_v1), ElementsAre(3))); absl::InlinedVector<int, 2> v2(original_size, 12345); const size_t original_capacity_v2 = v2.capacity(); v2 = {3}; EXPECT_THAT(v2, AllOf(SizeIs(1u), CapacityIs(original_capacity_v2), ElementsAre(3))); } } TEST(InitializerListAssign, SimpleTypeDoesNotFitInlineBacking) { for (size_t original_size = 0; original_size <= 4; ++original_size) { SCOPED_TRACE(original_size); absl::InlinedVector<int, 2> v1(original_size, 12345); v1.assign({3, 4, 5}); EXPECT_THAT(v1, AllOf(SizeIs(3u), ElementsAre(3, 4, 5))); EXPECT_LE(3u, v1.capacity()); absl::InlinedVector<int, 2> v2(original_size, 12345); v2 = {3, 4, 5}; EXPECT_THAT(v2, AllOf(SizeIs(3u), ElementsAre(3, 4, 5))); EXPECT_LE(3u, v2.capacity()); } } TEST(InitializerListAssign, DisparateTypesInList) { absl::InlinedVector<int, 2> v_int1; v_int1.assign({-7, 8ULL}); EXPECT_THAT(v_int1, ElementsAre(-7, 8)); absl::InlinedVector<int, 2> v_int2; v_int2 = {-7, 8ULL}; EXPECT_THAT(v_int2, ElementsAre(-7, 8)); absl::InlinedVector<std::string, 2> v_string1; v_string1.assign({"foo", std::string("bar")}); EXPECT_THAT(v_string1, ElementsAre("foo", "bar")); absl::InlinedVector<std::string, 2> v_string2; v_string2 = {"foo", std::string("bar")}; EXPECT_THAT(v_string2, ElementsAre("foo", "bar")); } TYPED_TEST_P(InstanceTest, InitializerListAssign) { using Instance = TypeParam; for (size_t original_size = 0; original_size <= 4; ++original_size) { SCOPED_TRACE(original_size); absl::InlinedVector<Instance, 2> v(original_size, Instance(12345)); const size_t original_capacity = v.capacity(); v.assign({Instance(3)}); EXPECT_THAT(v, AllOf(SizeIs(1u), CapacityIs(original_capacity), ElementsAre(ValueIs(3)))); } for (size_t original_size = 0; original_size <= 4; ++original_size) { SCOPED_TRACE(original_size); absl::InlinedVector<Instance, 2> v(original_size, Instance(12345)); v.assign({Instance(3), Instance(4), Instance(5)}); EXPECT_THAT( v, AllOf(SizeIs(3u), ElementsAre(ValueIs(3), ValueIs(4), ValueIs(5)))); EXPECT_LE(3u, v.capacity()); } } REGISTER_TYPED_TEST_SUITE_P(InstanceTest, Swap, CountConstructorsDestructors, CountConstructorsDestructorsOnCopyConstruction, CountConstructorsDestructorsOnMoveConstruction, CountConstructorsDestructorsOnAssignment, CountConstructorsDestructorsOnMoveAssignment, CountElemAssignInlineBacking, RangedConstructor, RangedAssign, InitializerListAssign); using InstanceTypes = ::testing::Types<CopyableOnlyInstance, CopyableMovableInstance>; INSTANTIATE_TYPED_TEST_SUITE_P(InstanceTestOnTypes, InstanceTest, InstanceTypes); TEST(DynamicVec, DynamicVecCompiles) { DynamicVec v; (void)v; } TEST(DynamicVec, CreateNonEmptyDynamicVec) { DynamicVec v(1); EXPECT_EQ(v.size(), 1u); } TEST(DynamicVec, EmplaceBack) { DynamicVec v; v.emplace_back(Dynamic{}); EXPECT_EQ(v.size(), 1u); } TEST(DynamicVec, EmplaceBackAfterHeapAllocation) { DynamicVec v; v.reserve(10); v.emplace_back(Dynamic{}); EXPECT_EQ(v.size(), 1u); } TEST(DynamicVec, EmptyIteratorComparison) { DynamicVec v; EXPECT_EQ(v.begin(), v.end()); EXPECT_EQ(v.cbegin(), v.cend()); } TEST(AllocatorSupportTest, Constructors) { using MyAlloc = CountingAllocator<int>; using AllocVec = absl::InlinedVector<int, 4, MyAlloc>; const int ia[] = {0, 1, 2, 3, 4, 5, 6, 7}; int64_t allocated = 0; MyAlloc alloc(&allocated); { AllocVec ABSL_ATTRIBUTE_UNUSED v; } { AllocVec ABSL_ATTRIBUTE_UNUSED v(alloc); } { AllocVec ABSL_ATTRIBUTE_UNUSED v(ia, ia + ABSL_ARRAYSIZE(ia), alloc); } { AllocVec ABSL_ATTRIBUTE_UNUSED v({1, 2, 3}, alloc); } AllocVec v2; { AllocVec ABSL_ATTRIBUTE_UNUSED v(v2, alloc); } { AllocVec ABSL_ATTRIBUTE_UNUSED v(std::move(v2), alloc); } } TEST(AllocatorSupportTest, CountAllocations) { using MyAlloc = CountingAllocator<int>; using AllocVec = absl::InlinedVector<int, 4, MyAlloc>; const int ia[] = {0, 1, 2, 3, 4, 5, 6, 7}; int64_t allocated = 0; MyAlloc alloc(&allocated); { AllocVec ABSL_ATTRIBUTE_UNUSED v(ia, ia + 4, alloc); EXPECT_THAT(allocated, Eq(0)); } EXPECT_THAT(allocated, Eq(0)); { AllocVec ABSL_ATTRIBUTE_UNUSED v(ia, ia + ABSL_ARRAYSIZE(ia), alloc); EXPECT_THAT(allocated, Eq(static_cast<int64_t>(v.size() * sizeof(int)))); } EXPECT_THAT(allocated, Eq(0)); { AllocVec v(4, 1, alloc); EXPECT_THAT(allocated, Eq(0)); int64_t allocated2 = 0; MyAlloc alloc2(&allocated2); AllocVec v2(v, alloc2); EXPECT_THAT(allocated2, Eq(0)); int64_t allocated3 = 0; MyAlloc alloc3(&allocated3); AllocVec v3(std::move(v), alloc3); EXPECT_THAT(allocated3, Eq(0)); } EXPECT_THAT(allocated, 0); { AllocVec v(8, 2, alloc); EXPECT_THAT(allocated, Eq(static_cast<int64_t>(v.size() * sizeof(int)))); int64_t allocated2 = 0; MyAlloc alloc2(&allocated2); AllocVec v2(v, alloc2); EXPECT_THAT(allocated2, Eq(static_cast<int64_t>(v2.size() * sizeof(int)))); int64_t allocated3 = 0; MyAlloc alloc3(&allocated3); AllocVec v3(std::move(v), alloc3); EXPECT_THAT(allocated3, Eq(static_cast<int64_t>(v3.size() * sizeof(int)))); } EXPECT_EQ(allocated, 0); { AllocVec v(8, 2, alloc); EXPECT_EQ(allocated, static_cast<int64_t>(8 * sizeof(int))); v.resize(5); EXPECT_EQ(allocated, static_cast<int64_t>(8 * sizeof(int))); v.shrink_to_fit(); EXPECT_EQ(allocated, static_cast<int64_t>(5 * sizeof(int))); v.resize(4); EXPECT_EQ(allocated, static_cast<int64_t>(5 * sizeof(int))); v.shrink_to_fit(); EXPECT_EQ(allocated, 0); } } TEST(AllocatorSupportTest, SwapBothAllocated) { using MyAlloc = CountingAllocator<int>; using AllocVec = absl::InlinedVector<int, 4, MyAlloc>; int64_t allocated1 = 0; int64_t allocated2 = 0; { const int ia1[] = {0, 1, 2, 3, 4, 5, 6, 7}; const int ia2[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; MyAlloc a1(&allocated1); MyAlloc a2(&allocated2); AllocVec v1(ia1, ia1 + ABSL_ARRAYSIZE(ia1), a1); AllocVec v2(ia2, ia2 + ABSL_ARRAYSIZE(ia2), a2); EXPECT_LT(v1.capacity(), v2.capacity()); EXPECT_THAT(allocated1, Eq(static_cast<int64_t>(v1.capacity() * sizeof(int)))); EXPECT_THAT(allocated2, Eq(static_cast<int64_t>(v2.capacity() * sizeof(int)))); v1.swap(v2); EXPECT_THAT(v1, ElementsAreArray(ia2)); EXPECT_THAT(v2, ElementsAreArray(ia1)); EXPECT_THAT(allocated1, Eq(static_cast<int64_t>(v2.capacity() * sizeof(int)))); EXPECT_THAT(allocated2, Eq(static_cast<int64_t>(v1.capacity() * sizeof(int)))); } EXPECT_THAT(allocated1, 0); EXPECT_THAT(allocated2, 0); } TEST(AllocatorSupportTest, SwapOneAllocated) { using MyAlloc = CountingAllocator<int>; using AllocVec = absl::InlinedVector<int, 4, MyAlloc>; int64_t allocated1 = 0; int64_t allocated2 = 0; { const int ia1[] = {0, 1, 2, 3, 4, 5, 6, 7}; const int ia2[] = {0, 1, 2, 3}; MyAlloc a1(&allocated1); MyAlloc a2(&allocated2); AllocVec v1(ia1, ia1 + ABSL_ARRAYSIZE(ia1), a1); AllocVec v2(ia2, ia2 + ABSL_ARRAYSIZE(ia2), a2); EXPECT_THAT(allocated1, Eq(static_cast<int64_t>(v1.capacity() * sizeof(int)))); EXPECT_THAT(allocated2, Eq(0)); v1.swap(v2); EXPECT_THAT(v1, ElementsAreArray(ia2)); EXPECT_THAT(v2, ElementsAreArray(ia1)); EXPECT_THAT(allocated1, Eq(static_cast<int64_t>(v2.capacity() * sizeof(int)))); EXPECT_THAT(allocated2, Eq(0)); EXPECT_TRUE(v2.get_allocator() == a1); EXPECT_TRUE(v1.get_allocator() == a2); } EXPECT_THAT(allocated1, 0); EXPECT_THAT(allocated2, 0); } TEST(AllocatorSupportTest, ScopedAllocatorWorksInlined) { using StdVector = std::vector<int, CountingAllocator<int>>; using Alloc = CountingAllocator<StdVector>; using ScopedAlloc = std::scoped_allocator_adaptor<Alloc>; using AllocVec = absl::InlinedVector<StdVector, 1, ScopedAlloc>; int64_t total_allocated_byte_count = 0; AllocVec inlined_case(ScopedAlloc(Alloc(+&total_allocated_byte_count))); inlined_case.emplace_back(); int64_t absl_responsible_for_count = total_allocated_byte_count; #if !defined(_MSC_VER) EXPECT_EQ(absl_responsible_for_count, 0); #endif inlined_case[0].emplace_back(); EXPECT_GT(total_allocated_byte_count, absl_responsible_for_count); inlined_case.clear(); inlined_case.shrink_to_fit(); EXPECT_EQ(total_allocated_byte_count, 0); } TEST(AllocatorSupportTest, ScopedAllocatorWorksAllocated) { using StdVector = std::vector<int, CountingAllocator<int>>; using Alloc = CountingAllocator<StdVector>; using ScopedAlloc = std::scoped_allocator_adaptor<Alloc>; using AllocVec = absl::InlinedVector<StdVector, 1, ScopedAlloc>; int64_t total_allocated_byte_count = 0; AllocVec allocated_case(ScopedAlloc(Alloc(+&total_allocated_byte_count))); allocated_case.emplace_back(); allocated_case.emplace_back(); int64_t absl_responsible_for_count = total_allocated_byte_count; EXPECT_GT(absl_responsible_for_count, 0); allocated_case[1].emplace_back(); EXPECT_GT(total_allocated_byte_count, absl_responsible_for_count); allocated_case.clear(); allocated_case.shrink_to_fit(); EXPECT_EQ(total_allocated_byte_count, 0); } TEST(AllocatorSupportTest, SizeAllocConstructor) { constexpr size_t inlined_size = 4; using Alloc = CountingAllocator<int>; using AllocVec = absl::InlinedVector<int, inlined_size, Alloc>; { auto len = inlined_size / 2; int64_t allocated = 0; auto v = AllocVec(len, Alloc(&allocated)); EXPECT_THAT(allocated, Eq(0)); EXPECT_THAT(v, AllOf(SizeIs(len), Each(0))); } { auto len = inlined_size * 2; int64_t allocated = 0; auto v = AllocVec(len, Alloc(&allocated)); EXPECT_THAT(allocated, Eq(static_cast<int64_t>(len * sizeof(int)))); EXPECT_THAT(v, AllOf(SizeIs(len), Each(0))); } } TEST(InlinedVectorTest, MinimumAllocatorCompilesUsingTraits) { using T = int; using A = std::allocator<T>; using ATraits = absl::allocator_traits<A>; struct MinimumAllocator { using value_type = T; value_type* allocate(size_t n) { A a; return ATraits::allocate(a, n); } void deallocate(value_type* p, size_t n) { A a; ATraits::deallocate(a, p, n); } }; absl::InlinedVector<T, 1, MinimumAllocator> vec; vec.emplace_back(); vec.resize(0); } TEST(InlinedVectorTest, AbslHashValueWorks) { using V = absl::InlinedVector<int, 4>; std::vector<V> cases; for (size_t i = 0; i < 10; ++i) { V v; for (int j = 0; j < static_cast<int>(i); ++j) { v.push_back(j); } cases.push_back(v); v.resize(i % 4); cases.push_back(v); } EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(cases)); } class MoveConstructibleOnlyInstance : public absl::test_internal::BaseCountedInstance { public: explicit MoveConstructibleOnlyInstance(int x) : BaseCountedInstance(x) {} MoveConstructibleOnlyInstance(MoveConstructibleOnlyInstance&& other) = default; MoveConstructibleOnlyInstance& operator=( MoveConstructibleOnlyInstance&& other) = delete; }; MATCHER(HasValue, "") { return ::testing::get<0>(arg).value() == ::testing::get<1>(arg); } TEST(NonAssignableMoveAssignmentTest, AllocatedToInline) { using X = MoveConstructibleOnlyInstance; InstanceTracker tracker; absl::InlinedVector<X, 2> inlined; inlined.emplace_back(1); absl::InlinedVector<X, 2> allocated; allocated.emplace_back(1); allocated.emplace_back(2); allocated.emplace_back(3); tracker.ResetCopiesMovesSwaps(); inlined = std::move(allocated); EXPECT_EQ(tracker.moves(), 0); EXPECT_EQ(tracker.live_instances(), 3); EXPECT_THAT(inlined, Pointwise(HasValue(), {1, 2, 3})); } TEST(NonAssignableMoveAssignmentTest, InlineToAllocated) { using X = MoveConstructibleOnlyInstance; InstanceTracker tracker; absl::InlinedVector<X, 2> inlined; inlined.emplace_back(1); absl::InlinedVector<X, 2> allocated; allocated.emplace_back(1); allocated.emplace_back(2); allocated.emplace_back(3); tracker.ResetCopiesMovesSwaps(); allocated = std::move(inlined); EXPECT_EQ(tracker.moves(), 1); EXPECT_EQ(tracker.live_instances(), 1); EXPECT_THAT(allocated, Pointwise(HasValue(), {1})); } TEST(NonAssignableMoveAssignmentTest, InlineToInline) { using X = MoveConstructibleOnlyInstance; InstanceTracker tracker; absl::InlinedVector<X, 2> inlined_a; inlined_a.emplace_back(1); absl::InlinedVector<X, 2> inlined_b; inlined_b.emplace_back(1); tracker.ResetCopiesMovesSwaps(); inlined_a = std::move(inlined_b); EXPECT_EQ(tracker.moves(), 1); EXPECT_EQ(tracker.live_instances(), 1); EXPECT_THAT(inlined_a, Pointwise(HasValue(), {1})); } TEST(NonAssignableMoveAssignmentTest, AllocatedToAllocated) { using X = MoveConstructibleOnlyInstance; InstanceTracker tracker; absl::InlinedVector<X, 2> allocated_a; allocated_a.emplace_back(1); allocated_a.emplace_back(2); allocated_a.emplace_back(3); absl::InlinedVector<X, 2> allocated_b; allocated_b.emplace_back(4); allocated_b.emplace_back(5); allocated_b.emplace_back(6); allocated_b.emplace_back(7); tracker.ResetCopiesMovesSwaps(); allocated_a = std::move(allocated_b); EXPECT_EQ(tracker.moves(), 0); EXPECT_EQ(tracker.live_instances(), 4); EXPECT_THAT(allocated_a, Pointwise(HasValue(), {4, 5, 6, 7})); } TEST(NonAssignableMoveAssignmentTest, AssignThis) { using X = MoveConstructibleOnlyInstance; InstanceTracker tracker; absl::InlinedVector<X, 2> v; v.emplace_back(1); v.emplace_back(2); v.emplace_back(3); tracker.ResetCopiesMovesSwaps(); v = std::move(*std::addressof(v)); EXPECT_EQ(tracker.moves(), 0); EXPECT_EQ(tracker.live_instances(), 3); EXPECT_THAT(v, Pointwise(HasValue(), {1, 2, 3})); } class NonSwappableInstance : public absl::test_internal::BaseCountedInstance { public: explicit NonSwappableInstance(int x) : BaseCountedInstance(x) {} NonSwappableInstance(const NonSwappableInstance& other) = default; NonSwappableInstance& operator=(const NonSwappableInstance& other) = default; NonSwappableInstance(NonSwappableInstance&& other) = default; NonSwappableInstance& operator=(NonSwappableInstance&& other) = default; }; void swap(NonSwappableInstance&, NonSwappableInstance&) = delete; TEST(NonSwappableSwapTest, InlineAndAllocatedTransferStorageAndMove) { using X = NonSwappableInstance; InstanceTracker tracker; absl::InlinedVector<X, 2> inlined; inlined.emplace_back(1); absl::InlinedVector<X, 2> allocated; allocated.emplace_back(1); allocated.emplace_back(2); allocated.emplace_back(3); tracker.ResetCopiesMovesSwaps(); inlined.swap(allocated); EXPECT_EQ(tracker.moves(), 1); EXPECT_EQ(tracker.live_instances(), 4); EXPECT_THAT(inlined, Pointwise(HasValue(), {1, 2, 3})); } TEST(NonSwappableSwapTest, InlineAndInlineMoveIndividualElements) { using X = NonSwappableInstance; InstanceTracker tracker; absl::InlinedVector<X, 2> inlined_a; inlined_a.emplace_back(1); absl::InlinedVector<X, 2> inlined_b; inlined_b.emplace_back(2); tracker.ResetCopiesMovesSwaps(); inlined_a.swap(inlined_b); EXPECT_EQ(tracker.moves(), 3); EXPECT_EQ(tracker.live_instances(), 2); EXPECT_THAT(inlined_a, Pointwise(HasValue(), {2})); EXPECT_THAT(inlined_b, Pointwise(HasValue(), {1})); } TEST(NonSwappableSwapTest, AllocatedAndAllocatedOnlyTransferStorage) { using X = NonSwappableInstance; InstanceTracker tracker; absl::InlinedVector<X, 2> allocated_a; allocated_a.emplace_back(1); allocated_a.emplace_back(2); allocated_a.emplace_back(3); absl::InlinedVector<X, 2> allocated_b; allocated_b.emplace_back(4); allocated_b.emplace_back(5); allocated_b.emplace_back(6); allocated_b.emplace_back(7); tracker.ResetCopiesMovesSwaps(); allocated_a.swap(allocated_b); EXPECT_EQ(tracker.moves(), 0); EXPECT_EQ(tracker.live_instances(), 7); EXPECT_THAT(allocated_a, Pointwise(HasValue(), {4, 5, 6, 7})); EXPECT_THAT(allocated_b, Pointwise(HasValue(), {1, 2, 3})); } TEST(NonSwappableSwapTest, SwapThis) { using X = NonSwappableInstance; InstanceTracker tracker; absl::InlinedVector<X, 2> v; v.emplace_back(1); v.emplace_back(2); v.emplace_back(3); tracker.ResetCopiesMovesSwaps(); v.swap(v); EXPECT_EQ(tracker.moves(), 0); EXPECT_EQ(tracker.live_instances(), 3); EXPECT_THAT(v, Pointwise(HasValue(), {1, 2, 3})); } template <size_t N> using CharVec = absl::InlinedVector<char, N>; template <typename T> struct MySpan { T* data; size_t size; }; TEST(StorageTest, InlinedCapacityAutoIncrease) { EXPECT_GT(CharVec<1>().capacity(), 1); EXPECT_EQ(CharVec<1>().capacity(), sizeof(MySpan<char>)); EXPECT_EQ(CharVec<1>().capacity(), CharVec<2>().capacity()); EXPECT_EQ(sizeof(CharVec<1>), sizeof(CharVec<2>)); EXPECT_GT((absl::InlinedVector<int, 1>().capacity()), 1); EXPECT_EQ((absl::InlinedVector<int, 1>().capacity()), sizeof(MySpan<int>) / sizeof(int)); } }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/inlined_vector.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/inlined_vector_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
967a66dc-1c0b-4779-ba8f-04e0591f8900
cpp
abseil/abseil-cpp
flat_hash_set
absl/container/flat_hash_set.h
absl/container/flat_hash_set_test.cc
#ifndef ABSL_CONTAINER_FLAT_HASH_SET_H_ #define ABSL_CONTAINER_FLAT_HASH_SET_H_ #include <cstddef> #include <memory> #include <type_traits> #include <utility> #include "absl/algorithm/container.h" #include "absl/base/attributes.h" #include "absl/base/macros.h" #include "absl/container/hash_container_defaults.h" #include "absl/container/internal/container_memory.h" #include "absl/container/internal/raw_hash_set.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { template <typename T> struct FlatHashSetPolicy; } template <class T, class Hash = DefaultHashContainerHash<T>, class Eq = DefaultHashContainerEq<T>, class Allocator = std::allocator<T>> class ABSL_ATTRIBUTE_OWNER flat_hash_set : public absl::container_internal::raw_hash_set< absl::container_internal::FlatHashSetPolicy<T>, Hash, Eq, Allocator> { using Base = typename flat_hash_set::raw_hash_set; public: flat_hash_set() {} using Base::Base; using Base::begin; using Base::cbegin; using Base::cend; using Base::end; using Base::capacity; using Base::empty; using Base::max_size; using Base::size; using Base::clear; using Base::erase; using Base::insert; using Base::emplace; using Base::emplace_hint; using Base::extract; using Base::merge; using Base::swap; using Base::rehash; using Base::reserve; using Base::contains; using Base::count; using Base::equal_range; using Base::find; using Base::bucket_count; using Base::load_factor; using Base::max_load_factor; using Base::get_allocator; using Base::hash_function; using Base::key_eq; }; template <typename T, typename H, typename E, typename A, typename Predicate> typename flat_hash_set<T, H, E, A>::size_type erase_if( flat_hash_set<T, H, E, A>& c, Predicate pred) { return container_internal::EraseIf(pred, &c); } template <typename T, typename H, typename E, typename A> void swap(flat_hash_set<T, H, E, A>& x, flat_hash_set<T, H, E, A>& y) noexcept(noexcept(x.swap(y))) { return x.swap(y); } namespace container_internal { template <typename T, typename H, typename E, typename A, typename Function> decay_t<Function> c_for_each_fast(const flat_hash_set<T, H, E, A>& c, Function&& f) { container_internal::ForEach(f, &c); return f; } template <typename T, typename H, typename E, typename A, typename Function> decay_t<Function> c_for_each_fast(flat_hash_set<T, H, E, A>& c, Function&& f) { container_internal::ForEach(f, &c); return f; } template <typename T, typename H, typename E, typename A, typename Function> decay_t<Function> c_for_each_fast(flat_hash_set<T, H, E, A>&& c, Function&& f) { container_internal::ForEach(f, &c); return f; } } namespace container_internal { template <class T> struct FlatHashSetPolicy { using slot_type = T; using key_type = T; using init_type = T; using constant_iterators = std::true_type; template <class Allocator, class... Args> static void construct(Allocator* alloc, slot_type* slot, Args&&... args) { absl::allocator_traits<Allocator>::construct(*alloc, slot, std::forward<Args>(args)...); } template <class Allocator> static auto destroy(Allocator* alloc, slot_type* slot) { absl::allocator_traits<Allocator>::destroy(*alloc, slot); return IsDestructionTrivial<Allocator, slot_type>(); } static T& element(slot_type* slot) { return *slot; } template <class F, class... Args> static decltype(absl::container_internal::DecomposeValue( std::declval<F>(), std::declval<Args>()...)) apply(F&& f, Args&&... args) { return absl::container_internal::DecomposeValue( std::forward<F>(f), std::forward<Args>(args)...); } static size_t space_used(const T*) { return 0; } template <class Hash> static constexpr HashSlotFn get_hash_slot_fn() { return &TypeErasedApplyToSlotFn<Hash, T>; } }; } namespace container_algorithm_internal { template <class Key, class Hash, class KeyEqual, class Allocator> struct IsUnorderedContainer<absl::flat_hash_set<Key, Hash, KeyEqual, Allocator>> : std::true_type {}; } ABSL_NAMESPACE_END } #endif
#include "absl/container/flat_hash_set.h" #include <cstddef> #include <cstdint> #include <memory> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/container/hash_container_defaults.h" #include "absl/container/internal/container_memory.h" #include "absl/container/internal/hash_generator_testing.h" #include "absl/container/internal/test_allocator.h" #include "absl/container/internal/unordered_set_constructor_test.h" #include "absl/container/internal/unordered_set_lookup_test.h" #include "absl/container/internal/unordered_set_members_test.h" #include "absl/container/internal/unordered_set_modifiers_test.h" #include "absl/hash/hash.h" #include "absl/log/check.h" #include "absl/memory/memory.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { using ::absl::container_internal::hash_internal::Enum; using ::absl::container_internal::hash_internal::EnumClass; using ::testing::IsEmpty; using ::testing::Pointee; using ::testing::UnorderedElementsAre; using ::testing::UnorderedElementsAreArray; struct BeforeMain { BeforeMain() { absl::flat_hash_set<int> x; x.insert(1); CHECK(!x.contains(0)) << "x should not contain 0"; CHECK(x.contains(1)) << "x should contain 1"; } }; const BeforeMain before_main; template <class T> using Set = absl::flat_hash_set<T, StatefulTestingHash, StatefulTestingEqual, Alloc<T>>; using SetTypes = ::testing::Types<Set<int>, Set<std::string>, Set<Enum>, Set<EnumClass>>; INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashSet, ConstructorTest, SetTypes); INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashSet, LookupTest, SetTypes); INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashSet, MembersTest, SetTypes); INSTANTIATE_TYPED_TEST_SUITE_P(FlatHashSet, ModifiersTest, SetTypes); TEST(FlatHashSet, EmplaceString) { std::vector<std::string> v = {"a", "b"}; absl::flat_hash_set<absl::string_view> hs(v.begin(), v.end()); EXPECT_THAT(hs, UnorderedElementsAreArray(v)); } TEST(FlatHashSet, BitfieldArgument) { union { int n : 1; }; n = 0; absl::flat_hash_set<int> s = {n}; s.insert(n); s.insert(s.end(), n); s.insert({n}); s.erase(n); s.count(n); s.prefetch(n); s.find(n); s.contains(n); s.equal_range(n); } TEST(FlatHashSet, MergeExtractInsert) { struct Hash { size_t operator()(const std::unique_ptr<int>& p) const { return *p; } }; struct Eq { bool operator()(const std::unique_ptr<int>& a, const std::unique_ptr<int>& b) const { return *a == *b; } }; absl::flat_hash_set<std::unique_ptr<int>, Hash, Eq> set1, set2; set1.insert(absl::make_unique<int>(7)); set1.insert(absl::make_unique<int>(17)); set2.insert(absl::make_unique<int>(7)); set2.insert(absl::make_unique<int>(19)); EXPECT_THAT(set1, UnorderedElementsAre(Pointee(7), Pointee(17))); EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7), Pointee(19))); set1.merge(set2); EXPECT_THAT(set1, UnorderedElementsAre(Pointee(7), Pointee(17), Pointee(19))); EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7))); auto node = set1.extract(absl::make_unique<int>(7)); EXPECT_TRUE(node); EXPECT_THAT(node.value(), Pointee(7)); EXPECT_THAT(set1, UnorderedElementsAre(Pointee(17), Pointee(19))); auto insert_result = set2.insert(std::move(node)); EXPECT_FALSE(node); EXPECT_FALSE(insert_result.inserted); EXPECT_TRUE(insert_result.node); EXPECT_THAT(insert_result.node.value(), Pointee(7)); EXPECT_EQ(**insert_result.position, 7); EXPECT_NE(insert_result.position->get(), insert_result.node.value().get()); EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7))); node = set1.extract(absl::make_unique<int>(17)); EXPECT_TRUE(node); EXPECT_THAT(node.value(), Pointee(17)); EXPECT_THAT(set1, UnorderedElementsAre(Pointee(19))); node.value() = absl::make_unique<int>(23); insert_result = set2.insert(std::move(node)); EXPECT_FALSE(node); EXPECT_TRUE(insert_result.inserted); EXPECT_FALSE(insert_result.node); EXPECT_EQ(**insert_result.position, 23); EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7), Pointee(23))); } bool IsEven(int k) { return k % 2 == 0; } TEST(FlatHashSet, EraseIf) { { flat_hash_set<int> s = {1, 2, 3, 4, 5}; EXPECT_EQ(erase_if(s, [](int) { return true; }), 5); EXPECT_THAT(s, IsEmpty()); } { flat_hash_set<int> s = {1, 2, 3, 4, 5}; EXPECT_EQ(erase_if(s, [](int) { return false; }), 0); EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5)); } { flat_hash_set<int> s = {1, 2, 3, 4, 5}; EXPECT_EQ(erase_if(s, [](int k) { return k % 2 == 1; }), 3); EXPECT_THAT(s, UnorderedElementsAre(2, 4)); } { flat_hash_set<int> s = {1, 2, 3, 4, 5}; EXPECT_EQ(erase_if(s, IsEven), 2); EXPECT_THAT(s, UnorderedElementsAre(1, 3, 5)); } { flat_hash_set<int> s = {1, 2, 3, 4, 5}; EXPECT_EQ(erase_if(s, &IsEven), 2); EXPECT_THAT(s, UnorderedElementsAre(1, 3, 5)); } } TEST(FlatHashSet, CForEach) { using ValueType = std::pair<int, int>; flat_hash_set<ValueType> s; std::vector<ValueType> expected; for (int i = 0; i < 100; ++i) { { SCOPED_TRACE("mutable object iteration"); std::vector<ValueType> v; absl::container_internal::c_for_each_fast( s, [&v](const ValueType& p) { v.push_back(p); }); ASSERT_THAT(v, UnorderedElementsAreArray(expected)); } { SCOPED_TRACE("const object iteration"); std::vector<ValueType> v; const flat_hash_set<ValueType>& cs = s; absl::container_internal::c_for_each_fast( cs, [&v](const ValueType& p) { v.push_back(p); }); ASSERT_THAT(v, UnorderedElementsAreArray(expected)); } { SCOPED_TRACE("temporary object iteration"); std::vector<ValueType> v; absl::container_internal::c_for_each_fast( flat_hash_set<ValueType>(s), [&v](const ValueType& p) { v.push_back(p); }); ASSERT_THAT(v, UnorderedElementsAreArray(expected)); } s.emplace(i, i); expected.emplace_back(i, i); } } class PoisonSoo { int64_t data_; public: explicit PoisonSoo(int64_t d) : data_(d) { SanitizerPoisonObject(&data_); } PoisonSoo(const PoisonSoo& that) : PoisonSoo(*that) {} ~PoisonSoo() { SanitizerUnpoisonObject(&data_); } int64_t operator*() const { SanitizerUnpoisonObject(&data_); const int64_t ret = data_; SanitizerPoisonObject(&data_); return ret; } template <typename H> friend H AbslHashValue(H h, const PoisonSoo& pi) { return H::combine(std::move(h), *pi); } bool operator==(const PoisonSoo& rhs) const { return **this == *rhs; } }; TEST(FlatHashSet, PoisonSooBasic) { PoisonSoo a(0), b(1); flat_hash_set<PoisonSoo> set; set.insert(a); EXPECT_THAT(set, UnorderedElementsAre(a)); set.insert(b); EXPECT_THAT(set, UnorderedElementsAre(a, b)); set.erase(a); EXPECT_THAT(set, UnorderedElementsAre(b)); set.rehash(0); EXPECT_THAT(set, UnorderedElementsAre(b)); } TEST(FlatHashSet, PoisonSooMoveConstructSooToSoo) { PoisonSoo a(0); flat_hash_set<PoisonSoo> set; set.insert(a); flat_hash_set<PoisonSoo> set2(std::move(set)); EXPECT_THAT(set2, UnorderedElementsAre(a)); } TEST(FlatHashSet, PoisonSooAllocMoveConstructSooToSoo) { PoisonSoo a(0); flat_hash_set<PoisonSoo> set; set.insert(a); flat_hash_set<PoisonSoo> set2(std::move(set), std::allocator<PoisonSoo>()); EXPECT_THAT(set2, UnorderedElementsAre(a)); } TEST(FlatHashSet, PoisonSooMoveAssignFullSooToEmptySoo) { PoisonSoo a(0); flat_hash_set<PoisonSoo> set, set2; set.insert(a); set2 = std::move(set); EXPECT_THAT(set2, UnorderedElementsAre(a)); } TEST(FlatHashSet, PoisonSooMoveAssignFullSooToFullSoo) { PoisonSoo a(0), b(1); flat_hash_set<PoisonSoo> set, set2; set.insert(a); set2.insert(b); set2 = std::move(set); EXPECT_THAT(set2, UnorderedElementsAre(a)); } TEST(FlatHashSet, FlatHashSetPolicyDestroyReturnsTrue) { EXPECT_TRUE((decltype(FlatHashSetPolicy<int>::destroy<std::allocator<int>>( nullptr, nullptr))())); EXPECT_FALSE( (decltype(FlatHashSetPolicy<int>::destroy<CountingAllocator<int>>( nullptr, nullptr))())); EXPECT_FALSE((decltype(FlatHashSetPolicy<std::unique_ptr<int>>::destroy< std::allocator<int>>(nullptr, nullptr))())); } struct HashEqInvalidOnMove { HashEqInvalidOnMove() = default; HashEqInvalidOnMove(const HashEqInvalidOnMove& rhs) = default; HashEqInvalidOnMove(HashEqInvalidOnMove&& rhs) { rhs.moved = true; } HashEqInvalidOnMove& operator=(const HashEqInvalidOnMove& rhs) = default; HashEqInvalidOnMove& operator=(HashEqInvalidOnMove&& rhs) { rhs.moved = true; return *this; } size_t operator()(int x) const { CHECK(!moved); return absl::HashOf(x); } bool operator()(int x, int y) const { CHECK(!moved); return x == y; } bool moved = false; }; TEST(FlatHashSet, MovedFromCleared_HashMustBeValid) { flat_hash_set<int, HashEqInvalidOnMove> s1, s2; s2 = std::move(s1); s1.clear(); s1.insert(2); EXPECT_THAT(s1, UnorderedElementsAre(2)); } TEST(FlatHashSet, MovedFromCleared_EqMustBeValid) { flat_hash_set<int, DefaultHashContainerHash<int>, HashEqInvalidOnMove> s1, s2; s2 = std::move(s1); s1.clear(); s1.insert(2); EXPECT_THAT(s1, UnorderedElementsAre(2)); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/flat_hash_set.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/flat_hash_set_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
c0f3b482-04ff-4db4-a205-27b295820274
cpp
abseil/abseil-cpp
node_hash_set
absl/container/node_hash_set.h
absl/container/node_hash_set_test.cc
#ifndef ABSL_CONTAINER_NODE_HASH_SET_H_ #define ABSL_CONTAINER_NODE_HASH_SET_H_ #include <cstddef> #include <memory> #include <type_traits> #include "absl/algorithm/container.h" #include "absl/base/attributes.h" #include "absl/container/hash_container_defaults.h" #include "absl/container/internal/container_memory.h" #include "absl/container/internal/node_slot_policy.h" #include "absl/container/internal/raw_hash_set.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { template <typename T> struct NodeHashSetPolicy; } template <class T, class Hash = DefaultHashContainerHash<T>, class Eq = DefaultHashContainerEq<T>, class Alloc = std::allocator<T>> class ABSL_ATTRIBUTE_OWNER node_hash_set : public absl::container_internal::raw_hash_set< absl::container_internal::NodeHashSetPolicy<T>, Hash, Eq, Alloc> { using Base = typename node_hash_set::raw_hash_set; public: node_hash_set() {} using Base::Base; using Base::begin; using Base::cbegin; using Base::cend; using Base::end; using Base::capacity; using Base::empty; using Base::max_size; using Base::size; using Base::clear; using Base::erase; using Base::insert; using Base::emplace; using Base::emplace_hint; using Base::extract; using Base::merge; using Base::swap; using Base::rehash; using Base::reserve; using Base::contains; using Base::count; using Base::equal_range; using Base::find; using Base::bucket_count; using Base::load_factor; using Base::max_load_factor; using Base::get_allocator; using Base::hash_function; using Base::key_eq; }; template <typename T, typename H, typename E, typename A, typename Predicate> typename node_hash_set<T, H, E, A>::size_type erase_if( node_hash_set<T, H, E, A>& c, Predicate pred) { return container_internal::EraseIf(pred, &c); } template <typename T, typename H, typename E, typename A> void swap(node_hash_set<T, H, E, A>& x, node_hash_set<T, H, E, A>& y) noexcept(noexcept(x.swap(y))) { return x.swap(y); } namespace container_internal { template <typename T, typename H, typename E, typename A, typename Function> decay_t<Function> c_for_each_fast(const node_hash_set<T, H, E, A>& c, Function&& f) { container_internal::ForEach(f, &c); return f; } template <typename T, typename H, typename E, typename A, typename Function> decay_t<Function> c_for_each_fast(node_hash_set<T, H, E, A>& c, Function&& f) { container_internal::ForEach(f, &c); return f; } template <typename T, typename H, typename E, typename A, typename Function> decay_t<Function> c_for_each_fast(node_hash_set<T, H, E, A>&& c, Function&& f) { container_internal::ForEach(f, &c); return f; } } namespace container_internal { template <class T> struct NodeHashSetPolicy : absl::container_internal::node_slot_policy<T&, NodeHashSetPolicy<T>> { using key_type = T; using init_type = T; using constant_iterators = std::true_type; template <class Allocator, class... Args> static T* new_element(Allocator* alloc, Args&&... args) { using ValueAlloc = typename absl::allocator_traits<Allocator>::template rebind_alloc<T>; ValueAlloc value_alloc(*alloc); T* res = absl::allocator_traits<ValueAlloc>::allocate(value_alloc, 1); absl::allocator_traits<ValueAlloc>::construct(value_alloc, res, std::forward<Args>(args)...); return res; } template <class Allocator> static void delete_element(Allocator* alloc, T* elem) { using ValueAlloc = typename absl::allocator_traits<Allocator>::template rebind_alloc<T>; ValueAlloc value_alloc(*alloc); absl::allocator_traits<ValueAlloc>::destroy(value_alloc, elem); absl::allocator_traits<ValueAlloc>::deallocate(value_alloc, elem, 1); } template <class F, class... Args> static decltype(absl::container_internal::DecomposeValue( std::declval<F>(), std::declval<Args>()...)) apply(F&& f, Args&&... args) { return absl::container_internal::DecomposeValue( std::forward<F>(f), std::forward<Args>(args)...); } static size_t element_space_used(const T*) { return sizeof(T); } template <class Hash> static constexpr HashSlotFn get_hash_slot_fn() { return &TypeErasedDerefAndApplyToSlotFn<Hash, T>; } }; } namespace container_algorithm_internal { template <class Key, class Hash, class KeyEqual, class Allocator> struct IsUnorderedContainer<absl::node_hash_set<Key, Hash, KeyEqual, Allocator>> : std::true_type {}; } ABSL_NAMESPACE_END } #endif
#include "absl/container/node_hash_set.h" #include <cstddef> #include <memory> #include <string> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/container/internal/hash_generator_testing.h" #include "absl/container/internal/hash_policy_testing.h" #include "absl/container/internal/unordered_set_constructor_test.h" #include "absl/container/internal/unordered_set_lookup_test.h" #include "absl/container/internal/unordered_set_members_test.h" #include "absl/container/internal/unordered_set_modifiers_test.h" #include "absl/memory/memory.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { using ::absl::container_internal::hash_internal::Enum; using ::absl::container_internal::hash_internal::EnumClass; using ::testing::IsEmpty; using ::testing::Pointee; using ::testing::UnorderedElementsAre; using ::testing::UnorderedElementsAreArray; using SetTypes = ::testing::Types< node_hash_set<int, StatefulTestingHash, StatefulTestingEqual, Alloc<int>>, node_hash_set<std::string, StatefulTestingHash, StatefulTestingEqual, Alloc<std::string>>, node_hash_set<Enum, StatefulTestingHash, StatefulTestingEqual, Alloc<Enum>>, node_hash_set<EnumClass, StatefulTestingHash, StatefulTestingEqual, Alloc<EnumClass>>>; INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashSet, ConstructorTest, SetTypes); INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashSet, LookupTest, SetTypes); INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashSet, MembersTest, SetTypes); INSTANTIATE_TYPED_TEST_SUITE_P(NodeHashSet, ModifiersTest, SetTypes); TEST(NodeHashSet, MoveableNotCopyableCompiles) { node_hash_set<std::unique_ptr<void*>> t; node_hash_set<std::unique_ptr<void*>> u; u = std::move(t); } TEST(NodeHashSet, MergeExtractInsert) { struct Hash { size_t operator()(const std::unique_ptr<int>& p) const { return *p; } }; struct Eq { bool operator()(const std::unique_ptr<int>& a, const std::unique_ptr<int>& b) const { return *a == *b; } }; absl::node_hash_set<std::unique_ptr<int>, Hash, Eq> set1, set2; set1.insert(absl::make_unique<int>(7)); set1.insert(absl::make_unique<int>(17)); set2.insert(absl::make_unique<int>(7)); set2.insert(absl::make_unique<int>(19)); EXPECT_THAT(set1, UnorderedElementsAre(Pointee(7), Pointee(17))); EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7), Pointee(19))); set1.merge(set2); EXPECT_THAT(set1, UnorderedElementsAre(Pointee(7), Pointee(17), Pointee(19))); EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7))); auto node = set1.extract(absl::make_unique<int>(7)); EXPECT_TRUE(node); EXPECT_THAT(node.value(), Pointee(7)); EXPECT_THAT(set1, UnorderedElementsAre(Pointee(17), Pointee(19))); auto insert_result = set2.insert(std::move(node)); EXPECT_FALSE(node); EXPECT_FALSE(insert_result.inserted); EXPECT_TRUE(insert_result.node); EXPECT_THAT(insert_result.node.value(), Pointee(7)); EXPECT_EQ(**insert_result.position, 7); EXPECT_NE(insert_result.position->get(), insert_result.node.value().get()); EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7))); node = set1.extract(absl::make_unique<int>(17)); EXPECT_TRUE(node); EXPECT_THAT(node.value(), Pointee(17)); EXPECT_THAT(set1, UnorderedElementsAre(Pointee(19))); node.value() = absl::make_unique<int>(23); insert_result = set2.insert(std::move(node)); EXPECT_FALSE(node); EXPECT_TRUE(insert_result.inserted); EXPECT_FALSE(insert_result.node); EXPECT_EQ(**insert_result.position, 23); EXPECT_THAT(set2, UnorderedElementsAre(Pointee(7), Pointee(23))); } bool IsEven(int k) { return k % 2 == 0; } TEST(NodeHashSet, EraseIf) { { node_hash_set<int> s = {1, 2, 3, 4, 5}; EXPECT_EQ(erase_if(s, [](int) { return true; }), 5); EXPECT_THAT(s, IsEmpty()); } { node_hash_set<int> s = {1, 2, 3, 4, 5}; EXPECT_EQ(erase_if(s, [](int) { return false; }), 0); EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5)); } { node_hash_set<int> s = {1, 2, 3, 4, 5}; EXPECT_EQ(erase_if(s, [](int k) { return k % 2 == 1; }), 3); EXPECT_THAT(s, UnorderedElementsAre(2, 4)); } { node_hash_set<int> s = {1, 2, 3, 4, 5}; EXPECT_EQ(erase_if(s, IsEven), 2); EXPECT_THAT(s, UnorderedElementsAre(1, 3, 5)); } { node_hash_set<int> s = {1, 2, 3, 4, 5}; EXPECT_EQ(erase_if(s, &IsEven), 2); EXPECT_THAT(s, UnorderedElementsAre(1, 3, 5)); } } TEST(NodeHashSet, CForEach) { using ValueType = std::pair<int, int>; node_hash_set<ValueType> s; std::vector<ValueType> expected; for (int i = 0; i < 100; ++i) { { SCOPED_TRACE("mutable object iteration"); std::vector<ValueType> v; absl::container_internal::c_for_each_fast( s, [&v](const ValueType& p) { v.push_back(p); }); ASSERT_THAT(v, UnorderedElementsAreArray(expected)); } { SCOPED_TRACE("const object iteration"); std::vector<ValueType> v; const node_hash_set<ValueType>& cs = s; absl::container_internal::c_for_each_fast( cs, [&v](const ValueType& p) { v.push_back(p); }); ASSERT_THAT(v, UnorderedElementsAreArray(expected)); } { SCOPED_TRACE("temporary object iteration"); std::vector<ValueType> v; absl::container_internal::c_for_each_fast( node_hash_set<ValueType>(s), [&v](const ValueType& p) { v.push_back(p); }); ASSERT_THAT(v, UnorderedElementsAreArray(expected)); } s.emplace(i, i); expected.emplace_back(i, i); } } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/node_hash_set.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/node_hash_set_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
03551e62-0ce4-4561-918a-6ab8eb0b98ac
cpp
abseil/abseil-cpp
compressed_tuple
absl/container/internal/compressed_tuple.h
absl/container/internal/compressed_tuple_test.cc
#ifndef ABSL_CONTAINER_INTERNAL_COMPRESSED_TUPLE_H_ #define ABSL_CONTAINER_INTERNAL_COMPRESSED_TUPLE_H_ #include <initializer_list> #include <tuple> #include <type_traits> #include <utility> #include "absl/utility/utility.h" #if defined(_MSC_VER) && !defined(__NVCC__) #define ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC __declspec(empty_bases) #else #define ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { template <typename... Ts> class CompressedTuple; namespace internal_compressed_tuple { template <typename D, size_t I> struct Elem; template <typename... B, size_t I> struct Elem<CompressedTuple<B...>, I> : std::tuple_element<I, std::tuple<B...>> {}; template <typename D, size_t I> using ElemT = typename Elem<D, I>::type; struct uses_inheritance {}; template <typename T> constexpr bool ShouldUseBase() { return std::is_class<T>::value && std::is_empty<T>::value && !std::is_final<T>::value && !std::is_base_of<uses_inheritance, T>::value; } template <typename T, size_t I, bool UseBase = ShouldUseBase<T>()> struct Storage { T value; constexpr Storage() = default; template <typename V> explicit constexpr Storage(absl::in_place_t, V&& v) : value(std::forward<V>(v)) {} constexpr const T& get() const& { return value; } constexpr T& get() & { return value; } constexpr const T&& get() const&& { return std::move(*this).value; } constexpr T&& get() && { return std::move(*this).value; } }; template <typename T, size_t I> struct ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC Storage<T, I, true> : T { constexpr Storage() = default; template <typename V> explicit constexpr Storage(absl::in_place_t, V&& v) : T(std::forward<V>(v)) {} constexpr const T& get() const& { return *this; } constexpr T& get() & { return *this; } constexpr const T&& get() const&& { return std::move(*this); } constexpr T&& get() && { return std::move(*this); } }; template <typename D, typename I, bool ShouldAnyUseBase> struct ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC CompressedTupleImpl; template <typename... Ts, size_t... I, bool ShouldAnyUseBase> struct ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC CompressedTupleImpl< CompressedTuple<Ts...>, absl::index_sequence<I...>, ShouldAnyUseBase> : uses_inheritance, Storage<Ts, std::integral_constant<size_t, I>::value>... { constexpr CompressedTupleImpl() = default; template <typename... Vs> explicit constexpr CompressedTupleImpl(absl::in_place_t, Vs&&... args) : Storage<Ts, I>(absl::in_place, std::forward<Vs>(args))... {} friend CompressedTuple<Ts...>; }; template <typename... Ts, size_t... I> struct ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC CompressedTupleImpl< CompressedTuple<Ts...>, absl::index_sequence<I...>, false> : Storage<Ts, std::integral_constant<size_t, I>::value, false>... { constexpr CompressedTupleImpl() = default; template <typename... Vs> explicit constexpr CompressedTupleImpl(absl::in_place_t, Vs&&... args) : Storage<Ts, I, false>(absl::in_place, std::forward<Vs>(args))... {} friend CompressedTuple<Ts...>; }; std::false_type Or(std::initializer_list<std::false_type>); std::true_type Or(std::initializer_list<bool>); template <typename... Ts> constexpr bool ShouldAnyUseBase() { return decltype( Or({std::integral_constant<bool, ShouldUseBase<Ts>()>()...})){}; } template <typename T, typename V> using TupleElementMoveConstructible = typename std::conditional<std::is_reference<T>::value, std::is_convertible<V, T>, std::is_constructible<T, V&&>>::type; template <bool SizeMatches, class T, class... Vs> struct TupleMoveConstructible : std::false_type {}; template <class... Ts, class... Vs> struct TupleMoveConstructible<true, CompressedTuple<Ts...>, Vs...> : std::integral_constant< bool, absl::conjunction< TupleElementMoveConstructible<Ts, Vs&&>...>::value> {}; template <typename T> struct compressed_tuple_size; template <typename... Es> struct compressed_tuple_size<CompressedTuple<Es...>> : public std::integral_constant<std::size_t, sizeof...(Es)> {}; template <class T, class... Vs> struct TupleItemsMoveConstructible : std::integral_constant< bool, TupleMoveConstructible<compressed_tuple_size<T>::value == sizeof...(Vs), T, Vs...>::value> {}; } template <typename... Ts> class ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC CompressedTuple : private internal_compressed_tuple::CompressedTupleImpl< CompressedTuple<Ts...>, absl::index_sequence_for<Ts...>, internal_compressed_tuple::ShouldAnyUseBase<Ts...>()> { private: template <int I> using ElemT = internal_compressed_tuple::ElemT<CompressedTuple, I>; template <int I> using StorageT = internal_compressed_tuple::Storage<ElemT<I>, I>; public: #if defined(_MSC_VER) constexpr CompressedTuple() : CompressedTuple::CompressedTupleImpl() {} #else constexpr CompressedTuple() = default; #endif explicit constexpr CompressedTuple(const Ts&... base) : CompressedTuple::CompressedTupleImpl(absl::in_place, base...) {} template <typename First, typename... Vs, absl::enable_if_t< absl::conjunction< absl::negation<std::is_same<void(CompressedTuple), void(absl::decay_t<First>)>>, internal_compressed_tuple::TupleItemsMoveConstructible< CompressedTuple<Ts...>, First, Vs...>>::value, bool> = true> explicit constexpr CompressedTuple(First&& first, Vs&&... base) : CompressedTuple::CompressedTupleImpl(absl::in_place, std::forward<First>(first), std::forward<Vs>(base)...) {} template <int I> constexpr ElemT<I>& get() & { return StorageT<I>::get(); } template <int I> constexpr const ElemT<I>& get() const& { return StorageT<I>::get(); } template <int I> constexpr ElemT<I>&& get() && { return std::move(*this).StorageT<I>::get(); } template <int I> constexpr const ElemT<I>&& get() const&& { return std::move(*this).StorageT<I>::get(); } }; template <> class ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC CompressedTuple<> {}; } ABSL_NAMESPACE_END } #undef ABSL_INTERNAL_COMPRESSED_TUPLE_DECLSPEC #endif
#include "absl/container/internal/compressed_tuple.h" #include <memory> #include <set> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/internal/test_instance_tracker.h" #include "absl/memory/memory.h" #include "absl/types/any.h" #include "absl/types/optional.h" #include "absl/utility/utility.h" enum class CallType { kMutableRef, kConstRef, kMutableMove, kConstMove }; template <int> struct Empty { constexpr CallType value() & { return CallType::kMutableRef; } constexpr CallType value() const& { return CallType::kConstRef; } constexpr CallType value() && { return CallType::kMutableMove; } constexpr CallType value() const&& { return CallType::kConstMove; } }; template <typename T> constexpr T& AsLValue(T&& t) { return t; } template <typename T> struct NotEmpty { T value; }; template <typename T, typename U> struct TwoValues { T value1; U value2; }; namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { using absl::test_internal::CopyableMovableInstance; using absl::test_internal::InstanceTracker; using ::testing::Each; TEST(CompressedTupleTest, Sizeof) { EXPECT_EQ(sizeof(int), sizeof(CompressedTuple<int>)); EXPECT_EQ(sizeof(int), sizeof(CompressedTuple<int, Empty<0>>)); EXPECT_EQ(sizeof(int), sizeof(CompressedTuple<int, Empty<0>, Empty<1>>)); EXPECT_EQ(sizeof(int), sizeof(CompressedTuple<int, Empty<0>, Empty<1>, Empty<2>>)); EXPECT_EQ(sizeof(TwoValues<int, double>), sizeof(CompressedTuple<int, NotEmpty<double>>)); EXPECT_EQ(sizeof(TwoValues<int, double>), sizeof(CompressedTuple<int, Empty<0>, NotEmpty<double>>)); EXPECT_EQ(sizeof(TwoValues<int, double>), sizeof(CompressedTuple<int, Empty<0>, NotEmpty<double>, Empty<1>>)); } TEST(CompressedTupleTest, PointerToEmpty) { auto to_void_ptrs = [](const auto&... objs) { return std::vector<const void*>{static_cast<const void*>(&objs)...}; }; { using Tuple = CompressedTuple<int, Empty<0>>; EXPECT_EQ(sizeof(int), sizeof(Tuple)); Tuple t; EXPECT_THAT(to_void_ptrs(t.get<1>()), Each(&t)); } { using Tuple = CompressedTuple<int, Empty<0>, Empty<1>>; EXPECT_EQ(sizeof(int), sizeof(Tuple)); Tuple t; EXPECT_THAT(to_void_ptrs(t.get<1>(), t.get<2>()), Each(&t)); } { using Tuple = CompressedTuple<int, Empty<0>, Empty<1>, Empty<2>>; EXPECT_EQ(sizeof(int), sizeof(Tuple)); Tuple t; EXPECT_THAT(to_void_ptrs(t.get<1>(), t.get<2>(), t.get<3>()), Each(&t)); } } TEST(CompressedTupleTest, OneMoveOnRValueConstructionTemp) { InstanceTracker tracker; CompressedTuple<CopyableMovableInstance> x1(CopyableMovableInstance(1)); EXPECT_EQ(tracker.instances(), 1); EXPECT_EQ(tracker.copies(), 0); EXPECT_LE(tracker.moves(), 1); EXPECT_EQ(x1.get<0>().value(), 1); } TEST(CompressedTupleTest, OneMoveOnRValueConstructionMove) { InstanceTracker tracker; CopyableMovableInstance i1(1); CompressedTuple<CopyableMovableInstance> x1(std::move(i1)); EXPECT_EQ(tracker.instances(), 2); EXPECT_EQ(tracker.copies(), 0); EXPECT_LE(tracker.moves(), 1); EXPECT_EQ(x1.get<0>().value(), 1); } TEST(CompressedTupleTest, OneMoveOnRValueConstructionMixedTypes) { InstanceTracker tracker; CopyableMovableInstance i1(1); CopyableMovableInstance i2(2); Empty<0> empty; CompressedTuple<CopyableMovableInstance, CopyableMovableInstance&, Empty<0>> x1(std::move(i1), i2, empty); EXPECT_EQ(x1.get<0>().value(), 1); EXPECT_EQ(x1.get<1>().value(), 2); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 1); } struct IncompleteType; CompressedTuple<CopyableMovableInstance, IncompleteType&, Empty<0>> MakeWithIncomplete(CopyableMovableInstance i1, IncompleteType& t, Empty<0> empty) { return CompressedTuple<CopyableMovableInstance, IncompleteType&, Empty<0>>{ std::move(i1), t, empty}; } struct IncompleteType {}; TEST(CompressedTupleTest, OneMoveOnRValueConstructionWithIncompleteType) { InstanceTracker tracker; CopyableMovableInstance i1(1); Empty<0> empty; struct DerivedType : IncompleteType {int value = 0;}; DerivedType fd; fd.value = 7; CompressedTuple<CopyableMovableInstance, IncompleteType&, Empty<0>> x1 = MakeWithIncomplete(std::move(i1), fd, empty); EXPECT_EQ(x1.get<0>().value(), 1); EXPECT_EQ(static_cast<DerivedType&>(x1.get<1>()).value, 7); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 2); } TEST(CompressedTupleTest, OneMoveOnRValueConstructionMixedTypes_BraceInitPoisonPillExpected) { InstanceTracker tracker; CopyableMovableInstance i1(1); CopyableMovableInstance i2(2); CompressedTuple<CopyableMovableInstance, CopyableMovableInstance&, Empty<0>> x1(std::move(i1), i2, {}); EXPECT_EQ(x1.get<0>().value(), 1); EXPECT_EQ(x1.get<1>().value(), 2); EXPECT_EQ(tracker.instances(), 3); EXPECT_EQ(tracker.copies(), 1); EXPECT_EQ(tracker.moves(), 0); } TEST(CompressedTupleTest, OneCopyOnLValueConstruction) { InstanceTracker tracker; CopyableMovableInstance i1(1); CompressedTuple<CopyableMovableInstance> x1(i1); EXPECT_EQ(tracker.copies(), 1); EXPECT_EQ(tracker.moves(), 0); tracker.ResetCopiesMovesSwaps(); CopyableMovableInstance i2(2); const CopyableMovableInstance& i2_ref = i2; CompressedTuple<CopyableMovableInstance> x2(i2_ref); EXPECT_EQ(tracker.copies(), 1); EXPECT_EQ(tracker.moves(), 0); } TEST(CompressedTupleTest, OneMoveOnRValueAccess) { InstanceTracker tracker; CopyableMovableInstance i1(1); CompressedTuple<CopyableMovableInstance> x(std::move(i1)); tracker.ResetCopiesMovesSwaps(); CopyableMovableInstance i2 = std::move(x).get<0>(); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 1); } TEST(CompressedTupleTest, OneCopyOnLValueAccess) { InstanceTracker tracker; CompressedTuple<CopyableMovableInstance> x(CopyableMovableInstance(0)); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 1); CopyableMovableInstance t = x.get<0>(); EXPECT_EQ(tracker.copies(), 1); EXPECT_EQ(tracker.moves(), 1); } TEST(CompressedTupleTest, ZeroCopyOnRefAccess) { InstanceTracker tracker; CompressedTuple<CopyableMovableInstance> x(CopyableMovableInstance(0)); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 1); CopyableMovableInstance& t1 = x.get<0>(); const CopyableMovableInstance& t2 = x.get<0>(); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 1); EXPECT_EQ(t1.value(), 0); EXPECT_EQ(t2.value(), 0); } TEST(CompressedTupleTest, Access) { struct S { std::string x; }; CompressedTuple<int, Empty<0>, S> x(7, {}, S{"ABC"}); EXPECT_EQ(sizeof(x), sizeof(TwoValues<int, S>)); EXPECT_EQ(7, x.get<0>()); EXPECT_EQ("ABC", x.get<2>().x); } TEST(CompressedTupleTest, NonClasses) { CompressedTuple<int, const char*> x(7, "ABC"); EXPECT_EQ(7, x.get<0>()); EXPECT_STREQ("ABC", x.get<1>()); } TEST(CompressedTupleTest, MixClassAndNonClass) { CompressedTuple<int, const char*, Empty<0>, NotEmpty<double>> x(7, "ABC", {}, {1.25}); struct Mock { int v; const char* p; double d; }; EXPECT_EQ(sizeof(x), sizeof(Mock)); EXPECT_EQ(7, x.get<0>()); EXPECT_STREQ("ABC", x.get<1>()); EXPECT_EQ(1.25, x.get<3>().value); } TEST(CompressedTupleTest, Nested) { CompressedTuple<int, CompressedTuple<int>, CompressedTuple<int, CompressedTuple<int>>> x(1, CompressedTuple<int>(2), CompressedTuple<int, CompressedTuple<int>>(3, CompressedTuple<int>(4))); EXPECT_EQ(1, x.get<0>()); EXPECT_EQ(2, x.get<1>().get<0>()); EXPECT_EQ(3, x.get<2>().get<0>()); EXPECT_EQ(4, x.get<2>().get<1>().get<0>()); CompressedTuple<Empty<0>, Empty<0>, CompressedTuple<Empty<0>, CompressedTuple<Empty<0>>>> y; std::set<Empty<0>*> empties{&y.get<0>(), &y.get<1>(), &y.get<2>().get<0>(), &y.get<2>().get<1>().get<0>()}; #ifdef _MSC_VER int expected = 1; #else int expected = 4; #endif EXPECT_EQ(expected, sizeof(y)); EXPECT_EQ(expected, empties.size()); EXPECT_EQ(sizeof(y), sizeof(Empty<0>) * empties.size()); EXPECT_EQ(4 * sizeof(char), sizeof(CompressedTuple<CompressedTuple<char, char>, CompressedTuple<char, char>>)); EXPECT_TRUE((std::is_empty<CompressedTuple<Empty<0>, Empty<1>>>::value)); struct CT_Empty : CompressedTuple<Empty<0>> {}; CompressedTuple<Empty<0>, CT_Empty> nested_empty; auto contained = nested_empty.get<0>(); auto nested = nested_empty.get<1>().get<0>(); EXPECT_TRUE((std::is_same<decltype(contained), decltype(nested)>::value)); } TEST(CompressedTupleTest, Reference) { int i = 7; std::string s = "Very long string that goes in the heap"; CompressedTuple<int, int&, std::string, std::string&> x(i, i, s, s); EXPECT_EQ(s, "Very long string that goes in the heap"); EXPECT_EQ(x.get<0>(), x.get<1>()); EXPECT_NE(&x.get<0>(), &x.get<1>()); EXPECT_EQ(&x.get<1>(), &i); EXPECT_EQ(x.get<2>(), x.get<3>()); EXPECT_NE(&x.get<2>(), &x.get<3>()); EXPECT_EQ(&x.get<3>(), &s); } TEST(CompressedTupleTest, NoElements) { CompressedTuple<> x; static_cast<void>(x); EXPECT_TRUE(std::is_empty<CompressedTuple<>>::value); } TEST(CompressedTupleTest, MoveOnlyElements) { CompressedTuple<std::unique_ptr<std::string>> str_tup( absl::make_unique<std::string>("str")); CompressedTuple<CompressedTuple<std::unique_ptr<std::string>>, std::unique_ptr<int>> x(std::move(str_tup), absl::make_unique<int>(5)); EXPECT_EQ(*x.get<0>().get<0>(), "str"); EXPECT_EQ(*x.get<1>(), 5); std::unique_ptr<std::string> x0 = std::move(x.get<0>()).get<0>(); std::unique_ptr<int> x1 = std::move(x).get<1>(); EXPECT_EQ(*x0, "str"); EXPECT_EQ(*x1, 5); } TEST(CompressedTupleTest, MoveConstructionMoveOnlyElements) { CompressedTuple<std::unique_ptr<std::string>> base( absl::make_unique<std::string>("str")); EXPECT_EQ(*base.get<0>(), "str"); CompressedTuple<std::unique_ptr<std::string>> copy(std::move(base)); EXPECT_EQ(*copy.get<0>(), "str"); } TEST(CompressedTupleTest, AnyElements) { any a(std::string("str")); CompressedTuple<any, any&> x(any(5), a); EXPECT_EQ(absl::any_cast<int>(x.get<0>()), 5); EXPECT_EQ(absl::any_cast<std::string>(x.get<1>()), "str"); a = 0.5f; EXPECT_EQ(absl::any_cast<float>(x.get<1>()), 0.5); } TEST(CompressedTupleTest, Constexpr) { struct NonTrivialStruct { constexpr NonTrivialStruct() = default; constexpr int value() const { return v; } int v = 5; }; struct TrivialStruct { TrivialStruct() = default; constexpr int value() const { return v; } int v; }; using Tuple = CompressedTuple<int, double, CompressedTuple<int>, Empty<0>>; constexpr int r0 = AsLValue(Tuple(1, 0.75, CompressedTuple<int>(9), {})).get<0>(); constexpr double r1 = AsLValue(Tuple(1, 0.75, CompressedTuple<int>(9), {})).get<1>(); constexpr int r2 = AsLValue(Tuple(1, 0.75, CompressedTuple<int>(9), {})).get<2>().get<0>(); constexpr CallType r3 = AsLValue(Tuple(1, 0.75, CompressedTuple<int>(9), {})).get<3>().value(); EXPECT_EQ(r0, 1); EXPECT_EQ(r1, 0.75); EXPECT_EQ(r2, 9); EXPECT_EQ(r3, CallType::kMutableRef); constexpr Tuple x(7, 1.25, CompressedTuple<int>(5), {}); constexpr int x0 = x.get<0>(); constexpr double x1 = x.get<1>(); constexpr int x2 = x.get<2>().get<0>(); constexpr CallType x3 = x.get<3>().value(); EXPECT_EQ(x0, 7); EXPECT_EQ(x1, 1.25); EXPECT_EQ(x2, 5); EXPECT_EQ(x3, CallType::kConstRef); constexpr int m0 = Tuple(5, 0.25, CompressedTuple<int>(3), {}).get<0>(); constexpr double m1 = Tuple(5, 0.25, CompressedTuple<int>(3), {}).get<1>(); constexpr int m2 = Tuple(5, 0.25, CompressedTuple<int>(3), {}).get<2>().get<0>(); constexpr CallType m3 = Tuple(5, 0.25, CompressedTuple<int>(3), {}).get<3>().value(); EXPECT_EQ(m0, 5); EXPECT_EQ(m1, 0.25); EXPECT_EQ(m2, 3); EXPECT_EQ(m3, CallType::kMutableMove); constexpr CompressedTuple<Empty<0>, TrivialStruct, int> trivial = {}; constexpr CallType trivial0 = trivial.get<0>().value(); constexpr int trivial1 = trivial.get<1>().value(); constexpr int trivial2 = trivial.get<2>(); EXPECT_EQ(trivial0, CallType::kConstRef); EXPECT_EQ(trivial1, 0); EXPECT_EQ(trivial2, 0); constexpr CompressedTuple<Empty<0>, NonTrivialStruct, absl::optional<int>> non_trivial = {}; constexpr CallType non_trivial0 = non_trivial.get<0>().value(); constexpr int non_trivial1 = non_trivial.get<1>().value(); constexpr absl::optional<int> non_trivial2 = non_trivial.get<2>(); EXPECT_EQ(non_trivial0, CallType::kConstRef); EXPECT_EQ(non_trivial1, 5); EXPECT_EQ(non_trivial2, absl::nullopt); static constexpr char data[] = "DEF"; constexpr CompressedTuple<const char*> z(data); constexpr const char* z1 = z.get<0>(); EXPECT_EQ(std::string(z1), std::string(data)); #if defined(__clang__) constexpr int x2m = std::move(x.get<2>()).get<0>(); constexpr CallType x3m = std::move(x).get<3>().value(); EXPECT_EQ(x2m, 5); EXPECT_EQ(x3m, CallType::kConstMove); #endif } #if defined(__clang__) || defined(__GNUC__) TEST(CompressedTupleTest, EmptyFinalClass) { struct S final { int f() const { return 5; } }; CompressedTuple<S> x; EXPECT_EQ(x.get<0>().f(), 5); } #endif TEST(CompressedTupleTest, DISABLED_NestedEbo) { struct Empty1 {}; struct Empty2 {}; CompressedTuple<Empty1, CompressedTuple<Empty2>, int> x; CompressedTuple<Empty1, Empty2, int> y; EXPECT_EQ(sizeof(x), sizeof(y)); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/compressed_tuple.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/compressed_tuple_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
f83be770-40eb-47f8-bdc5-9088f094734f
cpp
abseil/abseil-cpp
container_memory
absl/container/internal/container_memory.h
absl/container/internal/container_memory_test.cc
#ifndef ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_ #define ABSL_CONTAINER_INTERNAL_CONTAINER_MEMORY_H_ #include <cassert> #include <cstddef> #include <cstdint> #include <cstring> #include <memory> #include <new> #include <tuple> #include <type_traits> #include <utility> #include "absl/base/config.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/utility/utility.h" #ifdef ABSL_HAVE_ADDRESS_SANITIZER #include <sanitizer/asan_interface.h> #endif #ifdef ABSL_HAVE_MEMORY_SANITIZER #include <sanitizer/msan_interface.h> #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { template <size_t Alignment> struct alignas(Alignment) AlignedType {}; template <size_t Alignment, class Alloc> void* Allocate(Alloc* alloc, size_t n) { static_assert(Alignment > 0, ""); assert(n && "n must be positive"); using M = AlignedType<Alignment>; using A = typename absl::allocator_traits<Alloc>::template rebind_alloc<M>; using AT = typename absl::allocator_traits<Alloc>::template rebind_traits<M>; A my_mem_alloc(*alloc); void* p = AT::allocate(my_mem_alloc, (n + sizeof(M) - 1) / sizeof(M)); assert(reinterpret_cast<uintptr_t>(p) % Alignment == 0 && "allocator does not respect alignment"); return p; } template <class Allocator, class ValueType> constexpr auto IsDestructionTrivial() { constexpr bool result = std::is_trivially_destructible<ValueType>::value && std::is_same<typename absl::allocator_traits< Allocator>::template rebind_alloc<char>, std::allocator<char>>::value; return std::integral_constant<bool, result>(); } template <size_t Alignment, class Alloc> void Deallocate(Alloc* alloc, void* p, size_t n) { static_assert(Alignment > 0, ""); assert(n && "n must be positive"); using M = AlignedType<Alignment>; using A = typename absl::allocator_traits<Alloc>::template rebind_alloc<M>; using AT = typename absl::allocator_traits<Alloc>::template rebind_traits<M>; A my_mem_alloc(*alloc); AT::deallocate(my_mem_alloc, static_cast<M*>(p), (n + sizeof(M) - 1) / sizeof(M)); } namespace memory_internal { template <class Alloc, class T, class Tuple, size_t... I> void ConstructFromTupleImpl(Alloc* alloc, T* ptr, Tuple&& t, absl::index_sequence<I...>) { absl::allocator_traits<Alloc>::construct( *alloc, ptr, std::get<I>(std::forward<Tuple>(t))...); } template <class T, class F> struct WithConstructedImplF { template <class... Args> decltype(std::declval<F>()(std::declval<T>())) operator()( Args&&... args) const { return std::forward<F>(f)(T(std::forward<Args>(args)...)); } F&& f; }; template <class T, class Tuple, size_t... Is, class F> decltype(std::declval<F>()(std::declval<T>())) WithConstructedImpl( Tuple&& t, absl::index_sequence<Is...>, F&& f) { return WithConstructedImplF<T, F>{std::forward<F>(f)}( std::get<Is>(std::forward<Tuple>(t))...); } template <class T, size_t... Is> auto TupleRefImpl(T&& t, absl::index_sequence<Is...>) -> decltype(std::forward_as_tuple(std::get<Is>(std::forward<T>(t))...)) { return std::forward_as_tuple(std::get<Is>(std::forward<T>(t))...); } template <class T> auto TupleRef(T&& t) -> decltype(TupleRefImpl( std::forward<T>(t), absl::make_index_sequence< std::tuple_size<typename std::decay<T>::type>::value>())) { return TupleRefImpl( std::forward<T>(t), absl::make_index_sequence< std::tuple_size<typename std::decay<T>::type>::value>()); } template <class F, class K, class V> decltype(std::declval<F>()(std::declval<const K&>(), std::piecewise_construct, std::declval<std::tuple<K>>(), std::declval<V>())) DecomposePairImpl(F&& f, std::pair<std::tuple<K>, V> p) { const auto& key = std::get<0>(p.first); return std::forward<F>(f)(key, std::piecewise_construct, std::move(p.first), std::move(p.second)); } } template <class Alloc, class T, class Tuple> void ConstructFromTuple(Alloc* alloc, T* ptr, Tuple&& t) { memory_internal::ConstructFromTupleImpl( alloc, ptr, std::forward<Tuple>(t), absl::make_index_sequence< std::tuple_size<typename std::decay<Tuple>::type>::value>()); } template <class T, class Tuple, class F> decltype(std::declval<F>()(std::declval<T>())) WithConstructed(Tuple&& t, F&& f) { return memory_internal::WithConstructedImpl<T>( std::forward<Tuple>(t), absl::make_index_sequence< std::tuple_size<typename std::decay<Tuple>::type>::value>(), std::forward<F>(f)); } inline std::pair<std::tuple<>, std::tuple<>> PairArgs() { return {}; } template <class F, class S> std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(F&& f, S&& s) { return {std::piecewise_construct, std::forward_as_tuple(std::forward<F>(f)), std::forward_as_tuple(std::forward<S>(s))}; } template <class F, class S> std::pair<std::tuple<const F&>, std::tuple<const S&>> PairArgs( const std::pair<F, S>& p) { return PairArgs(p.first, p.second); } template <class F, class S> std::pair<std::tuple<F&&>, std::tuple<S&&>> PairArgs(std::pair<F, S>&& p) { return PairArgs(std::forward<F>(p.first), std::forward<S>(p.second)); } template <class F, class S> auto PairArgs(std::piecewise_construct_t, F&& f, S&& s) -> decltype(std::make_pair(memory_internal::TupleRef(std::forward<F>(f)), memory_internal::TupleRef(std::forward<S>(s)))) { return std::make_pair(memory_internal::TupleRef(std::forward<F>(f)), memory_internal::TupleRef(std::forward<S>(s))); } template <class F, class... Args> auto DecomposePair(F&& f, Args&&... args) -> decltype(memory_internal::DecomposePairImpl( std::forward<F>(f), PairArgs(std::forward<Args>(args)...))) { return memory_internal::DecomposePairImpl( std::forward<F>(f), PairArgs(std::forward<Args>(args)...)); } template <class F, class Arg> decltype(std::declval<F>()(std::declval<const Arg&>(), std::declval<Arg>())) DecomposeValue(F&& f, Arg&& arg) { const auto& key = arg; return std::forward<F>(f)(key, std::forward<Arg>(arg)); } inline void SanitizerPoisonMemoryRegion(const void* m, size_t s) { #ifdef ABSL_HAVE_ADDRESS_SANITIZER ASAN_POISON_MEMORY_REGION(m, s); #endif #ifdef ABSL_HAVE_MEMORY_SANITIZER __msan_poison(m, s); #endif (void)m; (void)s; } inline void SanitizerUnpoisonMemoryRegion(const void* m, size_t s) { #ifdef ABSL_HAVE_ADDRESS_SANITIZER ASAN_UNPOISON_MEMORY_REGION(m, s); #endif #ifdef ABSL_HAVE_MEMORY_SANITIZER __msan_unpoison(m, s); #endif (void)m; (void)s; } template <typename T> inline void SanitizerPoisonObject(const T* object) { SanitizerPoisonMemoryRegion(object, sizeof(T)); } template <typename T> inline void SanitizerUnpoisonObject(const T* object) { SanitizerUnpoisonMemoryRegion(object, sizeof(T)); } namespace memory_internal { template <class Pair, class = std::true_type> struct OffsetOf { static constexpr size_t kFirst = static_cast<size_t>(-1); static constexpr size_t kSecond = static_cast<size_t>(-1); }; template <class Pair> struct OffsetOf<Pair, typename std::is_standard_layout<Pair>::type> { static constexpr size_t kFirst = offsetof(Pair, first); static constexpr size_t kSecond = offsetof(Pair, second); }; template <class K, class V> struct IsLayoutCompatible { private: struct Pair { K first; V second; }; template <class P> static constexpr bool LayoutCompatible() { return std::is_standard_layout<P>() && sizeof(P) == sizeof(Pair) && alignof(P) == alignof(Pair) && memory_internal::OffsetOf<P>::kFirst == memory_internal::OffsetOf<Pair>::kFirst && memory_internal::OffsetOf<P>::kSecond == memory_internal::OffsetOf<Pair>::kSecond; } public: static constexpr bool value = std::is_standard_layout<K>() && std::is_standard_layout<Pair>() && memory_internal::OffsetOf<Pair>::kFirst == 0 && LayoutCompatible<std::pair<K, V>>() && LayoutCompatible<std::pair<const K, V>>(); }; } template <class K, class V> union map_slot_type { map_slot_type() {} ~map_slot_type() = delete; using value_type = std::pair<const K, V>; using mutable_value_type = std::pair<absl::remove_const_t<K>, absl::remove_const_t<V>>; value_type value; mutable_value_type mutable_value; absl::remove_const_t<K> key; }; template <class K, class V> struct map_slot_policy { using slot_type = map_slot_type<K, V>; using value_type = std::pair<const K, V>; using mutable_value_type = std::pair<absl::remove_const_t<K>, absl::remove_const_t<V>>; private: static void emplace(slot_type* slot) { new (slot) slot_type; } using kMutableKeys = memory_internal::IsLayoutCompatible<K, V>; public: static value_type& element(slot_type* slot) { return slot->value; } static const value_type& element(const slot_type* slot) { return slot->value; } #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606 static K& mutable_key(slot_type* slot) { return kMutableKeys::value ? slot->key : *std::launder(const_cast<K*>( std::addressof(slot->value.first))); } #else static const K& mutable_key(slot_type* slot) { return key(slot); } #endif static const K& key(const slot_type* slot) { return kMutableKeys::value ? slot->key : slot->value.first; } template <class Allocator, class... Args> static void construct(Allocator* alloc, slot_type* slot, Args&&... args) { emplace(slot); if (kMutableKeys::value) { absl::allocator_traits<Allocator>::construct(*alloc, &slot->mutable_value, std::forward<Args>(args)...); } else { absl::allocator_traits<Allocator>::construct(*alloc, &slot->value, std::forward<Args>(args)...); } } template <class Allocator> static void construct(Allocator* alloc, slot_type* slot, slot_type* other) { emplace(slot); if (kMutableKeys::value) { absl::allocator_traits<Allocator>::construct( *alloc, &slot->mutable_value, std::move(other->mutable_value)); } else { absl::allocator_traits<Allocator>::construct(*alloc, &slot->value, std::move(other->value)); } } template <class Allocator> static void construct(Allocator* alloc, slot_type* slot, const slot_type* other) { emplace(slot); absl::allocator_traits<Allocator>::construct(*alloc, &slot->value, other->value); } template <class Allocator> static auto destroy(Allocator* alloc, slot_type* slot) { if (kMutableKeys::value) { absl::allocator_traits<Allocator>::destroy(*alloc, &slot->mutable_value); } else { absl::allocator_traits<Allocator>::destroy(*alloc, &slot->value); } return IsDestructionTrivial<Allocator, value_type>(); } template <class Allocator> static auto transfer(Allocator* alloc, slot_type* new_slot, slot_type* old_slot) { auto is_relocatable = typename absl::is_trivially_relocatable<value_type>::type(); emplace(new_slot); #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606 if (is_relocatable) { std::memcpy(static_cast<void*>(std::launder(&new_slot->value)), static_cast<const void*>(&old_slot->value), sizeof(value_type)); return is_relocatable; } #endif if (kMutableKeys::value) { absl::allocator_traits<Allocator>::construct( *alloc, &new_slot->mutable_value, std::move(old_slot->mutable_value)); } else { absl::allocator_traits<Allocator>::construct(*alloc, &new_slot->value, std::move(old_slot->value)); } destroy(alloc, old_slot); return is_relocatable; } }; using HashSlotFn = size_t (*)(const void* hash_fn, void* slot); template <class Fn, class T> size_t TypeErasedApplyToSlotFn(const void* fn, void* slot) { const auto* f = static_cast<const Fn*>(fn); return (*f)(*static_cast<const T*>(slot)); } template <class Fn, class T> size_t TypeErasedDerefAndApplyToSlotFn(const void* fn, void* slot_ptr) { const auto* f = static_cast<const Fn*>(fn); const T* slot = *static_cast<const T**>(slot_ptr); return (*f)(*slot); } } ABSL_NAMESPACE_END } #endif
#include "absl/container/internal/container_memory.h" #include <cstddef> #include <cstdint> #include <memory> #include <tuple> #include <type_traits> #include <typeindex> #include <typeinfo> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/no_destructor.h" #include "absl/container/internal/test_instance_tracker.h" #include "absl/meta/type_traits.h" #include "absl/strings/string_view.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { using ::absl::test_internal::CopyableMovableInstance; using ::absl::test_internal::InstanceTracker; using ::testing::_; using ::testing::ElementsAre; using ::testing::Gt; using ::testing::Pair; TEST(Memory, AlignmentLargerThanBase) { std::allocator<int8_t> alloc; void* mem = Allocate<2>(&alloc, 3); EXPECT_EQ(0, reinterpret_cast<uintptr_t>(mem) % 2); memcpy(mem, "abc", 3); Deallocate<2>(&alloc, mem, 3); } TEST(Memory, AlignmentSmallerThanBase) { std::allocator<int64_t> alloc; void* mem = Allocate<2>(&alloc, 3); EXPECT_EQ(0, reinterpret_cast<uintptr_t>(mem) % 2); memcpy(mem, "abc", 3); Deallocate<2>(&alloc, mem, 3); } std::map<std::type_index, int>& AllocationMap() { static absl::NoDestructor<std::map<std::type_index, int>> map; return *map; } template <typename T> struct TypeCountingAllocator { TypeCountingAllocator() = default; template <typename U> TypeCountingAllocator(const TypeCountingAllocator<U>&) {} using value_type = T; T* allocate(size_t n, const void* = nullptr) { AllocationMap()[typeid(T)] += n; return std::allocator<T>().allocate(n); } void deallocate(T* p, std::size_t n) { AllocationMap()[typeid(T)] -= n; return std::allocator<T>().deallocate(p, n); } }; TEST(Memory, AllocateDeallocateMatchType) { TypeCountingAllocator<int> alloc; void* mem = Allocate<1>(&alloc, 1); EXPECT_THAT(AllocationMap(), ElementsAre(Pair(_, Gt(0)))); Deallocate<1>(&alloc, mem, 1); EXPECT_THAT(AllocationMap(), ElementsAre(Pair(_, 0))); } class Fixture : public ::testing::Test { using Alloc = std::allocator<std::string>; public: Fixture() { ptr_ = std::allocator_traits<Alloc>::allocate(*alloc(), 1); } ~Fixture() override { std::allocator_traits<Alloc>::destroy(*alloc(), ptr_); std::allocator_traits<Alloc>::deallocate(*alloc(), ptr_, 1); } std::string* ptr() { return ptr_; } Alloc* alloc() { return &alloc_; } private: Alloc alloc_; std::string* ptr_; }; TEST_F(Fixture, ConstructNoArgs) { ConstructFromTuple(alloc(), ptr(), std::forward_as_tuple()); EXPECT_EQ(*ptr(), ""); } TEST_F(Fixture, ConstructOneArg) { ConstructFromTuple(alloc(), ptr(), std::forward_as_tuple("abcde")); EXPECT_EQ(*ptr(), "abcde"); } 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, 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, 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(1, WithConstructed<absl::string_view>( std::make_tuple(std::string("a")), [](absl::string_view str) { return str.size(); })); } template <class F, class Arg> decltype(DecomposeValue(std::declval<F>(), std::declval<Arg>())) DecomposeValueImpl(int, F&& f, Arg&& arg) { return DecomposeValue(std::forward<F>(f), std::forward<Arg>(arg)); } template <class F, class Arg> const char* DecomposeValueImpl(char, F&& f, Arg&& arg) { return "not decomposable"; } template <class F, class Arg> decltype(DecomposeValueImpl(0, std::declval<F>(), std::declval<Arg>())) TryDecomposeValue(F&& f, Arg&& arg) { return DecomposeValueImpl(0, std::forward<F>(f), std::forward<Arg>(arg)); } TEST(DecomposeValue, Decomposable) { auto f = [](const int& x, int&& y) { EXPECT_EQ(&x, &y); EXPECT_EQ(42, x); return 'A'; }; EXPECT_EQ('A', TryDecomposeValue(f, 42)); } TEST(DecomposeValue, NotDecomposable) { auto f = [](void*) { ADD_FAILURE() << "Must not be called"; return 'A'; }; EXPECT_STREQ("not decomposable", TryDecomposeValue(f, 42)); } template <class F, class... Args> decltype(DecomposePair(std::declval<F>(), std::declval<Args>()...)) DecomposePairImpl(int, F&& f, Args&&... args) { return DecomposePair(std::forward<F>(f), std::forward<Args>(args)...); } template <class F, class... Args> const char* DecomposePairImpl(char, F&& f, Args&&... args) { return "not decomposable"; } template <class F, class... Args> decltype(DecomposePairImpl(0, std::declval<F>(), std::declval<Args>()...)) TryDecomposePair(F&& f, Args&&... args) { return DecomposePairImpl(0, std::forward<F>(f), std::forward<Args>(args)...); } TEST(DecomposePair, Decomposable) { auto f = [](const int& x, std::piecewise_construct_t, std::tuple<int&&> k, std::tuple<double>&& 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))); } 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))); } TEST(MapSlotPolicy, ConstKeyAndValue) { using slot_policy = map_slot_policy<const CopyableMovableInstance, const CopyableMovableInstance>; using slot_type = typename slot_policy::slot_type; union Slots { Slots() {} ~Slots() {} slot_type slots[100]; } slots; std::allocator< std::pair<const CopyableMovableInstance, const CopyableMovableInstance>> alloc; InstanceTracker tracker; slot_policy::construct(&alloc, &slots.slots[0], CopyableMovableInstance(1), CopyableMovableInstance(1)); for (int i = 0; i < 99; ++i) { slot_policy::transfer(&alloc, &slots.slots[i + 1], &slots.slots[i]); } slot_policy::destroy(&alloc, &slots.slots[99]); EXPECT_EQ(tracker.copies(), 0); } TEST(MapSlotPolicy, TransferReturnsTrue) { { using slot_policy = map_slot_policy<int, float>; EXPECT_TRUE( (std::is_same<decltype(slot_policy::transfer<std::allocator<char>>( nullptr, nullptr, nullptr)), std::true_type>::value)); } { struct NonRelocatable { NonRelocatable() = default; NonRelocatable(NonRelocatable&&) {} NonRelocatable& operator=(NonRelocatable&&) { return *this; } void* self = nullptr; }; EXPECT_FALSE(absl::is_trivially_relocatable<NonRelocatable>::value); using slot_policy = map_slot_policy<int, NonRelocatable>; EXPECT_TRUE( (std::is_same<decltype(slot_policy::transfer<std::allocator<char>>( nullptr, nullptr, nullptr)), std::false_type>::value)); } } TEST(MapSlotPolicy, DestroyReturnsTrue) { { using slot_policy = map_slot_policy<int, float>; EXPECT_TRUE( (std::is_same<decltype(slot_policy::destroy<std::allocator<char>>( nullptr, nullptr)), std::true_type>::value)); } { EXPECT_FALSE(std::is_trivially_destructible<std::unique_ptr<int>>::value); using slot_policy = map_slot_policy<int, std::unique_ptr<int>>; EXPECT_TRUE( (std::is_same<decltype(slot_policy::destroy<std::allocator<char>>( nullptr, nullptr)), std::false_type>::value)); } } TEST(ApplyTest, TypeErasedApplyToSlotFn) { size_t x = 7; auto fn = [](size_t v) { return v * 2; }; EXPECT_EQ((TypeErasedApplyToSlotFn<decltype(fn), size_t>(&fn, &x)), 14); } TEST(ApplyTest, TypeErasedDerefAndApplyToSlotFn) { size_t x = 7; auto fn = [](size_t v) { return v * 2; }; size_t* x_ptr = &x; EXPECT_EQ( (TypeErasedDerefAndApplyToSlotFn<decltype(fn), size_t>(&fn, &x_ptr)), 14); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/container_memory.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/container_memory_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
94052271-aa52-432f-9cbf-956e8d8a55fd
cpp
abseil/abseil-cpp
hash_function_defaults
absl/container/internal/hash_function_defaults.h
absl/container/internal/hash_function_defaults_test.cc
#ifndef ABSL_CONTAINER_INTERNAL_HASH_FUNCTION_DEFAULTS_H_ #define ABSL_CONTAINER_INTERNAL_HASH_FUNCTION_DEFAULTS_H_ #include <cstddef> #include <functional> #include <memory> #include <string> #include <type_traits> #include "absl/base/config.h" #include "absl/container/internal/common.h" #include "absl/hash/hash.h" #include "absl/meta/type_traits.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #ifdef ABSL_HAVE_STD_STRING_VIEW #include <string_view> #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { template <class T, class E = void> struct HashEq { using Hash = absl::Hash<T>; using Eq = std::equal_to<T>; }; struct StringHash { using is_transparent = void; size_t operator()(absl::string_view v) const { return absl::Hash<absl::string_view>{}(v); } size_t operator()(const absl::Cord& v) const { return absl::Hash<absl::Cord>{}(v); } }; struct StringEq { using is_transparent = void; bool operator()(absl::string_view lhs, absl::string_view rhs) const { return lhs == rhs; } bool operator()(const absl::Cord& lhs, const absl::Cord& rhs) const { return lhs == rhs; } bool operator()(const absl::Cord& lhs, absl::string_view rhs) const { return lhs == rhs; } bool operator()(absl::string_view lhs, const absl::Cord& rhs) const { return lhs == rhs; } }; struct StringHashEq { using Hash = StringHash; using Eq = StringEq; }; template <> struct HashEq<std::string> : StringHashEq {}; template <> struct HashEq<absl::string_view> : StringHashEq {}; template <> struct HashEq<absl::Cord> : StringHashEq {}; #ifdef ABSL_HAVE_STD_STRING_VIEW template <typename TChar> struct BasicStringHash { using is_transparent = void; size_t operator()(std::basic_string_view<TChar> v) const { return absl::Hash<std::basic_string_view<TChar>>{}(v); } }; template <typename TChar> struct BasicStringEq { using is_transparent = void; bool operator()(std::basic_string_view<TChar> lhs, std::basic_string_view<TChar> rhs) const { return lhs == rhs; } }; template <typename TChar> struct BasicStringHashEq { using Hash = BasicStringHash<TChar>; using Eq = BasicStringEq<TChar>; }; template <> struct HashEq<std::wstring> : BasicStringHashEq<wchar_t> {}; template <> struct HashEq<std::wstring_view> : BasicStringHashEq<wchar_t> {}; template <> struct HashEq<std::u16string> : BasicStringHashEq<char16_t> {}; template <> struct HashEq<std::u16string_view> : BasicStringHashEq<char16_t> {}; template <> struct HashEq<std::u32string> : BasicStringHashEq<char32_t> {}; template <> struct HashEq<std::u32string_view> : BasicStringHashEq<char32_t> {}; #endif template <class T> struct HashEq<T*> { struct Hash { using is_transparent = void; template <class U> size_t operator()(const U& ptr) const { return absl::Hash<const T*>{}(HashEq::ToPtr(ptr)); } }; struct Eq { using is_transparent = void; template <class A, class B> bool operator()(const A& a, const B& b) const { return HashEq::ToPtr(a) == HashEq::ToPtr(b); } }; private: static const T* ToPtr(const T* ptr) { return ptr; } template <class U, class D> static const T* ToPtr(const std::unique_ptr<U, D>& ptr) { return ptr.get(); } template <class U> static const T* ToPtr(const std::shared_ptr<U>& ptr) { return ptr.get(); } }; template <class T, class D> struct HashEq<std::unique_ptr<T, D>> : HashEq<T*> {}; template <class T> struct HashEq<std::shared_ptr<T>> : HashEq<T*> {}; template <typename T, typename E = void> struct HasAbslContainerHash : std::false_type {}; template <typename T> struct HasAbslContainerHash<T, absl::void_t<typename T::absl_container_hash>> : std::true_type {}; template <typename T, typename E = void> struct HasAbslContainerEq : std::false_type {}; template <typename T> struct HasAbslContainerEq<T, absl::void_t<typename T::absl_container_eq>> : std::true_type {}; template <typename T, typename E = void> struct AbslContainerEq { using type = std::equal_to<>; }; template <typename T> struct AbslContainerEq< T, typename std::enable_if_t<HasAbslContainerEq<T>::value>> { using type = typename T::absl_container_eq; }; template <typename T, typename E = void> struct AbslContainerHash { using type = void; }; template <typename T> struct AbslContainerHash< T, typename std::enable_if_t<HasAbslContainerHash<T>::value>> { using type = typename T::absl_container_hash; }; template <typename T> struct HashEq<T, typename std::enable_if_t<HasAbslContainerHash<T>::value>> { using Hash = typename AbslContainerHash<T>::type; using Eq = typename AbslContainerEq<T>::type; static_assert(IsTransparent<Hash>::value, "absl_container_hash must be transparent. To achieve it add a " "`using is_transparent = void;` clause to this type."); static_assert(IsTransparent<Eq>::value, "absl_container_eq must be transparent. To achieve it add a " "`using is_transparent = void;` clause to this type."); }; template <class T> using hash_default_hash = typename container_internal::HashEq<T>::Hash; template <class T> using hash_default_eq = typename container_internal::HashEq<T>::Eq; } ABSL_NAMESPACE_END } #endif
#include "absl/container/internal/hash_function_defaults.h" #include <cstddef> #include <functional> #include <type_traits> #include <utility> #include "gtest/gtest.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/hash/hash.h" #include "absl/random/random.h" #include "absl/strings/cord.h" #include "absl/strings/cord_test_helpers.h" #include "absl/strings/string_view.h" #ifdef ABSL_HAVE_STD_STRING_VIEW #include <string_view> #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { using ::testing::Types; TEST(Eq, Int32) { hash_default_eq<int32_t> eq; EXPECT_TRUE(eq(1, 1u)); EXPECT_TRUE(eq(1, char{1})); EXPECT_TRUE(eq(1, true)); EXPECT_TRUE(eq(1, double{1.1})); EXPECT_FALSE(eq(1, char{2})); EXPECT_FALSE(eq(1, 2u)); EXPECT_FALSE(eq(1, false)); EXPECT_FALSE(eq(1, 2.)); } TEST(Hash, Int32) { hash_default_hash<int32_t> hash; auto h = hash(1); EXPECT_EQ(h, hash(1u)); EXPECT_EQ(h, hash(char{1})); EXPECT_EQ(h, hash(true)); EXPECT_EQ(h, hash(double{1.1})); EXPECT_NE(h, hash(2u)); EXPECT_NE(h, hash(char{2})); EXPECT_NE(h, hash(false)); EXPECT_NE(h, hash(2.)); } enum class MyEnum { A, B, C, D }; TEST(Eq, Enum) { hash_default_eq<MyEnum> eq; EXPECT_TRUE(eq(MyEnum::A, MyEnum::A)); EXPECT_FALSE(eq(MyEnum::A, MyEnum::B)); } TEST(Hash, Enum) { hash_default_hash<MyEnum> hash; for (MyEnum e : {MyEnum::A, MyEnum::B, MyEnum::C}) { auto h = hash(e); EXPECT_EQ(h, hash_default_hash<int>{}(static_cast<int>(e))); EXPECT_NE(h, hash(MyEnum::D)); } } using StringTypes = ::testing::Types<std::string, absl::string_view>; template <class T> struct EqString : ::testing::Test { hash_default_eq<T> key_eq; }; TYPED_TEST_SUITE(EqString, StringTypes); template <class T> struct HashString : ::testing::Test { hash_default_hash<T> hasher; }; TYPED_TEST_SUITE(HashString, StringTypes); TYPED_TEST(EqString, Works) { auto eq = this->key_eq; EXPECT_TRUE(eq("a", "a")); EXPECT_TRUE(eq("a", absl::string_view("a"))); EXPECT_TRUE(eq("a", std::string("a"))); EXPECT_FALSE(eq("a", "b")); EXPECT_FALSE(eq("a", absl::string_view("b"))); EXPECT_FALSE(eq("a", std::string("b"))); } TYPED_TEST(HashString, Works) { auto hash = this->hasher; auto h = hash("a"); EXPECT_EQ(h, hash(absl::string_view("a"))); EXPECT_EQ(h, hash(std::string("a"))); EXPECT_NE(h, hash(absl::string_view("b"))); EXPECT_NE(h, hash(std::string("b"))); } TEST(BasicStringViewTest, WStringEqWorks) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else hash_default_eq<std::wstring> eq; EXPECT_TRUE(eq(L"a", L"a")); EXPECT_TRUE(eq(L"a", std::wstring_view(L"a"))); EXPECT_TRUE(eq(L"a", std::wstring(L"a"))); EXPECT_FALSE(eq(L"a", L"b")); EXPECT_FALSE(eq(L"a", std::wstring_view(L"b"))); EXPECT_FALSE(eq(L"a", std::wstring(L"b"))); #endif } TEST(BasicStringViewTest, WStringViewEqWorks) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else hash_default_eq<std::wstring_view> eq; EXPECT_TRUE(eq(L"a", L"a")); EXPECT_TRUE(eq(L"a", std::wstring_view(L"a"))); EXPECT_TRUE(eq(L"a", std::wstring(L"a"))); EXPECT_FALSE(eq(L"a", L"b")); EXPECT_FALSE(eq(L"a", std::wstring_view(L"b"))); EXPECT_FALSE(eq(L"a", std::wstring(L"b"))); #endif } TEST(BasicStringViewTest, U16StringEqWorks) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else hash_default_eq<std::u16string> eq; EXPECT_TRUE(eq(u"a", u"a")); EXPECT_TRUE(eq(u"a", std::u16string_view(u"a"))); EXPECT_TRUE(eq(u"a", std::u16string(u"a"))); EXPECT_FALSE(eq(u"a", u"b")); EXPECT_FALSE(eq(u"a", std::u16string_view(u"b"))); EXPECT_FALSE(eq(u"a", std::u16string(u"b"))); #endif } TEST(BasicStringViewTest, U16StringViewEqWorks) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else hash_default_eq<std::u16string_view> eq; EXPECT_TRUE(eq(u"a", u"a")); EXPECT_TRUE(eq(u"a", std::u16string_view(u"a"))); EXPECT_TRUE(eq(u"a", std::u16string(u"a"))); EXPECT_FALSE(eq(u"a", u"b")); EXPECT_FALSE(eq(u"a", std::u16string_view(u"b"))); EXPECT_FALSE(eq(u"a", std::u16string(u"b"))); #endif } TEST(BasicStringViewTest, U32StringEqWorks) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else hash_default_eq<std::u32string> eq; EXPECT_TRUE(eq(U"a", U"a")); EXPECT_TRUE(eq(U"a", std::u32string_view(U"a"))); EXPECT_TRUE(eq(U"a", std::u32string(U"a"))); EXPECT_FALSE(eq(U"a", U"b")); EXPECT_FALSE(eq(U"a", std::u32string_view(U"b"))); EXPECT_FALSE(eq(U"a", std::u32string(U"b"))); #endif } TEST(BasicStringViewTest, U32StringViewEqWorks) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else hash_default_eq<std::u32string_view> eq; EXPECT_TRUE(eq(U"a", U"a")); EXPECT_TRUE(eq(U"a", std::u32string_view(U"a"))); EXPECT_TRUE(eq(U"a", std::u32string(U"a"))); EXPECT_FALSE(eq(U"a", U"b")); EXPECT_FALSE(eq(U"a", std::u32string_view(U"b"))); EXPECT_FALSE(eq(U"a", std::u32string(U"b"))); #endif } TEST(BasicStringViewTest, WStringHashWorks) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else hash_default_hash<std::wstring> hash; auto h = hash(L"a"); EXPECT_EQ(h, hash(std::wstring_view(L"a"))); EXPECT_EQ(h, hash(std::wstring(L"a"))); EXPECT_NE(h, hash(std::wstring_view(L"b"))); EXPECT_NE(h, hash(std::wstring(L"b"))); #endif } TEST(BasicStringViewTest, WStringViewHashWorks) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else hash_default_hash<std::wstring_view> hash; auto h = hash(L"a"); EXPECT_EQ(h, hash(std::wstring_view(L"a"))); EXPECT_EQ(h, hash(std::wstring(L"a"))); EXPECT_NE(h, hash(std::wstring_view(L"b"))); EXPECT_NE(h, hash(std::wstring(L"b"))); #endif } TEST(BasicStringViewTest, U16StringHashWorks) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else hash_default_hash<std::u16string> hash; auto h = hash(u"a"); EXPECT_EQ(h, hash(std::u16string_view(u"a"))); EXPECT_EQ(h, hash(std::u16string(u"a"))); EXPECT_NE(h, hash(std::u16string_view(u"b"))); EXPECT_NE(h, hash(std::u16string(u"b"))); #endif } TEST(BasicStringViewTest, U16StringViewHashWorks) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else hash_default_hash<std::u16string_view> hash; auto h = hash(u"a"); EXPECT_EQ(h, hash(std::u16string_view(u"a"))); EXPECT_EQ(h, hash(std::u16string(u"a"))); EXPECT_NE(h, hash(std::u16string_view(u"b"))); EXPECT_NE(h, hash(std::u16string(u"b"))); #endif } TEST(BasicStringViewTest, U32StringHashWorks) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else hash_default_hash<std::u32string> hash; auto h = hash(U"a"); EXPECT_EQ(h, hash(std::u32string_view(U"a"))); EXPECT_EQ(h, hash(std::u32string(U"a"))); EXPECT_NE(h, hash(std::u32string_view(U"b"))); EXPECT_NE(h, hash(std::u32string(U"b"))); #endif } TEST(BasicStringViewTest, U32StringViewHashWorks) { #ifndef ABSL_HAVE_STD_STRING_VIEW GTEST_SKIP(); #else hash_default_hash<std::u32string_view> hash; auto h = hash(U"a"); EXPECT_EQ(h, hash(std::u32string_view(U"a"))); EXPECT_EQ(h, hash(std::u32string(U"a"))); EXPECT_NE(h, hash(std::u32string_view(U"b"))); EXPECT_NE(h, hash(std::u32string(U"b"))); #endif } struct NoDeleter { template <class T> void operator()(const T* ptr) const {} }; using PointerTypes = ::testing::Types<const int*, int*, std::unique_ptr<const int>, std::unique_ptr<const int, NoDeleter>, std::unique_ptr<int>, std::unique_ptr<int, NoDeleter>, std::shared_ptr<const int>, std::shared_ptr<int>>; template <class T> struct EqPointer : ::testing::Test { hash_default_eq<T> key_eq; }; TYPED_TEST_SUITE(EqPointer, PointerTypes); template <class T> struct HashPointer : ::testing::Test { hash_default_hash<T> hasher; }; TYPED_TEST_SUITE(HashPointer, PointerTypes); TYPED_TEST(EqPointer, Works) { int dummy; auto eq = this->key_eq; auto sptr = std::make_shared<int>(); std::shared_ptr<const int> csptr = sptr; int* ptr = sptr.get(); const int* cptr = ptr; std::unique_ptr<int, NoDeleter> uptr(ptr); std::unique_ptr<const int, NoDeleter> cuptr(ptr); EXPECT_TRUE(eq(ptr, cptr)); EXPECT_TRUE(eq(ptr, sptr)); EXPECT_TRUE(eq(ptr, uptr)); EXPECT_TRUE(eq(ptr, csptr)); EXPECT_TRUE(eq(ptr, cuptr)); EXPECT_FALSE(eq(&dummy, cptr)); EXPECT_FALSE(eq(&dummy, sptr)); EXPECT_FALSE(eq(&dummy, uptr)); EXPECT_FALSE(eq(&dummy, csptr)); EXPECT_FALSE(eq(&dummy, cuptr)); } TEST(Hash, DerivedAndBase) { struct Base {}; struct Derived : Base {}; hash_default_hash<Base*> hasher; Base base; Derived derived; EXPECT_NE(hasher(&base), hasher(&derived)); EXPECT_EQ(hasher(static_cast<Base*>(&derived)), hasher(&derived)); auto dp = std::make_shared<Derived>(); EXPECT_EQ(hasher(static_cast<Base*>(dp.get())), hasher(dp)); } TEST(Hash, FunctionPointer) { using Func = int (*)(); hash_default_hash<Func> hasher; hash_default_eq<Func> eq; Func p1 = [] { return 1; }, p2 = [] { return 2; }; EXPECT_EQ(hasher(p1), hasher(p1)); EXPECT_TRUE(eq(p1, p1)); EXPECT_NE(hasher(p1), hasher(p2)); EXPECT_FALSE(eq(p1, p2)); } TYPED_TEST(HashPointer, Works) { int dummy; auto hash = this->hasher; auto sptr = std::make_shared<int>(); std::shared_ptr<const int> csptr = sptr; int* ptr = sptr.get(); const int* cptr = ptr; std::unique_ptr<int, NoDeleter> uptr(ptr); std::unique_ptr<const int, NoDeleter> cuptr(ptr); EXPECT_EQ(hash(ptr), hash(cptr)); EXPECT_EQ(hash(ptr), hash(sptr)); EXPECT_EQ(hash(ptr), hash(uptr)); EXPECT_EQ(hash(ptr), hash(csptr)); EXPECT_EQ(hash(ptr), hash(cuptr)); EXPECT_NE(hash(&dummy), hash(cptr)); EXPECT_NE(hash(&dummy), hash(sptr)); EXPECT_NE(hash(&dummy), hash(uptr)); EXPECT_NE(hash(&dummy), hash(csptr)); EXPECT_NE(hash(&dummy), hash(cuptr)); } TEST(EqCord, Works) { hash_default_eq<absl::Cord> eq; const absl::string_view a_string_view = "a"; const absl::Cord a_cord(a_string_view); const absl::string_view b_string_view = "b"; const absl::Cord b_cord(b_string_view); EXPECT_TRUE(eq(a_cord, a_cord)); EXPECT_TRUE(eq(a_cord, a_string_view)); EXPECT_TRUE(eq(a_string_view, a_cord)); EXPECT_FALSE(eq(a_cord, b_cord)); EXPECT_FALSE(eq(a_cord, b_string_view)); EXPECT_FALSE(eq(b_string_view, a_cord)); } TEST(HashCord, Works) { hash_default_hash<absl::Cord> hash; const absl::string_view a_string_view = "a"; const absl::Cord a_cord(a_string_view); const absl::string_view b_string_view = "b"; const absl::Cord b_cord(b_string_view); EXPECT_EQ(hash(a_cord), hash(a_cord)); EXPECT_EQ(hash(b_cord), hash(b_cord)); EXPECT_EQ(hash(a_string_view), hash(a_cord)); EXPECT_EQ(hash(b_string_view), hash(b_cord)); EXPECT_EQ(hash(absl::Cord("")), hash("")); EXPECT_EQ(hash(absl::Cord()), hash(absl::string_view())); EXPECT_NE(hash(a_cord), hash(b_cord)); EXPECT_NE(hash(a_cord), hash(b_string_view)); EXPECT_NE(hash(a_string_view), hash(b_cord)); EXPECT_NE(hash(a_string_view), hash(b_string_view)); } void NoOpReleaser(absl::string_view data, void* arg) {} TEST(HashCord, FragmentedCordWorks) { hash_default_hash<absl::Cord> hash; absl::Cord c = absl::MakeFragmentedCord({"a", "b", "c"}); EXPECT_FALSE(c.TryFlat().has_value()); EXPECT_EQ(hash(c), hash("abc")); } TEST(HashCord, FragmentedLongCordWorks) { hash_default_hash<absl::Cord> hash; std::string a(65536, 'a'); std::string b(65536, 'b'); absl::Cord c = absl::MakeFragmentedCord({a, b}); EXPECT_FALSE(c.TryFlat().has_value()); EXPECT_EQ(hash(c), hash(a + b)); } TEST(HashCord, RandomCord) { hash_default_hash<absl::Cord> hash; auto bitgen = absl::BitGen(); for (int i = 0; i < 1000; ++i) { const int number_of_segments = absl::Uniform(bitgen, 0, 10); std::vector<std::string> pieces; for (size_t s = 0; s < number_of_segments; ++s) { std::string str; str.resize(absl::Uniform(bitgen, 0, 4096)); std::generate(str.begin(), str.end(), [&]() -> char { return static_cast<char>(absl::Uniform<unsigned char>(bitgen)); }); pieces.push_back(str); } absl::Cord c = absl::MakeFragmentedCord(pieces); EXPECT_EQ(hash(c), hash(std::string(c))); } } using StringTypesCartesianProduct = Types< std::pair<absl::Cord, std::string>, std::pair<absl::Cord, absl::string_view>, std::pair<absl::Cord, absl::Cord>, std::pair<absl::Cord, const char*>, std::pair<std::string, absl::Cord>, std::pair<absl::string_view, absl::Cord>, std::pair<absl::string_view, std::string>, std::pair<absl::string_view, absl::string_view>, std::pair<absl::string_view, const char*>>; constexpr char kFirstString[] = "abc123"; constexpr char kSecondString[] = "ijk456"; template <typename T> struct StringLikeTest : public ::testing::Test { typename T::first_type a1{kFirstString}; typename T::second_type b1{kFirstString}; typename T::first_type a2{kSecondString}; typename T::second_type b2{kSecondString}; hash_default_eq<typename T::first_type> eq; hash_default_hash<typename T::first_type> hash; }; TYPED_TEST_SUITE(StringLikeTest, StringTypesCartesianProduct); TYPED_TEST(StringLikeTest, Eq) { EXPECT_TRUE(this->eq(this->a1, this->b1)); EXPECT_TRUE(this->eq(this->b1, this->a1)); } TYPED_TEST(StringLikeTest, NotEq) { EXPECT_FALSE(this->eq(this->a1, this->b2)); EXPECT_FALSE(this->eq(this->b2, this->a1)); } TYPED_TEST(StringLikeTest, HashEq) { EXPECT_EQ(this->hash(this->a1), this->hash(this->b1)); EXPECT_EQ(this->hash(this->a2), this->hash(this->b2)); EXPECT_NE(this->hash(this->a1), this->hash(this->b2)); } struct TypeWithAbslContainerHash { struct absl_container_hash { using is_transparent = void; size_t operator()(const TypeWithAbslContainerHash& foo) const { return absl::HashOf(foo.value); } size_t operator()(int value) const { return absl::HashOf(value); } }; friend bool operator==(const TypeWithAbslContainerHash& lhs, const TypeWithAbslContainerHash& rhs) { return lhs.value == rhs.value; } friend bool operator==(const TypeWithAbslContainerHash& lhs, int rhs) { return lhs.value == rhs; } int value; int noise; }; struct TypeWithAbslContainerHashAndEq { struct absl_container_hash { using is_transparent = void; size_t operator()(const TypeWithAbslContainerHashAndEq& foo) const { return absl::HashOf(foo.value); } size_t operator()(int value) const { return absl::HashOf(value); } }; struct absl_container_eq { using is_transparent = void; bool operator()(const TypeWithAbslContainerHashAndEq& lhs, const TypeWithAbslContainerHashAndEq& rhs) const { return lhs.value == rhs.value; } bool operator()(const TypeWithAbslContainerHashAndEq& lhs, int rhs) const { return lhs.value == rhs; } }; template <typename T> bool operator==(T&& other) const = delete; int value; int noise; }; using AbslContainerHashTypes = Types<TypeWithAbslContainerHash, TypeWithAbslContainerHashAndEq>; template <typename T> using AbslContainerHashTest = ::testing::Test; TYPED_TEST_SUITE(AbslContainerHashTest, AbslContainerHashTypes); TYPED_TEST(AbslContainerHashTest, HasherWorks) { hash_default_hash<TypeParam> hasher; TypeParam foo1{1, 100}; TypeParam foo1_copy{1, 20}; TypeParam foo2{2, 100}; EXPECT_EQ(hasher(foo1), absl::HashOf(1)); EXPECT_EQ(hasher(foo2), absl::HashOf(2)); EXPECT_EQ(hasher(foo1), hasher(foo1_copy)); EXPECT_EQ(hasher(foo1), hasher(1)); EXPECT_EQ(hasher(foo2), hasher(2)); } TYPED_TEST(AbslContainerHashTest, EqWorks) { hash_default_eq<TypeParam> eq; TypeParam foo1{1, 100}; TypeParam foo1_copy{1, 20}; TypeParam foo2{2, 100}; EXPECT_TRUE(eq(foo1, foo1_copy)); EXPECT_FALSE(eq(foo1, foo2)); EXPECT_TRUE(eq(foo1, 1)); EXPECT_FALSE(eq(foo1, 2)); } TYPED_TEST(AbslContainerHashTest, HeterogeneityInMapWorks) { absl::flat_hash_map<TypeParam, int> map; TypeParam foo1{1, 100}; TypeParam foo1_copy{1, 20}; TypeParam foo2{2, 100}; TypeParam foo3{3, 100}; map[foo1] = 1; map[foo2] = 2; EXPECT_TRUE(map.contains(foo1_copy)); EXPECT_EQ(map.at(foo1_copy), 1); EXPECT_TRUE(map.contains(1)); EXPECT_EQ(map.at(1), 1); EXPECT_TRUE(map.contains(2)); EXPECT_EQ(map.at(2), 2); EXPECT_FALSE(map.contains(foo3)); EXPECT_FALSE(map.contains(3)); } TYPED_TEST(AbslContainerHashTest, HeterogeneityInSetWorks) { absl::flat_hash_set<TypeParam> set; TypeParam foo1{1, 100}; TypeParam foo1_copy{1, 20}; TypeParam foo2{2, 100}; set.insert(foo1); EXPECT_TRUE(set.contains(foo1_copy)); EXPECT_TRUE(set.contains(1)); EXPECT_FALSE(set.contains(foo2)); EXPECT_FALSE(set.contains(2)); } } } ABSL_NAMESPACE_END } enum Hash : size_t { kStd = 0x1, #ifdef _MSC_VER kExtension = kStd, #else kExtension = 0x2, #endif }; template <int H> struct Hashable { static constexpr bool HashableBy(Hash h) { return h & H; } }; namespace std { template <int H> struct hash<Hashable<H>> { template <class E = Hashable<H>, class = typename std::enable_if<E::HashableBy(kStd)>::type> size_t operator()(E) const { return kStd; } }; } namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { template <class T> size_t Hash(const T& v) { return hash_default_hash<T>()(v); } TEST(Delegate, HashDispatch) { EXPECT_EQ(Hash(kStd), Hash(Hashable<kStd>())); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/hash_function_defaults.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/hash_function_defaults_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
4f659819-6eca-4f9c-a250-a5fa655698cb
cpp
abseil/abseil-cpp
layout
absl/container/internal/layout.h
absl/container/internal/layout_test.cc
#ifndef ABSL_CONTAINER_INTERNAL_LAYOUT_H_ #define ABSL_CONTAINER_INTERNAL_LAYOUT_H_ #include <assert.h> #include <stddef.h> #include <stdint.h> #include <array> #include <string> #include <tuple> #include <type_traits> #include <typeinfo> #include <utility> #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/debugging/internal/demangle.h" #include "absl/meta/type_traits.h" #include "absl/strings/str_cat.h" #include "absl/types/span.h" #include "absl/utility/utility.h" #ifdef ABSL_HAVE_ADDRESS_SANITIZER #include <sanitizer/asan_interface.h> #endif namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { template <class T, size_t N> struct Aligned; namespace internal_layout { template <class T> struct NotAligned {}; template <class T, size_t N> struct NotAligned<const Aligned<T, N>> { static_assert(sizeof(T) == 0, "Aligned<T, N> cannot be const-qualified"); }; template <size_t> using IntToSize = size_t; template <class T> struct Type : NotAligned<T> { using type = T; }; template <class T, size_t N> struct Type<Aligned<T, N>> { using type = T; }; template <class T> struct SizeOf : NotAligned<T>, std::integral_constant<size_t, sizeof(T)> {}; template <class T, size_t N> struct SizeOf<Aligned<T, N>> : std::integral_constant<size_t, sizeof(T)> {}; template <class T> struct AlignOf : NotAligned<T> { static constexpr size_t value = alignof(T); }; template <class T, size_t N> struct AlignOf<Aligned<T, N>> { static_assert(N % alignof(T) == 0, "Custom alignment can't be lower than the type's alignment"); static constexpr size_t value = N; }; template <class T, class... Ts> using Contains = absl::disjunction<std::is_same<T, Ts>...>; template <class From, class To> using CopyConst = typename std::conditional<std::is_const<From>::value, const To, To>::type; template <class T> using SliceType = Span<T>; namespace adl_barrier { template <class Needle, class... Ts> constexpr size_t Find(Needle, Needle, Ts...) { static_assert(!Contains<Needle, Ts...>(), "Duplicate element type"); return 0; } template <class Needle, class T, class... Ts> constexpr size_t Find(Needle, T, Ts...) { return adl_barrier::Find(Needle(), Ts()...) + 1; } constexpr bool IsPow2(size_t n) { return !(n & (n - 1)); } constexpr size_t Align(size_t n, size_t m) { return (n + m - 1) & ~(m - 1); } 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 <class... Ts> constexpr size_t Max(size_t a, size_t b, Ts... rest) { return adl_barrier::Max(b < a ? a : b, rest...); } template <class T> std::string TypeName() { std::string out; #if ABSL_INTERNAL_HAS_RTTI absl::StrAppend(&out, "<", absl::debugging_internal::DemangleString(typeid(T).name()), ">"); #endif return out; } } template <bool C> using EnableIf = typename std::enable_if<C, int>::type; template <class T> using IsLegalElementType = std::integral_constant< bool, !std::is_reference<T>::value && !std::is_volatile<T>::value && !std::is_reference<typename Type<T>::type>::value && !std::is_volatile<typename Type<T>::type>::value && adl_barrier::IsPow2(AlignOf<T>::value)>; template <class Elements, class StaticSizeSeq, class RuntimeSizeSeq, class SizeSeq, class OffsetSeq> class LayoutImpl; template <class... Elements, size_t... StaticSizeSeq, size_t... RuntimeSizeSeq, size_t... SizeSeq, size_t... OffsetSeq> class LayoutImpl< std::tuple<Elements...>, absl::index_sequence<StaticSizeSeq...>, absl::index_sequence<RuntimeSizeSeq...>, absl::index_sequence<SizeSeq...>, absl::index_sequence<OffsetSeq...>> { private: static_assert(sizeof...(Elements) > 0, "At least one field is required"); static_assert(absl::conjunction<IsLegalElementType<Elements>...>::value, "Invalid element type (see IsLegalElementType)"); static_assert(sizeof...(StaticSizeSeq) <= sizeof...(Elements), "Too many static sizes specified"); enum { NumTypes = sizeof...(Elements), NumStaticSizes = sizeof...(StaticSizeSeq), NumRuntimeSizes = sizeof...(RuntimeSizeSeq), NumSizes = sizeof...(SizeSeq), NumOffsets = sizeof...(OffsetSeq), }; static_assert(NumStaticSizes + NumRuntimeSizes == NumSizes, "Internal error"); static_assert(NumSizes <= NumTypes, "Internal error"); static_assert(NumOffsets == adl_barrier::Min(NumTypes, NumSizes + 1), "Internal error"); static_assert(NumTypes > 0, "Internal error"); static constexpr std::array<size_t, sizeof...(StaticSizeSeq)> kStaticSizes = { StaticSizeSeq...}; template <class T> static constexpr size_t ElementIndex() { static_assert(Contains<Type<T>, Type<typename Type<Elements>::type>...>(), "Type not found"); return adl_barrier::Find(Type<T>(), Type<typename Type<Elements>::type>()...); } template <size_t N> using ElementAlignment = AlignOf<typename std::tuple_element<N, std::tuple<Elements...>>::type>; public: using ElementTypes = std::tuple<typename Type<Elements>::type...>; template <size_t N> using ElementType = typename std::tuple_element<N, ElementTypes>::type; constexpr explicit LayoutImpl(IntToSize<RuntimeSizeSeq>... sizes) : size_{sizes...} {} static constexpr size_t Alignment() { return adl_barrier::Max(AlignOf<Elements>::value...); } template <size_t N, EnableIf<N == 0> = 0> constexpr size_t Offset() const { return 0; } template <size_t N, EnableIf<N != 0> = 0> constexpr size_t Offset() const { static_assert(N < NumOffsets, "Index out of bounds"); return adl_barrier::Align( Offset<N - 1>() + SizeOf<ElementType<N - 1>>::value * Size<N - 1>(), ElementAlignment<N>::value); } template <class T> constexpr size_t Offset() const { return Offset<ElementIndex<T>()>(); } constexpr std::array<size_t, NumOffsets> Offsets() const { return {{Offset<OffsetSeq>()...}}; } template <size_t N, EnableIf<(N < NumStaticSizes)> = 0> constexpr size_t Size() const { return kStaticSizes[N]; } template <size_t N, EnableIf<(N >= NumStaticSizes)> = 0> constexpr size_t Size() const { static_assert(N < NumSizes, "Index out of bounds"); return size_[N - NumStaticSizes]; } template <class T> constexpr size_t Size() const { return Size<ElementIndex<T>()>(); } constexpr std::array<size_t, NumSizes> Sizes() const { return {{Size<SizeSeq>()...}}; } template <size_t N, class Char> CopyConst<Char, ElementType<N>>* Pointer(Char* p) const { using C = typename std::remove_const<Char>::type; static_assert( std::is_same<C, char>() || std::is_same<C, unsigned char>() || std::is_same<C, signed char>(), "The argument must be a pointer to [const] [signed|unsigned] char"); constexpr size_t alignment = Alignment(); (void)alignment; assert(reinterpret_cast<uintptr_t>(p) % alignment == 0); return reinterpret_cast<CopyConst<Char, ElementType<N>>*>(p + Offset<N>()); } template <class T, class Char> CopyConst<Char, T>* Pointer(Char* p) const { return Pointer<ElementIndex<T>()>(p); } template <class Char> auto Pointers(Char* p) const { return std::tuple<CopyConst<Char, ElementType<OffsetSeq>>*...>( Pointer<OffsetSeq>(p)...); } template <size_t N, class Char> SliceType<CopyConst<Char, ElementType<N>>> Slice(Char* p) const { return SliceType<CopyConst<Char, ElementType<N>>>(Pointer<N>(p), Size<N>()); } template <class T, class Char> SliceType<CopyConst<Char, T>> Slice(Char* p) const { return Slice<ElementIndex<T>()>(p); } template <class Char> auto Slices(ABSL_ATTRIBUTE_UNUSED Char* p) const { return std::tuple<SliceType<CopyConst<Char, ElementType<SizeSeq>>>...>( Slice<SizeSeq>(p)...); } constexpr size_t AllocSize() const { static_assert(NumTypes == NumSizes, "You must specify sizes of all fields"); return Offset<NumTypes - 1>() + SizeOf<ElementType<NumTypes - 1>>::value * Size<NumTypes - 1>(); } template <class Char, size_t N = NumOffsets - 1, EnableIf<N == 0> = 0> void PoisonPadding(const Char* p) const { Pointer<0>(p); } template <class Char, size_t N = NumOffsets - 1, EnableIf<N != 0> = 0> void PoisonPadding(const Char* p) const { static_assert(N < NumOffsets, "Index out of bounds"); (void)p; #ifdef ABSL_HAVE_ADDRESS_SANITIZER PoisonPadding<Char, N - 1>(p); if (ElementAlignment<N - 1>::value % ElementAlignment<N>::value) { size_t start = Offset<N - 1>() + SizeOf<ElementType<N - 1>>::value * Size<N - 1>(); ASAN_POISON_MEMORY_REGION(p + start, Offset<N>() - start); } #endif } std::string DebugString() const { const auto offsets = Offsets(); const size_t sizes[] = {SizeOf<ElementType<OffsetSeq>>::value...}; const std::string types[] = { adl_barrier::TypeName<ElementType<OffsetSeq>>()...}; std::string res = absl::StrCat("@0", types[0], "(", sizes[0], ")"); for (size_t i = 0; i != NumOffsets - 1; ++i) { absl::StrAppend(&res, "[", DebugSize(i), "]; @", offsets[i + 1], types[i + 1], "(", sizes[i + 1], ")"); } int last = static_cast<int>(NumSizes) - 1; if (NumTypes == NumSizes && last >= 0) { absl::StrAppend(&res, "[", DebugSize(static_cast<size_t>(last)), "]"); } return res; } private: size_t DebugSize(size_t n) const { if (n < NumStaticSizes) { return kStaticSizes[n]; } else { return size_[n - NumStaticSizes]; } } size_t size_[NumRuntimeSizes > 0 ? NumRuntimeSizes : 1]; }; template <class... Elements, size_t... StaticSizeSeq, size_t... RuntimeSizeSeq, size_t... SizeSeq, size_t... OffsetSeq> constexpr std::array<size_t, sizeof...(StaticSizeSeq)> LayoutImpl< std::tuple<Elements...>, absl::index_sequence<StaticSizeSeq...>, absl::index_sequence<RuntimeSizeSeq...>, absl::index_sequence<SizeSeq...>, absl::index_sequence<OffsetSeq...>>::kStaticSizes; template <class StaticSizeSeq, size_t NumRuntimeSizes, class... Ts> using LayoutType = LayoutImpl< std::tuple<Ts...>, StaticSizeSeq, absl::make_index_sequence<NumRuntimeSizes>, absl::make_index_sequence<NumRuntimeSizes + StaticSizeSeq::size()>, absl::make_index_sequence<adl_barrier::Min( sizeof...(Ts), NumRuntimeSizes + StaticSizeSeq::size() + 1)>>; template <class StaticSizeSeq, class... Ts> class LayoutWithStaticSizes : public LayoutType<StaticSizeSeq, sizeof...(Ts) - adl_barrier::Min(sizeof...(Ts), StaticSizeSeq::size()), Ts...> { private: using Super = LayoutType<StaticSizeSeq, sizeof...(Ts) - adl_barrier::Min(sizeof...(Ts), StaticSizeSeq::size()), Ts...>; public: template <size_t NumSizes> using PartialType = internal_layout::LayoutType<StaticSizeSeq, NumSizes, Ts...>; template <class... Sizes> static constexpr PartialType<sizeof...(Sizes)> Partial(Sizes&&... sizes) { static_assert(sizeof...(Sizes) + StaticSizeSeq::size() <= sizeof...(Ts), ""); return PartialType<sizeof...(Sizes)>( static_cast<size_t>(std::forward<Sizes>(sizes))...); } using Super::Super; }; } template <class... Ts> class Layout : public internal_layout::LayoutWithStaticSizes< absl::make_index_sequence<0>, Ts...> { private: using Super = internal_layout::LayoutWithStaticSizes<absl::make_index_sequence<0>, Ts...>; public: template <class StaticSizeSeq> using WithStaticSizeSequence = internal_layout::LayoutWithStaticSizes<StaticSizeSeq, Ts...>; template <size_t... StaticSizes> using WithStaticSizes = WithStaticSizeSequence<std::index_sequence<StaticSizes...>>; using Super::Super; }; } ABSL_NAMESPACE_END } #endif
#include "absl/container/internal/layout.h" #include <stddef.h> #include <cstdint> #include <cstring> #include <initializer_list> #include <memory> #include <ostream> #include <string> #include <tuple> #include <type_traits> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/log/check.h" #include "absl/types/span.h" #include "absl/utility/utility.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { using ::absl::Span; using ::testing::ElementsAre; size_t Distance(const void* from, const void* to) { CHECK_LE(from, to) << "Distance must be non-negative"; return static_cast<const char*>(to) - static_cast<const char*>(from); } template <class Expected, class Actual> Expected Type(Actual val) { static_assert(std::is_same<Expected, Actual>(), ""); return val; } struct alignas(8) Int128 { uint64_t a, b; friend bool operator==(Int128 lhs, Int128 rhs) { return std::tie(lhs.a, lhs.b) == std::tie(rhs.a, rhs.b); } static std::string Name() { return internal_layout::adl_barrier::TypeName<Int128>(); } }; struct alignas(8) Int64 { int64_t a; friend bool operator==(Int64 lhs, Int64 rhs) { return lhs.a == rhs.a; } }; static_assert(sizeof(int8_t) == 1, ""); static_assert(alignof(int8_t) == 1, ""); static_assert(sizeof(int16_t) == 2, ""); static_assert(alignof(int16_t) == 2, ""); static_assert(sizeof(int32_t) == 4, ""); static_assert(alignof(int32_t) == 4, ""); static_assert(sizeof(Int64) == 8, ""); static_assert(alignof(Int64) == 8, ""); static_assert(sizeof(Int128) == 16, ""); static_assert(alignof(Int128) == 8, ""); template <class Expected, class Actual> void SameType() { static_assert(std::is_same<Expected, Actual>(), ""); } TEST(Layout, ElementType) { { using L = Layout<int32_t>; SameType<int32_t, L::ElementType<0>>(); SameType<int32_t, decltype(L::Partial())::ElementType<0>>(); SameType<int32_t, decltype(L::Partial(0))::ElementType<0>>(); } { using L = Layout<int32_t, int32_t>; SameType<int32_t, L::ElementType<0>>(); SameType<int32_t, L::ElementType<1>>(); SameType<int32_t, decltype(L::Partial())::ElementType<0>>(); SameType<int32_t, decltype(L::Partial())::ElementType<1>>(); SameType<int32_t, decltype(L::Partial(0))::ElementType<0>>(); SameType<int32_t, decltype(L::Partial(0))::ElementType<1>>(); } { using L = Layout<int8_t, int32_t, Int128>; SameType<int8_t, L::ElementType<0>>(); SameType<int32_t, L::ElementType<1>>(); SameType<Int128, L::ElementType<2>>(); SameType<int8_t, decltype(L::Partial())::ElementType<0>>(); SameType<int8_t, decltype(L::Partial(0))::ElementType<0>>(); SameType<int32_t, decltype(L::Partial(0))::ElementType<1>>(); SameType<int8_t, decltype(L::Partial(0, 0))::ElementType<0>>(); SameType<int32_t, decltype(L::Partial(0, 0))::ElementType<1>>(); SameType<Int128, decltype(L::Partial(0, 0))::ElementType<2>>(); SameType<int8_t, decltype(L::Partial(0, 0, 0))::ElementType<0>>(); SameType<int32_t, decltype(L::Partial(0, 0, 0))::ElementType<1>>(); SameType<Int128, decltype(L::Partial(0, 0, 0))::ElementType<2>>(); } } TEST(Layout, ElementTypes) { { using L = Layout<int32_t>; SameType<std::tuple<int32_t>, L::ElementTypes>(); SameType<std::tuple<int32_t>, decltype(L::Partial())::ElementTypes>(); SameType<std::tuple<int32_t>, decltype(L::Partial(0))::ElementTypes>(); } { using L = Layout<int32_t, int32_t>; SameType<std::tuple<int32_t, int32_t>, L::ElementTypes>(); SameType<std::tuple<int32_t, int32_t>, decltype(L::Partial())::ElementTypes>(); SameType<std::tuple<int32_t, int32_t>, decltype(L::Partial(0))::ElementTypes>(); } { using L = Layout<int8_t, int32_t, Int128>; SameType<std::tuple<int8_t, int32_t, Int128>, L::ElementTypes>(); SameType<std::tuple<int8_t, int32_t, Int128>, decltype(L::Partial())::ElementTypes>(); SameType<std::tuple<int8_t, int32_t, Int128>, decltype(L::Partial(0))::ElementTypes>(); SameType<std::tuple<int8_t, int32_t, Int128>, decltype(L::Partial(0, 0))::ElementTypes>(); SameType<std::tuple<int8_t, int32_t, Int128>, decltype(L::Partial(0, 0, 0))::ElementTypes>(); } } TEST(Layout, OffsetByIndex) { { using L = Layout<int32_t>; EXPECT_EQ(0, L::Partial().Offset<0>()); EXPECT_EQ(0, L::Partial(3).Offset<0>()); EXPECT_EQ(0, L(3).Offset<0>()); } { using L = Layout<int32_t, int32_t>; EXPECT_EQ(0, L::Partial().Offset<0>()); EXPECT_EQ(0, L::Partial(3).Offset<0>()); EXPECT_EQ(12, L::Partial(3).Offset<1>()); EXPECT_EQ(0, L::Partial(3, 5).Offset<0>()); EXPECT_EQ(12, L::Partial(3, 5).Offset<1>()); EXPECT_EQ(0, L(3, 5).Offset<0>()); EXPECT_EQ(12, L(3, 5).Offset<1>()); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ(0, L::Partial().Offset<0>()); EXPECT_EQ(0, L::Partial(0).Offset<0>()); EXPECT_EQ(0, L::Partial(0).Offset<1>()); EXPECT_EQ(0, L::Partial(1).Offset<0>()); EXPECT_EQ(4, L::Partial(1).Offset<1>()); EXPECT_EQ(0, L::Partial(5).Offset<0>()); EXPECT_EQ(8, L::Partial(5).Offset<1>()); EXPECT_EQ(0, L::Partial(0, 0).Offset<0>()); EXPECT_EQ(0, L::Partial(0, 0).Offset<1>()); EXPECT_EQ(0, L::Partial(0, 0).Offset<2>()); EXPECT_EQ(0, L::Partial(1, 0).Offset<0>()); EXPECT_EQ(4, L::Partial(1, 0).Offset<1>()); EXPECT_EQ(8, L::Partial(1, 0).Offset<2>()); EXPECT_EQ(0, L::Partial(5, 3).Offset<0>()); EXPECT_EQ(8, L::Partial(5, 3).Offset<1>()); EXPECT_EQ(24, L::Partial(5, 3).Offset<2>()); EXPECT_EQ(0, L::Partial(0, 0, 0).Offset<0>()); EXPECT_EQ(0, L::Partial(0, 0, 0).Offset<1>()); EXPECT_EQ(0, L::Partial(0, 0, 0).Offset<2>()); EXPECT_EQ(0, L::Partial(1, 0, 0).Offset<0>()); EXPECT_EQ(4, L::Partial(1, 0, 0).Offset<1>()); EXPECT_EQ(8, L::Partial(1, 0, 0).Offset<2>()); EXPECT_EQ(0, L::Partial(5, 3, 1).Offset<0>()); EXPECT_EQ(24, L::Partial(5, 3, 1).Offset<2>()); EXPECT_EQ(8, L::Partial(5, 3, 1).Offset<1>()); EXPECT_EQ(0, L(5, 3, 1).Offset<0>()); EXPECT_EQ(24, L(5, 3, 1).Offset<2>()); EXPECT_EQ(8, L(5, 3, 1).Offset<1>()); } } TEST(Layout, OffsetByType) { { using L = Layout<int32_t>; EXPECT_EQ(0, L::Partial().Offset<int32_t>()); EXPECT_EQ(0, L::Partial(3).Offset<int32_t>()); EXPECT_EQ(0, L(3).Offset<int32_t>()); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ(0, L::Partial().Offset<int8_t>()); EXPECT_EQ(0, L::Partial(0).Offset<int8_t>()); EXPECT_EQ(0, L::Partial(0).Offset<int32_t>()); EXPECT_EQ(0, L::Partial(1).Offset<int8_t>()); EXPECT_EQ(4, L::Partial(1).Offset<int32_t>()); EXPECT_EQ(0, L::Partial(5).Offset<int8_t>()); EXPECT_EQ(8, L::Partial(5).Offset<int32_t>()); EXPECT_EQ(0, L::Partial(0, 0).Offset<int8_t>()); EXPECT_EQ(0, L::Partial(0, 0).Offset<int32_t>()); EXPECT_EQ(0, L::Partial(0, 0).Offset<Int128>()); EXPECT_EQ(0, L::Partial(1, 0).Offset<int8_t>()); EXPECT_EQ(4, L::Partial(1, 0).Offset<int32_t>()); EXPECT_EQ(8, L::Partial(1, 0).Offset<Int128>()); EXPECT_EQ(0, L::Partial(5, 3).Offset<int8_t>()); EXPECT_EQ(8, L::Partial(5, 3).Offset<int32_t>()); EXPECT_EQ(24, L::Partial(5, 3).Offset<Int128>()); EXPECT_EQ(0, L::Partial(0, 0, 0).Offset<int8_t>()); EXPECT_EQ(0, L::Partial(0, 0, 0).Offset<int32_t>()); EXPECT_EQ(0, L::Partial(0, 0, 0).Offset<Int128>()); EXPECT_EQ(0, L::Partial(1, 0, 0).Offset<int8_t>()); EXPECT_EQ(4, L::Partial(1, 0, 0).Offset<int32_t>()); EXPECT_EQ(8, L::Partial(1, 0, 0).Offset<Int128>()); EXPECT_EQ(0, L::Partial(5, 3, 1).Offset<int8_t>()); EXPECT_EQ(24, L::Partial(5, 3, 1).Offset<Int128>()); EXPECT_EQ(8, L::Partial(5, 3, 1).Offset<int32_t>()); EXPECT_EQ(0, L(5, 3, 1).Offset<int8_t>()); EXPECT_EQ(24, L(5, 3, 1).Offset<Int128>()); EXPECT_EQ(8, L(5, 3, 1).Offset<int32_t>()); } } TEST(Layout, Offsets) { { using L = Layout<int32_t>; EXPECT_THAT(L::Partial().Offsets(), ElementsAre(0)); EXPECT_THAT(L::Partial(3).Offsets(), ElementsAre(0)); EXPECT_THAT(L(3).Offsets(), ElementsAre(0)); } { using L = Layout<int32_t, int32_t>; EXPECT_THAT(L::Partial().Offsets(), ElementsAre(0)); EXPECT_THAT(L::Partial(3).Offsets(), ElementsAre(0, 12)); EXPECT_THAT(L::Partial(3, 5).Offsets(), ElementsAre(0, 12)); EXPECT_THAT(L(3, 5).Offsets(), ElementsAre(0, 12)); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_THAT(L::Partial().Offsets(), ElementsAre(0)); EXPECT_THAT(L::Partial(1).Offsets(), ElementsAre(0, 4)); EXPECT_THAT(L::Partial(5).Offsets(), ElementsAre(0, 8)); EXPECT_THAT(L::Partial(0, 0).Offsets(), ElementsAre(0, 0, 0)); EXPECT_THAT(L::Partial(1, 0).Offsets(), ElementsAre(0, 4, 8)); EXPECT_THAT(L::Partial(5, 3).Offsets(), ElementsAre(0, 8, 24)); EXPECT_THAT(L::Partial(0, 0, 0).Offsets(), ElementsAre(0, 0, 0)); EXPECT_THAT(L::Partial(1, 0, 0).Offsets(), ElementsAre(0, 4, 8)); EXPECT_THAT(L::Partial(5, 3, 1).Offsets(), ElementsAre(0, 8, 24)); EXPECT_THAT(L(5, 3, 1).Offsets(), ElementsAre(0, 8, 24)); } } TEST(Layout, StaticOffsets) { using L = Layout<int8_t, int32_t, Int128>; { using SL = L::WithStaticSizes<>; EXPECT_THAT(SL::Partial().Offsets(), ElementsAre(0)); EXPECT_THAT(SL::Partial(5).Offsets(), ElementsAre(0, 8)); EXPECT_THAT(SL::Partial(5, 3, 1).Offsets(), ElementsAre(0, 8, 24)); EXPECT_THAT(SL(5, 3, 1).Offsets(), ElementsAre(0, 8, 24)); } { using SL = L::WithStaticSizes<5>; EXPECT_THAT(SL::Partial().Offsets(), ElementsAre(0, 8)); EXPECT_THAT(SL::Partial(3).Offsets(), ElementsAre(0, 8, 24)); EXPECT_THAT(SL::Partial(3, 1).Offsets(), ElementsAre(0, 8, 24)); EXPECT_THAT(SL(3, 1).Offsets(), ElementsAre(0, 8, 24)); } { using SL = L::WithStaticSizes<5, 3>; EXPECT_THAT(SL::Partial().Offsets(), ElementsAre(0, 8, 24)); EXPECT_THAT(SL::Partial(1).Offsets(), ElementsAre(0, 8, 24)); EXPECT_THAT(SL(1).Offsets(), ElementsAre(0, 8, 24)); } { using SL = L::WithStaticSizes<5, 3, 1>; EXPECT_THAT(SL::Partial().Offsets(), ElementsAre(0, 8, 24)); EXPECT_THAT(SL().Offsets(), ElementsAre(0, 8, 24)); } } TEST(Layout, AllocSize) { { using L = Layout<int32_t>; EXPECT_EQ(0, L::Partial(0).AllocSize()); EXPECT_EQ(12, L::Partial(3).AllocSize()); EXPECT_EQ(12, L(3).AllocSize()); } { using L = Layout<int32_t, int32_t>; EXPECT_EQ(32, L::Partial(3, 5).AllocSize()); EXPECT_EQ(32, L(3, 5).AllocSize()); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ(0, L::Partial(0, 0, 0).AllocSize()); EXPECT_EQ(8, L::Partial(1, 0, 0).AllocSize()); EXPECT_EQ(8, L::Partial(0, 1, 0).AllocSize()); EXPECT_EQ(16, L::Partial(0, 0, 1).AllocSize()); EXPECT_EQ(24, L::Partial(1, 1, 1).AllocSize()); EXPECT_EQ(136, L::Partial(3, 5, 7).AllocSize()); EXPECT_EQ(136, L(3, 5, 7).AllocSize()); } } TEST(Layout, StaticAllocSize) { using L = Layout<int8_t, int32_t, Int128>; { using SL = L::WithStaticSizes<>; EXPECT_EQ(136, SL::Partial(3, 5, 7).AllocSize()); EXPECT_EQ(136, SL(3, 5, 7).AllocSize()); } { using SL = L::WithStaticSizes<3>; EXPECT_EQ(136, SL::Partial(5, 7).AllocSize()); EXPECT_EQ(136, SL(5, 7).AllocSize()); } { using SL = L::WithStaticSizes<3, 5>; EXPECT_EQ(136, SL::Partial(7).AllocSize()); EXPECT_EQ(136, SL(7).AllocSize()); } { using SL = L::WithStaticSizes<3, 5, 7>; EXPECT_EQ(136, SL::Partial().AllocSize()); EXPECT_EQ(136, SL().AllocSize()); } } TEST(Layout, SizeByIndex) { { using L = Layout<int32_t>; EXPECT_EQ(0, L::Partial(0).Size<0>()); EXPECT_EQ(3, L::Partial(3).Size<0>()); EXPECT_EQ(3, L(3).Size<0>()); } { using L = Layout<int32_t, int32_t>; EXPECT_EQ(0, L::Partial(0).Size<0>()); EXPECT_EQ(3, L::Partial(3).Size<0>()); EXPECT_EQ(3, L::Partial(3, 5).Size<0>()); EXPECT_EQ(5, L::Partial(3, 5).Size<1>()); EXPECT_EQ(3, L(3, 5).Size<0>()); EXPECT_EQ(5, L(3, 5).Size<1>()); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ(3, L::Partial(3).Size<0>()); EXPECT_EQ(3, L::Partial(3, 5).Size<0>()); EXPECT_EQ(5, L::Partial(3, 5).Size<1>()); EXPECT_EQ(3, L::Partial(3, 5, 7).Size<0>()); EXPECT_EQ(5, L::Partial(3, 5, 7).Size<1>()); EXPECT_EQ(7, L::Partial(3, 5, 7).Size<2>()); EXPECT_EQ(3, L(3, 5, 7).Size<0>()); EXPECT_EQ(5, L(3, 5, 7).Size<1>()); EXPECT_EQ(7, L(3, 5, 7).Size<2>()); } } TEST(Layout, SizeByType) { { using L = Layout<int32_t>; EXPECT_EQ(0, L::Partial(0).Size<int32_t>()); EXPECT_EQ(3, L::Partial(3).Size<int32_t>()); EXPECT_EQ(3, L(3).Size<int32_t>()); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ(3, L::Partial(3).Size<int8_t>()); EXPECT_EQ(3, L::Partial(3, 5).Size<int8_t>()); EXPECT_EQ(5, L::Partial(3, 5).Size<int32_t>()); EXPECT_EQ(3, L::Partial(3, 5, 7).Size<int8_t>()); EXPECT_EQ(5, L::Partial(3, 5, 7).Size<int32_t>()); EXPECT_EQ(7, L::Partial(3, 5, 7).Size<Int128>()); EXPECT_EQ(3, L(3, 5, 7).Size<int8_t>()); EXPECT_EQ(5, L(3, 5, 7).Size<int32_t>()); EXPECT_EQ(7, L(3, 5, 7).Size<Int128>()); } } TEST(Layout, Sizes) { { using L = Layout<int32_t>; EXPECT_THAT(L::Partial().Sizes(), ElementsAre()); EXPECT_THAT(L::Partial(3).Sizes(), ElementsAre(3)); EXPECT_THAT(L(3).Sizes(), ElementsAre(3)); } { using L = Layout<int32_t, int32_t>; EXPECT_THAT(L::Partial().Sizes(), ElementsAre()); EXPECT_THAT(L::Partial(3).Sizes(), ElementsAre(3)); EXPECT_THAT(L::Partial(3, 5).Sizes(), ElementsAre(3, 5)); EXPECT_THAT(L(3, 5).Sizes(), ElementsAre(3, 5)); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_THAT(L::Partial().Sizes(), ElementsAre()); EXPECT_THAT(L::Partial(3).Sizes(), ElementsAre(3)); EXPECT_THAT(L::Partial(3, 5).Sizes(), ElementsAre(3, 5)); EXPECT_THAT(L::Partial(3, 5, 7).Sizes(), ElementsAre(3, 5, 7)); EXPECT_THAT(L(3, 5, 7).Sizes(), ElementsAre(3, 5, 7)); } } TEST(Layout, StaticSize) { using L = Layout<int8_t, int32_t, Int128>; { using SL = L::WithStaticSizes<>; EXPECT_THAT(SL::Partial().Sizes(), ElementsAre()); EXPECT_THAT(SL::Partial(3).Size<0>(), 3); EXPECT_THAT(SL::Partial(3).Size<int8_t>(), 3); EXPECT_THAT(SL::Partial(3).Sizes(), ElementsAre(3)); EXPECT_THAT(SL::Partial(3, 5, 7).Size<0>(), 3); EXPECT_THAT(SL::Partial(3, 5, 7).Size<int8_t>(), 3); EXPECT_THAT(SL::Partial(3, 5, 7).Size<2>(), 7); EXPECT_THAT(SL::Partial(3, 5, 7).Size<Int128>(), 7); EXPECT_THAT(SL::Partial(3, 5, 7).Sizes(), ElementsAre(3, 5, 7)); EXPECT_THAT(SL(3, 5, 7).Size<0>(), 3); EXPECT_THAT(SL(3, 5, 7).Size<int8_t>(), 3); EXPECT_THAT(SL(3, 5, 7).Size<2>(), 7); EXPECT_THAT(SL(3, 5, 7).Size<Int128>(), 7); EXPECT_THAT(SL(3, 5, 7).Sizes(), ElementsAre(3, 5, 7)); } } TEST(Layout, PointerByIndex) { alignas(max_align_t) const unsigned char p[100] = {0}; { using L = Layout<int32_t>; EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L::Partial().Pointer<0>(p)))); EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L::Partial(3).Pointer<0>(p)))); EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L(3).Pointer<0>(p)))); } { using L = Layout<int32_t, int32_t>; EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L::Partial().Pointer<0>(p)))); EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L::Partial(3).Pointer<0>(p)))); EXPECT_EQ(12, Distance(p, Type<const int32_t*>(L::Partial(3).Pointer<1>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int32_t*>(L::Partial(3, 5).Pointer<0>(p)))); EXPECT_EQ( 12, Distance(p, Type<const int32_t*>(L::Partial(3, 5).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L(3, 5).Pointer<0>(p)))); EXPECT_EQ(12, Distance(p, Type<const int32_t*>(L(3, 5).Pointer<1>(p)))); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L::Partial().Pointer<0>(p)))); EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L::Partial(0).Pointer<0>(p)))); EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L::Partial(0).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L::Partial(1).Pointer<0>(p)))); EXPECT_EQ(4, Distance(p, Type<const int32_t*>(L::Partial(1).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L::Partial(5).Pointer<0>(p)))); EXPECT_EQ(8, Distance(p, Type<const int32_t*>(L::Partial(5).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L::Partial(0, 0).Pointer<0>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int32_t*>(L::Partial(0, 0).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<const Int128*>(L::Partial(0, 0).Pointer<2>(p)))); EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L::Partial(1, 0).Pointer<0>(p)))); EXPECT_EQ( 4, Distance(p, Type<const int32_t*>(L::Partial(1, 0).Pointer<1>(p)))); EXPECT_EQ(8, Distance(p, Type<const Int128*>(L::Partial(1, 0).Pointer<2>(p)))); EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L::Partial(5, 3).Pointer<0>(p)))); EXPECT_EQ( 8, Distance(p, Type<const int32_t*>(L::Partial(5, 3).Pointer<1>(p)))); EXPECT_EQ(24, Distance(p, Type<const Int128*>(L::Partial(5, 3).Pointer<2>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int8_t*>(L::Partial(0, 0, 0).Pointer<0>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int32_t*>(L::Partial(0, 0, 0).Pointer<1>(p)))); EXPECT_EQ( 0, Distance(p, Type<const Int128*>(L::Partial(0, 0, 0).Pointer<2>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int8_t*>(L::Partial(1, 0, 0).Pointer<0>(p)))); EXPECT_EQ( 4, Distance(p, Type<const int32_t*>(L::Partial(1, 0, 0).Pointer<1>(p)))); EXPECT_EQ( 8, Distance(p, Type<const Int128*>(L::Partial(1, 0, 0).Pointer<2>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int8_t*>(L::Partial(5, 3, 1).Pointer<0>(p)))); EXPECT_EQ( 24, Distance(p, Type<const Int128*>(L::Partial(5, 3, 1).Pointer<2>(p)))); EXPECT_EQ( 8, Distance(p, Type<const int32_t*>(L::Partial(5, 3, 1).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<const int8_t*>(L(5, 3, 1).Pointer<0>(p)))); EXPECT_EQ(24, Distance(p, Type<const Int128*>(L(5, 3, 1).Pointer<2>(p)))); EXPECT_EQ(8, Distance(p, Type<const int32_t*>(L(5, 3, 1).Pointer<1>(p)))); } } TEST(Layout, PointerByType) { alignas(max_align_t) const unsigned char p[100] = {0}; { using L = Layout<int32_t>; EXPECT_EQ( 0, Distance(p, Type<const int32_t*>(L::Partial().Pointer<int32_t>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int32_t*>(L::Partial(3).Pointer<int32_t>(p)))); EXPECT_EQ(0, Distance(p, Type<const int32_t*>(L(3).Pointer<int32_t>(p)))); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ( 0, Distance(p, Type<const int8_t*>(L::Partial().Pointer<int8_t>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int8_t*>(L::Partial(0).Pointer<int8_t>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int32_t*>(L::Partial(0).Pointer<int32_t>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int8_t*>(L::Partial(1).Pointer<int8_t>(p)))); EXPECT_EQ( 4, Distance(p, Type<const int32_t*>(L::Partial(1).Pointer<int32_t>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int8_t*>(L::Partial(5).Pointer<int8_t>(p)))); EXPECT_EQ( 8, Distance(p, Type<const int32_t*>(L::Partial(5).Pointer<int32_t>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int8_t*>(L::Partial(0, 0).Pointer<int8_t>(p)))); EXPECT_EQ(0, Distance(p, Type<const int32_t*>( L::Partial(0, 0).Pointer<int32_t>(p)))); EXPECT_EQ( 0, Distance(p, Type<const Int128*>(L::Partial(0, 0).Pointer<Int128>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int8_t*>(L::Partial(1, 0).Pointer<int8_t>(p)))); EXPECT_EQ(4, Distance(p, Type<const int32_t*>( L::Partial(1, 0).Pointer<int32_t>(p)))); EXPECT_EQ( 8, Distance(p, Type<const Int128*>(L::Partial(1, 0).Pointer<Int128>(p)))); EXPECT_EQ( 0, Distance(p, Type<const int8_t*>(L::Partial(5, 3).Pointer<int8_t>(p)))); EXPECT_EQ(8, Distance(p, Type<const int32_t*>( L::Partial(5, 3).Pointer<int32_t>(p)))); EXPECT_EQ( 24, Distance(p, Type<const Int128*>(L::Partial(5, 3).Pointer<Int128>(p)))); EXPECT_EQ(0, Distance(p, Type<const int8_t*>( L::Partial(0, 0, 0).Pointer<int8_t>(p)))); EXPECT_EQ(0, Distance(p, Type<const int32_t*>( L::Partial(0, 0, 0).Pointer<int32_t>(p)))); EXPECT_EQ(0, Distance(p, Type<const Int128*>( L::Partial(0, 0, 0).Pointer<Int128>(p)))); EXPECT_EQ(0, Distance(p, Type<const int8_t*>( L::Partial(1, 0, 0).Pointer<int8_t>(p)))); EXPECT_EQ(4, Distance(p, Type<const int32_t*>( L::Partial(1, 0, 0).Pointer<int32_t>(p)))); EXPECT_EQ(8, Distance(p, Type<const Int128*>( L::Partial(1, 0, 0).Pointer<Int128>(p)))); EXPECT_EQ(0, Distance(p, Type<const int8_t*>( L::Partial(5, 3, 1).Pointer<int8_t>(p)))); EXPECT_EQ(24, Distance(p, Type<const Int128*>( L::Partial(5, 3, 1).Pointer<Int128>(p)))); EXPECT_EQ(8, Distance(p, Type<const int32_t*>( L::Partial(5, 3, 1).Pointer<int32_t>(p)))); EXPECT_EQ(24, Distance(p, Type<const Int128*>(L(5, 3, 1).Pointer<Int128>(p)))); EXPECT_EQ( 8, Distance(p, Type<const int32_t*>(L(5, 3, 1).Pointer<int32_t>(p)))); } } TEST(Layout, MutablePointerByIndex) { alignas(max_align_t) unsigned char p[100] = {0}; { using L = Layout<int32_t>; EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial().Pointer<0>(p)))); EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(3).Pointer<0>(p)))); EXPECT_EQ(0, Distance(p, Type<int32_t*>(L(3).Pointer<0>(p)))); } { using L = Layout<int32_t, int32_t>; EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial().Pointer<0>(p)))); EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(3).Pointer<0>(p)))); EXPECT_EQ(12, Distance(p, Type<int32_t*>(L::Partial(3).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(3, 5).Pointer<0>(p)))); EXPECT_EQ(12, Distance(p, Type<int32_t*>(L::Partial(3, 5).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<int32_t*>(L(3, 5).Pointer<0>(p)))); EXPECT_EQ(12, Distance(p, Type<int32_t*>(L(3, 5).Pointer<1>(p)))); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial().Pointer<0>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(0).Pointer<0>(p)))); EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(0).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(1).Pointer<0>(p)))); EXPECT_EQ(4, Distance(p, Type<int32_t*>(L::Partial(1).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(5).Pointer<0>(p)))); EXPECT_EQ(8, Distance(p, Type<int32_t*>(L::Partial(5).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(0, 0).Pointer<0>(p)))); EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(0, 0).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<Int128*>(L::Partial(0, 0).Pointer<2>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(1, 0).Pointer<0>(p)))); EXPECT_EQ(4, Distance(p, Type<int32_t*>(L::Partial(1, 0).Pointer<1>(p)))); EXPECT_EQ(8, Distance(p, Type<Int128*>(L::Partial(1, 0).Pointer<2>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(5, 3).Pointer<0>(p)))); EXPECT_EQ(8, Distance(p, Type<int32_t*>(L::Partial(5, 3).Pointer<1>(p)))); EXPECT_EQ(24, Distance(p, Type<Int128*>(L::Partial(5, 3).Pointer<2>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(0, 0, 0).Pointer<0>(p)))); EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(0, 0, 0).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<Int128*>(L::Partial(0, 0, 0).Pointer<2>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(1, 0, 0).Pointer<0>(p)))); EXPECT_EQ(4, Distance(p, Type<int32_t*>(L::Partial(1, 0, 0).Pointer<1>(p)))); EXPECT_EQ(8, Distance(p, Type<Int128*>(L::Partial(1, 0, 0).Pointer<2>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(5, 3, 1).Pointer<0>(p)))); EXPECT_EQ(24, Distance(p, Type<Int128*>(L::Partial(5, 3, 1).Pointer<2>(p)))); EXPECT_EQ(8, Distance(p, Type<int32_t*>(L::Partial(5, 3, 1).Pointer<1>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L(5, 3, 1).Pointer<0>(p)))); EXPECT_EQ(24, Distance(p, Type<Int128*>(L(5, 3, 1).Pointer<2>(p)))); EXPECT_EQ(8, Distance(p, Type<int32_t*>(L(5, 3, 1).Pointer<1>(p)))); } } TEST(Layout, MutablePointerByType) { alignas(max_align_t) unsigned char p[100] = {0}; { using L = Layout<int32_t>; EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial().Pointer<int32_t>(p)))); EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(3).Pointer<int32_t>(p)))); EXPECT_EQ(0, Distance(p, Type<int32_t*>(L(3).Pointer<int32_t>(p)))); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial().Pointer<int8_t>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(0).Pointer<int8_t>(p)))); EXPECT_EQ(0, Distance(p, Type<int32_t*>(L::Partial(0).Pointer<int32_t>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(1).Pointer<int8_t>(p)))); EXPECT_EQ(4, Distance(p, Type<int32_t*>(L::Partial(1).Pointer<int32_t>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(5).Pointer<int8_t>(p)))); EXPECT_EQ(8, Distance(p, Type<int32_t*>(L::Partial(5).Pointer<int32_t>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(0, 0).Pointer<int8_t>(p)))); EXPECT_EQ( 0, Distance(p, Type<int32_t*>(L::Partial(0, 0).Pointer<int32_t>(p)))); EXPECT_EQ(0, Distance(p, Type<Int128*>(L::Partial(0, 0).Pointer<Int128>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(1, 0).Pointer<int8_t>(p)))); EXPECT_EQ( 4, Distance(p, Type<int32_t*>(L::Partial(1, 0).Pointer<int32_t>(p)))); EXPECT_EQ(8, Distance(p, Type<Int128*>(L::Partial(1, 0).Pointer<Int128>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L::Partial(5, 3).Pointer<int8_t>(p)))); EXPECT_EQ( 8, Distance(p, Type<int32_t*>(L::Partial(5, 3).Pointer<int32_t>(p)))); EXPECT_EQ(24, Distance(p, Type<Int128*>(L::Partial(5, 3).Pointer<Int128>(p)))); EXPECT_EQ( 0, Distance(p, Type<int8_t*>(L::Partial(0, 0, 0).Pointer<int8_t>(p)))); EXPECT_EQ( 0, Distance(p, Type<int32_t*>(L::Partial(0, 0, 0).Pointer<int32_t>(p)))); EXPECT_EQ( 0, Distance(p, Type<Int128*>(L::Partial(0, 0, 0).Pointer<Int128>(p)))); EXPECT_EQ( 0, Distance(p, Type<int8_t*>(L::Partial(1, 0, 0).Pointer<int8_t>(p)))); EXPECT_EQ( 4, Distance(p, Type<int32_t*>(L::Partial(1, 0, 0).Pointer<int32_t>(p)))); EXPECT_EQ( 8, Distance(p, Type<Int128*>(L::Partial(1, 0, 0).Pointer<Int128>(p)))); EXPECT_EQ( 0, Distance(p, Type<int8_t*>(L::Partial(5, 3, 1).Pointer<int8_t>(p)))); EXPECT_EQ( 24, Distance(p, Type<Int128*>(L::Partial(5, 3, 1).Pointer<Int128>(p)))); EXPECT_EQ( 8, Distance(p, Type<int32_t*>(L::Partial(5, 3, 1).Pointer<int32_t>(p)))); EXPECT_EQ(0, Distance(p, Type<int8_t*>(L(5, 3, 1).Pointer<int8_t>(p)))); EXPECT_EQ(24, Distance(p, Type<Int128*>(L(5, 3, 1).Pointer<Int128>(p)))); EXPECT_EQ(8, Distance(p, Type<int32_t*>(L(5, 3, 1).Pointer<int32_t>(p)))); } } TEST(Layout, Pointers) { alignas(max_align_t) const unsigned char p[100] = {0}; using L = Layout<int8_t, int8_t, Int128>; { const auto x = L::Partial(); EXPECT_EQ(std::make_tuple(x.Pointer<0>(p)), Type<std::tuple<const int8_t*>>(x.Pointers(p))); } { const auto x = L::Partial(1); EXPECT_EQ(std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p)), (Type<std::tuple<const int8_t*, const int8_t*>>(x.Pointers(p)))); } { const auto x = L::Partial(1, 2); EXPECT_EQ( std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)), (Type<std::tuple<const int8_t*, const int8_t*, const Int128*>>( x.Pointers(p)))); } { const auto x = L::Partial(1, 2, 3); EXPECT_EQ( std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)), (Type<std::tuple<const int8_t*, const int8_t*, const Int128*>>( x.Pointers(p)))); } { const L x(1, 2, 3); EXPECT_EQ( std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)), (Type<std::tuple<const int8_t*, const int8_t*, const Int128*>>( x.Pointers(p)))); } } TEST(Layout, MutablePointers) { alignas(max_align_t) unsigned char p[100] = {0}; using L = Layout<int8_t, int8_t, Int128>; { const auto x = L::Partial(); EXPECT_EQ(std::make_tuple(x.Pointer<0>(p)), Type<std::tuple<int8_t*>>(x.Pointers(p))); } { const auto x = L::Partial(1); EXPECT_EQ(std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p)), (Type<std::tuple<int8_t*, int8_t*>>(x.Pointers(p)))); } { const auto x = L::Partial(1, 2); EXPECT_EQ( std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)), (Type<std::tuple<int8_t*, int8_t*, Int128*>>(x.Pointers(p)))); } { const auto x = L::Partial(1, 2, 3); EXPECT_EQ( std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)), (Type<std::tuple<int8_t*, int8_t*, Int128*>>(x.Pointers(p)))); } { const L x(1, 2, 3); EXPECT_EQ( std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)), (Type<std::tuple<int8_t*, int8_t*, Int128*>>(x.Pointers(p)))); } } TEST(Layout, StaticPointers) { alignas(max_align_t) const unsigned char p[100] = {0}; using L = Layout<int8_t, int8_t, Int128>; { const auto x = L::WithStaticSizes<>::Partial(); EXPECT_EQ(std::make_tuple(x.Pointer<0>(p)), Type<std::tuple<const int8_t*>>(x.Pointers(p))); } { const auto x = L::WithStaticSizes<>::Partial(1); EXPECT_EQ(std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p)), (Type<std::tuple<const int8_t*, const int8_t*>>(x.Pointers(p)))); } { const auto x = L::WithStaticSizes<1>::Partial(); EXPECT_EQ(std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p)), (Type<std::tuple<const int8_t*, const int8_t*>>(x.Pointers(p)))); } { const auto x = L::WithStaticSizes<>::Partial(1, 2, 3); EXPECT_EQ( std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)), (Type<std::tuple<const int8_t*, const int8_t*, const Int128*>>( x.Pointers(p)))); } { const auto x = L::WithStaticSizes<1>::Partial(2, 3); EXPECT_EQ( std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)), (Type<std::tuple<const int8_t*, const int8_t*, const Int128*>>( x.Pointers(p)))); } { const auto x = L::WithStaticSizes<1, 2>::Partial(3); EXPECT_EQ( std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)), (Type<std::tuple<const int8_t*, const int8_t*, const Int128*>>( x.Pointers(p)))); } { const auto x = L::WithStaticSizes<1, 2, 3>::Partial(); EXPECT_EQ( std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)), (Type<std::tuple<const int8_t*, const int8_t*, const Int128*>>( x.Pointers(p)))); } { const L::WithStaticSizes<1, 2, 3> x; EXPECT_EQ( std::make_tuple(x.Pointer<0>(p), x.Pointer<1>(p), x.Pointer<2>(p)), (Type<std::tuple<const int8_t*, const int8_t*, const Int128*>>( x.Pointers(p)))); } } TEST(Layout, SliceByIndexSize) { alignas(max_align_t) const unsigned char p[100] = {0}; { using L = Layout<int32_t>; EXPECT_EQ(0, L::Partial(0).Slice<0>(p).size()); EXPECT_EQ(3, L::Partial(3).Slice<0>(p).size()); EXPECT_EQ(3, L(3).Slice<0>(p).size()); } { using L = Layout<int32_t, int32_t>; EXPECT_EQ(3, L::Partial(3).Slice<0>(p).size()); EXPECT_EQ(5, L::Partial(3, 5).Slice<1>(p).size()); EXPECT_EQ(5, L(3, 5).Slice<1>(p).size()); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ(3, L::Partial(3).Slice<0>(p).size()); EXPECT_EQ(3, L::Partial(3, 5).Slice<0>(p).size()); EXPECT_EQ(5, L::Partial(3, 5).Slice<1>(p).size()); EXPECT_EQ(3, L::Partial(3, 5, 7).Slice<0>(p).size()); EXPECT_EQ(5, L::Partial(3, 5, 7).Slice<1>(p).size()); EXPECT_EQ(7, L::Partial(3, 5, 7).Slice<2>(p).size()); EXPECT_EQ(3, L(3, 5, 7).Slice<0>(p).size()); EXPECT_EQ(5, L(3, 5, 7).Slice<1>(p).size()); EXPECT_EQ(7, L(3, 5, 7).Slice<2>(p).size()); } } TEST(Layout, SliceByTypeSize) { alignas(max_align_t) const unsigned char p[100] = {0}; { using L = Layout<int32_t>; EXPECT_EQ(0, L::Partial(0).Slice<int32_t>(p).size()); EXPECT_EQ(3, L::Partial(3).Slice<int32_t>(p).size()); EXPECT_EQ(3, L(3).Slice<int32_t>(p).size()); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ(3, L::Partial(3).Slice<int8_t>(p).size()); EXPECT_EQ(3, L::Partial(3, 5).Slice<int8_t>(p).size()); EXPECT_EQ(5, L::Partial(3, 5).Slice<int32_t>(p).size()); EXPECT_EQ(3, L::Partial(3, 5, 7).Slice<int8_t>(p).size()); EXPECT_EQ(5, L::Partial(3, 5, 7).Slice<int32_t>(p).size()); EXPECT_EQ(7, L::Partial(3, 5, 7).Slice<Int128>(p).size()); EXPECT_EQ(3, L(3, 5, 7).Slice<int8_t>(p).size()); EXPECT_EQ(5, L(3, 5, 7).Slice<int32_t>(p).size()); EXPECT_EQ(7, L(3, 5, 7).Slice<Int128>(p).size()); } } TEST(Layout, MutableSliceByIndexSize) { alignas(max_align_t) unsigned char p[100] = {0}; { using L = Layout<int32_t>; EXPECT_EQ(0, L::Partial(0).Slice<0>(p).size()); EXPECT_EQ(3, L::Partial(3).Slice<0>(p).size()); EXPECT_EQ(3, L(3).Slice<0>(p).size()); } { using L = Layout<int32_t, int32_t>; EXPECT_EQ(3, L::Partial(3).Slice<0>(p).size()); EXPECT_EQ(5, L::Partial(3, 5).Slice<1>(p).size()); EXPECT_EQ(5, L(3, 5).Slice<1>(p).size()); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ(3, L::Partial(3).Slice<0>(p).size()); EXPECT_EQ(3, L::Partial(3, 5).Slice<0>(p).size()); EXPECT_EQ(5, L::Partial(3, 5).Slice<1>(p).size()); EXPECT_EQ(3, L::Partial(3, 5, 7).Slice<0>(p).size()); EXPECT_EQ(5, L::Partial(3, 5, 7).Slice<1>(p).size()); EXPECT_EQ(7, L::Partial(3, 5, 7).Slice<2>(p).size()); EXPECT_EQ(3, L(3, 5, 7).Slice<0>(p).size()); EXPECT_EQ(5, L(3, 5, 7).Slice<1>(p).size()); EXPECT_EQ(7, L(3, 5, 7).Slice<2>(p).size()); } } TEST(Layout, MutableSliceByTypeSize) { alignas(max_align_t) unsigned char p[100] = {0}; { using L = Layout<int32_t>; EXPECT_EQ(0, L::Partial(0).Slice<int32_t>(p).size()); EXPECT_EQ(3, L::Partial(3).Slice<int32_t>(p).size()); EXPECT_EQ(3, L(3).Slice<int32_t>(p).size()); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ(3, L::Partial(3).Slice<int8_t>(p).size()); EXPECT_EQ(3, L::Partial(3, 5).Slice<int8_t>(p).size()); EXPECT_EQ(5, L::Partial(3, 5).Slice<int32_t>(p).size()); EXPECT_EQ(3, L::Partial(3, 5, 7).Slice<int8_t>(p).size()); EXPECT_EQ(5, L::Partial(3, 5, 7).Slice<int32_t>(p).size()); EXPECT_EQ(7, L::Partial(3, 5, 7).Slice<Int128>(p).size()); EXPECT_EQ(3, L(3, 5, 7).Slice<int8_t>(p).size()); EXPECT_EQ(5, L(3, 5, 7).Slice<int32_t>(p).size()); EXPECT_EQ(7, L(3, 5, 7).Slice<Int128>(p).size()); } } TEST(Layout, StaticSliceSize) { alignas(max_align_t) const unsigned char cp[100] = {0}; alignas(max_align_t) unsigned char p[100] = {0}; using L = Layout<int8_t, int32_t, Int128>; using SL = L::WithStaticSizes<3, 5>; EXPECT_EQ(3, SL::Partial().Slice<0>(cp).size()); EXPECT_EQ(3, SL::Partial().Slice<int8_t>(cp).size()); EXPECT_EQ(3, SL::Partial(7).Slice<0>(cp).size()); EXPECT_EQ(3, SL::Partial(7).Slice<int8_t>(cp).size()); EXPECT_EQ(5, SL::Partial().Slice<1>(cp).size()); EXPECT_EQ(5, SL::Partial().Slice<int32_t>(cp).size()); EXPECT_EQ(5, SL::Partial(7).Slice<1>(cp).size()); EXPECT_EQ(5, SL::Partial(7).Slice<int32_t>(cp).size()); EXPECT_EQ(7, SL::Partial(7).Slice<2>(cp).size()); EXPECT_EQ(7, SL::Partial(7).Slice<Int128>(cp).size()); EXPECT_EQ(3, SL::Partial().Slice<0>(p).size()); EXPECT_EQ(3, SL::Partial().Slice<int8_t>(p).size()); EXPECT_EQ(3, SL::Partial(7).Slice<0>(p).size()); EXPECT_EQ(3, SL::Partial(7).Slice<int8_t>(p).size()); EXPECT_EQ(5, SL::Partial().Slice<1>(p).size()); EXPECT_EQ(5, SL::Partial().Slice<int32_t>(p).size()); EXPECT_EQ(5, SL::Partial(7).Slice<1>(p).size()); EXPECT_EQ(5, SL::Partial(7).Slice<int32_t>(p).size()); EXPECT_EQ(7, SL::Partial(7).Slice<2>(p).size()); EXPECT_EQ(7, SL::Partial(7).Slice<Int128>(p).size()); } TEST(Layout, SliceByIndexData) { alignas(max_align_t) const unsigned char p[100] = {0}; { using L = Layout<int32_t>; EXPECT_EQ( 0, Distance( p, Type<Span<const int32_t>>(L::Partial(0).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int32_t>>(L::Partial(3).Slice<0>(p)).data())); EXPECT_EQ(0, Distance(p, Type<Span<const int32_t>>(L(3).Slice<0>(p)).data())); } { using L = Layout<int32_t, int32_t>; EXPECT_EQ( 0, Distance( p, Type<Span<const int32_t>>(L::Partial(3).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int32_t>>(L::Partial(3, 5).Slice<0>(p)).data())); EXPECT_EQ( 12, Distance( p, Type<Span<const int32_t>>(L::Partial(3, 5).Slice<1>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<const int32_t>>(L(3, 5).Slice<0>(p)).data())); EXPECT_EQ( 12, Distance(p, Type<Span<const int32_t>>(L(3, 5).Slice<1>(p)).data())); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ( 0, Distance( p, Type<Span<const int8_t>>(L::Partial(0).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int8_t>>(L::Partial(1).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int8_t>>(L::Partial(5).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int8_t>>(L::Partial(0, 0).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int32_t>>(L::Partial(0, 0).Slice<1>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int8_t>>(L::Partial(1, 0).Slice<0>(p)).data())); EXPECT_EQ( 4, Distance( p, Type<Span<const int32_t>>(L::Partial(1, 0).Slice<1>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int8_t>>(L::Partial(5, 3).Slice<0>(p)).data())); EXPECT_EQ( 8, Distance( p, Type<Span<const int32_t>>(L::Partial(5, 3).Slice<1>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int8_t>>(L::Partial(0, 0, 0).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int32_t>>(L::Partial(0, 0, 0).Slice<1>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const Int128>>(L::Partial(0, 0, 0).Slice<2>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int8_t>>(L::Partial(1, 0, 0).Slice<0>(p)).data())); EXPECT_EQ( 4, Distance( p, Type<Span<const int32_t>>(L::Partial(1, 0, 0).Slice<1>(p)).data())); EXPECT_EQ( 8, Distance( p, Type<Span<const Int128>>(L::Partial(1, 0, 0).Slice<2>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int8_t>>(L::Partial(5, 3, 1).Slice<0>(p)).data())); EXPECT_EQ( 24, Distance( p, Type<Span<const Int128>>(L::Partial(5, 3, 1).Slice<2>(p)).data())); EXPECT_EQ( 8, Distance( p, Type<Span<const int32_t>>(L::Partial(5, 3, 1).Slice<1>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<const int8_t>>(L(5, 3, 1).Slice<0>(p)).data())); EXPECT_EQ( 24, Distance(p, Type<Span<const Int128>>(L(5, 3, 1).Slice<2>(p)).data())); EXPECT_EQ( 8, Distance(p, Type<Span<const int32_t>>(L(5, 3, 1).Slice<1>(p)).data())); } } TEST(Layout, SliceByTypeData) { alignas(max_align_t) const unsigned char p[100] = {0}; { using L = Layout<int32_t>; EXPECT_EQ( 0, Distance( p, Type<Span<const int32_t>>(L::Partial(0).Slice<int32_t>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int32_t>>(L::Partial(3).Slice<int32_t>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<const int32_t>>(L(3).Slice<int32_t>(p)).data())); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ( 0, Distance( p, Type<Span<const int8_t>>(L::Partial(0).Slice<int8_t>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int8_t>>(L::Partial(1).Slice<int8_t>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<const int8_t>>(L::Partial(5).Slice<int8_t>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<const int8_t>>(L::Partial(0, 0).Slice<int8_t>(p)) .data())); EXPECT_EQ(0, Distance(p, Type<Span<const int32_t>>( L::Partial(0, 0).Slice<int32_t>(p)) .data())); EXPECT_EQ( 0, Distance(p, Type<Span<const int8_t>>(L::Partial(1, 0).Slice<int8_t>(p)) .data())); EXPECT_EQ(4, Distance(p, Type<Span<const int32_t>>( L::Partial(1, 0).Slice<int32_t>(p)) .data())); EXPECT_EQ( 0, Distance(p, Type<Span<const int8_t>>(L::Partial(5, 3).Slice<int8_t>(p)) .data())); EXPECT_EQ(8, Distance(p, Type<Span<const int32_t>>( L::Partial(5, 3).Slice<int32_t>(p)) .data())); EXPECT_EQ(0, Distance(p, Type<Span<const int8_t>>( L::Partial(0, 0, 0).Slice<int8_t>(p)) .data())); EXPECT_EQ(0, Distance(p, Type<Span<const int32_t>>( L::Partial(0, 0, 0).Slice<int32_t>(p)) .data())); EXPECT_EQ(0, Distance(p, Type<Span<const Int128>>( L::Partial(0, 0, 0).Slice<Int128>(p)) .data())); EXPECT_EQ(0, Distance(p, Type<Span<const int8_t>>( L::Partial(1, 0, 0).Slice<int8_t>(p)) .data())); EXPECT_EQ(4, Distance(p, Type<Span<const int32_t>>( L::Partial(1, 0, 0).Slice<int32_t>(p)) .data())); EXPECT_EQ(8, Distance(p, Type<Span<const Int128>>( L::Partial(1, 0, 0).Slice<Int128>(p)) .data())); EXPECT_EQ(0, Distance(p, Type<Span<const int8_t>>( L::Partial(5, 3, 1).Slice<int8_t>(p)) .data())); EXPECT_EQ(24, Distance(p, Type<Span<const Int128>>( L::Partial(5, 3, 1).Slice<Int128>(p)) .data())); EXPECT_EQ(8, Distance(p, Type<Span<const int32_t>>( L::Partial(5, 3, 1).Slice<int32_t>(p)) .data())); EXPECT_EQ( 0, Distance(p, Type<Span<const int8_t>>(L(5, 3, 1).Slice<int8_t>(p)).data())); EXPECT_EQ( 24, Distance(p, Type<Span<const Int128>>(L(5, 3, 1).Slice<Int128>(p)).data())); EXPECT_EQ( 8, Distance( p, Type<Span<const int32_t>>(L(5, 3, 1).Slice<int32_t>(p)).data())); } } TEST(Layout, MutableSliceByIndexData) { alignas(max_align_t) unsigned char p[100] = {0}; { using L = Layout<int32_t>; EXPECT_EQ( 0, Distance(p, Type<Span<int32_t>>(L::Partial(0).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int32_t>>(L::Partial(3).Slice<0>(p)).data())); EXPECT_EQ(0, Distance(p, Type<Span<int32_t>>(L(3).Slice<0>(p)).data())); } { using L = Layout<int32_t, int32_t>; EXPECT_EQ( 0, Distance(p, Type<Span<int32_t>>(L::Partial(3).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int32_t>>(L::Partial(3, 5).Slice<0>(p)).data())); EXPECT_EQ( 12, Distance(p, Type<Span<int32_t>>(L::Partial(3, 5).Slice<1>(p)).data())); EXPECT_EQ(0, Distance(p, Type<Span<int32_t>>(L(3, 5).Slice<0>(p)).data())); EXPECT_EQ(12, Distance(p, Type<Span<int32_t>>(L(3, 5).Slice<1>(p)).data())); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L::Partial(0).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L::Partial(1).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L::Partial(5).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L::Partial(0, 0).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int32_t>>(L::Partial(0, 0).Slice<1>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L::Partial(1, 0).Slice<0>(p)).data())); EXPECT_EQ( 4, Distance(p, Type<Span<int32_t>>(L::Partial(1, 0).Slice<1>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L::Partial(5, 3).Slice<0>(p)).data())); EXPECT_EQ( 8, Distance(p, Type<Span<int32_t>>(L::Partial(5, 3).Slice<1>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<int8_t>>(L::Partial(0, 0, 0).Slice<0>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<int32_t>>(L::Partial(0, 0, 0).Slice<1>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<Int128>>(L::Partial(0, 0, 0).Slice<2>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<int8_t>>(L::Partial(1, 0, 0).Slice<0>(p)).data())); EXPECT_EQ( 4, Distance( p, Type<Span<int32_t>>(L::Partial(1, 0, 0).Slice<1>(p)).data())); EXPECT_EQ( 8, Distance( p, Type<Span<Int128>>(L::Partial(1, 0, 0).Slice<2>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<int8_t>>(L::Partial(5, 3, 1).Slice<0>(p)).data())); EXPECT_EQ( 24, Distance( p, Type<Span<Int128>>(L::Partial(5, 3, 1).Slice<2>(p)).data())); EXPECT_EQ( 8, Distance( p, Type<Span<int32_t>>(L::Partial(5, 3, 1).Slice<1>(p)).data())); EXPECT_EQ(0, Distance(p, Type<Span<int8_t>>(L(5, 3, 1).Slice<0>(p)).data())); EXPECT_EQ(24, Distance(p, Type<Span<Int128>>(L(5, 3, 1).Slice<2>(p)).data())); EXPECT_EQ(8, Distance(p, Type<Span<int32_t>>(L(5, 3, 1).Slice<1>(p)).data())); } } TEST(Layout, MutableSliceByTypeData) { alignas(max_align_t) unsigned char p[100] = {0}; { using L = Layout<int32_t>; EXPECT_EQ( 0, Distance( p, Type<Span<int32_t>>(L::Partial(0).Slice<int32_t>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<int32_t>>(L::Partial(3).Slice<int32_t>(p)).data())); EXPECT_EQ(0, Distance(p, Type<Span<int32_t>>(L(3).Slice<int32_t>(p)).data())); } { using L = Layout<int8_t, int32_t, Int128>; EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L::Partial(0).Slice<int8_t>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L::Partial(1).Slice<int8_t>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L::Partial(5).Slice<int8_t>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L::Partial(0, 0).Slice<int8_t>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<int32_t>>(L::Partial(0, 0).Slice<int32_t>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L::Partial(1, 0).Slice<int8_t>(p)).data())); EXPECT_EQ( 4, Distance( p, Type<Span<int32_t>>(L::Partial(1, 0).Slice<int32_t>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L::Partial(5, 3).Slice<int8_t>(p)).data())); EXPECT_EQ( 8, Distance( p, Type<Span<int32_t>>(L::Partial(5, 3).Slice<int32_t>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<int8_t>>(L::Partial(0, 0, 0).Slice<int8_t>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<int32_t>>(L::Partial(0, 0, 0).Slice<int32_t>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<Int128>>(L::Partial(0, 0, 0).Slice<Int128>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<int8_t>>(L::Partial(1, 0, 0).Slice<int8_t>(p)).data())); EXPECT_EQ( 4, Distance( p, Type<Span<int32_t>>(L::Partial(1, 0, 0).Slice<int32_t>(p)).data())); EXPECT_EQ( 8, Distance( p, Type<Span<Int128>>(L::Partial(1, 0, 0).Slice<Int128>(p)).data())); EXPECT_EQ( 0, Distance( p, Type<Span<int8_t>>(L::Partial(5, 3, 1).Slice<int8_t>(p)).data())); EXPECT_EQ( 24, Distance( p, Type<Span<Int128>>(L::Partial(5, 3, 1).Slice<Int128>(p)).data())); EXPECT_EQ( 8, Distance( p, Type<Span<int32_t>>(L::Partial(5, 3, 1).Slice<int32_t>(p)).data())); EXPECT_EQ( 0, Distance(p, Type<Span<int8_t>>(L(5, 3, 1).Slice<int8_t>(p)).data())); EXPECT_EQ( 24, Distance(p, Type<Span<Int128>>(L(5, 3, 1).Slice<Int128>(p)).data())); EXPECT_EQ( 8, Distance(p, Type<Span<int32_t>>(L(5, 3, 1).Slice<int32_t>(p)).data())); } } TEST(Layout, StaticSliceData) { alignas(max_align_t) const unsigned char cp[100] = {0}; alignas(max_align_t) unsigned char p[100] = {0}; using L = Layout<int8_t, int32_t, Int128>; using SL = L::WithStaticSizes<3, 5>; EXPECT_EQ(0, Distance(cp, SL::Partial().Slice<0>(cp).data())); EXPECT_EQ(0, Distance(cp, SL::Partial().Slice<int8_t>(cp).data())); EXPECT_EQ(0, Distance(cp, SL::Partial(7).Slice<0>(cp).data())); EXPECT_EQ(0, Distance(cp, SL::Partial(7).Slice<int8_t>(cp).data())); EXPECT_EQ(4, Distance(cp, SL::Partial().Slice<1>(cp).data())); EXPECT_EQ(4, Distance(cp, SL::Partial().Slice<int32_t>(cp).data())); EXPECT_EQ(4, Distance(cp, SL::Partial(7).Slice<1>(cp).data())); EXPECT_EQ(4, Distance(cp, SL::Partial(7).Slice<int32_t>(cp).data())); EXPECT_EQ(24, Distance(cp, SL::Partial(7).Slice<2>(cp).data())); EXPECT_EQ(24, Distance(cp, SL::Partial(7).Slice<Int128>(cp).data())); EXPECT_EQ(0, Distance(p, SL::Partial().Slice<0>(p).data())); EXPECT_EQ(0, Distance(p, SL::Partial().Slice<int8_t>(p).data())); EXPECT_EQ(0, Distance(p, SL::Partial(7).Slice<0>(p).data())); EXPECT_EQ(0, Distance(p, SL::Partial(7).Slice<int8_t>(p).data())); EXPECT_EQ(4, Distance(p, SL::Partial().Slice<1>(p).data())); EXPECT_EQ(4, Distance(p, SL::Partial().Slice<int32_t>(p).data())); EXPECT_EQ(4, Distance(p, SL::Partial(7).Slice<1>(p).data())); EXPECT_EQ(4, Distance(p, SL::Partial(7).Slice<int32_t>(p).data())); EXPECT_EQ(24, Distance(p, SL::Partial(7).Slice<2>(p).data())); EXPECT_EQ(24, Distance(p, SL::Partial(7).Slice<Int128>(p).data())); } MATCHER_P(IsSameSlice, slice, "") { return arg.size() == slice.size() && arg.data() == slice.data(); } template <typename... M> class TupleMatcher { public: explicit TupleMatcher(M... matchers) : matchers_(std::move(matchers)...) {} template <typename Tuple> bool MatchAndExplain(const Tuple& p, testing::MatchResultListener* ) const { static_assert(std::tuple_size<Tuple>::value == sizeof...(M), ""); return MatchAndExplainImpl( p, absl::make_index_sequence<std::tuple_size<Tuple>::value>{}); } void DescribeTo(::std::ostream* os) const {} void DescribeNegationTo(::std::ostream* os) const {} private: template <typename Tuple, size_t... Is> bool MatchAndExplainImpl(const Tuple& p, absl::index_sequence<Is...>) const { return std::min( {true, testing::SafeMatcherCast< const typename std::tuple_element<Is, Tuple>::type&>( std::get<Is>(matchers_)) .Matches(std::get<Is>(p))...}); } std::tuple<M...> matchers_; }; template <typename... M> testing::PolymorphicMatcher<TupleMatcher<M...>> Tuple(M... matchers) { return testing::MakePolymorphicMatcher( TupleMatcher<M...>(std::move(matchers)...)); } TEST(Layout, Slices) { alignas(max_align_t) const unsigned char p[100] = {0}; using L = Layout<int8_t, int8_t, Int128>; { const auto x = L::Partial(); EXPECT_THAT(Type<std::tuple<>>(x.Slices(p)), Tuple()); } { const auto x = L::Partial(1); EXPECT_THAT(Type<std::tuple<Span<const int8_t>>>(x.Slices(p)), Tuple(IsSameSlice(x.Slice<0>(p)))); } { const auto x = L::Partial(1, 2); EXPECT_THAT( (Type<std::tuple<Span<const int8_t>, Span<const int8_t>>>(x.Slices(p))), Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)))); } { const auto x = L::Partial(1, 2, 3); EXPECT_THAT((Type<std::tuple<Span<const int8_t>, Span<const int8_t>, Span<const Int128>>>(x.Slices(p))), Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)), IsSameSlice(x.Slice<2>(p)))); } { const L x(1, 2, 3); EXPECT_THAT((Type<std::tuple<Span<const int8_t>, Span<const int8_t>, Span<const Int128>>>(x.Slices(p))), Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)), IsSameSlice(x.Slice<2>(p)))); } } TEST(Layout, MutableSlices) { alignas(max_align_t) unsigned char p[100] = {0}; using L = Layout<int8_t, int8_t, Int128>; { const auto x = L::Partial(); EXPECT_THAT(Type<std::tuple<>>(x.Slices(p)), Tuple()); } { const auto x = L::Partial(1); EXPECT_THAT(Type<std::tuple<Span<int8_t>>>(x.Slices(p)), Tuple(IsSameSlice(x.Slice<0>(p)))); } { const auto x = L::Partial(1, 2); EXPECT_THAT((Type<std::tuple<Span<int8_t>, Span<int8_t>>>(x.Slices(p))), Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)))); } { const auto x = L::Partial(1, 2, 3); EXPECT_THAT((Type<std::tuple<Span<int8_t>, Span<int8_t>, Span<Int128>>>( x.Slices(p))), Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)), IsSameSlice(x.Slice<2>(p)))); } { const L x(1, 2, 3); EXPECT_THAT((Type<std::tuple<Span<int8_t>, Span<int8_t>, Span<Int128>>>( x.Slices(p))), Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)), IsSameSlice(x.Slice<2>(p)))); } } TEST(Layout, StaticSlices) { alignas(max_align_t) const unsigned char cp[100] = {0}; alignas(max_align_t) unsigned char p[100] = {0}; using SL = Layout<int8_t, int8_t, Int128>::WithStaticSizes<1, 2>; { const auto x = SL::Partial(); EXPECT_THAT( (Type<std::tuple<Span<const int8_t>, Span<const int8_t>>>( x.Slices(cp))), Tuple(IsSameSlice(x.Slice<0>(cp)), IsSameSlice(x.Slice<1>(cp)))); EXPECT_THAT((Type<std::tuple<Span<int8_t>, Span<int8_t>>>(x.Slices(p))), Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)))); } { const auto x = SL::Partial(3); EXPECT_THAT((Type<std::tuple<Span<const int8_t>, Span<const int8_t>, Span<const Int128>>>(x.Slices(cp))), Tuple(IsSameSlice(x.Slice<0>(cp)), IsSameSlice(x.Slice<1>(cp)), IsSameSlice(x.Slice<2>(cp)))); EXPECT_THAT((Type<std::tuple<Span<int8_t>, Span<int8_t>, Span<Int128>>>( x.Slices(p))), Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)), IsSameSlice(x.Slice<2>(p)))); } { const SL x(3); EXPECT_THAT((Type<std::tuple<Span<const int8_t>, Span<const int8_t>, Span<const Int128>>>(x.Slices(cp))), Tuple(IsSameSlice(x.Slice<0>(cp)), IsSameSlice(x.Slice<1>(cp)), IsSameSlice(x.Slice<2>(cp)))); EXPECT_THAT((Type<std::tuple<Span<int8_t>, Span<int8_t>, Span<Int128>>>( x.Slices(p))), Tuple(IsSameSlice(x.Slice<0>(p)), IsSameSlice(x.Slice<1>(p)), IsSameSlice(x.Slice<2>(p)))); } } TEST(Layout, UnalignedTypes) { constexpr Layout<unsigned char, unsigned char, unsigned char> x(1, 2, 3); alignas(max_align_t) unsigned char p[x.AllocSize() + 1]; EXPECT_THAT(x.Pointers(p + 1), Tuple(p + 1, p + 2, p + 4)); } TEST(Layout, CustomAlignment) { constexpr Layout<unsigned char, Aligned<unsigned char, 8>> x(1, 2); alignas(max_align_t) unsigned char p[x.AllocSize()]; EXPECT_EQ(10, x.AllocSize()); EXPECT_THAT(x.Pointers(p), Tuple(p + 0, p + 8)); } TEST(Layout, OverAligned) { constexpr size_t M = alignof(max_align_t); constexpr Layout<unsigned char, Aligned<unsigned char, 2 * M>> x(1, 3); #ifdef __GNUC__ __attribute__((aligned(2 * M))) unsigned char p[x.AllocSize()]; #else alignas(2 * M) unsigned char p[x.AllocSize()]; #endif EXPECT_EQ(2 * M + 3, x.AllocSize()); EXPECT_THAT(x.Pointers(p), Tuple(p + 0, p + 2 * M)); } TEST(Layout, Alignment) { static_assert(Layout<int8_t>::Alignment() == 1, ""); static_assert(Layout<int32_t>::Alignment() == 4, ""); static_assert(Layout<Int64>::Alignment() == 8, ""); static_assert(Layout<Aligned<int8_t, 64>>::Alignment() == 64, ""); static_assert(Layout<int8_t, int32_t, Int64>::Alignment() == 8, ""); static_assert(Layout<int8_t, Int64, int32_t>::Alignment() == 8, ""); static_assert(Layout<int32_t, int8_t, Int64>::Alignment() == 8, ""); static_assert(Layout<int32_t, Int64, int8_t>::Alignment() == 8, ""); static_assert(Layout<Int64, int8_t, int32_t>::Alignment() == 8, ""); static_assert(Layout<Int64, int32_t, int8_t>::Alignment() == 8, ""); static_assert(Layout<Int64, int32_t, int8_t>::Alignment() == 8, ""); static_assert( Layout<Aligned<int8_t, 64>>::WithStaticSizes<>::Alignment() == 64, ""); static_assert( Layout<Aligned<int8_t, 64>>::WithStaticSizes<2>::Alignment() == 64, ""); } TEST(Layout, StaticAlignment) { static_assert(Layout<int8_t>::WithStaticSizes<>::Alignment() == 1, ""); static_assert(Layout<int8_t>::WithStaticSizes<0>::Alignment() == 1, ""); static_assert(Layout<int8_t>::WithStaticSizes<7>::Alignment() == 1, ""); static_assert(Layout<int32_t>::WithStaticSizes<>::Alignment() == 4, ""); static_assert(Layout<int32_t>::WithStaticSizes<0>::Alignment() == 4, ""); static_assert(Layout<int32_t>::WithStaticSizes<3>::Alignment() == 4, ""); static_assert( Layout<Aligned<int8_t, 64>>::WithStaticSizes<>::Alignment() == 64, ""); static_assert( Layout<Aligned<int8_t, 64>>::WithStaticSizes<0>::Alignment() == 64, ""); static_assert( Layout<Aligned<int8_t, 64>>::WithStaticSizes<2>::Alignment() == 64, ""); static_assert( Layout<int32_t, Int64, int8_t>::WithStaticSizes<>::Alignment() == 8, ""); static_assert( Layout<int32_t, Int64, int8_t>::WithStaticSizes<0, 0, 0>::Alignment() == 8, ""); static_assert( Layout<int32_t, Int64, int8_t>::WithStaticSizes<1, 1, 1>::Alignment() == 8, ""); } TEST(Layout, ConstexprPartial) { constexpr size_t M = alignof(max_align_t); constexpr Layout<unsigned char, Aligned<unsigned char, 2 * M>> x(1, 3); static_assert(x.Partial(1).template Offset<1>() == 2 * M, ""); } TEST(Layout, StaticConstexpr) { constexpr size_t M = alignof(max_align_t); using L = Layout<unsigned char, Aligned<unsigned char, 2 * M>>; using SL = L::WithStaticSizes<1, 3>; constexpr SL x; static_assert(x.Offset<1>() == 2 * M, ""); } struct Region { size_t from; size_t to; }; void ExpectRegionPoisoned(const unsigned char* p, size_t n, bool poisoned) { #ifdef ABSL_HAVE_ADDRESS_SANITIZER for (size_t i = 0; i != n; ++i) { EXPECT_EQ(poisoned, __asan_address_is_poisoned(p + i)); } #endif } template <size_t N> void ExpectPoisoned(const unsigned char (&buf)[N], std::initializer_list<Region> reg) { size_t prev = 0; for (const Region& r : reg) { ExpectRegionPoisoned(buf + prev, r.from - prev, false); ExpectRegionPoisoned(buf + r.from, r.to - r.from, true); prev = r.to; } ExpectRegionPoisoned(buf + prev, N - prev, false); } TEST(Layout, PoisonPadding) { using L = Layout<int8_t, Int64, int32_t, Int128>; constexpr size_t n = L::Partial(1, 2, 3, 4).AllocSize(); { constexpr auto x = L::Partial(); alignas(max_align_t) const unsigned char c[n] = {}; x.PoisonPadding(c); EXPECT_EQ(x.Slices(c), x.Slices(c)); ExpectPoisoned(c, {}); } { constexpr auto x = L::Partial(1); alignas(max_align_t) const unsigned char c[n] = {}; x.PoisonPadding(c); EXPECT_EQ(x.Slices(c), x.Slices(c)); ExpectPoisoned(c, {{1, 8}}); } { constexpr auto x = L::Partial(1, 2); alignas(max_align_t) const unsigned char c[n] = {}; x.PoisonPadding(c); EXPECT_EQ(x.Slices(c), x.Slices(c)); ExpectPoisoned(c, {{1, 8}}); } { constexpr auto x = L::Partial(1, 2, 3); alignas(max_align_t) const unsigned char c[n] = {}; x.PoisonPadding(c); EXPECT_EQ(x.Slices(c), x.Slices(c)); ExpectPoisoned(c, {{1, 8}, {36, 40}}); } { constexpr auto x = L::Partial(1, 2, 3, 4); alignas(max_align_t) const unsigned char c[n] = {}; x.PoisonPadding(c); EXPECT_EQ(x.Slices(c), x.Slices(c)); ExpectPoisoned(c, {{1, 8}, {36, 40}}); } { constexpr L x(1, 2, 3, 4); alignas(max_align_t) const unsigned char c[n] = {}; x.PoisonPadding(c); EXPECT_EQ(x.Slices(c), x.Slices(c)); ExpectPoisoned(c, {{1, 8}, {36, 40}}); } } TEST(Layout, StaticPoisonPadding) { using L = Layout<int8_t, Int64, int32_t, Int128>; using SL = L::WithStaticSizes<1, 2>; constexpr size_t n = L::Partial(1, 2, 3, 4).AllocSize(); { constexpr auto x = SL::Partial(); alignas(max_align_t) const unsigned char c[n] = {}; x.PoisonPadding(c); EXPECT_EQ(x.Slices(c), x.Slices(c)); ExpectPoisoned(c, {{1, 8}}); } { constexpr auto x = SL::Partial(3); alignas(max_align_t) const unsigned char c[n] = {}; x.PoisonPadding(c); EXPECT_EQ(x.Slices(c), x.Slices(c)); ExpectPoisoned(c, {{1, 8}, {36, 40}}); } { constexpr auto x = SL::Partial(3, 4); alignas(max_align_t) const unsigned char c[n] = {}; x.PoisonPadding(c); EXPECT_EQ(x.Slices(c), x.Slices(c)); ExpectPoisoned(c, {{1, 8}, {36, 40}}); } { constexpr SL x(3, 4); alignas(max_align_t) const unsigned char c[n] = {}; x.PoisonPadding(c); EXPECT_EQ(x.Slices(c), x.Slices(c)); ExpectPoisoned(c, {{1, 8}, {36, 40}}); } } TEST(Layout, DebugString) { { constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::Partial(); EXPECT_EQ("@0<signed char>(1)", x.DebugString()); } { constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::Partial(1); EXPECT_EQ("@0<signed char>(1)[1]; @4<int>(4)", x.DebugString()); } { constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::Partial(1, 2); EXPECT_EQ("@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)", x.DebugString()); } { constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::Partial(1, 2, 3); EXPECT_EQ( "@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)[3]; " "@16" + Int128::Name() + "(16)", x.DebugString()); } { constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::Partial(1, 2, 3, 4); EXPECT_EQ( "@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)[3]; " "@16" + Int128::Name() + "(16)[4]", x.DebugString()); } { constexpr Layout<int8_t, int32_t, int8_t, Int128> x(1, 2, 3, 4); EXPECT_EQ( "@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)[3]; " "@16" + Int128::Name() + "(16)[4]", x.DebugString()); } } TEST(Layout, StaticDebugString) { { constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::WithStaticSizes<>::Partial(); EXPECT_EQ("@0<signed char>(1)", x.DebugString()); } { constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::WithStaticSizes<>::Partial(1); EXPECT_EQ("@0<signed char>(1)[1]; @4<int>(4)", x.DebugString()); } { constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::WithStaticSizes<1>::Partial(); EXPECT_EQ("@0<signed char>(1)[1]; @4<int>(4)", x.DebugString()); } { constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::WithStaticSizes<>::Partial(1, 2); EXPECT_EQ("@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)", x.DebugString()); } { constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::WithStaticSizes<1>::Partial(2); EXPECT_EQ("@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)", x.DebugString()); } { constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::WithStaticSizes<1, 2>::Partial(); EXPECT_EQ("@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)", x.DebugString()); } { constexpr auto x = Layout<int8_t, int32_t, int8_t, Int128>::WithStaticSizes<1, 2, 3, 4>::Partial(); EXPECT_EQ( "@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)[3]; " "@16" + Int128::Name() + "(16)[4]", x.DebugString()); } { constexpr Layout<int8_t, int32_t, int8_t, Int128>::WithStaticSizes<1, 2, 3, 4> x; EXPECT_EQ( "@0<signed char>(1)[1]; @4<int>(4)[2]; @12<signed char>(1)[3]; " "@16" + Int128::Name() + "(16)[4]", x.DebugString()); } } TEST(Layout, CharTypes) { constexpr Layout<int32_t> x(1); alignas(max_align_t) char c[x.AllocSize()] = {}; alignas(max_align_t) unsigned char uc[x.AllocSize()] = {}; alignas(max_align_t) signed char sc[x.AllocSize()] = {}; alignas(max_align_t) const char cc[x.AllocSize()] = {}; alignas(max_align_t) const unsigned char cuc[x.AllocSize()] = {}; alignas(max_align_t) const signed char csc[x.AllocSize()] = {}; Type<int32_t*>(x.Pointer<0>(c)); Type<int32_t*>(x.Pointer<0>(uc)); Type<int32_t*>(x.Pointer<0>(sc)); Type<const int32_t*>(x.Pointer<0>(cc)); Type<const int32_t*>(x.Pointer<0>(cuc)); Type<const int32_t*>(x.Pointer<0>(csc)); Type<int32_t*>(x.Pointer<int32_t>(c)); Type<int32_t*>(x.Pointer<int32_t>(uc)); Type<int32_t*>(x.Pointer<int32_t>(sc)); Type<const int32_t*>(x.Pointer<int32_t>(cc)); Type<const int32_t*>(x.Pointer<int32_t>(cuc)); Type<const int32_t*>(x.Pointer<int32_t>(csc)); Type<std::tuple<int32_t*>>(x.Pointers(c)); Type<std::tuple<int32_t*>>(x.Pointers(uc)); Type<std::tuple<int32_t*>>(x.Pointers(sc)); Type<std::tuple<const int32_t*>>(x.Pointers(cc)); Type<std::tuple<const int32_t*>>(x.Pointers(cuc)); Type<std::tuple<const int32_t*>>(x.Pointers(csc)); Type<Span<int32_t>>(x.Slice<0>(c)); Type<Span<int32_t>>(x.Slice<0>(uc)); Type<Span<int32_t>>(x.Slice<0>(sc)); Type<Span<const int32_t>>(x.Slice<0>(cc)); Type<Span<const int32_t>>(x.Slice<0>(cuc)); Type<Span<const int32_t>>(x.Slice<0>(csc)); Type<std::tuple<Span<int32_t>>>(x.Slices(c)); Type<std::tuple<Span<int32_t>>>(x.Slices(uc)); Type<std::tuple<Span<int32_t>>>(x.Slices(sc)); Type<std::tuple<Span<const int32_t>>>(x.Slices(cc)); Type<std::tuple<Span<const int32_t>>>(x.Slices(cuc)); Type<std::tuple<Span<const int32_t>>>(x.Slices(csc)); } TEST(Layout, ConstElementType) { constexpr Layout<const int32_t> x(1); alignas(int32_t) char c[x.AllocSize()] = {}; const char* cc = c; const int32_t* p = reinterpret_cast<const int32_t*>(cc); EXPECT_EQ(alignof(int32_t), x.Alignment()); EXPECT_EQ(0, x.Offset<0>()); EXPECT_EQ(0, x.Offset<const int32_t>()); EXPECT_THAT(x.Offsets(), ElementsAre(0)); EXPECT_EQ(1, x.Size<0>()); EXPECT_EQ(1, x.Size<const int32_t>()); EXPECT_THAT(x.Sizes(), ElementsAre(1)); EXPECT_EQ(sizeof(int32_t), x.AllocSize()); EXPECT_EQ(p, Type<const int32_t*>(x.Pointer<0>(c))); EXPECT_EQ(p, Type<const int32_t*>(x.Pointer<0>(cc))); EXPECT_EQ(p, Type<const int32_t*>(x.Pointer<const int32_t>(c))); EXPECT_EQ(p, Type<const int32_t*>(x.Pointer<const int32_t>(cc))); EXPECT_THAT(Type<std::tuple<const int32_t*>>(x.Pointers(c)), Tuple(p)); EXPECT_THAT(Type<std::tuple<const int32_t*>>(x.Pointers(cc)), Tuple(p)); EXPECT_THAT(Type<Span<const int32_t>>(x.Slice<0>(c)), IsSameSlice(Span<const int32_t>(p, 1))); EXPECT_THAT(Type<Span<const int32_t>>(x.Slice<0>(cc)), IsSameSlice(Span<const int32_t>(p, 1))); EXPECT_THAT(Type<Span<const int32_t>>(x.Slice<const int32_t>(c)), IsSameSlice(Span<const int32_t>(p, 1))); EXPECT_THAT(Type<Span<const int32_t>>(x.Slice<const int32_t>(cc)), IsSameSlice(Span<const int32_t>(p, 1))); EXPECT_THAT(Type<std::tuple<Span<const int32_t>>>(x.Slices(c)), Tuple(IsSameSlice(Span<const int32_t>(p, 1)))); EXPECT_THAT(Type<std::tuple<Span<const int32_t>>>(x.Slices(cc)), Tuple(IsSameSlice(Span<const int32_t>(p, 1)))); } namespace example { class CompactString { public: CompactString(const char* s = "") { const size_t size = strlen(s); const L layout(1, size + 1); p_.reset(new unsigned char[layout.AllocSize()]); layout.PoisonPadding(p_.get()); *layout.Pointer<size_t>(p_.get()) = size; memcpy(layout.Pointer<char>(p_.get()), s, size + 1); } size_t size() const { return *L::Partial().Pointer<size_t>(p_.get()); } const char* c_str() const { return L::Partial(1).Pointer<char>(p_.get()); } private: using L = Layout<size_t, char>; std::unique_ptr<unsigned char[]> p_; }; TEST(CompactString, Works) { CompactString s = "hello"; EXPECT_EQ(5, s.size()); EXPECT_STREQ("hello", s.c_str()); } class StaticCompactString { public: StaticCompactString(const char* s = "") { const size_t size = strlen(s); const SL layout(size + 1); p_.reset(new unsigned char[layout.AllocSize()]); layout.PoisonPadding(p_.get()); *layout.Pointer<size_t>(p_.get()) = size; memcpy(layout.Pointer<char>(p_.get()), s, size + 1); } size_t size() const { return *SL::Partial().Pointer<size_t>(p_.get()); } const char* c_str() const { return SL::Partial().Pointer<char>(p_.get()); } private: using SL = Layout<size_t, char>::WithStaticSizes<1>; std::unique_ptr<unsigned char[]> p_; }; TEST(StaticCompactString, Works) { StaticCompactString s = "hello"; EXPECT_EQ(5, s.size()); EXPECT_STREQ("hello", s.c_str()); } } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/layout.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/layout_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
daaeac09-e0ed-4298-b4dd-3f9607b3f0d2
cpp
abseil/abseil-cpp
btree
absl/container/internal/btree.h
absl/container/btree_test.cc
#ifndef ABSL_CONTAINER_INTERNAL_BTREE_H_ #define ABSL_CONTAINER_INTERNAL_BTREE_H_ #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> #include <cstring> #include <functional> #include <iterator> #include <limits> #include <string> #include <type_traits> #include <utility> #include "absl/base/config.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/macros.h" #include "absl/container/internal/common.h" #include "absl/container/internal/common_policy_traits.h" #include "absl/container/internal/compressed_tuple.h" #include "absl/container/internal/container_memory.h" #include "absl/container/internal/layout.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/strings/cord.h" #include "absl/strings/string_view.h" #include "absl/types/compare.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { #ifdef ABSL_BTREE_ENABLE_GENERATIONS #error ABSL_BTREE_ENABLE_GENERATIONS cannot be directly set #elif (defined(ABSL_HAVE_ADDRESS_SANITIZER) || \ defined(ABSL_HAVE_HWADDRESS_SANITIZER) || \ defined(ABSL_HAVE_MEMORY_SANITIZER)) && \ !defined(NDEBUG_SANITIZER) #define ABSL_BTREE_ENABLE_GENERATIONS #endif #ifdef ABSL_BTREE_ENABLE_GENERATIONS constexpr bool BtreeGenerationsEnabled() { return true; } #else constexpr bool BtreeGenerationsEnabled() { return false; } #endif template <typename Compare, typename T, typename U> using compare_result_t = absl::result_of_t<const Compare(const T &, const U &)>; template <typename Compare, typename T> using btree_is_key_compare_to = std::is_convertible<compare_result_t<Compare, T, T>, absl::weak_ordering>; struct StringBtreeDefaultLess { using is_transparent = void; StringBtreeDefaultLess() = default; StringBtreeDefaultLess(std::less<std::string>) {} StringBtreeDefaultLess(std::less<absl::string_view>) {} explicit operator std::less<std::string>() const { return {}; } explicit operator std::less<absl::string_view>() const { return {}; } explicit operator std::less<absl::Cord>() const { return {}; } absl::weak_ordering operator()(absl::string_view lhs, absl::string_view rhs) const { return compare_internal::compare_result_as_ordering(lhs.compare(rhs)); } StringBtreeDefaultLess(std::less<absl::Cord>) {} absl::weak_ordering operator()(const absl::Cord &lhs, const absl::Cord &rhs) const { return compare_internal::compare_result_as_ordering(lhs.Compare(rhs)); } absl::weak_ordering operator()(const absl::Cord &lhs, absl::string_view rhs) const { return compare_internal::compare_result_as_ordering(lhs.Compare(rhs)); } absl::weak_ordering operator()(absl::string_view lhs, const absl::Cord &rhs) const { return compare_internal::compare_result_as_ordering(-rhs.Compare(lhs)); } }; struct StringBtreeDefaultGreater { using is_transparent = void; StringBtreeDefaultGreater() = default; StringBtreeDefaultGreater(std::greater<std::string>) {} StringBtreeDefaultGreater(std::greater<absl::string_view>) {} explicit operator std::greater<std::string>() const { return {}; } explicit operator std::greater<absl::string_view>() const { return {}; } explicit operator std::greater<absl::Cord>() const { return {}; } absl::weak_ordering operator()(absl::string_view lhs, absl::string_view rhs) const { return compare_internal::compare_result_as_ordering(rhs.compare(lhs)); } StringBtreeDefaultGreater(std::greater<absl::Cord>) {} absl::weak_ordering operator()(const absl::Cord &lhs, const absl::Cord &rhs) const { return compare_internal::compare_result_as_ordering(rhs.Compare(lhs)); } absl::weak_ordering operator()(const absl::Cord &lhs, absl::string_view rhs) const { return compare_internal::compare_result_as_ordering(-lhs.Compare(rhs)); } absl::weak_ordering operator()(absl::string_view lhs, const absl::Cord &rhs) const { return compare_internal::compare_result_as_ordering(rhs.Compare(lhs)); } }; template <typename Compare, bool is_class = std::is_class<Compare>::value> struct checked_compare_base : Compare { using Compare::Compare; explicit checked_compare_base(Compare c) : Compare(std::move(c)) {} const Compare &comp() const { return *this; } }; template <typename Compare> struct checked_compare_base<Compare, false> { explicit checked_compare_base(Compare c) : compare(std::move(c)) {} const Compare &comp() const { return compare; } Compare compare; }; struct BtreeTestOnlyCheckedCompareOptOutBase {}; template <typename Compare, typename Key> struct key_compare_adapter { struct checked_compare : checked_compare_base<Compare> { private: using Base = typename checked_compare::checked_compare_base; using Base::comp; bool is_self_equivalent(const Key &k) const { return comp()(k, k) == 0; } template <typename T> bool is_self_equivalent(const T &) const { return true; } public: using Base::Base; checked_compare(Compare comp) : Base(std::move(comp)) {} explicit operator Compare() const { return comp(); } template <typename T, typename U, absl::enable_if_t< std::is_same<bool, compare_result_t<Compare, T, U>>::value, int> = 0> bool operator()(const T &lhs, const U &rhs) const { assert(is_self_equivalent(lhs)); assert(is_self_equivalent(rhs)); const bool lhs_comp_rhs = comp()(lhs, rhs); assert(!lhs_comp_rhs || !comp()(rhs, lhs)); return lhs_comp_rhs; } template < typename T, typename U, absl::enable_if_t<std::is_convertible<compare_result_t<Compare, T, U>, absl::weak_ordering>::value, int> = 0> absl::weak_ordering operator()(const T &lhs, const U &rhs) const { assert(is_self_equivalent(lhs)); assert(is_self_equivalent(rhs)); const absl::weak_ordering lhs_comp_rhs = comp()(lhs, rhs); #ifndef NDEBUG const absl::weak_ordering rhs_comp_lhs = comp()(rhs, lhs); if (lhs_comp_rhs > 0) { assert(rhs_comp_lhs < 0 && "lhs_comp_rhs > 0 -> rhs_comp_lhs < 0"); } else if (lhs_comp_rhs == 0) { assert(rhs_comp_lhs == 0 && "lhs_comp_rhs == 0 -> rhs_comp_lhs == 0"); } else { assert(rhs_comp_lhs > 0 && "lhs_comp_rhs < 0 -> rhs_comp_lhs > 0"); } #endif return lhs_comp_rhs; } }; using type = absl::conditional_t< std::is_base_of<BtreeTestOnlyCheckedCompareOptOutBase, Compare>::value, Compare, checked_compare>; }; template <> struct key_compare_adapter<std::less<std::string>, std::string> { using type = StringBtreeDefaultLess; }; template <> struct key_compare_adapter<std::greater<std::string>, std::string> { using type = StringBtreeDefaultGreater; }; template <> struct key_compare_adapter<std::less<absl::string_view>, absl::string_view> { using type = StringBtreeDefaultLess; }; template <> struct key_compare_adapter<std::greater<absl::string_view>, absl::string_view> { using type = StringBtreeDefaultGreater; }; template <> struct key_compare_adapter<std::less<absl::Cord>, absl::Cord> { using type = StringBtreeDefaultLess; }; template <> struct key_compare_adapter<std::greater<absl::Cord>, absl::Cord> { using type = StringBtreeDefaultGreater; }; template <typename T, typename = void> struct has_linear_node_search_preference : std::false_type {}; template <typename T, typename = void> struct prefers_linear_node_search : std::false_type {}; template <typename T> struct has_linear_node_search_preference< T, absl::void_t<typename T::absl_btree_prefer_linear_node_search>> : std::true_type {}; template <typename T> struct prefers_linear_node_search< T, absl::void_t<typename T::absl_btree_prefer_linear_node_search>> : T::absl_btree_prefer_linear_node_search {}; template <typename Compare, typename Key> constexpr bool compare_has_valid_result_type() { using compare_result_type = compare_result_t<Compare, Key, Key>; return std::is_same<compare_result_type, bool>::value || std::is_convertible<compare_result_type, absl::weak_ordering>::value; } template <typename original_key_compare, typename value_type> class map_value_compare { template <typename Params> friend class btree; protected: explicit map_value_compare(original_key_compare c) : comp(std::move(c)) {} original_key_compare comp; public: auto operator()(const value_type &lhs, const value_type &rhs) const -> decltype(comp(lhs.first, rhs.first)) { return comp(lhs.first, rhs.first); } }; template <typename Key, typename Compare, typename Alloc, int TargetNodeSize, bool IsMulti, bool IsMap, typename SlotPolicy> struct common_params : common_policy_traits<SlotPolicy> { using original_key_compare = Compare; using key_compare = absl::conditional_t<!compare_has_valid_result_type<Compare, Key>(), Compare, typename key_compare_adapter<Compare, Key>::type>; static constexpr bool kIsKeyCompareStringAdapted = std::is_same<key_compare, StringBtreeDefaultLess>::value || std::is_same<key_compare, StringBtreeDefaultGreater>::value; static constexpr bool kIsKeyCompareTransparent = IsTransparent<original_key_compare>::value || kIsKeyCompareStringAdapted; using is_key_compare_to = btree_is_key_compare_to<key_compare, Key>; using allocator_type = Alloc; using key_type = Key; using size_type = size_t; using difference_type = ptrdiff_t; using slot_policy = SlotPolicy; using slot_type = typename slot_policy::slot_type; using value_type = typename slot_policy::value_type; using init_type = typename slot_policy::mutable_value_type; using pointer = value_type *; using const_pointer = const value_type *; using reference = value_type &; using const_reference = const value_type &; using value_compare = absl::conditional_t<IsMap, map_value_compare<original_key_compare, value_type>, original_key_compare>; using is_map_container = std::integral_constant<bool, IsMap>; template <typename LookupKey> constexpr static bool can_have_multiple_equivalent_keys() { return IsMulti || (IsTransparent<key_compare>::value && !std::is_same<LookupKey, Key>::value && !kIsKeyCompareStringAdapted); } enum { kTargetNodeSize = TargetNodeSize, kNodeSlotSpace = TargetNodeSize - (sizeof(void *) + 4), }; using node_count_type = absl::conditional_t<(kNodeSlotSpace / sizeof(slot_type) > (std::numeric_limits<uint8_t>::max)()), uint16_t, uint8_t>; }; template <typename Compare> struct upper_bound_adapter { explicit upper_bound_adapter(const Compare &c) : comp(c) {} template <typename K1, typename K2> bool operator()(const K1 &a, const K2 &b) const { return !compare_internal::compare_result_as_less_than(comp(b, a)); } private: Compare comp; }; enum class MatchKind : uint8_t { kEq, kNe }; template <typename V, bool IsCompareTo> struct SearchResult { V value; MatchKind match; static constexpr bool HasMatch() { return true; } bool IsEq() const { return match == MatchKind::kEq; } }; template <typename V> struct SearchResult<V, false> { SearchResult() = default; explicit SearchResult(V v) : value(v) {} SearchResult(V v, MatchKind ) : value(v) {} V value; static constexpr bool HasMatch() { return false; } static constexpr bool IsEq() { return false; } }; template <typename Params> class btree_node { using is_key_compare_to = typename Params::is_key_compare_to; using field_type = typename Params::node_count_type; using allocator_type = typename Params::allocator_type; using slot_type = typename Params::slot_type; using original_key_compare = typename Params::original_key_compare; public: using params_type = Params; using key_type = typename Params::key_type; using value_type = typename Params::value_type; using pointer = typename Params::pointer; using const_pointer = typename Params::const_pointer; using reference = typename Params::reference; using const_reference = typename Params::const_reference; using key_compare = typename Params::key_compare; using size_type = typename Params::size_type; using difference_type = typename Params::difference_type; using use_linear_search = std::integral_constant< bool, has_linear_node_search_preference<original_key_compare>::value ? prefers_linear_node_search<original_key_compare>::value : has_linear_node_search_preference<key_type>::value ? prefers_linear_node_search<key_type>::value : std::is_arithmetic<key_type>::value && (std::is_same<std::less<key_type>, original_key_compare>::value || std::is_same<std::greater<key_type>, original_key_compare>::value)>; ~btree_node() = default; btree_node(btree_node const &) = delete; btree_node &operator=(btree_node const &) = delete; protected: btree_node() = default; private: using layout_type = absl::container_internal::Layout<btree_node *, uint32_t, field_type, slot_type, btree_node *>; using leaf_layout_type = typename layout_type::template WithStaticSizes< 1, BtreeGenerationsEnabled() ? 1 : 0, 4>; constexpr static size_type SizeWithNSlots(size_type n) { return leaf_layout_type( n, 0).AllocSize(); } constexpr static size_type MinimumOverhead() { return SizeWithNSlots(1) - sizeof(slot_type); } constexpr static size_type NodeTargetSlots(const size_type begin, const size_type end) { return begin == end ? begin : SizeWithNSlots((begin + end) / 2 + 1) > params_type::kTargetNodeSize ? NodeTargetSlots(begin, (begin + end) / 2) : NodeTargetSlots((begin + end) / 2 + 1, end); } constexpr static size_type kTargetNodeSize = params_type::kTargetNodeSize; constexpr static size_type kNodeTargetSlots = NodeTargetSlots(0, kTargetNodeSize); constexpr static size_type kMinNodeSlots = 4; constexpr static size_type kNodeSlots = kNodeTargetSlots >= kMinNodeSlots ? kNodeTargetSlots : kMinNodeSlots; using internal_layout_type = typename layout_type::template WithStaticSizes< 1, BtreeGenerationsEnabled() ? 1 : 0, 4, kNodeSlots, kNodeSlots + 1>; constexpr static field_type kInternalNodeMaxCount = 0; constexpr static leaf_layout_type LeafLayout( const size_type slot_count = kNodeSlots) { return leaf_layout_type(slot_count, 0); } constexpr static auto InternalLayout() { return internal_layout_type(); } constexpr static size_type LeafSize(const size_type slot_count = kNodeSlots) { return LeafLayout(slot_count).AllocSize(); } constexpr static size_type InternalSize() { return InternalLayout().AllocSize(); } constexpr static size_type Alignment() { static_assert(LeafLayout(1).Alignment() == InternalLayout().Alignment(), "Alignment of all nodes must be equal."); return InternalLayout().Alignment(); } template <size_type N> inline typename layout_type::template ElementType<N> *GetField() { assert(N < 4 || is_internal()); return InternalLayout().template Pointer<N>(reinterpret_cast<char *>(this)); } template <size_type N> inline const typename layout_type::template ElementType<N> *GetField() const { assert(N < 4 || is_internal()); return InternalLayout().template Pointer<N>( reinterpret_cast<const char *>(this)); } void set_parent(btree_node *p) { *GetField<0>() = p; } field_type &mutable_finish() { return GetField<2>()[2]; } slot_type *slot(size_type i) { return &GetField<3>()[i]; } slot_type *start_slot() { return slot(start()); } slot_type *finish_slot() { return slot(finish()); } const slot_type *slot(size_type i) const { return &GetField<3>()[i]; } void set_position(field_type v) { GetField<2>()[0] = v; } void set_start(field_type v) { GetField<2>()[1] = v; } void set_finish(field_type v) { GetField<2>()[2] = v; } void set_max_count(field_type v) { GetField<2>()[3] = v; } public: bool is_leaf() const { return GetField<2>()[3] != kInternalNodeMaxCount; } bool is_internal() const { return !is_leaf(); } field_type position() const { return GetField<2>()[0]; } field_type start() const { assert(GetField<2>()[1] == 0); return 0; } field_type finish() const { return GetField<2>()[2]; } field_type count() const { assert(finish() >= start()); return finish() - start(); } field_type max_count() const { const field_type max_count = GetField<2>()[3]; return max_count == field_type{kInternalNodeMaxCount} ? field_type{kNodeSlots} : max_count; } btree_node *parent() const { return *GetField<0>(); } bool is_root() const { return parent()->is_leaf(); } void make_root() { assert(parent()->is_root()); set_generation(parent()->generation()); set_parent(parent()->parent()); } uint32_t *get_root_generation() const { assert(BtreeGenerationsEnabled()); const btree_node *curr = this; for (; !curr->is_root(); curr = curr->parent()) continue; return const_cast<uint32_t *>(&curr->GetField<1>()[0]); } uint32_t generation() const { return BtreeGenerationsEnabled() ? *get_root_generation() : 0; } void set_generation(uint32_t generation) { if (BtreeGenerationsEnabled()) GetField<1>()[0] = generation; } void next_generation() { if (BtreeGenerationsEnabled()) ++*get_root_generation(); } const key_type &key(size_type i) const { return params_type::key(slot(i)); } reference value(size_type i) { return params_type::element(slot(i)); } const_reference value(size_type i) const { return params_type::element(slot(i)); } btree_node *child(field_type i) const { return GetField<4>()[i]; } btree_node *start_child() const { return child(start()); } btree_node *&mutable_child(field_type i) { return GetField<4>()[i]; } void clear_child(field_type i) { absl::container_internal::SanitizerPoisonObject(&mutable_child(i)); } void set_child_noupdate_position(field_type i, btree_node *c) { absl::container_internal::SanitizerUnpoisonObject(&mutable_child(i)); mutable_child(i) = c; } void set_child(field_type i, btree_node *c) { set_child_noupdate_position(i, c); c->set_position(i); } void init_child(field_type i, btree_node *c) { set_child(i, c); c->set_parent(this); } template <typename K> SearchResult<size_type, is_key_compare_to::value> lower_bound( const K &k, const key_compare &comp) const { return use_linear_search::value ? linear_search(k, comp) : binary_search(k, comp); } template <typename K> size_type upper_bound(const K &k, const key_compare &comp) const { auto upper_compare = upper_bound_adapter<key_compare>(comp); return use_linear_search::value ? linear_search(k, upper_compare).value : binary_search(k, upper_compare).value; } template <typename K, typename Compare> SearchResult<size_type, btree_is_key_compare_to<Compare, key_type>::value> linear_search(const K &k, const Compare &comp) const { return linear_search_impl(k, start(), finish(), comp, btree_is_key_compare_to<Compare, key_type>()); } template <typename K, typename Compare> SearchResult<size_type, btree_is_key_compare_to<Compare, key_type>::value> binary_search(const K &k, const Compare &comp) const { return binary_search_impl(k, start(), finish(), comp, btree_is_key_compare_to<Compare, key_type>()); } template <typename K, typename Compare> SearchResult<size_type, false> linear_search_impl( const K &k, size_type s, const size_type e, const Compare &comp, std::false_type ) const { while (s < e) { if (!comp(key(s), k)) { break; } ++s; } return SearchResult<size_type, false>{s}; } template <typename K, typename Compare> SearchResult<size_type, true> linear_search_impl( const K &k, size_type s, const size_type e, const Compare &comp, std::true_type ) const { while (s < e) { const absl::weak_ordering c = comp(key(s), k); if (c == 0) { return {s, MatchKind::kEq}; } else if (c > 0) { break; } ++s; } return {s, MatchKind::kNe}; } template <typename K, typename Compare> SearchResult<size_type, false> binary_search_impl( const K &k, size_type s, size_type e, const Compare &comp, std::false_type ) const { while (s != e) { const size_type mid = (s + e) >> 1; if (comp(key(mid), k)) { s = mid + 1; } else { e = mid; } } return SearchResult<size_type, false>{s}; } template <typename K, typename CompareTo> SearchResult<size_type, true> binary_search_impl( const K &k, size_type s, size_type e, const CompareTo &comp, std::true_type ) const { if (params_type::template can_have_multiple_equivalent_keys<K>()) { MatchKind exact_match = MatchKind::kNe; while (s != e) { const size_type mid = (s + e) >> 1; const absl::weak_ordering c = comp(key(mid), k); if (c < 0) { s = mid + 1; } else { e = mid; if (c == 0) { exact_match = MatchKind::kEq; } } } return {s, exact_match}; } else { while (s != e) { const size_type mid = (s + e) >> 1; const absl::weak_ordering c = comp(key(mid), k); if (c < 0) { s = mid + 1; } else if (c > 0) { e = mid; } else { return {mid, MatchKind::kEq}; } } return {s, MatchKind::kNe}; } } template <typename Compare> bool is_ordered_correctly(field_type i, const Compare &comp) const { if (std::is_base_of<BtreeTestOnlyCheckedCompareOptOutBase, Compare>::value || params_type::kIsKeyCompareStringAdapted) { return true; } const auto compare = [&](field_type a, field_type b) { const absl::weak_ordering cmp = compare_internal::do_three_way_comparison(comp, key(a), key(b)); return cmp < 0 ? -1 : cmp > 0 ? 1 : 0; }; int cmp = -1; constexpr bool kCanHaveEquivKeys = params_type::template can_have_multiple_equivalent_keys<key_type>(); for (field_type j = start(); j < finish(); ++j) { if (j == i) { if (cmp > 0) return false; continue; } int new_cmp = compare(j, i); if (new_cmp < cmp || (!kCanHaveEquivKeys && new_cmp == 0)) return false; cmp = new_cmp; } return true; } template <typename... Args> void emplace_value(field_type i, allocator_type *alloc, Args &&...args); void remove_values(field_type i, field_type to_erase, allocator_type *alloc); void rebalance_right_to_left(field_type to_move, btree_node *right, allocator_type *alloc); void rebalance_left_to_right(field_type to_move, btree_node *right, allocator_type *alloc); void split(int insert_position, btree_node *dest, allocator_type *alloc); void merge(btree_node *src, allocator_type *alloc); void init_leaf(field_type position, field_type max_count, btree_node *parent) { set_generation(0); set_parent(parent); set_position(position); set_start(0); set_finish(0); set_max_count(max_count); absl::container_internal::SanitizerPoisonMemoryRegion( start_slot(), max_count * sizeof(slot_type)); } void init_internal(field_type position, btree_node *parent) { init_leaf(position, kNodeSlots, parent); set_max_count(kInternalNodeMaxCount); absl::container_internal::SanitizerPoisonMemoryRegion( &mutable_child(start()), (kNodeSlots + 1) * sizeof(btree_node *)); } static void deallocate(const size_type size, btree_node *node, allocator_type *alloc) { absl::container_internal::SanitizerUnpoisonMemoryRegion(node, size); absl::container_internal::Deallocate<Alignment()>(alloc, node, size); } static void clear_and_delete(btree_node *node, allocator_type *alloc); private: template <typename... Args> void value_init(const field_type i, allocator_type *alloc, Args &&...args) { next_generation(); absl::container_internal::SanitizerUnpoisonObject(slot(i)); params_type::construct(alloc, slot(i), std::forward<Args>(args)...); } void value_destroy(const field_type i, allocator_type *alloc) { next_generation(); params_type::destroy(alloc, slot(i)); absl::container_internal::SanitizerPoisonObject(slot(i)); } void value_destroy_n(const field_type i, const field_type n, allocator_type *alloc) { next_generation(); for (slot_type *s = slot(i), *end = slot(i + n); s != end; ++s) { params_type::destroy(alloc, s); absl::container_internal::SanitizerPoisonObject(s); } } static void transfer(slot_type *dest, slot_type *src, allocator_type *alloc) { absl::container_internal::SanitizerUnpoisonObject(dest); params_type::transfer(alloc, dest, src); absl::container_internal::SanitizerPoisonObject(src); } void transfer(const size_type dest_i, const size_type src_i, btree_node *src_node, allocator_type *alloc) { next_generation(); transfer(slot(dest_i), src_node->slot(src_i), alloc); } void transfer_n(const size_type n, const size_type dest_i, const size_type src_i, btree_node *src_node, allocator_type *alloc) { next_generation(); for (slot_type *src = src_node->slot(src_i), *end = src + n, *dest = slot(dest_i); src != end; ++src, ++dest) { transfer(dest, src, alloc); } } void transfer_n_backward(const size_type n, const size_type dest_i, const size_type src_i, btree_node *src_node, allocator_type *alloc) { next_generation(); for (slot_type *src = src_node->slot(src_i + n), *end = src - n, *dest = slot(dest_i + n); src != end; --src, --dest) { transfer(dest - 1, src - 1, alloc); } } template <typename P> friend class btree; template <typename N, typename R, typename P> friend class btree_iterator; friend class BtreeNodePeer; friend struct btree_access; }; template <typename Node> bool AreNodesFromSameContainer(const Node *node_a, const Node *node_b) { if (node_a == nullptr || node_b == nullptr) return true; while (!node_a->is_root()) node_a = node_a->parent(); while (!node_b->is_root()) node_b = node_b->parent(); return node_a == node_b; } class btree_iterator_generation_info_enabled { public: explicit btree_iterator_generation_info_enabled(uint32_t g) : generation_(g) {} template <typename Node> void update_generation(const Node *node) { if (node != nullptr) generation_ = node->generation(); } uint32_t generation() const { return generation_; } template <typename Node> void assert_valid_generation(const Node *node) const { if (node != nullptr && node->generation() != generation_) { ABSL_INTERNAL_LOG( FATAL, "Attempting to use an invalidated iterator. The corresponding b-tree " "container has been mutated since this iterator was constructed."); } } private: uint32_t generation_; }; class btree_iterator_generation_info_disabled { public: explicit btree_iterator_generation_info_disabled(uint32_t) {} static void update_generation(const void *) {} static uint32_t generation() { return 0; } static void assert_valid_generation(const void *) {} }; #ifdef ABSL_BTREE_ENABLE_GENERATIONS using btree_iterator_generation_info = btree_iterator_generation_info_enabled; #else using btree_iterator_generation_info = btree_iterator_generation_info_disabled; #endif template <typename Node, typename Reference, typename Pointer> class btree_iterator : private btree_iterator_generation_info { using field_type = typename Node::field_type; using key_type = typename Node::key_type; using size_type = typename Node::size_type; using params_type = typename Node::params_type; using is_map_container = typename params_type::is_map_container; using node_type = Node; using normal_node = typename std::remove_const<Node>::type; using const_node = const Node; using normal_pointer = typename params_type::pointer; using normal_reference = typename params_type::reference; using const_pointer = typename params_type::const_pointer; using const_reference = typename params_type::const_reference; using slot_type = typename params_type::slot_type; using iterator = absl::conditional_t< is_map_container::value, btree_iterator<normal_node, normal_reference, normal_pointer>, btree_iterator<normal_node, const_reference, const_pointer>>; using const_iterator = btree_iterator<const_node, const_reference, const_pointer>; public: using difference_type = typename Node::difference_type; using value_type = typename params_type::value_type; using pointer = Pointer; using reference = Reference; using iterator_category = std::bidirectional_iterator_tag; btree_iterator() : btree_iterator(nullptr, -1) {} explicit btree_iterator(Node *n) : btree_iterator(n, n->start()) {} btree_iterator(Node *n, int p) : btree_iterator_generation_info(n != nullptr ? n->generation() : ~uint32_t{}), node_(n), position_(p) {} template <typename N, typename R, typename P, absl::enable_if_t< std::is_same<btree_iterator<N, R, P>, iterator>::value && std::is_same<btree_iterator, const_iterator>::value, int> = 0> btree_iterator(const btree_iterator<N, R, P> other) : btree_iterator_generation_info(other), node_(other.node_), position_(other.position_) {} bool operator==(const iterator &other) const { return Equals(other); } bool operator==(const const_iterator &other) const { return Equals(other); } bool operator!=(const iterator &other) const { return !Equals(other); } bool operator!=(const const_iterator &other) const { return !Equals(other); } difference_type operator-(const_iterator other) const { if (node_ == other.node_) { if (node_->is_leaf()) return position_ - other.position_; if (position_ == other.position_) return 0; } return distance_slow(other); } reference operator*() const { ABSL_HARDENING_ASSERT(node_ != nullptr); assert_valid_generation(node_); ABSL_HARDENING_ASSERT(position_ >= node_->start()); if (position_ >= node_->finish()) { ABSL_HARDENING_ASSERT(!IsEndIterator() && "Dereferencing end() iterator"); ABSL_HARDENING_ASSERT(position_ < node_->finish()); } return node_->value(static_cast<field_type>(position_)); } pointer operator->() const { return &operator*(); } btree_iterator &operator++() { increment(); return *this; } btree_iterator &operator--() { decrement(); return *this; } btree_iterator operator++(int) { btree_iterator tmp = *this; ++*this; return tmp; } btree_iterator operator--(int) { btree_iterator tmp = *this; --*this; return tmp; } private: friend iterator; friend const_iterator; template <typename Params> friend class btree; template <typename Tree> friend class btree_container; template <typename Tree> friend class btree_set_container; template <typename Tree> friend class btree_map_container; template <typename Tree> friend class btree_multiset_container; template <typename TreeType, typename CheckerType> friend class base_checker; friend struct btree_access; template <typename N, typename R, typename P, absl::enable_if_t< std::is_same<btree_iterator<N, R, P>, const_iterator>::value && std::is_same<btree_iterator, iterator>::value, int> = 0> explicit btree_iterator(const btree_iterator<N, R, P> other) : btree_iterator_generation_info(other.generation()), node_(const_cast<node_type *>(other.node_)), position_(other.position_) {} bool Equals(const const_iterator other) const { ABSL_HARDENING_ASSERT(((node_ == nullptr && other.node_ == nullptr) || (node_ != nullptr && other.node_ != nullptr)) && "Comparing default-constructed iterator with " "non-default-constructed iterator."); assert(AreNodesFromSameContainer(node_, other.node_) && "Comparing iterators from different containers."); assert_valid_generation(node_); other.assert_valid_generation(other.node_); return node_ == other.node_ && position_ == other.position_; } bool IsEndIterator() const { if (position_ != node_->finish()) return false; node_type *node = node_; while (!node->is_root()) { if (node->position() != node->parent()->finish()) return false; node = node->parent(); } return true; } difference_type distance_slow(const_iterator other) const; void increment() { assert_valid_generation(node_); if (node_->is_leaf() && ++position_ < node_->finish()) { return; } increment_slow(); } void increment_slow(); void decrement() { assert_valid_generation(node_); if (node_->is_leaf() && --position_ >= node_->start()) { return; } decrement_slow(); } void decrement_slow(); const key_type &key() const { return node_->key(static_cast<size_type>(position_)); } decltype(std::declval<Node *>()->slot(0)) slot() { return node_->slot(static_cast<size_type>(position_)); } void update_generation() { btree_iterator_generation_info::update_generation(node_); } Node *node_; int position_; }; template <typename Params> class btree { using node_type = btree_node<Params>; using is_key_compare_to = typename Params::is_key_compare_to; using field_type = typename node_type::field_type; struct EmptyNodeType : node_type { using field_type = typename node_type::field_type; node_type *parent; #ifdef ABSL_BTREE_ENABLE_GENERATIONS uint32_t generation = 0; #endif field_type position = 0; field_type start = 0; field_type finish = 0; field_type max_count = node_type::kInternalNodeMaxCount + 1; constexpr EmptyNodeType() : parent(this) {} }; static node_type *EmptyNode() { alignas(node_type::Alignment()) static constexpr EmptyNodeType empty_node; return const_cast<EmptyNodeType *>(&empty_node); } enum : uint32_t { kNodeSlots = node_type::kNodeSlots, kMinNodeValues = kNodeSlots / 2, }; struct node_stats { using size_type = typename Params::size_type; node_stats(size_type l, size_type i) : leaf_nodes(l), internal_nodes(i) {} node_stats &operator+=(const node_stats &other) { leaf_nodes += other.leaf_nodes; internal_nodes += other.internal_nodes; return *this; } size_type leaf_nodes; size_type internal_nodes; }; public: using key_type = typename Params::key_type; using value_type = typename Params::value_type; using size_type = typename Params::size_type; using difference_type = typename Params::difference_type; using key_compare = typename Params::key_compare; using original_key_compare = typename Params::original_key_compare; using value_compare = typename Params::value_compare; using allocator_type = typename Params::allocator_type; using reference = typename Params::reference; using const_reference = typename Params::const_reference; using pointer = typename Params::pointer; using const_pointer = typename Params::const_pointer; using iterator = typename btree_iterator<node_type, reference, pointer>::iterator; using const_iterator = typename iterator::const_iterator; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using node_handle_type = node_handle<Params, Params, allocator_type>; using params_type = Params; using slot_type = typename Params::slot_type; private: template <typename Btree> void copy_or_move_values_in_order(Btree &other); constexpr static bool static_assert_validation(); public: btree(const key_compare &comp, const allocator_type &alloc) : root_(EmptyNode()), rightmost_(comp, alloc, EmptyNode()), size_(0) {} btree(const btree &other) : btree(other, other.allocator()) {} btree(const btree &other, const allocator_type &alloc) : btree(other.key_comp(), alloc) { copy_or_move_values_in_order(other); } btree(btree &&other) noexcept : root_(std::exchange(other.root_, EmptyNode())), rightmost_(std::move(other.rightmost_)), size_(std::exchange(other.size_, 0u)) { other.mutable_rightmost() = EmptyNode(); } btree(btree &&other, const allocator_type &alloc) : btree(other.key_comp(), alloc) { if (alloc == other.allocator()) { swap(other); } else { copy_or_move_values_in_order(other); } } ~btree() { static_assert(static_assert_validation(), "This call must be elided."); clear(); } btree &operator=(const btree &other); btree &operator=(btree &&other) noexcept; iterator begin() { return iterator(leftmost()); } const_iterator begin() const { return const_iterator(leftmost()); } iterator end() { return iterator(rightmost(), rightmost()->finish()); } const_iterator end() const { return const_iterator(rightmost(), rightmost()->finish()); } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } template <typename K> iterator lower_bound(const K &key) { return internal_end(internal_lower_bound(key).value); } template <typename K> const_iterator lower_bound(const K &key) const { return internal_end(internal_lower_bound(key).value); } template <typename K> std::pair<iterator, bool> lower_bound_equal(const K &key) const; template <typename K> iterator upper_bound(const K &key) { return internal_end(internal_upper_bound(key)); } template <typename K> const_iterator upper_bound(const K &key) const { return internal_end(internal_upper_bound(key)); } template <typename K> std::pair<iterator, iterator> equal_range(const K &key); template <typename K> std::pair<const_iterator, const_iterator> equal_range(const K &key) const { return const_cast<btree *>(this)->equal_range(key); } template <typename K, typename... Args> std::pair<iterator, bool> insert_unique(const K &key, Args &&...args); template <typename K, typename... Args> std::pair<iterator, bool> insert_hint_unique(iterator position, const K &key, Args &&...args); template <typename InputIterator, typename = decltype(std::declval<const key_compare &>()( params_type::key(*std::declval<InputIterator>()), std::declval<const key_type &>()))> void insert_iterator_unique(InputIterator b, InputIterator e, int); template <typename InputIterator> void insert_iterator_unique(InputIterator b, InputIterator e, char); template <typename ValueType> iterator insert_multi(const key_type &key, ValueType &&v); template <typename ValueType> iterator insert_multi(ValueType &&v) { return insert_multi(params_type::key(v), std::forward<ValueType>(v)); } template <typename ValueType> iterator insert_hint_multi(iterator position, ValueType &&v); template <typename InputIterator> void insert_iterator_multi(InputIterator b, InputIterator e); iterator erase(iterator iter); std::pair<size_type, iterator> erase_range(iterator begin, iterator end); template <typename K> iterator find(const K &key) { return internal_end(internal_find(key)); } template <typename K> const_iterator find(const K &key) const { return internal_end(internal_find(key)); } void clear(); void swap(btree &other); const key_compare &key_comp() const noexcept { return rightmost_.template get<0>(); } template <typename K1, typename K2> bool compare_keys(const K1 &a, const K2 &b) const { return compare_internal::compare_result_as_less_than(key_comp()(a, b)); } value_compare value_comp() const { return value_compare(original_key_compare(key_comp())); } void verify() const; size_type size() const { return size_; } size_type max_size() const { return (std::numeric_limits<size_type>::max)(); } bool empty() const { return size_ == 0; } size_type height() const { size_type h = 0; if (!empty()) { const node_type *n = root(); do { ++h; n = n->parent(); } while (n != root()); } return h; } 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 { node_stats stats = internal_stats(root()); return stats.leaf_nodes + stats.internal_nodes; } 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()); } else { return sizeof(*this) + stats.leaf_nodes * node_type::LeafSize() + stats.internal_nodes * node_type::InternalSize(); } } static double average_bytes_per_value() { const double expected_values_per_node = (kNodeSlots + kMinNodeValues) / 2.0; return node_type::LeafSize() / expected_values_per_node; } double fullness() const { if (empty()) return 0.0; return static_cast<double>(size()) / (nodes() * kNodeSlots); } double overhead() const { if (empty()) return 0.0; return (bytes_used() - size() * sizeof(value_type)) / static_cast<double>(size()); } allocator_type get_allocator() const { return allocator(); } private: friend struct btree_access; node_type *root() { return root_; } const node_type *root() const { return root_; } node_type *&mutable_root() noexcept { return root_; } node_type *rightmost() { return rightmost_.template get<2>(); } const node_type *rightmost() const { return rightmost_.template get<2>(); } node_type *&mutable_rightmost() noexcept { return rightmost_.template get<2>(); } key_compare *mutable_key_comp() noexcept { return &rightmost_.template get<0>(); } node_type *leftmost() { return root()->parent(); } const node_type *leftmost() const { return root()->parent(); } allocator_type *mutable_allocator() noexcept { return &rightmost_.template get<1>(); } const allocator_type &allocator() const noexcept { return rightmost_.template get<1>(); } node_type *allocate(size_type size) { return reinterpret_cast<node_type *>( absl::container_internal::Allocate<node_type::Alignment()>( mutable_allocator(), size)); } node_type *new_internal_node(field_type position, node_type *parent) { node_type *n = allocate(node_type::InternalSize()); n->init_internal(position, parent); return n; } node_type *new_leaf_node(field_type position, node_type *parent) { node_type *n = allocate(node_type::LeafSize()); n->init_leaf(position, kNodeSlots, parent); return n; } node_type *new_leaf_root_node(field_type max_count) { node_type *n = allocate(node_type::LeafSize(max_count)); n->init_leaf(0, max_count, n); return n; } iterator rebalance_after_delete(iterator iter); void rebalance_or_split(iterator *iter); void merge_nodes(node_type *left, node_type *right); bool try_merge_or_rebalance(iterator *iter); void try_shrink(); iterator internal_end(iterator iter) { return iter.node_ != nullptr ? iter : end(); } const_iterator internal_end(const_iterator iter) const { return iter.node_ != nullptr ? iter : end(); } template <typename... Args> iterator internal_emplace(iterator iter, Args &&...args); template <typename IterType> static IterType internal_last(IterType iter); template <typename K> SearchResult<iterator, is_key_compare_to::value> internal_locate( const K &key) const; template <typename K> SearchResult<iterator, is_key_compare_to::value> internal_lower_bound( const K &key) const; template <typename K> iterator internal_upper_bound(const K &key) const; template <typename K> iterator internal_find(const K &key) const; 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 { if (node == nullptr || (node == root() && empty())) { return node_stats(0, 0); } if (node->is_leaf()) { return node_stats(1, 0); } node_stats res(0, 1); for (int i = node->start(); i <= node->finish(); ++i) { res += internal_stats(node->child(i)); } return res; } node_type *root_; absl::container_internal::CompressedTuple<key_compare, allocator_type, node_type *> rightmost_; size_type size_; }; template <typename P> template <typename... Args> inline void btree_node<P>::emplace_value(const field_type i, allocator_type *alloc, Args &&...args) { assert(i >= start()); assert(i <= finish()); if (i < finish()) { transfer_n_backward(finish() - i, i + 1, i, this, alloc); } value_init(static_cast<field_type>(i), alloc, std::forward<Args>(args)...); set_finish(finish() + 1); if (is_internal() && finish() > i + 1) { for (field_type j = finish(); j > i + 1; --j) { set_child(j, child(j - 1)); } clear_child(i + 1); } } template <typename P> inline void btree_node<P>::remove_values(const field_type i, const field_type to_erase, allocator_type *alloc) { value_destroy_n(i, to_erase, alloc); const field_type orig_finish = finish(); const field_type src_i = i + to_erase; transfer_n(orig_finish - src_i, i, src_i, this, alloc); if (is_internal()) { for (field_type j = 0; j < to_erase; ++j) { clear_and_delete(child(i + j + 1), alloc); } for (field_type j = i + to_erase + 1; j <= orig_finish; ++j) { set_child(j - to_erase, child(j)); clear_child(j); } } set_finish(orig_finish - to_erase); } template <typename P> void btree_node<P>::rebalance_right_to_left(field_type to_move, btree_node *right, allocator_type *alloc) { assert(parent() == right->parent()); assert(position() + 1 == right->position()); assert(right->count() >= count()); assert(to_move >= 1); assert(to_move <= right->count()); transfer(finish(), position(), parent(), alloc); transfer_n(to_move - 1, finish() + 1, right->start(), right, alloc); parent()->transfer(position(), right->start() + to_move - 1, right, alloc); right->transfer_n(right->count() - to_move, right->start(), right->start() + to_move, right, alloc); if (is_internal()) { for (field_type i = 0; i < to_move; ++i) { init_child(finish() + i + 1, right->child(i)); } for (field_type i = right->start(); i <= right->finish() - to_move; ++i) { assert(i + to_move <= right->max_count()); right->init_child(i, right->child(i + to_move)); right->clear_child(i + to_move); } } set_finish(finish() + to_move); right->set_finish(right->finish() - to_move); } template <typename P> void btree_node<P>::rebalance_left_to_right(field_type to_move, btree_node *right, allocator_type *alloc) { assert(parent() == right->parent()); assert(position() + 1 == right->position()); assert(count() >= right->count()); assert(to_move >= 1); assert(to_move <= count()); right->transfer_n_backward(right->count(), right->start() + to_move, right->start(), right, alloc); right->transfer(right->start() + to_move - 1, position(), parent(), alloc); right->transfer_n(to_move - 1, right->start(), finish() - (to_move - 1), this, alloc); parent()->transfer(position(), finish() - to_move, this, alloc); if (is_internal()) { for (field_type i = right->finish() + 1; i > right->start(); --i) { right->init_child(i - 1 + to_move, right->child(i - 1)); right->clear_child(i - 1); } for (field_type i = 1; i <= to_move; ++i) { right->init_child(i - 1, child(finish() - to_move + i)); clear_child(finish() - to_move + i); } } set_finish(finish() - to_move); right->set_finish(right->finish() + to_move); } template <typename P> void btree_node<P>::split(const int insert_position, btree_node *dest, allocator_type *alloc) { assert(dest->count() == 0); assert(max_count() == kNodeSlots); assert(position() + 1 == dest->position()); assert(parent() == dest->parent()); if (insert_position == start()) { dest->set_finish(dest->start() + finish() - 1); } else if (insert_position == kNodeSlots) { dest->set_finish(dest->start()); } else { dest->set_finish(dest->start() + count() / 2); } set_finish(finish() - dest->count()); assert(count() >= 1); dest->transfer_n(dest->count(), dest->start(), finish(), this, alloc); --mutable_finish(); parent()->emplace_value(position(), alloc, finish_slot()); value_destroy(finish(), alloc); parent()->set_child_noupdate_position(position() + 1, dest); if (is_internal()) { for (field_type i = dest->start(), j = finish() + 1; i <= dest->finish(); ++i, ++j) { assert(child(j) != nullptr); dest->init_child(i, child(j)); clear_child(j); } } } template <typename P> void btree_node<P>::merge(btree_node *src, allocator_type *alloc) { assert(parent() == src->parent()); assert(position() + 1 == src->position()); value_init(finish(), alloc, parent()->slot(position())); transfer_n(src->count(), finish() + 1, src->start(), src, alloc); if (is_internal()) { for (field_type i = src->start(), j = finish() + 1; i <= src->finish(); ++i, ++j) { init_child(j, src->child(i)); src->clear_child(i); } } set_finish(start() + 1 + count() + src->count()); src->set_finish(src->start()); parent()->remove_values(position(), 1, alloc); } template <typename P> void btree_node<P>::clear_and_delete(btree_node *node, allocator_type *alloc) { if (node->is_leaf()) { node->value_destroy_n(node->start(), node->count(), alloc); deallocate(LeafSize(node->max_count()), node, alloc); return; } if (node->count() == 0) { deallocate(InternalSize(), node, alloc); return; } btree_node *delete_root_parent = node->parent(); while (node->is_internal()) node = node->start_child(); #ifdef ABSL_BTREE_ENABLE_GENERATIONS btree_node *leftmost_leaf = node; #endif size_type pos = node->position(); btree_node *parent = node->parent(); for (;;) { assert(pos <= parent->finish()); do { node = parent->child(static_cast<field_type>(pos)); if (node->is_internal()) { while (node->is_internal()) node = node->start_child(); pos = node->position(); parent = node->parent(); } node->value_destroy_n(node->start(), node->count(), alloc); #ifdef ABSL_BTREE_ENABLE_GENERATIONS if (leftmost_leaf != node) #endif deallocate(LeafSize(node->max_count()), node, alloc); ++pos; } while (pos <= parent->finish()); assert(pos > parent->finish()); do { node = parent; pos = node->position(); parent = node->parent(); node->value_destroy_n(node->start(), node->count(), alloc); deallocate(InternalSize(), node, alloc); if (parent == delete_root_parent) { #ifdef ABSL_BTREE_ENABLE_GENERATIONS deallocate(LeafSize(leftmost_leaf->max_count()), leftmost_leaf, alloc); #endif return; } ++pos; } while (pos > parent->finish()); } } template <typename N, typename R, typename P> auto btree_iterator<N, R, P>::distance_slow(const_iterator other) const -> difference_type { const_iterator begin = other; const_iterator end = *this; assert(begin.node_ != end.node_ || !begin.node_->is_leaf() || begin.position_ != end.position_); const node_type *node = begin.node_; difference_type count = node->is_leaf() ? -begin.position_ : 0; if (node->is_internal()) { ++count; node = node->child(begin.position_ + 1); } while (node->is_internal()) node = node->start_child(); size_type pos = node->position(); const node_type *parent = node->parent(); for (;;) { assert(pos <= parent->finish()); do { node = parent->child(static_cast<field_type>(pos)); if (node->is_internal()) { while (node->is_internal()) node = node->start_child(); pos = node->position(); parent = node->parent(); } if (node == end.node_) return count + end.position_; if (parent == end.node_ && pos == static_cast<size_type>(end.position_)) return count + node->count(); count += node->count() + 1; ++pos; } while (pos <= parent->finish()); assert(pos > parent->finish()); do { node = parent; pos = node->position(); parent = node->parent(); if (parent == end.node_ && pos == static_cast<size_type>(end.position_)) return count - 1; ++pos; } while (pos > parent->finish()); } } template <typename N, typename R, typename P> void btree_iterator<N, R, P>::increment_slow() { if (node_->is_leaf()) { assert(position_ >= node_->finish()); btree_iterator save(*this); while (position_ == node_->finish() && !node_->is_root()) { assert(node_->parent()->child(node_->position()) == node_); position_ = node_->position(); node_ = node_->parent(); } if (position_ == node_->finish()) { *this = save; } } else { assert(position_ < node_->finish()); node_ = node_->child(static_cast<field_type>(position_ + 1)); while (node_->is_internal()) { node_ = node_->start_child(); } position_ = node_->start(); } } template <typename N, typename R, typename P> void btree_iterator<N, R, P>::decrement_slow() { if (node_->is_leaf()) { assert(position_ <= -1); btree_iterator save(*this); while (position_ < node_->start() && !node_->is_root()) { assert(node_->parent()->child(node_->position()) == node_); position_ = node_->position() - 1; node_ = node_->parent(); } if (position_ < node_->start()) { *this = save; } } else { assert(position_ >= node_->start()); node_ = node_->child(static_cast<field_type>(position_)); while (node_->is_internal()) { node_ = node_->child(node_->finish()); } position_ = node_->finish() - 1; } } template <typename P> template <typename Btree> void btree<P>::copy_or_move_values_in_order(Btree &other) { static_assert(std::is_same<btree, Btree>::value || std::is_same<const btree, Btree>::value, "Btree type must be same or const."); assert(empty()); auto iter = other.begin(); if (iter == other.end()) return; insert_multi(iter.slot()); ++iter; for (; iter != other.end(); ++iter) { internal_emplace(end(), iter.slot()); } } template <typename P> constexpr bool btree<P>::static_assert_validation() { static_assert(std::is_nothrow_copy_constructible<key_compare>::value, "Key comparison must be nothrow copy constructible"); static_assert(std::is_nothrow_copy_constructible<allocator_type>::value, "Allocator must be nothrow copy constructible"); static_assert(std::is_trivially_copyable<iterator>::value, "iterator not trivially copyable."); static_assert( kNodeSlots < (1 << (8 * sizeof(typename node_type::field_type))), "target node size too large"); static_assert( compare_has_valid_result_type<key_compare, key_type>(), "key comparison function must return absl::{weak,strong}_ordering or " "bool."); static_assert(node_type::MinimumOverhead() >= sizeof(void *) + 4, "node space assumption incorrect"); return true; } template <typename P> template <typename K> auto btree<P>::lower_bound_equal(const K &key) const -> std::pair<iterator, bool> { const SearchResult<iterator, is_key_compare_to::value> res = internal_lower_bound(key); const iterator lower = iterator(internal_end(res.value)); const bool equal = res.HasMatch() ? res.IsEq() : lower != end() && !compare_keys(key, lower.key()); return {lower, equal}; } template <typename P> template <typename K> auto btree<P>::equal_range(const K &key) -> std::pair<iterator, iterator> { const std::pair<iterator, bool> lower_and_equal = lower_bound_equal(key); const iterator lower = lower_and_equal.first; if (!lower_and_equal.second) { return {lower, lower}; } const iterator next = std::next(lower); if (!params_type::template can_have_multiple_equivalent_keys<K>()) { assert(next == end() || compare_keys(key, next.key())); return {lower, next}; } if (next == end() || compare_keys(key, next.key())) return {lower, next}; return {lower, upper_bound(key)}; } template <typename P> template <typename K, typename... Args> auto btree<P>::insert_unique(const K &key, Args &&...args) -> std::pair<iterator, bool> { if (empty()) { mutable_root() = mutable_rightmost() = new_leaf_root_node(1); } SearchResult<iterator, is_key_compare_to::value> res = internal_locate(key); iterator iter = res.value; if (res.HasMatch()) { if (res.IsEq()) { return {iter, false}; } } else { iterator last = internal_last(iter); if (last.node_ && !compare_keys(key, last.key())) { return {last, false}; } } return {internal_emplace(iter, std::forward<Args>(args)...), true}; } template <typename P> template <typename K, typename... Args> inline auto btree<P>::insert_hint_unique(iterator position, const K &key, Args &&...args) -> std::pair<iterator, bool> { if (!empty()) { if (position == end() || compare_keys(key, position.key())) { if (position == begin() || compare_keys(std::prev(position).key(), key)) { return {internal_emplace(position, std::forward<Args>(args)...), true}; } } else if (compare_keys(position.key(), key)) { ++position; if (position == end() || compare_keys(key, position.key())) { return {internal_emplace(position, std::forward<Args>(args)...), true}; } } else { return {position, false}; } } return insert_unique(key, std::forward<Args>(args)...); } template <typename P> template <typename InputIterator, typename> void btree<P>::insert_iterator_unique(InputIterator b, InputIterator e, int) { for (; b != e; ++b) { insert_hint_unique(end(), params_type::key(*b), *b); } } template <typename P> template <typename InputIterator> void btree<P>::insert_iterator_unique(InputIterator b, InputIterator e, char) { for (; b != e; ++b) { auto node_handle = CommonAccess::Construct<node_handle_type>(get_allocator(), *b); slot_type *slot = CommonAccess::GetSlot(node_handle); insert_hint_unique(end(), params_type::key(slot), slot); } } template <typename P> template <typename ValueType> auto btree<P>::insert_multi(const key_type &key, ValueType &&v) -> iterator { if (empty()) { mutable_root() = mutable_rightmost() = new_leaf_root_node(1); } iterator iter = internal_upper_bound(key); if (iter.node_ == nullptr) { iter = end(); } return internal_emplace(iter, std::forward<ValueType>(v)); } template <typename P> template <typename ValueType> auto btree<P>::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)) { if (position == begin() || !compare_keys(key, std::prev(position).key())) { return internal_emplace(position, std::forward<ValueType>(v)); } } else { ++position; if (position == end() || !compare_keys(position.key(), key)) { return internal_emplace(position, std::forward<ValueType>(v)); } } } return insert_multi(std::forward<ValueType>(v)); } template <typename P> template <typename InputIterator> void btree<P>::insert_iterator_multi(InputIterator b, InputIterator e) { for (; b != e; ++b) { insert_hint_multi(end(), *b); } } template <typename P> auto btree<P>::operator=(const btree &other) -> btree & { if (this != &other) { clear(); *mutable_key_comp() = other.key_comp(); if (absl::allocator_traits< allocator_type>::propagate_on_container_copy_assignment::value) { *mutable_allocator() = other.allocator(); } copy_or_move_values_in_order(other); } return *this; } template <typename P> auto btree<P>::operator=(btree &&other) noexcept -> btree & { if (this != &other) { clear(); using std::swap; if (absl::allocator_traits< allocator_type>::propagate_on_container_move_assignment::value) { swap(root_, other.root_); swap(rightmost_, other.rightmost_); swap(size_, other.size_); } else { if (allocator() == other.allocator()) { swap(mutable_root(), other.mutable_root()); swap(*mutable_key_comp(), *other.mutable_key_comp()); swap(mutable_rightmost(), other.mutable_rightmost()); swap(size_, other.size_); } else { *mutable_key_comp() = other.key_comp(); copy_or_move_values_in_order(other); } } } return *this; } template <typename P> auto btree<P>::erase(iterator iter) -> iterator { iter.node_->value_destroy(static_cast<field_type>(iter.position_), mutable_allocator()); iter.update_generation(); const bool internal_delete = iter.node_->is_internal(); if (internal_delete) { iterator internal_iter(iter); --iter; assert(iter.node_->is_leaf()); internal_iter.node_->transfer( static_cast<size_type>(internal_iter.position_), static_cast<size_type>(iter.position_), iter.node_, mutable_allocator()); } else { const field_type transfer_from = static_cast<field_type>(iter.position_ + 1); const field_type num_to_transfer = iter.node_->finish() - transfer_from; iter.node_->transfer_n(num_to_transfer, static_cast<size_type>(iter.position_), transfer_from, iter.node_, mutable_allocator()); } iter.node_->set_finish(iter.node_->finish() - 1); --size_; iterator res = rebalance_after_delete(iter); if (internal_delete) { ++res; } return res; } template <typename P> auto btree<P>::rebalance_after_delete(iterator iter) -> iterator { iterator res(iter); bool first_iteration = true; for (;;) { if (iter.node_ == root()) { try_shrink(); if (empty()) { return end(); } break; } if (iter.node_->count() >= kMinNodeValues) { break; } bool merged = try_merge_or_rebalance(&iter); if (first_iteration) { res = iter; first_iteration = false; } if (!merged) { break; } iter.position_ = iter.node_->position(); iter.node_ = iter.node_->parent(); } res.update_generation(); if (res.position_ == res.node_->finish()) { res.position_ = res.node_->finish() - 1; ++res; } return res; } template <typename P> auto btree<P>::erase_range(iterator begin, iterator end) -> std::pair<size_type, iterator> { size_type count = static_cast<size_type>(end - begin); assert(count >= 0); if (count == 0) { return {0, begin}; } if (static_cast<size_type>(count) == size_) { clear(); return {count, this->end()}; } if (begin.node_ == end.node_) { assert(end.position_ > begin.position_); begin.node_->remove_values( static_cast<field_type>(begin.position_), static_cast<field_type>(end.position_ - begin.position_), mutable_allocator()); size_ -= count; return {count, rebalance_after_delete(begin)}; } const size_type target_size = size_ - count; while (size_ > target_size) { if (begin.node_->is_leaf()) { const size_type remaining_to_erase = size_ - target_size; const size_type remaining_in_node = static_cast<size_type>(begin.node_->finish() - begin.position_); const field_type to_erase = static_cast<field_type>( (std::min)(remaining_to_erase, remaining_in_node)); begin.node_->remove_values(static_cast<field_type>(begin.position_), to_erase, mutable_allocator()); size_ -= to_erase; begin = rebalance_after_delete(begin); } else { begin = erase(begin); } } begin.update_generation(); return {count, begin}; } template <typename P> void btree<P>::clear() { if (!empty()) { node_type::clear_and_delete(root(), mutable_allocator()); } mutable_root() = mutable_rightmost() = EmptyNode(); size_ = 0; } template <typename P> void btree<P>::swap(btree &other) { using std::swap; if (absl::allocator_traits< allocator_type>::propagate_on_container_swap::value) { swap(rightmost_, other.rightmost_); } else { assert(allocator() == other.allocator()); swap(mutable_rightmost(), other.mutable_rightmost()); swap(*mutable_key_comp(), *other.mutable_key_comp()); } swap(mutable_root(), other.mutable_root()); swap(size_, other.size_); } template <typename P> void btree<P>::verify() const { assert(root() != nullptr); assert(leftmost() != nullptr); assert(rightmost() != nullptr); assert(empty() || size() == internal_verify(root(), nullptr, nullptr)); assert(leftmost() == (++const_iterator(root(), -1)).node_); assert(rightmost() == (--const_iterator(root(), root()->finish())).node_); assert(leftmost()->is_leaf()); assert(rightmost()->is_leaf()); } template <typename P> void btree<P>::rebalance_or_split(iterator *iter) { node_type *&node = iter->node_; int &insert_position = iter->position_; assert(node->count() == node->max_count()); assert(kNodeSlots == node->max_count()); node_type *parent = node->parent(); if (node != root()) { if (node->position() > parent->start()) { node_type *left = parent->child(node->position() - 1); assert(left->max_count() == kNodeSlots); if (left->count() < kNodeSlots) { field_type to_move = (kNodeSlots - left->count()) / (1 + (static_cast<field_type>(insert_position) < kNodeSlots)); to_move = (std::max)(field_type{1}, to_move); if (static_cast<field_type>(insert_position) - to_move >= node->start() || left->count() + to_move < kNodeSlots) { left->rebalance_right_to_left(to_move, node, mutable_allocator()); assert(node->max_count() - node->count() == to_move); insert_position = static_cast<int>( static_cast<field_type>(insert_position) - to_move); if (insert_position < node->start()) { insert_position = insert_position + left->count() + 1; node = left; } assert(node->count() < node->max_count()); return; } } } if (node->position() < parent->finish()) { node_type *right = parent->child(node->position() + 1); assert(right->max_count() == kNodeSlots); if (right->count() < kNodeSlots) { field_type to_move = (kNodeSlots - right->count()) / (1 + (insert_position > node->start())); to_move = (std::max)(field_type{1}, to_move); if (static_cast<field_type>(insert_position) <= node->finish() - to_move || right->count() + to_move < kNodeSlots) { node->rebalance_left_to_right(to_move, right, mutable_allocator()); if (insert_position > node->finish()) { insert_position = insert_position - node->count() - 1; node = right; } assert(node->count() < node->max_count()); return; } } } assert(parent->max_count() == kNodeSlots); if (parent->count() == kNodeSlots) { iterator parent_iter(parent, node->position()); rebalance_or_split(&parent_iter); parent = node->parent(); } } else { parent = new_internal_node(0, parent); parent->set_generation(root()->generation()); parent->init_child(parent->start(), node); mutable_root() = parent; assert(parent->start_child()->is_internal() || parent->start_child() == rightmost()); } node_type *split_node; if (node->is_leaf()) { split_node = new_leaf_node(node->position() + 1, parent); node->split(insert_position, split_node, mutable_allocator()); if (rightmost() == node) mutable_rightmost() = split_node; } else { split_node = new_internal_node(node->position() + 1, parent); node->split(insert_position, split_node, mutable_allocator()); } if (insert_position > node->finish()) { insert_position = insert_position - node->count() - 1; node = split_node; } } template <typename P> void btree<P>::merge_nodes(node_type *left, node_type *right) { left->merge(right, mutable_allocator()); if (rightmost() == right) mutable_rightmost() = left; } template <typename P> bool btree<P>::try_merge_or_rebalance(iterator *iter) { node_type *parent = iter->node_->parent(); if (iter->node_->position() > parent->start()) { node_type *left = parent->child(iter->node_->position() - 1); assert(left->max_count() == kNodeSlots); if (1U + left->count() + iter->node_->count() <= kNodeSlots) { iter->position_ += 1 + left->count(); merge_nodes(left, iter->node_); iter->node_ = left; return true; } } if (iter->node_->position() < parent->finish()) { node_type *right = parent->child(iter->node_->position() + 1); assert(right->max_count() == kNodeSlots); if (1U + iter->node_->count() + right->count() <= kNodeSlots) { merge_nodes(iter->node_, right); return true; } if (right->count() > kMinNodeValues && (iter->node_->count() == 0 || iter->position_ > iter->node_->start())) { field_type to_move = (right->count() - iter->node_->count()) / 2; to_move = (std::min)(to_move, static_cast<field_type>(right->count() - 1)); iter->node_->rebalance_right_to_left(to_move, right, mutable_allocator()); return false; } } if (iter->node_->position() > parent->start()) { node_type *left = parent->child(iter->node_->position() - 1); if (left->count() > kMinNodeValues && (iter->node_->count() == 0 || iter->position_ < iter->node_->finish())) { field_type to_move = (left->count() - iter->node_->count()) / 2; to_move = (std::min)(to_move, static_cast<field_type>(left->count() - 1)); left->rebalance_left_to_right(to_move, iter->node_, mutable_allocator()); iter->position_ += to_move; return false; } } return false; } template <typename P> void btree<P>::try_shrink() { node_type *orig_root = root(); if (orig_root->count() > 0) { return; } if (orig_root->is_leaf()) { assert(size() == 0); mutable_root() = mutable_rightmost() = EmptyNode(); } else { node_type *child = orig_root->start_child(); child->make_root(); mutable_root() = child; } node_type::clear_and_delete(orig_root, mutable_allocator()); } template <typename P> template <typename IterType> inline IterType btree<P>::internal_last(IterType iter) { assert(iter.node_ != nullptr); while (iter.position_ == iter.node_->finish()) { iter.position_ = iter.node_->position(); iter.node_ = iter.node_->parent(); if (iter.node_->is_leaf()) { iter.node_ = nullptr; break; } } iter.update_generation(); return iter; } template <typename P> template <typename... Args> inline auto btree<P>::internal_emplace(iterator iter, Args &&...args) -> iterator { if (iter.node_->is_internal()) { --iter; ++iter.position_; } const field_type max_count = iter.node_->max_count(); allocator_type *alloc = mutable_allocator(); const auto transfer_and_delete = [&](node_type *old_node, node_type *new_node) { new_node->transfer_n(old_node->count(), new_node->start(), old_node->start(), old_node, alloc); new_node->set_finish(old_node->finish()); old_node->set_finish(old_node->start()); new_node->set_generation(old_node->generation()); node_type::clear_and_delete(old_node, alloc); }; const auto replace_leaf_root_node = [&](field_type new_node_size) { assert(iter.node_ == root()); node_type *old_root = iter.node_; node_type *new_root = iter.node_ = new_leaf_root_node(new_node_size); transfer_and_delete(old_root, new_root); mutable_root() = mutable_rightmost() = new_root; }; bool replaced_node = false; if (iter.node_->count() == max_count) { if (max_count < kNodeSlots) { replace_leaf_root_node(static_cast<field_type>( (std::min)(static_cast<int>(kNodeSlots), 2 * max_count))); replaced_node = true; } else { rebalance_or_split(&iter); } } (void)replaced_node; #if defined(ABSL_HAVE_ADDRESS_SANITIZER) || \ defined(ABSL_HAVE_HWADDRESS_SANITIZER) if (!replaced_node) { assert(iter.node_->is_leaf()); if (iter.node_->is_root()) { replace_leaf_root_node(max_count); } else { node_type *old_node = iter.node_; const bool was_rightmost = rightmost() == old_node; const bool was_leftmost = leftmost() == old_node; node_type *parent = old_node->parent(); const field_type position = old_node->position(); node_type *new_node = iter.node_ = new_leaf_node(position, parent); parent->set_child_noupdate_position(position, new_node); transfer_and_delete(old_node, new_node); if (was_rightmost) mutable_rightmost() = new_node; if (was_leftmost) root()->set_parent(new_node); } } #endif iter.node_->emplace_value(static_cast<field_type>(iter.position_), alloc, std::forward<Args>(args)...); assert( iter.node_->is_ordered_correctly(static_cast<field_type>(iter.position_), original_key_compare(key_comp())) && "If this assert fails, then either (1) the comparator may violate " "transitivity, i.e. comp(a,b) && comp(b,c) -> comp(a,c) (see " "https: "key may have been mutated after it was inserted into the tree."); ++size_; iter.update_generation(); return iter; } template <typename P> template <typename K> inline auto btree<P>::internal_locate(const K &key) const -> SearchResult<iterator, is_key_compare_to::value> { iterator iter(const_cast<node_type *>(root())); for (;;) { SearchResult<size_type, is_key_compare_to::value> res = iter.node_->lower_bound(key, key_comp()); iter.position_ = static_cast<int>(res.value); if (res.IsEq()) { return {iter, MatchKind::kEq}; } if (iter.node_->is_leaf()) { break; } iter.node_ = iter.node_->child(static_cast<field_type>(iter.position_)); } return {iter, MatchKind::kNe}; } template <typename P> template <typename K> auto btree<P>::internal_lower_bound(const K &key) const -> SearchResult<iterator, is_key_compare_to::value> { if (!params_type::template can_have_multiple_equivalent_keys<K>()) { SearchResult<iterator, is_key_compare_to::value> ret = internal_locate(key); ret.value = internal_last(ret.value); return ret; } iterator iter(const_cast<node_type *>(root())); SearchResult<size_type, is_key_compare_to::value> res; bool seen_eq = false; for (;;) { res = iter.node_->lower_bound(key, key_comp()); iter.position_ = static_cast<int>(res.value); if (iter.node_->is_leaf()) { break; } seen_eq = seen_eq || res.IsEq(); iter.node_ = iter.node_->child(static_cast<field_type>(iter.position_)); } if (res.IsEq()) return {iter, MatchKind::kEq}; return {internal_last(iter), seen_eq ? MatchKind::kEq : MatchKind::kNe}; } template <typename P> template <typename K> auto btree<P>::internal_upper_bound(const K &key) const -> iterator { iterator iter(const_cast<node_type *>(root())); for (;;) { iter.position_ = static_cast<int>(iter.node_->upper_bound(key, key_comp())); if (iter.node_->is_leaf()) { break; } iter.node_ = iter.node_->child(static_cast<field_type>(iter.position_)); } return internal_last(iter); } template <typename P> template <typename K> auto btree<P>::internal_find(const K &key) const -> iterator { SearchResult<iterator, is_key_compare_to::value> res = internal_locate(key); if (res.HasMatch()) { if (res.IsEq()) { return res.value; } } else { const iterator iter = internal_last(res.value); if (iter.node_ != nullptr && !compare_keys(key, iter.key())) { return iter; } } return {nullptr, 0}; } template <typename P> typename btree<P>::size_type btree<P>::internal_verify( const node_type *node, const key_type *lo, const key_type *hi) const { assert(node->count() > 0); assert(node->count() <= node->max_count()); if (lo) { assert(!compare_keys(node->key(node->start()), *lo)); } if (hi) { assert(!compare_keys(*hi, node->key(node->finish() - 1))); } for (int i = node->start() + 1; i < node->finish(); ++i) { assert(!compare_keys(node->key(i), node->key(i - 1))); } size_type count = node->count(); if (node->is_internal()) { for (field_type i = node->start(); i <= node->finish(); ++i) { assert(node->child(i) != nullptr); assert(node->child(i)->parent() == node); assert(node->child(i)->position() == i); count += internal_verify(node->child(i), i == node->start() ? lo : &node->key(i - 1), i == node->finish() ? hi : &node->key(i)); } } return count; } struct btree_access { template <typename BtreeContainer, typename Pred> static auto erase_if(BtreeContainer &container, Pred pred) -> typename BtreeContainer::size_type { const auto initial_size = container.size(); auto &tree = container.tree_; auto *alloc = tree.mutable_allocator(); for (auto it = container.begin(); it != container.end();) { if (!pred(*it)) { ++it; continue; } auto *node = it.node_; if (node->is_internal()) { it = container.erase(it); continue; } int to_pos = it.position_; node->value_destroy(it.position_, alloc); while (++it.position_ < node->finish()) { it.update_generation(); if (pred(*it)) { node->value_destroy(it.position_, alloc); } else { node->transfer(node->slot(to_pos++), node->slot(it.position_), alloc); } } const int num_deleted = node->finish() - to_pos; tree.size_ -= num_deleted; node->set_finish(to_pos); it.position_ = to_pos; it = tree.rebalance_after_delete(it); } return initial_size - container.size(); } }; #undef ABSL_BTREE_ENABLE_GENERATIONS } ABSL_NAMESPACE_END } #endif
#include "absl/container/btree_test.h" #include <algorithm> #include <array> #include <cstdint> #include <functional> #include <iostream> #include <iterator> #include <limits> #include <map> #include <memory> #include <numeric> #include <stdexcept> #include <string> #include <type_traits> #include <utility> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/algorithm/container.h" #include "absl/base/internal/raw_logging.h" #include "absl/base/macros.h" #include "absl/container/btree_map.h" #include "absl/container/btree_set.h" #include "absl/container/internal/test_allocator.h" #include "absl/container/internal/test_instance_tracker.h" #include "absl/flags/flag.h" #include "absl/hash/hash_testing.h" #include "absl/memory/memory.h" #include "absl/random/random.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/types/compare.h" #include "absl/types/optional.h" ABSL_FLAG(int, test_values, 10000, "The number of values to use for tests"); namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { using ::absl::test_internal::CopyableMovableInstance; using ::absl::test_internal::InstanceTracker; using ::absl::test_internal::MovableOnlyInstance; using ::testing::ElementsAre; using ::testing::ElementsAreArray; using ::testing::IsEmpty; using ::testing::IsNull; using ::testing::Pair; using ::testing::SizeIs; template <typename T, typename U> void CheckPairEquals(const T &x, const U &y) { ABSL_INTERNAL_CHECK(x == y, "Values are unequal."); } template <typename T, typename U, typename V, typename W> void CheckPairEquals(const std::pair<T, U> &x, const std::pair<V, W> &y) { CheckPairEquals(x.first, y.first); CheckPairEquals(x.second, y.second); } } template <typename TreeType, typename CheckerType> class base_checker { public: using key_type = typename TreeType::key_type; using value_type = typename TreeType::value_type; using key_compare = typename TreeType::key_compare; using pointer = typename TreeType::pointer; using const_pointer = typename TreeType::const_pointer; using reference = typename TreeType::reference; using const_reference = typename TreeType::const_reference; using size_type = typename TreeType::size_type; using difference_type = typename TreeType::difference_type; using iterator = typename TreeType::iterator; using const_iterator = typename TreeType::const_iterator; using reverse_iterator = typename TreeType::reverse_iterator; using const_reverse_iterator = typename TreeType::const_reverse_iterator; public: base_checker() : const_tree_(tree_) {} base_checker(const base_checker &other) : tree_(other.tree_), const_tree_(tree_), checker_(other.checker_) {} template <typename InputIterator> base_checker(InputIterator b, InputIterator e) : tree_(b, e), const_tree_(tree_), checker_(b, e) {} iterator begin() { return tree_.begin(); } const_iterator begin() const { return tree_.begin(); } iterator end() { return tree_.end(); } const_iterator end() const { return tree_.end(); } reverse_iterator rbegin() { return tree_.rbegin(); } const_reverse_iterator rbegin() const { return tree_.rbegin(); } reverse_iterator rend() { return tree_.rend(); } const_reverse_iterator rend() const { return tree_.rend(); } template <typename IterType, typename CheckerIterType> IterType iter_check(IterType tree_iter, CheckerIterType checker_iter) const { if (tree_iter == tree_.end()) { ABSL_INTERNAL_CHECK(checker_iter == checker_.end(), "Checker iterator not at end."); } else { CheckPairEquals(*tree_iter, *checker_iter); } return tree_iter; } template <typename IterType, typename CheckerIterType> IterType riter_check(IterType tree_iter, CheckerIterType checker_iter) const { if (tree_iter == tree_.rend()) { ABSL_INTERNAL_CHECK(checker_iter == checker_.rend(), "Checker iterator not at rend."); } else { CheckPairEquals(*tree_iter, *checker_iter); } return tree_iter; } void value_check(const value_type &v) { typename KeyOfValue<typename TreeType::key_type, typename TreeType::value_type>::type key_of_value; const key_type &key = key_of_value(v); CheckPairEquals(*find(key), v); lower_bound(key); upper_bound(key); equal_range(key); contains(key); count(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)); EXPECT_EQ(const_tree_.find(key), tree_.end()); EXPECT_EQ(tree_.equal_range(key).first, const_tree_.equal_range(key).second); } 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)); } 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)); } std::pair<iterator, iterator> equal_range(const key_type &key) { std::pair<typename CheckerType::iterator, typename CheckerType::iterator> checker_res = checker_.equal_range(key); std::pair<iterator, iterator> 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; } std::pair<const_iterator, const_iterator> equal_range( const key_type &key) const { std::pair<typename CheckerType::const_iterator, typename CheckerType::const_iterator> checker_res = checker_.equal_range(key); std::pair<const_iterator, const_iterator> 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 { size_type res = checker_.count(key); EXPECT_EQ(res, tree_.count(key)); return res; } base_checker &operator=(const base_checker &other) { tree_ = other.tree_; checker_ = other.checker_; return *this; } int erase(const key_type &key) { int size = tree_.size(); int res = checker_.erase(key); EXPECT_EQ(res, tree_.count(key)); EXPECT_EQ(res, tree_.erase(key)); EXPECT_EQ(tree_.count(key), 0); EXPECT_EQ(tree_.size(), size - res); erase_check(key); return res; } iterator erase(iterator iter) { key_type key = iter.key(); int size = tree_.size(); int count = tree_.count(key); auto checker_iter = checker_.lower_bound(key); for (iterator tmp(tree_.lower_bound(key)); tmp != iter; ++tmp) { ++checker_iter; } auto checker_next = checker_iter; ++checker_next; checker_.erase(checker_iter); iter = tree_.erase(iter); EXPECT_EQ(tree_.size(), checker_.size()); EXPECT_EQ(tree_.size(), size - 1); EXPECT_EQ(tree_.count(key), count - 1); if (count == 1) { erase_check(key); } return iter_check(iter, checker_next); } void erase(iterator begin, iterator end) { int size = tree_.size(); int count = std::distance(begin, end); auto checker_begin = checker_.lower_bound(begin.key()); for (iterator tmp(tree_.lower_bound(begin.key())); tmp != begin; ++tmp) { ++checker_begin; } auto checker_end = end == tree_.end() ? checker_.end() : checker_.lower_bound(end.key()); if (end != tree_.end()) { for (iterator tmp(tree_.lower_bound(end.key())); tmp != end; ++tmp) { ++checker_end; } } const auto checker_ret = checker_.erase(checker_begin, checker_end); const auto tree_ret = tree_.erase(begin, end); EXPECT_EQ(std::distance(checker_.begin(), checker_ret), std::distance(tree_.begin(), tree_ret)); EXPECT_EQ(tree_.size(), checker_.size()); EXPECT_EQ(tree_.size(), size - count); } void clear() { tree_.clear(); checker_.clear(); } void swap(base_checker &other) { tree_.swap(other.tree_); checker_.swap(other.checker_); } void verify() const { tree_.verify(); EXPECT_EQ(tree_.size(), checker_.size()); auto checker_iter = checker_.begin(); const_iterator tree_iter(tree_.begin()); for (; tree_iter != tree_.end(); ++tree_iter, ++checker_iter) { CheckPairEquals(*tree_iter, *checker_iter); } for (int n = tree_.size() - 1; n >= 0; --n) { iter_check(tree_iter, checker_iter); --tree_iter; --checker_iter; } EXPECT_EQ(tree_iter, tree_.begin()); EXPECT_EQ(checker_iter, checker_.begin()); auto checker_riter = checker_.rbegin(); const_reverse_iterator tree_riter(tree_.rbegin()); for (; tree_riter != tree_.rend(); ++tree_riter, ++checker_riter) { CheckPairEquals(*tree_riter, *checker_riter); } for (int n = tree_.size() - 1; n >= 0; --n) { riter_check(tree_riter, checker_riter); --tree_riter; --checker_riter; } EXPECT_EQ(tree_riter, tree_.rbegin()); EXPECT_EQ(checker_riter, checker_.rbegin()); } const TreeType &tree() const { return tree_; } 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 { EXPECT_EQ(tree_.empty(), checker_.empty()); return tree_.empty(); } protected: TreeType tree_; const TreeType &const_tree_; CheckerType checker_; }; namespace { template <typename TreeType, typename CheckerType> class unique_checker : public base_checker<TreeType, CheckerType> { using super_type = base_checker<TreeType, CheckerType>; public: using iterator = typename super_type::iterator; using value_type = typename super_type::value_type; public: unique_checker() : super_type() {} unique_checker(const unique_checker &other) : super_type(other) {} template <class InputIterator> unique_checker(InputIterator b, InputIterator e) : super_type(b, e) {} unique_checker &operator=(const unique_checker &) = default; std::pair<iterator, bool> insert(const value_type &v) { int size = this->tree_.size(); std::pair<typename CheckerType::iterator, bool> checker_res = this->checker_.insert(v); std::pair<iterator, bool> tree_res = this->tree_.insert(v); CheckPairEquals(*tree_res.first, *checker_res.first); EXPECT_EQ(tree_res.second, checker_res.second); EXPECT_EQ(this->tree_.size(), this->checker_.size()); EXPECT_EQ(this->tree_.size(), size + tree_res.second); return tree_res; } iterator insert(iterator position, const value_type &v) { int size = this->tree_.size(); std::pair<typename CheckerType::iterator, bool> checker_res = this->checker_.insert(v); iterator tree_res = this->tree_.insert(position, v); 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 <typename InputIterator> void insert(InputIterator b, InputIterator e) { for (; b != e; ++b) { insert(*b); } } }; template <typename TreeType, typename CheckerType> class multi_checker : public base_checker<TreeType, CheckerType> { using super_type = base_checker<TreeType, CheckerType>; public: using iterator = typename super_type::iterator; using value_type = typename super_type::value_type; public: multi_checker() : super_type() {} multi_checker(const multi_checker &other) : super_type(other) {} template <class InputIterator> multi_checker(InputIterator b, InputIterator e) : super_type(b, e) {} multi_checker &operator=(const multi_checker &) = default; iterator insert(const value_type &v) { int size = this->tree_.size(); auto checker_res = this->checker_.insert(v); iterator tree_res = this->tree_.insert(v); CheckPairEquals(*tree_res, *checker_res); EXPECT_EQ(this->tree_.size(), this->checker_.size()); EXPECT_EQ(this->tree_.size(), size + 1); return tree_res; } iterator insert(iterator position, const value_type &v) { int size = this->tree_.size(); auto checker_res = this->checker_.insert(v); iterator tree_res = this->tree_.insert(position, v); CheckPairEquals(*tree_res, *checker_res); EXPECT_EQ(this->tree_.size(), this->checker_.size()); EXPECT_EQ(this->tree_.size(), size + 1); return tree_res; } template <typename InputIterator> void insert(InputIterator b, InputIterator e) { for (; b != e; ++b) { insert(*b); } } }; template <typename T, typename V> void DoTest(const char *name, T *b, const std::vector<V> &values) { typename KeyOfValue<typename T::key_type, V>::type key_of_value; T &mutable_b = *b; const T &const_b = *b; for (int i = 0; i < values.size(); ++i) { mutable_b.insert(values[i]); mutable_b.value_check(values[i]); } ASSERT_EQ(mutable_b.size(), values.size()); const_b.verify(); T b_copy(const_b); EXPECT_EQ(b_copy.size(), const_b.size()); for (int i = 0; i < values.size(); ++i) { CheckPairEquals(*b_copy.find(key_of_value(values[i])), values[i]); } T b_range(const_b.begin(), const_b.end()); EXPECT_EQ(b_range.size(), const_b.size()); for (int i = 0; i < values.size(); ++i) { CheckPairEquals(*b_range.find(key_of_value(values[i])), values[i]); } b_range.insert(b_copy.begin(), b_copy.end()); b_range.verify(); b_range.clear(); b_range.insert(b_copy.begin(), b_copy.end()); EXPECT_EQ(b_range.size(), b_copy.size()); for (int i = 0; i < values.size(); ++i) { CheckPairEquals(*b_range.find(key_of_value(values[i])), values[i]); } b_range.operator=(b_range); EXPECT_EQ(b_range.size(), b_copy.size()); b_range.clear(); b_range = b_copy; EXPECT_EQ(b_range.size(), b_copy.size()); b_range.clear(); b_range.swap(b_copy); EXPECT_EQ(b_copy.size(), 0); EXPECT_EQ(b_range.size(), const_b.size()); for (int i = 0; i < values.size(); ++i) { CheckPairEquals(*b_range.find(key_of_value(values[i])), values[i]); } b_range.swap(b_copy); swap(b_range, b_copy); EXPECT_EQ(b_copy.size(), 0); EXPECT_EQ(b_range.size(), const_b.size()); for (int i = 0; i < values.size(); ++i) { CheckPairEquals(*b_range.find(key_of_value(values[i])), values[i]); } swap(b_range, b_copy); for (int i = 0; i < values.size(); ++i) { mutable_b.erase(key_of_value(values[i])); ASSERT_EQ(mutable_b.erase(key_of_value(values[i])), 0); } const_b.verify(); EXPECT_EQ(const_b.size(), 0); mutable_b = b_copy; for (int i = 0; i < values.size(); ++i) { mutable_b.erase(mutable_b.find(key_of_value(values[i]))); } const_b.verify(); EXPECT_EQ(const_b.size(), 0); for (int i = 0; i < values.size(); i++) { mutable_b.insert(mutable_b.upper_bound(key_of_value(values[i])), values[i]); } const_b.verify(); mutable_b.erase(mutable_b.begin(), mutable_b.end()); EXPECT_EQ(mutable_b.size(), 0); const_b.verify(); mutable_b = b_copy; typename T::iterator mutable_iter_end = mutable_b.begin(); for (int i = 0; i < values.size() / 2; ++i) ++mutable_iter_end; mutable_b.erase(mutable_b.begin(), mutable_iter_end); EXPECT_EQ(mutable_b.size(), values.size() - values.size() / 2); const_b.verify(); mutable_b = b_copy; typename T::iterator mutable_iter_begin = mutable_b.begin(); for (int i = 0; i < values.size() / 2; ++i) ++mutable_iter_begin; mutable_b.erase(mutable_iter_begin, mutable_b.end()); EXPECT_EQ(mutable_b.size(), values.size() / 2); const_b.verify(); mutable_b = b_copy; mutable_iter_begin = mutable_b.begin(); for (int i = 0; i < values.size() / 4; ++i) ++mutable_iter_begin; mutable_iter_end = mutable_iter_begin; for (int i = 0; i < values.size() / 4; ++i) ++mutable_iter_end; mutable_b.erase(mutable_iter_begin, mutable_iter_end); EXPECT_EQ(mutable_b.size(), values.size() - values.size() / 4); const_b.verify(); mutable_b.clear(); } template <typename T> void ConstTest() { using value_type = typename T::value_type; typename KeyOfValue<typename T::key_type, value_type>::type key_of_value; T mutable_b; const T &const_b = mutable_b; value_type value = Generator<value_type>(2)(2); mutable_b.insert(value); EXPECT_TRUE(mutable_b.contains(key_of_value(value))); EXPECT_NE(mutable_b.find(key_of_value(value)), const_b.end()); EXPECT_TRUE(const_b.contains(key_of_value(value))); EXPECT_NE(const_b.find(key_of_value(value)), mutable_b.end()); EXPECT_EQ(*const_b.lower_bound(key_of_value(value)), value); EXPECT_EQ(const_b.upper_bound(key_of_value(value)), const_b.end()); EXPECT_EQ(*const_b.equal_range(key_of_value(value)).first, value); typename T::iterator mutable_iter(mutable_b.begin()); EXPECT_EQ(mutable_iter, const_b.begin()); EXPECT_NE(mutable_iter, const_b.end()); EXPECT_EQ(const_b.begin(), mutable_iter); EXPECT_NE(const_b.end(), mutable_iter); typename T::reverse_iterator mutable_riter(mutable_b.rbegin()); EXPECT_EQ(mutable_riter, const_b.rbegin()); EXPECT_NE(mutable_riter, const_b.rend()); EXPECT_EQ(const_b.rbegin(), mutable_riter); EXPECT_NE(const_b.rend(), mutable_riter); typename T::const_iterator const_iter(mutable_iter); EXPECT_EQ(const_iter, mutable_b.begin()); EXPECT_NE(const_iter, mutable_b.end()); EXPECT_EQ(mutable_b.begin(), const_iter); EXPECT_NE(mutable_b.end(), const_iter); typename T::const_reverse_iterator const_riter(mutable_riter); EXPECT_EQ(const_riter, mutable_b.rbegin()); EXPECT_NE(const_riter, mutable_b.rend()); EXPECT_EQ(mutable_b.rbegin(), const_riter); EXPECT_NE(mutable_b.rend(), const_riter); const_b.verify(); ASSERT_TRUE(!const_b.empty()); EXPECT_EQ(const_b.size(), 1); EXPECT_GT(const_b.max_size(), 0); EXPECT_TRUE(const_b.contains(key_of_value(value))); EXPECT_EQ(const_b.count(key_of_value(value)), 1); } template <typename T, typename C> void BtreeTest() { ConstTest<T>(); using V = typename remove_pair_const<typename T::value_type>::type; const std::vector<V> random_values = GenerateValuesWithSeed<V>( absl::GetFlag(FLAGS_test_values), 4 * absl::GetFlag(FLAGS_test_values), GTEST_FLAG_GET(random_seed)); unique_checker<T, C> container; std::vector<V> sorted_values(random_values); std::sort(sorted_values.begin(), sorted_values.end()); DoTest("sorted: ", &container, sorted_values); std::reverse(sorted_values.begin(), sorted_values.end()); DoTest("rsorted: ", &container, sorted_values); DoTest("random: ", &container, random_values); } template <typename T, typename C> void BtreeMultiTest() { ConstTest<T>(); using V = typename remove_pair_const<typename T::value_type>::type; const std::vector<V> random_values = GenerateValuesWithSeed<V>( absl::GetFlag(FLAGS_test_values), 4 * absl::GetFlag(FLAGS_test_values), GTEST_FLAG_GET(random_seed)); multi_checker<T, C> container; std::vector<V> sorted_values(random_values); std::sort(sorted_values.begin(), sorted_values.end()); DoTest("sorted: ", &container, sorted_values); std::reverse(sorted_values.begin(), sorted_values.end()); DoTest("rsorted: ", &container, sorted_values); DoTest("random: ", &container, random_values); std::vector<V> duplicate_values(random_values); duplicate_values.insert(duplicate_values.end(), random_values.begin(), random_values.end()); DoTest("duplicates:", &container, duplicate_values); std::vector<V> identical_values(100); std::fill(identical_values.begin(), identical_values.end(), Generator<V>(2)(2)); DoTest("identical: ", &container, identical_values); } template <typename T> void BtreeMapTest() { using value_type = typename T::value_type; using mapped_type = typename T::mapped_type; mapped_type m = Generator<mapped_type>(0)(0); (void)m; T b; for (int i = 0; i < 1000; i++) { value_type v = Generator<value_type>(1000)(i); b[v.first] = v.second; } EXPECT_EQ(b.size(), 1000); EXPECT_EQ(b.begin()->first, Generator<value_type>(1000)(0).first); EXPECT_EQ(b.begin()->second, Generator<value_type>(1000)(0).second); EXPECT_EQ(b.rbegin()->first, Generator<value_type>(1000)(999).first); EXPECT_EQ(b.rbegin()->second, Generator<value_type>(1000)(999).second); } template <typename T> void BtreeMultiMapTest() { using mapped_type = typename T::mapped_type; mapped_type m = Generator<mapped_type>(0)(0); (void)m; } template <typename K, int N = 256> void SetTest() { EXPECT_EQ( sizeof(absl::btree_set<K>), 2 * sizeof(void *) + sizeof(typename absl::btree_set<K>::size_type)); using BtreeSet = absl::btree_set<K>; BtreeTest<BtreeSet, std::set<K>>(); } template <typename K, int N = 256> void MapTest() { EXPECT_EQ( sizeof(absl::btree_map<K, K>), 2 * sizeof(void *) + sizeof(typename absl::btree_map<K, K>::size_type)); using BtreeMap = absl::btree_map<K, K>; BtreeTest<BtreeMap, std::map<K, K>>(); BtreeMapTest<BtreeMap>(); } TEST(Btree, set_int32) { SetTest<int32_t>(); } TEST(Btree, set_string) { SetTest<std::string>(); } TEST(Btree, set_cord) { SetTest<absl::Cord>(); } TEST(Btree, map_int32) { MapTest<int32_t>(); } TEST(Btree, map_string) { MapTest<std::string>(); } TEST(Btree, map_cord) { MapTest<absl::Cord>(); } template <typename K, int N = 256> void MultiSetTest() { EXPECT_EQ( sizeof(absl::btree_multiset<K>), 2 * sizeof(void *) + sizeof(typename absl::btree_multiset<K>::size_type)); using BtreeMSet = absl::btree_multiset<K>; BtreeMultiTest<BtreeMSet, std::multiset<K>>(); } template <typename K, int N = 256> void MultiMapTest() { EXPECT_EQ(sizeof(absl::btree_multimap<K, K>), 2 * sizeof(void *) + sizeof(typename absl::btree_multimap<K, K>::size_type)); using BtreeMMap = absl::btree_multimap<K, K>; BtreeMultiTest<BtreeMMap, std::multimap<K, K>>(); BtreeMultiMapTest<BtreeMMap>(); } TEST(Btree, multiset_int32) { MultiSetTest<int32_t>(); } TEST(Btree, multiset_string) { MultiSetTest<std::string>(); } TEST(Btree, multiset_cord) { MultiSetTest<absl::Cord>(); } TEST(Btree, multimap_int32) { MultiMapTest<int32_t>(); } TEST(Btree, multimap_string) { MultiMapTest<std::string>(); } TEST(Btree, multimap_cord) { MultiMapTest<absl::Cord>(); } 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 < absl::StrCat(b); } bool operator()(int a, const std::string &b) const { return absl::StrCat(a) < b; } using is_transparent = void; }; struct NonTransparentCompare { template <typename T, typename U> bool operator()(const T &t, const U &u) const { EXPECT_TRUE((std::is_same<T, U>())); return t < u; } }; template <typename T> bool CanEraseWithEmptyBrace(T t, decltype(t.erase({})) *) { return true; } template <typename T> bool CanEraseWithEmptyBrace(T, ...) { return false; } template <typename T> void TestHeterogeneous(T table) { auto lb = table.lower_bound("3"); EXPECT_EQ(lb, table.lower_bound(3)); EXPECT_NE(lb, table.lower_bound(4)); EXPECT_EQ(lb, table.lower_bound({"3"})); EXPECT_NE(lb, table.lower_bound({})); auto ub = table.upper_bound("3"); EXPECT_EQ(ub, table.upper_bound(3)); EXPECT_NE(ub, table.upper_bound(5)); EXPECT_EQ(ub, table.upper_bound({"3"})); EXPECT_NE(ub, table.upper_bound({})); auto er = table.equal_range("3"); EXPECT_EQ(er, table.equal_range(3)); EXPECT_NE(er, table.equal_range(4)); EXPECT_EQ(er, table.equal_range({"3"})); EXPECT_NE(er, table.equal_range({})); auto it = table.find("3"); EXPECT_EQ(it, table.find(3)); EXPECT_NE(it, table.find(4)); EXPECT_EQ(it, table.find({"3"})); EXPECT_NE(it, table.find({})); EXPECT_TRUE(table.contains(3)); EXPECT_FALSE(table.contains(4)); EXPECT_TRUE(table.count({"3"})); EXPECT_FALSE(table.contains({})); EXPECT_EQ(1, table.count(3)); EXPECT_EQ(0, table.count(4)); EXPECT_EQ(1, table.count({"3"})); EXPECT_EQ(0, table.count({})); auto copy = table; copy.erase(3); EXPECT_EQ(table.size() - 1, copy.size()); copy.erase(4); EXPECT_EQ(table.size() - 1, copy.size()); copy.erase({"5"}); EXPECT_EQ(table.size() - 2, copy.size()); EXPECT_FALSE(CanEraseWithEmptyBrace(table, nullptr)); if (std::is_class<T>()) TestHeterogeneous<const T &>(table); } TEST(Btree, HeterogeneousLookup) { TestHeterogeneous(btree_set<std::string, CompareIntToString>{"1", "3", "5"}); TestHeterogeneous(btree_map<std::string, int, CompareIntToString>{ {"1", 1}, {"3", 3}, {"5", 5}}); TestHeterogeneous( btree_multiset<std::string, CompareIntToString>{"1", "3", "5"}); TestHeterogeneous(btree_multimap<std::string, int, CompareIntToString>{ {"1", 1}, {"3", 3}, {"5", 5}}); btree_map<std::string, int, CompareIntToString> map{ {"", -1}, {"1", 1}, {"3", 3}, {"5", 5}}; EXPECT_EQ(1, map.at(1)); EXPECT_EQ(3, map.at({"3"})); EXPECT_EQ(-1, map.at({})); const auto &cmap = map; EXPECT_EQ(1, cmap.at(1)); EXPECT_EQ(3, cmap.at({"3"})); EXPECT_EQ(-1, cmap.at({})); } TEST(Btree, NoHeterogeneousLookupWithoutAlias) { using StringSet = absl::btree_set<std::string, NonTransparentCompare>; StringSet s; ASSERT_TRUE(s.insert("hello").second); ASSERT_TRUE(s.insert("world").second); EXPECT_TRUE(s.end() == s.find("blah")); EXPECT_TRUE(s.begin() == s.lower_bound("hello")); EXPECT_EQ(1, s.count("world")); EXPECT_TRUE(s.contains("hello")); EXPECT_TRUE(s.contains("world")); EXPECT_FALSE(s.contains("blah")); using StringMultiSet = absl::btree_multiset<std::string, NonTransparentCompare>; StringMultiSet ms; ms.insert("hello"); ms.insert("world"); ms.insert("world"); EXPECT_TRUE(ms.end() == ms.find("blah")); EXPECT_TRUE(ms.begin() == ms.lower_bound("hello")); EXPECT_EQ(2, ms.count("world")); EXPECT_TRUE(ms.contains("hello")); EXPECT_TRUE(ms.contains("world")); EXPECT_FALSE(ms.contains("blah")); } TEST(Btree, DefaultTransparent) { { btree_set<int> s = {1}; double d = 1.1; EXPECT_EQ(s.begin(), s.find(d)); EXPECT_TRUE(s.contains(d)); } { btree_set<std::string> s = {"A"}; EXPECT_EQ(s.begin(), s.find(absl::string_view("A"))); EXPECT_TRUE(s.contains(absl::string_view("A"))); } } class StringLike { public: StringLike() = default; StringLike(const char *s) : s_(s) { ++constructor_calls_; } bool operator<(const StringLike &a) const { return s_ < a.s_; } static void clear_constructor_call_count() { constructor_calls_ = 0; } static int constructor_calls() { return constructor_calls_; } private: static int constructor_calls_; std::string s_; }; int StringLike::constructor_calls_ = 0; TEST(Btree, HeterogeneousLookupDoesntDegradePerformance) { using StringSet = absl::btree_set<StringLike>; StringSet s; for (int i = 0; i < 100; ++i) { ASSERT_TRUE(s.insert(absl::StrCat(i).c_str()).second); } StringLike::clear_constructor_call_count(); s.find("50"); ASSERT_EQ(1, StringLike::constructor_calls()); StringLike::clear_constructor_call_count(); s.contains("50"); ASSERT_EQ(1, StringLike::constructor_calls()); StringLike::clear_constructor_call_count(); s.count("50"); ASSERT_EQ(1, StringLike::constructor_calls()); StringLike::clear_constructor_call_count(); s.lower_bound("50"); ASSERT_EQ(1, StringLike::constructor_calls()); StringLike::clear_constructor_call_count(); s.upper_bound("50"); ASSERT_EQ(1, StringLike::constructor_calls()); StringLike::clear_constructor_call_count(); s.equal_range("50"); ASSERT_EQ(1, StringLike::constructor_calls()); StringLike::clear_constructor_call_count(); s.erase("50"); ASSERT_EQ(1, StringLike::constructor_calls()); } struct SubstringLess { SubstringLess() = delete; explicit SubstringLess(int length) : n(length) {} bool operator()(const std::string &a, const std::string &b) const { return absl::string_view(a).substr(0, n) < absl::string_view(b).substr(0, n); } int n; }; TEST(Btree, SwapKeyCompare) { using SubstringSet = absl::btree_set<std::string, SubstringLess>; SubstringSet s1(SubstringLess(1), SubstringSet::allocator_type()); SubstringSet s2(SubstringLess(2), SubstringSet::allocator_type()); ASSERT_TRUE(s1.insert("a").second); ASSERT_FALSE(s1.insert("aa").second); ASSERT_TRUE(s2.insert("a").second); ASSERT_TRUE(s2.insert("aa").second); ASSERT_FALSE(s2.insert("aaa").second); swap(s1, s2); ASSERT_TRUE(s1.insert("b").second); ASSERT_TRUE(s1.insert("bb").second); ASSERT_FALSE(s1.insert("bbb").second); ASSERT_TRUE(s2.insert("b").second); ASSERT_FALSE(s2.insert("bb").second); } TEST(Btree, UpperBoundRegression) { using SubstringSet = absl::btree_set<std::string, SubstringLess>; SubstringSet my_set(SubstringLess(3)); my_set.insert("aab"); my_set.insert("abb"); SubstringSet::iterator it = my_set.upper_bound("aaa"); ASSERT_TRUE(it != my_set.end()); EXPECT_EQ("aab", *it); } TEST(Btree, Comparison) { const int kSetSize = 1201; absl::btree_set<int64_t> my_set; for (int i = 0; i < kSetSize; ++i) { my_set.insert(i); } absl::btree_set<int64_t> my_set_copy(my_set); EXPECT_TRUE(my_set_copy == my_set); EXPECT_TRUE(my_set == my_set_copy); EXPECT_FALSE(my_set_copy != my_set); EXPECT_FALSE(my_set != my_set_copy); my_set.insert(kSetSize); EXPECT_FALSE(my_set_copy == my_set); EXPECT_FALSE(my_set == my_set_copy); EXPECT_TRUE(my_set_copy != my_set); EXPECT_TRUE(my_set != my_set_copy); my_set.erase(kSetSize - 1); EXPECT_FALSE(my_set_copy == my_set); EXPECT_FALSE(my_set == my_set_copy); EXPECT_TRUE(my_set_copy != my_set); EXPECT_TRUE(my_set != my_set_copy); absl::btree_map<std::string, int64_t> my_map; for (int i = 0; i < kSetSize; ++i) { my_map[std::string(i, 'a')] = i; } absl::btree_map<std::string, int64_t> my_map_copy(my_map); EXPECT_TRUE(my_map_copy == my_map); EXPECT_TRUE(my_map == my_map_copy); EXPECT_FALSE(my_map_copy != my_map); EXPECT_FALSE(my_map != my_map_copy); ++my_map_copy[std::string(7, 'a')]; EXPECT_FALSE(my_map_copy == my_map); EXPECT_FALSE(my_map == my_map_copy); EXPECT_TRUE(my_map_copy != my_map); EXPECT_TRUE(my_map != my_map_copy); my_map_copy = my_map; my_map["hello"] = kSetSize; EXPECT_FALSE(my_map_copy == my_map); EXPECT_FALSE(my_map == my_map_copy); EXPECT_TRUE(my_map_copy != my_map); EXPECT_TRUE(my_map != my_map_copy); my_map.erase(std::string(kSetSize - 1, 'a')); EXPECT_FALSE(my_map_copy == my_map); EXPECT_FALSE(my_map == my_map_copy); EXPECT_TRUE(my_map_copy != my_map); EXPECT_TRUE(my_map != my_map_copy); } TEST(Btree, RangeCtorSanity) { std::vector<int> ivec; ivec.push_back(1); std::map<int, int> imap; imap.insert(std::make_pair(1, 2)); absl::btree_multiset<int> tmset(ivec.begin(), ivec.end()); absl::btree_multimap<int, int> tmmap(imap.begin(), imap.end()); absl::btree_set<int> tset(ivec.begin(), ivec.end()); absl::btree_map<int, int> tmap(imap.begin(), imap.end()); EXPECT_EQ(1, tmset.size()); EXPECT_EQ(1, tmmap.size()); EXPECT_EQ(1, tset.size()); EXPECT_EQ(1, tmap.size()); } } class BtreeNodePeer { public: template <typename ValueType> constexpr static size_t GetTargetNodeSize(size_t target_values_per_node) { return btree_node< set_params<ValueType, std::less<ValueType>, std::allocator<ValueType>, 256, false>>::SizeWithNSlots(target_values_per_node); } template <typename Btree> constexpr static size_t GetNumSlotsPerNode() { return btree_node<typename Btree::params_type>::kNodeSlots; } template <typename Btree> constexpr static size_t GetMaxFieldType() { return std::numeric_limits< typename btree_node<typename Btree::params_type>::field_type>::max(); } template <typename Btree> constexpr static bool UsesLinearNodeSearch() { return btree_node<typename Btree::params_type>::use_linear_search::value; } template <typename Btree> constexpr static bool FieldTypeEqualsSlotType() { return std::is_same< typename btree_node<typename Btree::params_type>::field_type, typename btree_node<typename Btree::params_type>::slot_type>::value; } }; namespace { class BtreeMapTest : public ::testing::Test { public: struct Key {}; struct Cmp { template <typename T> bool operator()(T, T) const { return false; } }; struct KeyLin { using absl_btree_prefer_linear_node_search = std::true_type; }; struct CmpLin : Cmp { using absl_btree_prefer_linear_node_search = std::true_type; }; struct KeyBin { using absl_btree_prefer_linear_node_search = std::false_type; }; struct CmpBin : Cmp { using absl_btree_prefer_linear_node_search = std::false_type; }; template <typename K, typename C> static bool IsLinear() { return BtreeNodePeer::UsesLinearNodeSearch<absl::btree_map<K, int, C>>(); } }; TEST_F(BtreeMapTest, TestLinearSearchPreferredForKeyLinearViaAlias) { EXPECT_FALSE((IsLinear<Key, Cmp>())); EXPECT_TRUE((IsLinear<KeyLin, Cmp>())); EXPECT_TRUE((IsLinear<Key, CmpLin>())); EXPECT_TRUE((IsLinear<KeyLin, CmpLin>())); } TEST_F(BtreeMapTest, LinearChoiceTree) { EXPECT_FALSE((IsLinear<Key, CmpBin>())); EXPECT_FALSE((IsLinear<KeyLin, CmpBin>())); EXPECT_FALSE((IsLinear<KeyBin, CmpBin>())); EXPECT_FALSE((IsLinear<int, CmpBin>())); EXPECT_FALSE((IsLinear<std::string, CmpBin>())); EXPECT_TRUE((IsLinear<Key, CmpLin>())); EXPECT_TRUE((IsLinear<KeyLin, CmpLin>())); EXPECT_TRUE((IsLinear<KeyBin, CmpLin>())); EXPECT_TRUE((IsLinear<int, CmpLin>())); EXPECT_TRUE((IsLinear<std::string, CmpLin>())); EXPECT_FALSE((IsLinear<Key, Cmp>())); EXPECT_TRUE((IsLinear<KeyLin, Cmp>())); EXPECT_FALSE((IsLinear<KeyBin, Cmp>())); EXPECT_TRUE((IsLinear<int, std::less<int>>())); EXPECT_TRUE((IsLinear<double, std::greater<double>>())); EXPECT_FALSE((IsLinear<int, Cmp>())); EXPECT_FALSE((IsLinear<std::string, std::less<std::string>>())); } TEST(Btree, BtreeMapCanHoldMoveOnlyTypes) { absl::btree_map<std::string, std::unique_ptr<std::string>> m; std::unique_ptr<std::string> &v = m["A"]; EXPECT_TRUE(v == nullptr); v = absl::make_unique<std::string>("X"); auto iter = m.find("A"); EXPECT_EQ("X", *iter->second); } TEST(Btree, InitializerListConstructor) { absl::btree_set<std::string> set({"a", "b"}); EXPECT_EQ(set.count("a"), 1); EXPECT_EQ(set.count("b"), 1); absl::btree_multiset<int> mset({1, 1, 4}); EXPECT_EQ(mset.count(1), 2); EXPECT_EQ(mset.count(4), 1); absl::btree_map<int, int> map({{1, 5}, {2, 10}}); EXPECT_EQ(map[1], 5); EXPECT_EQ(map[2], 10); absl::btree_multimap<int, int> mmap({{1, 5}, {1, 10}}); auto range = mmap.equal_range(1); auto it = range.first; ASSERT_NE(it, range.second); EXPECT_EQ(it->second, 5); ASSERT_NE(++it, range.second); EXPECT_EQ(it->second, 10); EXPECT_EQ(++it, range.second); } TEST(Btree, InitializerListInsert) { absl::btree_set<std::string> set; set.insert({"a", "b"}); EXPECT_EQ(set.count("a"), 1); EXPECT_EQ(set.count("b"), 1); absl::btree_multiset<int> mset; mset.insert({1, 1, 4}); EXPECT_EQ(mset.count(1), 2); EXPECT_EQ(mset.count(4), 1); absl::btree_map<int, int> map; map.insert({{1, 5}, {2, 10}}); map.insert({3, 15}); EXPECT_EQ(map[1], 5); EXPECT_EQ(map[2], 10); EXPECT_EQ(map[3], 15); absl::btree_multimap<int, int> mmap; mmap.insert({{1, 5}, {1, 10}}); auto range = mmap.equal_range(1); auto it = range.first; ASSERT_NE(it, range.second); EXPECT_EQ(it->second, 5); ASSERT_NE(++it, range.second); EXPECT_EQ(it->second, 10); EXPECT_EQ(++it, range.second); } template <typename Compare, typename Key> void AssertKeyCompareStringAdapted() { using Adapted = typename key_compare_adapter<Compare, Key>::type; static_assert( std::is_same<Adapted, StringBtreeDefaultLess>::value || std::is_same<Adapted, StringBtreeDefaultGreater>::value, "key_compare_adapter should have string-adapted this comparator."); } template <typename Compare, typename Key> void AssertKeyCompareNotStringAdapted() { using Adapted = typename key_compare_adapter<Compare, Key>::type; static_assert( !std::is_same<Adapted, StringBtreeDefaultLess>::value && !std::is_same<Adapted, StringBtreeDefaultGreater>::value, "key_compare_adapter shouldn't have string-adapted this comparator."); } TEST(Btree, KeyCompareAdapter) { AssertKeyCompareStringAdapted<std::less<std::string>, std::string>(); AssertKeyCompareStringAdapted<std::greater<std::string>, std::string>(); AssertKeyCompareStringAdapted<std::less<absl::string_view>, absl::string_view>(); AssertKeyCompareStringAdapted<std::greater<absl::string_view>, absl::string_view>(); AssertKeyCompareStringAdapted<std::less<absl::Cord>, absl::Cord>(); AssertKeyCompareStringAdapted<std::greater<absl::Cord>, absl::Cord>(); AssertKeyCompareNotStringAdapted<std::less<int>, int>(); AssertKeyCompareNotStringAdapted<std::greater<int>, int>(); } TEST(Btree, RValueInsert) { InstanceTracker tracker; absl::btree_set<MovableOnlyInstance> set; set.insert(MovableOnlyInstance(1)); set.insert(MovableOnlyInstance(3)); MovableOnlyInstance two(2); set.insert(set.find(MovableOnlyInstance(3)), std::move(two)); auto it = set.find(MovableOnlyInstance(2)); ASSERT_NE(it, set.end()); ASSERT_NE(++it, set.end()); EXPECT_EQ(it->value(), 3); absl::btree_multiset<MovableOnlyInstance> mset; MovableOnlyInstance zero(0); MovableOnlyInstance zero2(0); mset.insert(std::move(zero)); mset.insert(mset.find(MovableOnlyInstance(0)), std::move(zero2)); EXPECT_EQ(mset.count(MovableOnlyInstance(0)), 2); absl::btree_map<int, MovableOnlyInstance> map; std::pair<const int, MovableOnlyInstance> p1 = {1, MovableOnlyInstance(5)}; std::pair<const int, MovableOnlyInstance> p2 = {2, MovableOnlyInstance(10)}; std::pair<const int, MovableOnlyInstance> p3 = {3, MovableOnlyInstance(15)}; map.insert(std::move(p1)); map.insert(std::move(p3)); map.insert(map.find(3), std::move(p2)); ASSERT_NE(map.find(2), map.end()); EXPECT_EQ(map.find(2)->second.value(), 10); absl::btree_multimap<int, MovableOnlyInstance> mmap; std::pair<const int, MovableOnlyInstance> p4 = {1, MovableOnlyInstance(5)}; std::pair<const int, MovableOnlyInstance> p5 = {1, MovableOnlyInstance(10)}; mmap.insert(std::move(p4)); mmap.insert(mmap.find(1), std::move(p5)); auto range = mmap.equal_range(1); auto it1 = range.first; ASSERT_NE(it1, range.second); EXPECT_EQ(it1->second.value(), 10); ASSERT_NE(++it1, range.second); EXPECT_EQ(it1->second.value(), 5); EXPECT_EQ(++it1, range.second); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.swaps(), 0); } template <typename Cmp> struct CheckedCompareOptedOutCmp : Cmp, BtreeTestOnlyCheckedCompareOptOutBase { using Cmp::Cmp; CheckedCompareOptedOutCmp() {} CheckedCompareOptedOutCmp(Cmp cmp) : Cmp(std::move(cmp)) {} }; template <typename Key, int TargetValuesPerNode, typename Cmp = std::less<Key>> class SizedBtreeSet : public btree_set_container<btree< set_params<Key, CheckedCompareOptedOutCmp<Cmp>, std::allocator<Key>, BtreeNodePeer::GetTargetNodeSize<Key>(TargetValuesPerNode), false>>> { using Base = typename SizedBtreeSet::btree_set_container; public: SizedBtreeSet() = default; using Base::Base; }; template <typename Set> void ExpectOperationCounts(const int expected_moves, const int expected_comparisons, const std::vector<int> &values, InstanceTracker *tracker, Set *set) { for (const int v : values) set->insert(MovableOnlyInstance(v)); set->clear(); EXPECT_EQ(tracker->moves(), expected_moves); EXPECT_EQ(tracker->comparisons(), expected_comparisons); EXPECT_EQ(tracker->copies(), 0); EXPECT_EQ(tracker->swaps(), 0); tracker->ResetCopiesMovesSwaps(); } #if defined(ABSL_HAVE_ADDRESS_SANITIZER) || \ defined(ABSL_HAVE_HWADDRESS_SANITIZER) constexpr bool kAsan = true; #else constexpr bool kAsan = false; #endif TEST(Btree, MovesComparisonsCopiesSwapsTracking) { if (kAsan) GTEST_SKIP() << "We do extra operations in ASan mode."; InstanceTracker tracker; SizedBtreeSet<MovableOnlyInstance, 4> set4; SizedBtreeSet<MovableOnlyInstance, 61> set61; SizedBtreeSet<MovableOnlyInstance, 100> set100; std::vector<int> values = GenerateValuesWithSeed<int>(10000, 1 << 22, 23); EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<decltype(set4)>(), 4); EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<decltype(set61)>(), 61); EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<decltype(set100)>(), 100); if (sizeof(void *) == 8) { EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<absl::btree_set<int32_t>>(), BtreeGenerationsEnabled() ? 60 : 61); } ExpectOperationCounts(56540, 134212, values, &tracker, &set4); ExpectOperationCounts(386718, 129807, values, &tracker, &set61); ExpectOperationCounts(586761, 130310, values, &tracker, &set100); std::sort(values.begin(), values.end()); ExpectOperationCounts(24972, 85563, values, &tracker, &set4); ExpectOperationCounts(20208, 87757, values, &tracker, &set61); ExpectOperationCounts(20124, 96583, values, &tracker, &set100); std::reverse(values.begin(), values.end()); ExpectOperationCounts(54949, 127531, values, &tracker, &set4); ExpectOperationCounts(338813, 118266, values, &tracker, &set61); ExpectOperationCounts(534529, 125279, values, &tracker, &set100); } struct MovableOnlyInstanceThreeWayCompare { absl::weak_ordering operator()(const MovableOnlyInstance &a, const MovableOnlyInstance &b) const { return a.compare(b); } }; TEST(Btree, MovesComparisonsCopiesSwapsTrackingThreeWayCompare) { if (kAsan) GTEST_SKIP() << "We do extra operations in ASan mode."; InstanceTracker tracker; SizedBtreeSet<MovableOnlyInstance, 4, MovableOnlyInstanceThreeWayCompare> set4; SizedBtreeSet<MovableOnlyInstance, 61, MovableOnlyInstanceThreeWayCompare> set61; SizedBtreeSet<MovableOnlyInstance, 100, MovableOnlyInstanceThreeWayCompare> set100; std::vector<int> values = GenerateValuesWithSeed<int>(10000, 1 << 22, 23); EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<decltype(set4)>(), 4); EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<decltype(set61)>(), 61); EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<decltype(set100)>(), 100); if (sizeof(void *) == 8) { EXPECT_EQ(BtreeNodePeer::GetNumSlotsPerNode<absl::btree_set<int32_t>>(), BtreeGenerationsEnabled() ? 60 : 61); } ExpectOperationCounts(56540, 124221, values, &tracker, &set4); ExpectOperationCounts(386718, 119816, values, &tracker, &set61); ExpectOperationCounts(586761, 120319, values, &tracker, &set100); std::sort(values.begin(), values.end()); ExpectOperationCounts(24972, 85563, values, &tracker, &set4); ExpectOperationCounts(20208, 87757, values, &tracker, &set61); ExpectOperationCounts(20124, 96583, values, &tracker, &set100); std::reverse(values.begin(), values.end()); ExpectOperationCounts(54949, 117532, values, &tracker, &set4); ExpectOperationCounts(338813, 108267, values, &tracker, &set61); ExpectOperationCounts(534529, 115280, values, &tracker, &set100); } struct NoDefaultCtor { int num; explicit NoDefaultCtor(int i) : num(i) {} friend bool operator<(const NoDefaultCtor &a, const NoDefaultCtor &b) { return a.num < b.num; } }; TEST(Btree, BtreeMapCanHoldNoDefaultCtorTypes) { absl::btree_map<NoDefaultCtor, NoDefaultCtor> m; for (int i = 1; i <= 99; ++i) { SCOPED_TRACE(i); EXPECT_TRUE(m.emplace(NoDefaultCtor(i), NoDefaultCtor(100 - i)).second); } EXPECT_FALSE(m.emplace(NoDefaultCtor(78), NoDefaultCtor(0)).second); auto iter99 = m.find(NoDefaultCtor(99)); ASSERT_NE(iter99, m.end()); EXPECT_EQ(iter99->second.num, 1); auto iter1 = m.find(NoDefaultCtor(1)); ASSERT_NE(iter1, m.end()); EXPECT_EQ(iter1->second.num, 99); auto iter50 = m.find(NoDefaultCtor(50)); ASSERT_NE(iter50, m.end()); EXPECT_EQ(iter50->second.num, 50); auto iter25 = m.find(NoDefaultCtor(25)); ASSERT_NE(iter25, m.end()); EXPECT_EQ(iter25->second.num, 75); } TEST(Btree, BtreeMultimapCanHoldNoDefaultCtorTypes) { absl::btree_multimap<NoDefaultCtor, NoDefaultCtor> m; for (int i = 1; i <= 99; ++i) { SCOPED_TRACE(i); m.emplace(NoDefaultCtor(i), NoDefaultCtor(100 - i)); } auto iter99 = m.find(NoDefaultCtor(99)); ASSERT_NE(iter99, m.end()); EXPECT_EQ(iter99->second.num, 1); auto iter1 = m.find(NoDefaultCtor(1)); ASSERT_NE(iter1, m.end()); EXPECT_EQ(iter1->second.num, 99); auto iter50 = m.find(NoDefaultCtor(50)); ASSERT_NE(iter50, m.end()); EXPECT_EQ(iter50->second.num, 50); auto iter25 = m.find(NoDefaultCtor(25)); ASSERT_NE(iter25, m.end()); EXPECT_EQ(iter25->second.num, 75); } TEST(Btree, MapAt) { absl::btree_map<int, int> map = {{1, 2}, {2, 4}}; EXPECT_EQ(map.at(1), 2); EXPECT_EQ(map.at(2), 4); map.at(2) = 8; const absl::btree_map<int, int> &const_map = map; EXPECT_EQ(const_map.at(1), 2); EXPECT_EQ(const_map.at(2), 8); #ifdef ABSL_HAVE_EXCEPTIONS EXPECT_THROW(map.at(3), std::out_of_range); #else EXPECT_DEATH_IF_SUPPORTED(map.at(3), "absl::btree_map::at"); #endif } TEST(Btree, BtreeMultisetEmplace) { const int value_to_insert = 123456; absl::btree_multiset<int> s; auto iter = s.emplace(value_to_insert); ASSERT_NE(iter, s.end()); EXPECT_EQ(*iter, value_to_insert); iter = s.emplace(value_to_insert); ASSERT_NE(iter, s.end()); EXPECT_EQ(*iter, value_to_insert); auto result = s.equal_range(value_to_insert); EXPECT_EQ(std::distance(result.first, result.second), 2); } TEST(Btree, BtreeMultisetEmplaceHint) { const int value_to_insert = 123456; absl::btree_multiset<int> s; auto iter = s.emplace(value_to_insert); ASSERT_NE(iter, s.end()); EXPECT_EQ(*iter, value_to_insert); iter = s.emplace_hint(iter, value_to_insert); EXPECT_EQ(iter, s.lower_bound(value_to_insert)); ASSERT_NE(iter, s.end()); EXPECT_EQ(*iter, value_to_insert); } TEST(Btree, BtreeMultimapEmplace) { const int key_to_insert = 123456; const char value0[] = "a"; absl::btree_multimap<int, std::string> m; auto iter = m.emplace(key_to_insert, value0); ASSERT_NE(iter, m.end()); EXPECT_EQ(iter->first, key_to_insert); EXPECT_EQ(iter->second, value0); const char value1[] = "b"; iter = m.emplace(key_to_insert, value1); ASSERT_NE(iter, m.end()); EXPECT_EQ(iter->first, key_to_insert); EXPECT_EQ(iter->second, value1); auto result = m.equal_range(key_to_insert); EXPECT_EQ(std::distance(result.first, result.second), 2); } TEST(Btree, BtreeMultimapEmplaceHint) { const int key_to_insert = 123456; const char value0[] = "a"; absl::btree_multimap<int, std::string> m; auto iter = m.emplace(key_to_insert, value0); ASSERT_NE(iter, m.end()); EXPECT_EQ(iter->first, key_to_insert); EXPECT_EQ(iter->second, value0); const char value1[] = "b"; iter = m.emplace_hint(iter, key_to_insert, value1); EXPECT_EQ(iter, m.lower_bound(key_to_insert)); ASSERT_NE(iter, m.end()); EXPECT_EQ(iter->first, key_to_insert); EXPECT_EQ(iter->second, value1); } TEST(Btree, ConstIteratorAccessors) { absl::btree_set<int> set; for (int i = 0; i < 100; ++i) { set.insert(i); } auto it = set.cbegin(); auto r_it = set.crbegin(); for (int i = 0; i < 100; ++i, ++it, ++r_it) { ASSERT_EQ(*it, i); ASSERT_EQ(*r_it, 99 - i); } EXPECT_EQ(it, set.cend()); EXPECT_EQ(r_it, set.crend()); } TEST(Btree, StrSplitCompatible) { const absl::btree_set<std::string> split_set = absl::StrSplit("a,b,c", ','); const absl::btree_set<std::string> expected_set = {"a", "b", "c"}; EXPECT_EQ(split_set, expected_set); } TEST(Btree, KeyComp) { absl::btree_set<int> s; EXPECT_TRUE(s.key_comp()(1, 2)); EXPECT_FALSE(s.key_comp()(2, 2)); EXPECT_FALSE(s.key_comp()(2, 1)); absl::btree_map<int, int> m1; EXPECT_TRUE(m1.key_comp()(1, 2)); EXPECT_FALSE(m1.key_comp()(2, 2)); EXPECT_FALSE(m1.key_comp()(2, 1)); absl::btree_map<std::string, int> m2; EXPECT_TRUE(m2.key_comp()("a", "b")); EXPECT_FALSE(m2.key_comp()("b", "b")); EXPECT_FALSE(m2.key_comp()("b", "a")); } TEST(Btree, ValueComp) { absl::btree_set<int> s; EXPECT_TRUE(s.value_comp()(1, 2)); EXPECT_FALSE(s.value_comp()(2, 2)); EXPECT_FALSE(s.value_comp()(2, 1)); absl::btree_map<int, int> m1; EXPECT_TRUE(m1.value_comp()(std::make_pair(1, 0), std::make_pair(2, 0))); EXPECT_FALSE(m1.value_comp()(std::make_pair(2, 0), std::make_pair(2, 0))); EXPECT_FALSE(m1.value_comp()(std::make_pair(2, 0), std::make_pair(1, 0))); absl::btree_map<std::string, int> m2; EXPECT_TRUE(m2.value_comp()(std::make_pair("a", 0), std::make_pair("b", 0))); EXPECT_FALSE(m2.value_comp()(std::make_pair("b", 0), std::make_pair("b", 0))); EXPECT_FALSE(m2.value_comp()(std::make_pair("b", 0), std::make_pair("a", 0))); } TEST(Btree, MapValueCompProtected) { struct key_compare { bool operator()(int l, int r) const { return l < r; } int id; }; using value_compare = absl::btree_map<int, int, key_compare>::value_compare; struct value_comp_child : public value_compare { explicit value_comp_child(key_compare kc) : value_compare(kc) {} int GetId() const { return comp.id; } }; value_comp_child c(key_compare{10}); EXPECT_EQ(c.GetId(), 10); } TEST(Btree, DefaultConstruction) { absl::btree_set<int> s; absl::btree_map<int, int> m; absl::btree_multiset<int> ms; absl::btree_multimap<int, int> mm; EXPECT_TRUE(s.empty()); EXPECT_TRUE(m.empty()); EXPECT_TRUE(ms.empty()); EXPECT_TRUE(mm.empty()); } TEST(Btree, SwissTableHashable) { static constexpr int kValues = 10000; std::vector<int> values(kValues); std::iota(values.begin(), values.end(), 0); std::vector<std::pair<int, int>> map_values; for (int v : values) map_values.emplace_back(v, -v); using set = absl::btree_set<int>; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({ set{}, set{1}, set{2}, set{1, 2}, set{2, 1}, set(values.begin(), values.end()), set(values.rbegin(), values.rend()), })); using mset = absl::btree_multiset<int>; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({ mset{}, mset{1}, mset{1, 1}, mset{2}, mset{2, 2}, mset{1, 2}, mset{1, 1, 2}, mset{1, 2, 2}, mset{1, 1, 2, 2}, mset(values.begin(), values.end()), mset(values.rbegin(), values.rend()), })); using map = absl::btree_map<int, int>; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({ map{}, map{{1, 0}}, map{{1, 1}}, map{{2, 0}}, map{{2, 2}}, map{{1, 0}, {2, 1}}, map(map_values.begin(), map_values.end()), map(map_values.rbegin(), map_values.rend()), })); using mmap = absl::btree_multimap<int, int>; EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly({ mmap{}, mmap{{1, 0}}, mmap{{1, 1}}, mmap{{1, 0}, {1, 1}}, mmap{{1, 1}, {1, 0}}, mmap{{2, 0}}, mmap{{2, 2}}, mmap{{1, 0}, {2, 1}}, mmap(map_values.begin(), map_values.end()), mmap(map_values.rbegin(), map_values.rend()), })); } TEST(Btree, ComparableSet) { absl::btree_set<int> s1 = {1, 2}; absl::btree_set<int> s2 = {2, 3}; EXPECT_LT(s1, s2); EXPECT_LE(s1, s2); EXPECT_LE(s1, s1); EXPECT_GT(s2, s1); EXPECT_GE(s2, s1); EXPECT_GE(s1, s1); } TEST(Btree, ComparableSetsDifferentLength) { absl::btree_set<int> s1 = {1, 2}; absl::btree_set<int> s2 = {1, 2, 3}; EXPECT_LT(s1, s2); EXPECT_LE(s1, s2); EXPECT_GT(s2, s1); EXPECT_GE(s2, s1); } TEST(Btree, ComparableMultiset) { absl::btree_multiset<int> s1 = {1, 2}; absl::btree_multiset<int> s2 = {2, 3}; EXPECT_LT(s1, s2); EXPECT_LE(s1, s2); EXPECT_LE(s1, s1); EXPECT_GT(s2, s1); EXPECT_GE(s2, s1); EXPECT_GE(s1, s1); } TEST(Btree, ComparableMap) { absl::btree_map<int, int> s1 = {{1, 2}}; absl::btree_map<int, int> s2 = {{2, 3}}; EXPECT_LT(s1, s2); EXPECT_LE(s1, s2); EXPECT_LE(s1, s1); EXPECT_GT(s2, s1); EXPECT_GE(s2, s1); EXPECT_GE(s1, s1); } TEST(Btree, ComparableMultimap) { absl::btree_multimap<int, int> s1 = {{1, 2}}; absl::btree_multimap<int, int> s2 = {{2, 3}}; EXPECT_LT(s1, s2); EXPECT_LE(s1, s2); EXPECT_LE(s1, s1); EXPECT_GT(s2, s1); EXPECT_GE(s2, s1); EXPECT_GE(s1, s1); } TEST(Btree, ComparableSetWithCustomComparator) { absl::btree_set<int, std::greater<int>> s1 = {1, 2}; absl::btree_set<int, std::greater<int>> s2 = {2, 3}; EXPECT_LT(s1, s2); EXPECT_LE(s1, s2); EXPECT_LE(s1, s1); EXPECT_GT(s2, s1); EXPECT_GE(s2, s1); EXPECT_GE(s1, s1); } TEST(Btree, EraseReturnsIterator) { absl::btree_set<int> set = {1, 2, 3, 4, 5}; auto result_it = set.erase(set.begin(), set.find(3)); EXPECT_EQ(result_it, set.find(3)); result_it = set.erase(set.find(5)); EXPECT_EQ(result_it, set.end()); } TEST(Btree, ExtractAndInsertNodeHandleSet) { absl::btree_set<int> src1 = {1, 2, 3, 4, 5}; auto nh = src1.extract(src1.find(3)); EXPECT_THAT(src1, ElementsAre(1, 2, 4, 5)); absl::btree_set<int> other; absl::btree_set<int>::insert_return_type res = other.insert(std::move(nh)); EXPECT_THAT(other, ElementsAre(3)); EXPECT_EQ(res.position, other.find(3)); EXPECT_TRUE(res.inserted); EXPECT_TRUE(res.node.empty()); absl::btree_set<int> src2 = {3, 4}; nh = src2.extract(src2.find(3)); EXPECT_THAT(src2, ElementsAre(4)); res = other.insert(std::move(nh)); EXPECT_THAT(other, ElementsAre(3)); EXPECT_EQ(res.position, other.find(3)); EXPECT_FALSE(res.inserted); ASSERT_FALSE(res.node.empty()); EXPECT_EQ(res.node.value(), 3); } template <typename Set> void TestExtractWithTrackingForSet() { InstanceTracker tracker; { Set s; const size_t kSize = 1000; while (s.size() < kSize) { s.insert(MovableOnlyInstance(s.size())); } for (int i = 0; i < kSize; ++i) { auto nh = s.extract(MovableOnlyInstance(i)); EXPECT_EQ(s.size(), kSize - 1); EXPECT_EQ(nh.value().value(), i); s.insert(std::move(nh)); EXPECT_EQ(s.size(), kSize); auto it = s.find(MovableOnlyInstance(i)); nh = s.extract(it); EXPECT_EQ(s.size(), kSize - 1); EXPECT_EQ(nh.value().value(), i); s.insert(s.begin(), std::move(nh)); EXPECT_EQ(s.size(), kSize); } } EXPECT_EQ(0, tracker.instances()); } template <typename Map> void TestExtractWithTrackingForMap() { InstanceTracker tracker; { Map m; const size_t kSize = 1000; while (m.size() < kSize) { m.insert( {CopyableMovableInstance(m.size()), MovableOnlyInstance(m.size())}); } for (int i = 0; i < kSize; ++i) { auto nh = m.extract(CopyableMovableInstance(i)); EXPECT_EQ(m.size(), kSize - 1); EXPECT_EQ(nh.key().value(), i); EXPECT_EQ(nh.mapped().value(), i); m.insert(std::move(nh)); EXPECT_EQ(m.size(), kSize); auto it = m.find(CopyableMovableInstance(i)); nh = m.extract(it); EXPECT_EQ(m.size(), kSize - 1); EXPECT_EQ(nh.key().value(), i); EXPECT_EQ(nh.mapped().value(), i); m.insert(m.begin(), std::move(nh)); EXPECT_EQ(m.size(), kSize); } } EXPECT_EQ(0, tracker.instances()); } TEST(Btree, ExtractTracking) { TestExtractWithTrackingForSet<absl::btree_set<MovableOnlyInstance>>(); TestExtractWithTrackingForSet<absl::btree_multiset<MovableOnlyInstance>>(); TestExtractWithTrackingForMap< absl::btree_map<CopyableMovableInstance, MovableOnlyInstance>>(); TestExtractWithTrackingForMap< absl::btree_multimap<CopyableMovableInstance, MovableOnlyInstance>>(); } TEST(Btree, ExtractAndInsertNodeHandleMultiSet) { absl::btree_multiset<int> src1 = {1, 2, 3, 3, 4, 5}; auto nh = src1.extract(src1.find(3)); EXPECT_THAT(src1, ElementsAre(1, 2, 3, 4, 5)); absl::btree_multiset<int> other; auto res = other.insert(std::move(nh)); EXPECT_THAT(other, ElementsAre(3)); EXPECT_EQ(res, other.find(3)); absl::btree_multiset<int> src2 = {3, 4}; nh = src2.extract(src2.find(3)); EXPECT_THAT(src2, ElementsAre(4)); res = other.insert(std::move(nh)); EXPECT_THAT(other, ElementsAre(3, 3)); EXPECT_EQ(res, ++other.find(3)); } TEST(Btree, ExtractAndInsertNodeHandleMap) { absl::btree_map<int, int> src1 = {{1, 2}, {3, 4}, {5, 6}}; auto nh = src1.extract(src1.find(3)); EXPECT_THAT(src1, ElementsAre(Pair(1, 2), Pair(5, 6))); absl::btree_map<int, int> other; absl::btree_map<int, int>::insert_return_type res = other.insert(std::move(nh)); EXPECT_THAT(other, ElementsAre(Pair(3, 4))); EXPECT_EQ(res.position, other.find(3)); EXPECT_TRUE(res.inserted); EXPECT_TRUE(res.node.empty()); absl::btree_map<int, int> src2 = {{3, 6}}; nh = src2.extract(src2.find(3)); EXPECT_TRUE(src2.empty()); res = other.insert(std::move(nh)); EXPECT_THAT(other, ElementsAre(Pair(3, 4))); EXPECT_EQ(res.position, other.find(3)); EXPECT_FALSE(res.inserted); ASSERT_FALSE(res.node.empty()); EXPECT_EQ(res.node.key(), 3); EXPECT_EQ(res.node.mapped(), 6); } TEST(Btree, ExtractAndInsertNodeHandleMultiMap) { absl::btree_multimap<int, int> src1 = {{1, 2}, {3, 4}, {5, 6}}; auto nh = src1.extract(src1.find(3)); EXPECT_THAT(src1, ElementsAre(Pair(1, 2), Pair(5, 6))); absl::btree_multimap<int, int> other; auto res = other.insert(std::move(nh)); EXPECT_THAT(other, ElementsAre(Pair(3, 4))); EXPECT_EQ(res, other.find(3)); absl::btree_multimap<int, int> src2 = {{3, 6}}; nh = src2.extract(src2.find(3)); EXPECT_TRUE(src2.empty()); res = other.insert(std::move(nh)); EXPECT_THAT(other, ElementsAre(Pair(3, 4), Pair(3, 6))); EXPECT_EQ(res, ++other.begin()); } TEST(Btree, ExtractMultiMapEquivalentKeys) { absl::btree_multimap<std::string, int> map; for (int i = 0; i < 100; ++i) { for (int j = 0; j < 100; ++j) { map.insert({absl::StrCat(i), j}); } } for (int i = 0; i < 100; ++i) { const std::string key = absl::StrCat(i); auto node_handle = map.extract(key); EXPECT_EQ(node_handle.key(), key); EXPECT_EQ(node_handle.mapped(), 0) << i; } for (int i = 0; i < 100; ++i) { const std::string key = absl::StrCat(i); auto node_handle = map.extract(key); EXPECT_EQ(node_handle.key(), key); EXPECT_EQ(node_handle.mapped(), 1) << i; } } TEST(Btree, ExtractAndGetNextSet) { absl::btree_set<int> src = {1, 2, 3, 4, 5}; auto it = src.find(3); auto extracted_and_next = src.extract_and_get_next(it); EXPECT_THAT(src, ElementsAre(1, 2, 4, 5)); EXPECT_EQ(extracted_and_next.node.value(), 3); EXPECT_EQ(*extracted_and_next.next, 4); } TEST(Btree, ExtractAndGetNextMultiSet) { absl::btree_multiset<int> src = {1, 2, 3, 4, 5}; auto it = src.find(3); auto extracted_and_next = src.extract_and_get_next(it); EXPECT_THAT(src, ElementsAre(1, 2, 4, 5)); EXPECT_EQ(extracted_and_next.node.value(), 3); EXPECT_EQ(*extracted_and_next.next, 4); } TEST(Btree, ExtractAndGetNextMap) { absl::btree_map<int, int> src = {{1, 2}, {3, 4}, {5, 6}}; auto it = src.find(3); auto extracted_and_next = src.extract_and_get_next(it); EXPECT_THAT(src, ElementsAre(Pair(1, 2), Pair(5, 6))); EXPECT_EQ(extracted_and_next.node.key(), 3); EXPECT_EQ(extracted_and_next.node.mapped(), 4); EXPECT_THAT(*extracted_and_next.next, Pair(5, 6)); } TEST(Btree, ExtractAndGetNextMultiMap) { absl::btree_multimap<int, int> src = {{1, 2}, {3, 4}, {5, 6}}; auto it = src.find(3); auto extracted_and_next = src.extract_and_get_next(it); EXPECT_THAT(src, ElementsAre(Pair(1, 2), Pair(5, 6))); EXPECT_EQ(extracted_and_next.node.key(), 3); EXPECT_EQ(extracted_and_next.node.mapped(), 4); EXPECT_THAT(*extracted_and_next.next, Pair(5, 6)); } TEST(Btree, ExtractAndGetNextEndIter) { absl::btree_set<int> src = {1, 2, 3, 4, 5}; auto it = src.find(5); auto extracted_and_next = src.extract_and_get_next(it); EXPECT_THAT(src, ElementsAre(1, 2, 3, 4)); EXPECT_EQ(extracted_and_next.node.value(), 5); EXPECT_EQ(extracted_and_next.next, src.end()); } TEST(Btree, ExtractDoesntCauseExtraMoves) { #ifdef _MSC_VER GTEST_SKIP() << "This test fails on MSVC."; #endif using Set = absl::btree_set<MovableOnlyInstance>; std::array<std::function<void(Set &)>, 3> extracters = { [](Set &s) { auto node = s.extract(s.begin()); }, [](Set &s) { auto ret = s.extract_and_get_next(s.begin()); }, [](Set &s) { auto node = s.extract(MovableOnlyInstance(0)); }}; InstanceTracker tracker; for (int i = 0; i < 3; ++i) { Set s; s.insert(MovableOnlyInstance(0)); tracker.ResetCopiesMovesSwaps(); extracters[i](s); EXPECT_EQ(tracker.copies(), 0) << i; EXPECT_EQ(tracker.moves(), 1) << i; EXPECT_EQ(tracker.swaps(), 0) << i; } } struct InsertMultiHintData { int key; int not_key; bool operator==(const InsertMultiHintData other) const { return key == other.key && not_key == other.not_key; } }; struct InsertMultiHintDataKeyCompare { using is_transparent = void; 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) { { absl::btree_set<int> src = {1, 2, 3, 4, 5}; auto nh = src.extract(src.find(3)); EXPECT_THAT(src, ElementsAre(1, 2, 4, 5)); absl::btree_set<int> other = {0, 100}; auto it = other.insert(other.lower_bound(3), std::move(nh)); EXPECT_THAT(other, ElementsAre(0, 3, 100)); EXPECT_EQ(it, other.find(3)); nh = src.extract(src.find(5)); it = other.insert(other.end(), std::move(nh)); EXPECT_THAT(other, ElementsAre(0, 3, 5, 100)); EXPECT_EQ(it, other.find(5)); } absl::btree_multiset<InsertMultiHintData, InsertMultiHintDataKeyCompare> src = {{1, 2}, {3, 4}, {3, 5}}; auto nh = src.extract(src.lower_bound(3)); EXPECT_EQ(nh.value(), (InsertMultiHintData{3, 4})); absl::btree_multiset<InsertMultiHintData, InsertMultiHintDataKeyCompare> other = {{3, 1}, {3, 2}, {3, 3}}; auto it = other.insert(--other.end(), std::move(nh)); EXPECT_THAT( other, ElementsAre(InsertMultiHintData{3, 1}, InsertMultiHintData{3, 2}, InsertMultiHintData{3, 4}, InsertMultiHintData{3, 3})); EXPECT_EQ(it, --(--other.end())); nh = src.extract(src.find(3)); EXPECT_EQ(nh.value(), (InsertMultiHintData{3, 5})); it = other.insert(other.begin(), std::move(nh)); EXPECT_THAT(other, ElementsAre(InsertMultiHintData{3, 5}, InsertMultiHintData{3, 1}, InsertMultiHintData{3, 2}, InsertMultiHintData{3, 4}, InsertMultiHintData{3, 3})); EXPECT_EQ(it, other.begin()); } struct IntCompareToCmp { absl::weak_ordering operator()(int a, int b) const { if (a < b) return absl::weak_ordering::less; if (a > b) return absl::weak_ordering::greater; return absl::weak_ordering::equivalent; } }; TEST(Btree, MergeIntoUniqueContainers) { absl::btree_set<int, IntCompareToCmp> src1 = {1, 2, 3}; absl::btree_multiset<int> src2 = {3, 4, 4, 5}; absl::btree_set<int> dst; dst.merge(src1); EXPECT_TRUE(src1.empty()); EXPECT_THAT(dst, ElementsAre(1, 2, 3)); dst.merge(src2); EXPECT_THAT(src2, ElementsAre(3, 4)); EXPECT_THAT(dst, ElementsAre(1, 2, 3, 4, 5)); } TEST(Btree, MergeIntoUniqueContainersWithCompareTo) { absl::btree_set<int, IntCompareToCmp> src1 = {1, 2, 3}; absl::btree_multiset<int> src2 = {3, 4, 4, 5}; absl::btree_set<int, IntCompareToCmp> dst; dst.merge(src1); EXPECT_TRUE(src1.empty()); EXPECT_THAT(dst, ElementsAre(1, 2, 3)); dst.merge(src2); EXPECT_THAT(src2, ElementsAre(3, 4)); EXPECT_THAT(dst, ElementsAre(1, 2, 3, 4, 5)); } TEST(Btree, MergeIntoMultiContainers) { absl::btree_set<int, IntCompareToCmp> src1 = {1, 2, 3}; absl::btree_multiset<int> src2 = {3, 4, 4, 5}; absl::btree_multiset<int> dst; dst.merge(src1); EXPECT_TRUE(src1.empty()); EXPECT_THAT(dst, ElementsAre(1, 2, 3)); dst.merge(src2); EXPECT_TRUE(src2.empty()); EXPECT_THAT(dst, ElementsAre(1, 2, 3, 3, 4, 4, 5)); } TEST(Btree, MergeIntoMultiContainersWithCompareTo) { absl::btree_set<int, IntCompareToCmp> src1 = {1, 2, 3}; absl::btree_multiset<int> src2 = {3, 4, 4, 5}; absl::btree_multiset<int, IntCompareToCmp> dst; dst.merge(src1); EXPECT_TRUE(src1.empty()); EXPECT_THAT(dst, ElementsAre(1, 2, 3)); dst.merge(src2); EXPECT_TRUE(src2.empty()); EXPECT_THAT(dst, ElementsAre(1, 2, 3, 3, 4, 4, 5)); } TEST(Btree, MergeIntoMultiMapsWithDifferentComparators) { absl::btree_map<int, int, IntCompareToCmp> src1 = {{1, 1}, {2, 2}, {3, 3}}; absl::btree_multimap<int, int, std::greater<int>> src2 = { {5, 5}, {4, 1}, {4, 4}, {3, 2}}; absl::btree_multimap<int, int> dst; dst.merge(src1); EXPECT_TRUE(src1.empty()); 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))); } TEST(Btree, MergeIntoSetMovableOnly) { absl::btree_set<MovableOnlyInstance> src; src.insert(MovableOnlyInstance(1)); absl::btree_multiset<MovableOnlyInstance> dst1; dst1.insert(MovableOnlyInstance(2)); absl::btree_set<MovableOnlyInstance> dst2; dst1.merge(src); EXPECT_TRUE(src.empty()); ASSERT_THAT(dst1, SizeIs(2)); EXPECT_EQ(*dst1.begin(), MovableOnlyInstance(1)); EXPECT_EQ(*std::next(dst1.begin()), MovableOnlyInstance(2)); dst2.merge(dst1); EXPECT_TRUE(dst1.empty()); ASSERT_THAT(dst2, SizeIs(2)); EXPECT_EQ(*dst2.begin(), MovableOnlyInstance(1)); EXPECT_EQ(*std::next(dst2.begin()), MovableOnlyInstance(2)); } struct KeyCompareToWeakOrdering { template <typename T> absl::weak_ordering operator()(const T &a, const T &b) const { return a < b ? absl::weak_ordering::less : a == b ? absl::weak_ordering::equivalent : absl::weak_ordering::greater; } }; struct KeyCompareToStrongOrdering { template <typename T> absl::strong_ordering operator()(const T &a, const T &b) const { return a < b ? absl::strong_ordering::less : a == b ? absl::strong_ordering::equal : absl::strong_ordering::greater; } }; TEST(Btree, UserProvidedKeyCompareToComparators) { absl::btree_set<int, KeyCompareToWeakOrdering> weak_set = {1, 2, 3}; EXPECT_TRUE(weak_set.contains(2)); EXPECT_FALSE(weak_set.contains(4)); absl::btree_set<int, KeyCompareToStrongOrdering> strong_set = {1, 2, 3}; EXPECT_TRUE(strong_set.contains(2)); EXPECT_FALSE(strong_set.contains(4)); } TEST(Btree, TryEmplaceBasicTest) { absl::btree_map<int, std::string> m; m.try_emplace(1, "one"); EXPECT_EQ(1, m.size()); const int key(42); m.try_emplace(key, 3, 'a'); m.try_emplace(2, std::string("two")); EXPECT_TRUE(std::is_sorted(m.begin(), m.end())); EXPECT_THAT(m, ElementsAreArray(std::vector<std::pair<int, std::string>>{ {1, "one"}, {2, "two"}, {42, "aaa"}})); } TEST(Btree, TryEmplaceWithHintWorks) { int calls = 0; auto cmp = [&calls](int x, int y) { ++calls; return x < y; }; using Cmp = decltype(cmp); absl::btree_map<int, int, CheckedCompareOptedOutCmp<Cmp>> m(cmp); for (int i = 0; i < 128; ++i) { m.emplace(i, i); } calls = 0; m.emplace(127, 127); EXPECT_GE(calls, 4); calls = 0; auto it = m.try_emplace(m.begin(), -1, -1); EXPECT_EQ(129, m.size()); EXPECT_EQ(it, m.begin()); EXPECT_LE(calls, 2); calls = 0; std::pair<int, int> pair1024 = {1024, 1024}; it = m.try_emplace(m.end(), pair1024.first, pair1024.second); EXPECT_EQ(130, m.size()); EXPECT_EQ(it, --m.end()); EXPECT_LE(calls, 2); calls = 0; it = m.try_emplace(m.end(), 16, 17); EXPECT_EQ(130, m.size()); EXPECT_GE(calls, 4); EXPECT_EQ(it, m.find(16)); calls = 0; it = m.try_emplace(it, 16, 17); EXPECT_EQ(130, m.size()); EXPECT_LE(calls, 2); EXPECT_EQ(it, m.find(16)); m.erase(2); EXPECT_EQ(129, m.size()); auto hint = m.find(3); calls = 0; m.try_emplace(hint, 2, 2); EXPECT_EQ(130, m.size()); EXPECT_LE(calls, 2); EXPECT_TRUE(std::is_sorted(m.begin(), m.end())); } TEST(Btree, TryEmplaceWithBadHint) { absl::btree_map<int, int> m = {{1, 1}, {9, 9}}; auto it = m.try_emplace(m.begin(), 2, 2); EXPECT_EQ(it, ++m.begin()); EXPECT_THAT(m, ElementsAreArray( std::vector<std::pair<int, int>>{{1, 1}, {2, 2}, {9, 9}})); it = m.try_emplace(++(++m.begin()), 0, 0); EXPECT_EQ(it, m.begin()); EXPECT_THAT(m, ElementsAreArray(std::vector<std::pair<int, int>>{ {0, 0}, {1, 1}, {2, 2}, {9, 9}})); } TEST(Btree, TryEmplaceMaintainsSortedOrder) { absl::btree_map<int, std::string> m; std::pair<int, std::string> pair5 = {5, "five"}; m.try_emplace(10, "ten"); m.try_emplace(pair5.first, pair5.second); EXPECT_EQ(2, m.size()); EXPECT_TRUE(std::is_sorted(m.begin(), m.end())); int int100{100}; m.try_emplace(int100, "hundred"); m.try_emplace(1, "one"); EXPECT_EQ(4, m.size()); EXPECT_TRUE(std::is_sorted(m.begin(), m.end())); } TEST(Btree, TryEmplaceWithHintAndNoValueArgsWorks) { absl::btree_map<int, int> m; m.try_emplace(m.end(), 1); EXPECT_EQ(0, m[1]); } TEST(Btree, TryEmplaceWithHintAndMultipleValueArgsWorks) { absl::btree_map<int, std::string> m; m.try_emplace(m.end(), 1, 10, 'a'); EXPECT_EQ(std::string(10, 'a'), m[1]); } template <typename Alloc> using BtreeSetAlloc = absl::btree_set<int, std::less<int>, Alloc>; TEST(Btree, AllocatorPropagation) { TestAllocPropagation<BtreeSetAlloc>(); } TEST(Btree, MinimumAlignmentAllocator) { absl::btree_set<int8_t, std::less<int8_t>, MinimumAlignmentAlloc<int8_t>> set; for (int8_t i = 0; i < 100; ++i) set.insert(i); set.erase(set.find(50), set.end()); for (int8_t i = 51; i < 101; ++i) set.insert(i); EXPECT_EQ(set.size(), 100); } TEST(Btree, EmptyTree) { absl::btree_set<int> s; EXPECT_TRUE(s.empty()); EXPECT_EQ(s.size(), 0); EXPECT_GT(s.max_size(), 0); } bool IsEven(int k) { return k % 2 == 0; } TEST(Btree, EraseIf) { { absl::btree_set<int> s = {1, 3, 5, 6, 100}; EXPECT_EQ(erase_if(s, [](int k) { return k > 3; }), 3); EXPECT_THAT(s, ElementsAre(1, 3)); } { absl::btree_multiset<int> s = {1, 3, 3, 5, 6, 6, 100}; EXPECT_EQ(erase_if(s, [](int k) { return k <= 3; }), 3); EXPECT_THAT(s, ElementsAre(5, 6, 6, 100)); } { absl::btree_map<int, int> m = {{1, 1}, {3, 3}, {6, 6}, {100, 100}}; EXPECT_EQ( erase_if(m, [](std::pair<const int, int> kv) { return kv.first > 3; }), 2); EXPECT_THAT(m, ElementsAre(Pair(1, 1), Pair(3, 3))); } { absl::btree_multimap<int, int> m = {{1, 1}, {3, 3}, {3, 6}, {6, 6}, {6, 7}, {100, 6}}; EXPECT_EQ( erase_if(m, [](std::pair<const int, int> kv) { return kv.second == 6; }), 3); EXPECT_THAT(m, ElementsAre(Pair(1, 1), Pair(3, 3), Pair(6, 7))); } { absl::btree_set<int> s; for (int i = 0; i < 1000; ++i) s.insert(2 * i); EXPECT_EQ(erase_if(s, IsEven), 1000); EXPECT_THAT(s, IsEmpty()); } { absl::btree_set<int> s = {1, 3, 5, 6, 100}; EXPECT_EQ(erase_if(s, &IsEven), 2); EXPECT_THAT(s, ElementsAre(1, 3, 5)); } { absl::btree_set<int> s; for (int i = 0; i < 1000; ++i) s.insert(i); int pred_calls = 0; EXPECT_EQ(erase_if(s, [&pred_calls](int k) { ++pred_calls; return k % 2; }), 500); EXPECT_THAT(s, SizeIs(500)); EXPECT_EQ(pred_calls, 1000); } } TEST(Btree, InsertOrAssign) { absl::btree_map<int, int> m = {{1, 1}, {3, 3}}; using value_type = typename decltype(m)::value_type; auto ret = m.insert_or_assign(4, 4); EXPECT_EQ(*ret.first, value_type(4, 4)); EXPECT_TRUE(ret.second); ret = m.insert_or_assign(3, 100); EXPECT_EQ(*ret.first, value_type(3, 100)); EXPECT_FALSE(ret.second); auto hint_ret = m.insert_or_assign(ret.first, 3, 200); EXPECT_EQ(*hint_ret, value_type(3, 200)); hint_ret = m.insert_or_assign(m.find(1), 0, 1); EXPECT_EQ(*hint_ret, value_type(0, 1)); hint_ret = m.insert_or_assign(m.end(), -1, 1); EXPECT_EQ(*hint_ret, value_type(-1, 1)); EXPECT_THAT(m, ElementsAre(Pair(-1, 1), Pair(0, 1), Pair(1, 1), Pair(3, 200), Pair(4, 4))); } TEST(Btree, InsertOrAssignMovableOnly) { absl::btree_map<int, MovableOnlyInstance> m; using value_type = typename decltype(m)::value_type; auto ret = m.insert_or_assign(4, MovableOnlyInstance(4)); EXPECT_EQ(*ret.first, value_type(4, MovableOnlyInstance(4))); EXPECT_TRUE(ret.second); ret = m.insert_or_assign(4, MovableOnlyInstance(100)); EXPECT_EQ(*ret.first, value_type(4, MovableOnlyInstance(100))); EXPECT_FALSE(ret.second); auto hint_ret = m.insert_or_assign(ret.first, 3, MovableOnlyInstance(200)); EXPECT_EQ(*hint_ret, value_type(3, MovableOnlyInstance(200))); EXPECT_EQ(m.size(), 2); } TEST(Btree, BitfieldArgument) { union { int n : 1; }; n = 0; absl::btree_map<int, int> m; m.erase(n); m.count(n); m.find(n); m.contains(n); m.equal_range(n); m.insert_or_assign(n, n); m.insert_or_assign(m.end(), n, n); m.try_emplace(n); m.try_emplace(m.end(), n); m.at(n); m[n]; } TEST(Btree, SetRangeConstructorAndInsertSupportExplicitConversionComparable) { const absl::string_view names[] = {"n1", "n2"}; absl::btree_set<std::string> name_set1{std::begin(names), std::end(names)}; EXPECT_THAT(name_set1, ElementsAreArray(names)); absl::btree_set<std::string> name_set2; name_set2.insert(std::begin(names), std::end(names)); EXPECT_THAT(name_set2, ElementsAreArray(names)); } struct ConstructorCounted { explicit ConstructorCounted(int i) : i(i) { ++constructor_calls; } bool operator==(int other) const { return i == other; } int i; static int constructor_calls; }; int ConstructorCounted::constructor_calls = 0; struct ConstructorCountedCompare { bool operator()(int a, const ConstructorCounted &b) const { return a < b.i; } bool operator()(const ConstructorCounted &a, int b) const { return a.i < b; } bool operator()(const ConstructorCounted &a, const ConstructorCounted &b) const { return a.i < b.i; } using is_transparent = void; }; TEST(Btree, SetRangeConstructorAndInsertExplicitConvComparableLimitConstruction) { const int i[] = {0, 1, 1}; ConstructorCounted::constructor_calls = 0; absl::btree_set<ConstructorCounted, ConstructorCountedCompare> set{ std::begin(i), std::end(i)}; EXPECT_THAT(set, ElementsAre(0, 1)); EXPECT_EQ(ConstructorCounted::constructor_calls, 2); set.insert(std::begin(i), std::end(i)); EXPECT_THAT(set, ElementsAre(0, 1)); EXPECT_EQ(ConstructorCounted::constructor_calls, 2); } TEST(Btree, SetRangeConstructorAndInsertSupportExplicitConversionNonComparable) { const int i[] = {0, 1}; absl::btree_set<std::vector<void *>> s1{std::begin(i), std::end(i)}; EXPECT_THAT(s1, ElementsAre(IsEmpty(), ElementsAre(IsNull()))); absl::btree_set<std::vector<void *>> s2; s2.insert(std::begin(i), std::end(i)); EXPECT_THAT(s2, ElementsAre(IsEmpty(), ElementsAre(IsNull()))); } #if !defined(__GLIBCXX__) || \ (defined(_GLIBCXX_RELEASE) && _GLIBCXX_RELEASE >= 7) TEST(Btree, MapRangeConstructorAndInsertSupportExplicitConversionComparable) { const std::pair<absl::string_view, int> names[] = {{"n1", 1}, {"n2", 2}}; absl::btree_map<std::string, int> name_map1{std::begin(names), std::end(names)}; EXPECT_THAT(name_map1, ElementsAre(Pair("n1", 1), Pair("n2", 2))); absl::btree_map<std::string, int> name_map2; name_map2.insert(std::begin(names), std::end(names)); EXPECT_THAT(name_map2, ElementsAre(Pair("n1", 1), Pair("n2", 2))); } TEST(Btree, MapRangeConstructorAndInsertExplicitConvComparableLimitConstruction) { const std::pair<int, int> i[] = {{0, 1}, {1, 2}, {1, 3}}; ConstructorCounted::constructor_calls = 0; absl::btree_map<ConstructorCounted, int, ConstructorCountedCompare> map{ std::begin(i), std::end(i)}; EXPECT_THAT(map, ElementsAre(Pair(0, 1), Pair(1, 2))); EXPECT_EQ(ConstructorCounted::constructor_calls, 2); map.insert(std::begin(i), std::end(i)); EXPECT_THAT(map, ElementsAre(Pair(0, 1), Pair(1, 2))); EXPECT_EQ(ConstructorCounted::constructor_calls, 2); } TEST(Btree, MapRangeConstructorAndInsertSupportExplicitConversionNonComparable) { const std::pair<int, int> i[] = {{0, 1}, {1, 2}}; absl::btree_map<std::vector<void *>, int> m1{std::begin(i), std::end(i)}; EXPECT_THAT(m1, ElementsAre(Pair(IsEmpty(), 1), Pair(ElementsAre(IsNull()), 2))); absl::btree_map<std::vector<void *>, int> m2; m2.insert(std::begin(i), std::end(i)); EXPECT_THAT(m2, ElementsAre(Pair(IsEmpty(), 1), Pair(ElementsAre(IsNull()), 2))); } TEST(Btree, HeterogeneousTryEmplace) { absl::btree_map<std::string, int> m; std::string s = "key"; absl::string_view sv = s; m.try_emplace(sv, 1); EXPECT_EQ(m[s], 1); m.try_emplace(m.end(), sv, 2); EXPECT_EQ(m[s], 1); } TEST(Btree, HeterogeneousOperatorMapped) { absl::btree_map<std::string, int> m; std::string s = "key"; absl::string_view sv = s; m[sv] = 1; EXPECT_EQ(m[s], 1); m[sv] = 2; EXPECT_EQ(m[s], 2); } TEST(Btree, HeterogeneousInsertOrAssign) { absl::btree_map<std::string, int> m; std::string s = "key"; absl::string_view sv = s; m.insert_or_assign(sv, 1); EXPECT_EQ(m[s], 1); m.insert_or_assign(m.end(), sv, 2); EXPECT_EQ(m[s], 2); } #endif #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606 TEST(Btree, NodeHandleMutableKeyAccess) { { absl::btree_map<std::string, std::string> map; map["key1"] = "mapped"; auto nh = map.extract(map.begin()); nh.key().resize(3); map.insert(std::move(nh)); EXPECT_THAT(map, ElementsAre(Pair("key", "mapped"))); } { absl::btree_multimap<std::string, std::string> map; map.emplace("key1", "mapped"); auto nh = map.extract(map.begin()); nh.key().resize(3); map.insert(std::move(nh)); EXPECT_THAT(map, ElementsAre(Pair("key", "mapped"))); } } #endif struct MultiKey { int i1; int i2; }; bool operator==(const MultiKey a, const MultiKey b) { return a.i1 == b.i1 && a.i2 == b.i2; } struct MultiKeyComp { using is_transparent = void; bool operator()(const MultiKey a, const MultiKey b) const { if (a.i1 != b.i1) return a.i1 < b.i1; return a.i2 < b.i2; } bool operator()(const int a, const MultiKey b) const { return a < b.i1; } bool operator()(const MultiKey a, const int b) const { return a.i1 < b; } }; struct MultiKeyThreeWayComp { using is_transparent = void; absl::weak_ordering operator()(const MultiKey a, const MultiKey b) const { if (a.i1 < b.i1) return absl::weak_ordering::less; if (a.i1 > b.i1) return absl::weak_ordering::greater; if (a.i2 < b.i2) return absl::weak_ordering::less; if (a.i2 > b.i2) return absl::weak_ordering::greater; return absl::weak_ordering::equivalent; } absl::weak_ordering operator()(const int a, const MultiKey b) const { if (a < b.i1) return absl::weak_ordering::less; if (a > b.i1) return absl::weak_ordering::greater; return absl::weak_ordering::equivalent; } absl::weak_ordering operator()(const MultiKey a, const int b) const { if (a.i1 < b) return absl::weak_ordering::less; if (a.i1 > b) return absl::weak_ordering::greater; return absl::weak_ordering::equivalent; } }; template <typename Compare> class BtreeMultiKeyTest : public ::testing::Test {}; using MultiKeyComps = ::testing::Types<MultiKeyComp, MultiKeyThreeWayComp>; TYPED_TEST_SUITE(BtreeMultiKeyTest, MultiKeyComps); TYPED_TEST(BtreeMultiKeyTest, EqualRange) { absl::btree_set<MultiKey, TypeParam> set; for (int i = 0; i < 100; ++i) { for (int j = 0; j < 100; ++j) { set.insert({i, j}); } } for (int i = 0; i < 100; ++i) { auto equal_range = set.equal_range(i); EXPECT_EQ(equal_range.first->i1, i); EXPECT_EQ(equal_range.first->i2, 0) << i; EXPECT_EQ(std::distance(equal_range.first, equal_range.second), 100) << i; } } TYPED_TEST(BtreeMultiKeyTest, Extract) { absl::btree_set<MultiKey, TypeParam> set; for (int i = 0; i < 100; ++i) { for (int j = 0; j < 100; ++j) { set.insert({i, j}); } } for (int i = 0; i < 100; ++i) { auto node_handle = set.extract(i); EXPECT_EQ(node_handle.value().i1, i); EXPECT_EQ(node_handle.value().i2, 0) << i; } for (int i = 0; i < 100; ++i) { auto node_handle = set.extract(i); EXPECT_EQ(node_handle.value().i1, i); EXPECT_EQ(node_handle.value().i2, 1) << i; } } TYPED_TEST(BtreeMultiKeyTest, Erase) { absl::btree_set<MultiKey, TypeParam> set = { {1, 1}, {2, 1}, {2, 2}, {3, 1}}; EXPECT_EQ(set.erase(2), 2); EXPECT_THAT(set, ElementsAre(MultiKey{1, 1}, MultiKey{3, 1})); } TYPED_TEST(BtreeMultiKeyTest, Count) { const absl::btree_set<MultiKey, TypeParam> set = { {1, 1}, {2, 1}, {2, 2}, {3, 1}}; EXPECT_EQ(set.count(2), 2); } TEST(Btree, SetIteratorsAreConst) { using Set = absl::btree_set<int>; EXPECT_TRUE( (std::is_same<typename Set::iterator::reference, const int &>::value)); EXPECT_TRUE( (std::is_same<typename Set::iterator::pointer, const int *>::value)); using MSet = absl::btree_multiset<int>; EXPECT_TRUE( (std::is_same<typename MSet::iterator::reference, const int &>::value)); EXPECT_TRUE( (std::is_same<typename MSet::iterator::pointer, const int *>::value)); } TEST(Btree, AllocConstructor) { using Alloc = CountingAllocator<int>; using Set = absl::btree_set<int, std::less<int>, Alloc>; int64_t bytes_used = 0; Alloc alloc(&bytes_used); Set set(alloc); set.insert({1, 2, 3}); EXPECT_THAT(set, ElementsAre(1, 2, 3)); EXPECT_GT(bytes_used, set.size() * sizeof(int)); } TEST(Btree, AllocInitializerListConstructor) { using Alloc = CountingAllocator<int>; using Set = absl::btree_set<int, std::less<int>, Alloc>; int64_t bytes_used = 0; Alloc alloc(&bytes_used); Set set({1, 2, 3}, alloc); EXPECT_THAT(set, ElementsAre(1, 2, 3)); EXPECT_GT(bytes_used, set.size() * sizeof(int)); } TEST(Btree, AllocRangeConstructor) { using Alloc = CountingAllocator<int>; using Set = absl::btree_set<int, std::less<int>, Alloc>; int64_t bytes_used = 0; Alloc alloc(&bytes_used); std::vector<int> v = {1, 2, 3}; Set set(v.begin(), v.end(), alloc); EXPECT_THAT(set, ElementsAre(1, 2, 3)); EXPECT_GT(bytes_used, set.size() * sizeof(int)); } TEST(Btree, AllocCopyConstructor) { using Alloc = CountingAllocator<int>; using Set = absl::btree_set<int, std::less<int>, Alloc>; int64_t bytes_used1 = 0; Alloc alloc1(&bytes_used1); Set set1(alloc1); set1.insert({1, 2, 3}); int64_t bytes_used2 = 0; Alloc alloc2(&bytes_used2); Set set2(set1, alloc2); EXPECT_THAT(set1, ElementsAre(1, 2, 3)); EXPECT_THAT(set2, ElementsAre(1, 2, 3)); EXPECT_GT(bytes_used1, set1.size() * sizeof(int)); EXPECT_EQ(bytes_used1, bytes_used2); } TEST(Btree, AllocMoveConstructor_SameAlloc) { using Alloc = CountingAllocator<int>; using Set = absl::btree_set<int, std::less<int>, Alloc>; int64_t bytes_used = 0; Alloc alloc(&bytes_used); Set set1(alloc); set1.insert({1, 2, 3}); const int64_t original_bytes_used = bytes_used; EXPECT_GT(original_bytes_used, set1.size() * sizeof(int)); Set set2(std::move(set1), alloc); EXPECT_THAT(set2, ElementsAre(1, 2, 3)); EXPECT_EQ(bytes_used, original_bytes_used); } TEST(Btree, AllocMoveConstructor_DifferentAlloc) { using Alloc = CountingAllocator<int>; using Set = absl::btree_set<int, std::less<int>, Alloc>; int64_t bytes_used1 = 0; Alloc alloc1(&bytes_used1); Set set1(alloc1); set1.insert({1, 2, 3}); const int64_t original_bytes_used = bytes_used1; EXPECT_GT(original_bytes_used, set1.size() * sizeof(int)); int64_t bytes_used2 = 0; Alloc alloc2(&bytes_used2); Set set2(std::move(set1), alloc2); EXPECT_THAT(set2, ElementsAre(1, 2, 3)); EXPECT_EQ(bytes_used1, original_bytes_used); EXPECT_EQ(bytes_used2, original_bytes_used); } bool IntCmp(const int a, const int b) { return a < b; } TEST(Btree, SupportsFunctionPtrComparator) { absl::btree_set<int, decltype(IntCmp) *> set(IntCmp); set.insert({1, 2, 3}); EXPECT_THAT(set, ElementsAre(1, 2, 3)); EXPECT_TRUE(set.key_comp()(1, 2)); EXPECT_TRUE(set.value_comp()(1, 2)); absl::btree_map<int, int, decltype(IntCmp) *> map(&IntCmp); map[1] = 1; EXPECT_THAT(map, ElementsAre(Pair(1, 1))); EXPECT_TRUE(map.key_comp()(1, 2)); EXPECT_TRUE(map.value_comp()(std::make_pair(1, 1), std::make_pair(2, 2))); } template <typename Compare> struct TransparentPassThroughComp { using is_transparent = void; template <typename T, typename U> bool operator()(const T &lhs, const U &rhs) const { return Compare()(lhs, rhs); } }; TEST(Btree, SupportsTransparentComparatorThatDoesNotImplementAllVisibleOperators) { absl::btree_set<MultiKey, TransparentPassThroughComp<MultiKeyComp>> set; set.insert(MultiKey{1, 2}); EXPECT_TRUE(set.contains(1)); } TEST(Btree, ConstructImplicitlyWithUnadaptedComparator) { absl::btree_set<MultiKey, MultiKeyComp> set = {{}, MultiKeyComp{}}; } TEST(Btree, InvalidComparatorsCaught) { if (!IsAssertEnabled()) GTEST_SKIP() << "Assertions not enabled."; { struct ZeroAlwaysLessCmp { bool operator()(int lhs, int rhs) const { if (lhs == 0) return true; return lhs < rhs; } }; absl::btree_set<int, ZeroAlwaysLessCmp> set; EXPECT_DEATH(set.insert({0, 1, 2}), "is_self_equivalent"); } { struct ThreeWayAlwaysLessCmp { absl::weak_ordering operator()(int, int) const { return absl::weak_ordering::less; } }; absl::btree_set<int, ThreeWayAlwaysLessCmp> set; EXPECT_DEATH(set.insert({0, 1, 2}), "is_self_equivalent"); } { struct SumGreaterZeroCmp { bool operator()(int lhs, int rhs) const { if (lhs == rhs) return false; return lhs + rhs > 0; } }; absl::btree_set<int, SumGreaterZeroCmp> set; EXPECT_DEATH(set.insert({0, 1, 2}), R"regex(\!lhs_comp_rhs \|\| !comp\(\)\(rhs, lhs\))regex"); } { struct ThreeWaySumGreaterZeroCmp { absl::weak_ordering operator()(int lhs, int rhs) const { if (lhs == rhs) return absl::weak_ordering::equivalent; if (lhs + rhs > 0) return absl::weak_ordering::less; if (lhs + rhs == 0) return absl::weak_ordering::equivalent; return absl::weak_ordering::greater; } }; absl::btree_set<int, ThreeWaySumGreaterZeroCmp> set; EXPECT_DEATH(set.insert({0, 1, 2}), "lhs_comp_rhs < 0 -> rhs_comp_lhs > 0"); } struct ClockTime { absl::optional<int> hour; int minute; }; ClockTime a = {absl::nullopt, 1}; ClockTime b = {2, 5}; ClockTime c = {6, 0}; { struct NonTransitiveTimeCmp { bool operator()(ClockTime lhs, ClockTime rhs) const { if (lhs.hour.has_value() && rhs.hour.has_value() && *lhs.hour != *rhs.hour) { return *lhs.hour < *rhs.hour; } return lhs.minute < rhs.minute; } }; NonTransitiveTimeCmp cmp; ASSERT_TRUE(cmp(a, b) && cmp(b, c) && !cmp(a, c)); absl::btree_set<ClockTime, NonTransitiveTimeCmp> set; EXPECT_DEATH(set.insert({a, b, c}), "is_ordered_correctly"); absl::btree_multiset<ClockTime, NonTransitiveTimeCmp> mset; EXPECT_DEATH(mset.insert({a, a, b, b, c, c}), "is_ordered_correctly"); } { struct ThreeWayNonTransitiveTimeCmp { absl::weak_ordering operator()(ClockTime lhs, ClockTime rhs) const { if (lhs.hour.has_value() && rhs.hour.has_value() && *lhs.hour != *rhs.hour) { return *lhs.hour < *rhs.hour ? absl::weak_ordering::less : absl::weak_ordering::greater; } return lhs.minute < rhs.minute ? absl::weak_ordering::less : lhs.minute == rhs.minute ? absl::weak_ordering::equivalent : absl::weak_ordering::greater; } }; ThreeWayNonTransitiveTimeCmp cmp; ASSERT_TRUE(cmp(a, b) < 0 && cmp(b, c) < 0 && cmp(a, c) > 0); absl::btree_set<ClockTime, ThreeWayNonTransitiveTimeCmp> set; EXPECT_DEATH(set.insert({a, b, c}), "is_ordered_correctly"); absl::btree_multiset<ClockTime, ThreeWayNonTransitiveTimeCmp> mset; EXPECT_DEATH(mset.insert({a, a, b, b, c, c}), "is_ordered_correctly"); } } TEST(Btree, MutatedKeysCaught) { if (!IsAssertEnabled()) GTEST_SKIP() << "Assertions not enabled."; struct IntPtrCmp { bool operator()(int *lhs, int *rhs) const { return *lhs < *rhs; } }; { absl::btree_set<int *, IntPtrCmp> set; int arr[] = {0, 1, 2}; set.insert({&arr[0], &arr[1], &arr[2]}); arr[0] = 100; EXPECT_DEATH(set.insert(&arr[0]), "is_ordered_correctly"); } { absl::btree_multiset<int *, IntPtrCmp> set; int arr[] = {0, 1, 2}; set.insert({&arr[0], &arr[0], &arr[1], &arr[1], &arr[2], &arr[2]}); arr[0] = 100; EXPECT_DEATH(set.insert(&arr[0]), "is_ordered_correctly"); } } #ifndef _MSC_VER TEST(Btree, InvalidIteratorUse) { if (!BtreeGenerationsEnabled()) GTEST_SKIP() << "Generation validation for iterators is disabled."; constexpr const char *kInvalidMemoryDeathMessage = "use-after-free|invalidated iterator"; { absl::btree_set<int> set; for (int i = 0; i < 10; ++i) set.insert(i); auto it = set.begin(); set.erase(it++); EXPECT_DEATH(set.erase(it++), kInvalidMemoryDeathMessage); } { absl::btree_set<int> set; for (int i = 0; i < 10; ++i) set.insert(i); auto it = set.insert(20).first; set.insert(30); EXPECT_DEATH(*it, kInvalidMemoryDeathMessage); } { absl::btree_set<int> set; for (int i = 0; i < 10000; ++i) set.insert(i); auto it = set.find(5000); ASSERT_NE(it, set.end()); set.erase(1); EXPECT_DEATH(*it, kInvalidMemoryDeathMessage); } { absl::btree_set<int> set; for (int i = 0; i < 10; ++i) set.insert(i); auto it = set.insert(20).first; set.insert(30); EXPECT_DEATH(void(it == set.begin()), kInvalidMemoryDeathMessage); EXPECT_DEATH(void(set.begin() == it), kInvalidMemoryDeathMessage); } } #endif class OnlyConstructibleByAllocator { explicit OnlyConstructibleByAllocator(int i) : i_(i) {} public: OnlyConstructibleByAllocator(const OnlyConstructibleByAllocator &other) : i_(other.i_) {} OnlyConstructibleByAllocator &operator=( const OnlyConstructibleByAllocator &other) { i_ = other.i_; return *this; } int Get() const { return i_; } bool operator==(int i) const { return i_ == i; } private: template <typename T> friend class OnlyConstructibleAllocator; int i_; }; template <typename T = OnlyConstructibleByAllocator> class OnlyConstructibleAllocator : public std::allocator<T> { public: OnlyConstructibleAllocator() = default; template <class U> explicit OnlyConstructibleAllocator(const OnlyConstructibleAllocator<U> &) {} void construct(OnlyConstructibleByAllocator *p, int i) { new (p) OnlyConstructibleByAllocator(i); } template <typename Pair> void construct(Pair *p, const int i) { OnlyConstructibleByAllocator only(i); new (p) Pair(std::move(only), i); } template <class U> struct rebind { using other = OnlyConstructibleAllocator<U>; }; }; struct OnlyConstructibleByAllocatorComp { using is_transparent = void; bool operator()(OnlyConstructibleByAllocator a, OnlyConstructibleByAllocator b) const { return a.Get() < b.Get(); } bool operator()(int a, OnlyConstructibleByAllocator b) const { return a < b.Get(); } bool operator()(OnlyConstructibleByAllocator a, int b) const { return a.Get() < b; } }; TEST(Btree, OnlyConstructibleByAllocatorType) { const std::array<int, 2> arr = {3, 4}; { absl::btree_set<OnlyConstructibleByAllocator, OnlyConstructibleByAllocatorComp, OnlyConstructibleAllocator<>> set; set.emplace(1); set.emplace_hint(set.end(), 2); set.insert(arr.begin(), arr.end()); EXPECT_THAT(set, ElementsAre(1, 2, 3, 4)); } { absl::btree_multiset<OnlyConstructibleByAllocator, OnlyConstructibleByAllocatorComp, OnlyConstructibleAllocator<>> set; set.emplace(1); set.emplace_hint(set.end(), 2); EXPECT_THAT(set, ElementsAre(1, 2)); } { absl::btree_map<OnlyConstructibleByAllocator, int, OnlyConstructibleByAllocatorComp, OnlyConstructibleAllocator<>> map; map.emplace(1); map.emplace_hint(map.end(), 2); map.insert(arr.begin(), arr.end()); EXPECT_THAT(map, ElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3), Pair(4, 4))); } { absl::btree_multimap<OnlyConstructibleByAllocator, int, OnlyConstructibleByAllocatorComp, OnlyConstructibleAllocator<>> map; map.emplace(1); map.emplace_hint(map.end(), 2); EXPECT_THAT(map, ElementsAre(Pair(1, 1), Pair(2, 2))); } } class NotAssignable { public: explicit NotAssignable(int i) : i_(i) {} NotAssignable(const NotAssignable &other) : i_(other.i_) {} NotAssignable &operator=(NotAssignable &&other) = delete; int Get() const { return i_; } bool operator==(int i) const { return i_ == i; } friend bool operator<(NotAssignable a, NotAssignable b) { return a.i_ < b.i_; } private: int i_; }; TEST(Btree, NotAssignableType) { { absl::btree_set<NotAssignable> set; set.emplace(1); set.emplace_hint(set.end(), 2); set.insert(NotAssignable(3)); set.insert(set.end(), NotAssignable(4)); EXPECT_THAT(set, ElementsAre(1, 2, 3, 4)); set.erase(set.begin()); EXPECT_THAT(set, ElementsAre(2, 3, 4)); } { absl::btree_multiset<NotAssignable> set; set.emplace(1); set.emplace_hint(set.end(), 2); set.insert(NotAssignable(2)); set.insert(set.end(), NotAssignable(3)); EXPECT_THAT(set, ElementsAre(1, 2, 2, 3)); set.erase(set.begin()); EXPECT_THAT(set, ElementsAre(2, 2, 3)); } { absl::btree_map<NotAssignable, int> map; map.emplace(NotAssignable(1), 1); map.emplace_hint(map.end(), NotAssignable(2), 2); map.insert({NotAssignable(3), 3}); map.insert(map.end(), {NotAssignable(4), 4}); EXPECT_THAT(map, ElementsAre(Pair(1, 1), Pair(2, 2), Pair(3, 3), Pair(4, 4))); map.erase(map.begin()); EXPECT_THAT(map, ElementsAre(Pair(2, 2), Pair(3, 3), Pair(4, 4))); } { absl::btree_multimap<NotAssignable, int> map; map.emplace(NotAssignable(1), 1); map.emplace_hint(map.end(), NotAssignable(2), 2); map.insert({NotAssignable(2), 3}); map.insert(map.end(), {NotAssignable(3), 3}); EXPECT_THAT(map, ElementsAre(Pair(1, 1), Pair(2, 2), Pair(2, 3), Pair(3, 3))); map.erase(map.begin()); EXPECT_THAT(map, ElementsAre(Pair(2, 2), Pair(2, 3), Pair(3, 3))); } } struct ArenaLike { void* recycled = nullptr; size_t recycled_size = 0; }; template <typename T> class ArenaLikeAllocator : public std::allocator<T> { public: template <typename U> struct rebind { using other = ArenaLikeAllocator<U>; }; explicit ArenaLikeAllocator(ArenaLike* arena) noexcept : arena_(arena) {} ~ArenaLikeAllocator() { if (arena_->recycled != nullptr) { delete [] static_cast<T*>(arena_->recycled); arena_->recycled = nullptr; } } template<typename U> explicit ArenaLikeAllocator(const ArenaLikeAllocator<U>& other) noexcept : arena_(other.arena_) {} T* allocate(size_t num_objects, const void* = nullptr) { size_t size = num_objects * sizeof(T); if (arena_->recycled != nullptr && arena_->recycled_size == size) { T* result = static_cast<T*>(arena_->recycled); arena_->recycled = nullptr; return result; } return new T[num_objects]; } void deallocate(T* p, size_t num_objects) { size_t size = num_objects * sizeof(T); memset(p, 0xde, size); if (arena_->recycled == nullptr) { arena_->recycled = p; arena_->recycled_size = size; } else { delete [] p; } } ArenaLike* arena_; }; TEST(Btree, ReusePoisonMemory) { using Alloc = ArenaLikeAllocator<int64_t>; using Set = absl::btree_set<int64_t, std::less<int64_t>, Alloc>; ArenaLike arena; Alloc alloc(&arena); Set set(alloc); set.insert(0); set.erase(0); set.insert(0); } TEST(Btree, IteratorSubtraction) { absl::BitGen bitgen; std::vector<int> vec; for (int i = 0; i < 1000000; ++i) vec.push_back(i); absl::c_shuffle(vec, bitgen); absl::btree_set<int> set; for (int i : vec) set.insert(i); for (int i = 0; i < 1000; ++i) { size_t begin = absl::Uniform(bitgen, 0u, set.size()); size_t end = absl::Uniform(bitgen, begin, set.size()); ASSERT_EQ(end - begin, set.find(end) - set.find(begin)) << begin << " " << end; } } TEST(Btree, DereferencingEndIterator) { if (!IsAssertEnabled()) GTEST_SKIP() << "Assertions not enabled."; absl::btree_set<int> set; for (int i = 0; i < 1000; ++i) set.insert(i); EXPECT_DEATH(*set.end(), R"regex(Dereferencing end\(\) iterator)regex"); } TEST(Btree, InvalidIteratorComparison) { if (!IsAssertEnabled()) GTEST_SKIP() << "Assertions not enabled."; absl::btree_set<int> set1, set2; for (int i = 0; i < 1000; ++i) { set1.insert(i); set2.insert(i); } constexpr const char *kValueInitDeathMessage = "Comparing default-constructed iterator with .*non-default-constructed " "iterator"; typename absl::btree_set<int>::iterator iter1, iter2; EXPECT_EQ(iter1, iter2); EXPECT_DEATH(void(set1.begin() == iter1), kValueInitDeathMessage); EXPECT_DEATH(void(iter1 == set1.begin()), kValueInitDeathMessage); constexpr const char *kDifferentContainerDeathMessage = "Comparing iterators from different containers"; iter1 = set1.begin(); iter2 = set2.begin(); EXPECT_DEATH(void(iter1 == iter2), kDifferentContainerDeathMessage); EXPECT_DEATH(void(iter2 == iter1), kDifferentContainerDeathMessage); } TEST(Btree, InvalidPointerUse) { if (!kAsan) GTEST_SKIP() << "We only detect invalid pointer use in ASan mode."; absl::btree_set<int> set; set.insert(0); const int *ptr = &*set.begin(); set.insert(1); EXPECT_DEATH(std::cout << *ptr, "use-after-free"); size_t slots_per_node = BtreeNodePeer::GetNumSlotsPerNode<decltype(set)>(); for (int i = 2; i < slots_per_node - 1; ++i) set.insert(i); ptr = &*set.begin(); set.insert(static_cast<int>(slots_per_node)); EXPECT_DEATH(std::cout << *ptr, "use-after-free"); } template<typename Set> void TestBasicFunctionality(Set set) { using value_type = typename Set::value_type; for (int i = 0; i < 100; ++i) { set.insert(value_type(i)); } for (int i = 50; i < 100; ++i) { set.erase(value_type(i)); } auto it = set.begin(); for (int i = 0; i < 50; ++i, ++it) { ASSERT_EQ(set.find(value_type(i)), it) << i; } } template<size_t align> struct alignas(align) OveralignedKey { explicit OveralignedKey(int i) : key(i) {} bool operator<(const OveralignedKey &other) const { return key < other.key; } int key = 0; }; TEST(Btree, OveralignedKey) { TestBasicFunctionality( SizedBtreeSet<OveralignedKey<16>, 8>()); TestBasicFunctionality( SizedBtreeSet<OveralignedKey<16>, 9>()); } TEST(Btree, FieldTypeEqualsSlotType) { using set_type = absl::btree_set<uint8_t>; static_assert(BtreeNodePeer::FieldTypeEqualsSlotType<set_type>(), ""); TestBasicFunctionality(set_type()); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/btree.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/btree_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4
652cec0f-4852-4e27-a73d-b04dfbb8ac33
cpp
abseil/abseil-cpp
node_slot_policy
absl/container/internal/node_slot_policy.h
absl/container/internal/node_slot_policy_test.cc
#ifndef ABSL_CONTAINER_INTERNAL_NODE_SLOT_POLICY_H_ #define ABSL_CONTAINER_INTERNAL_NODE_SLOT_POLICY_H_ #include <cassert> #include <cstddef> #include <memory> #include <type_traits> #include <utility> #include "absl/base/config.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { template <class Reference, class Policy> struct node_slot_policy { static_assert(std::is_lvalue_reference<Reference>::value, ""); using slot_type = typename std::remove_cv< typename std::remove_reference<Reference>::type>::type*; template <class Alloc, class... Args> static void construct(Alloc* alloc, slot_type* slot, Args&&... args) { *slot = Policy::new_element(alloc, std::forward<Args>(args)...); } template <class Alloc> static void destroy(Alloc* alloc, slot_type* slot) { Policy::delete_element(alloc, *slot); } template <class Alloc> static std::true_type transfer(Alloc*, slot_type* new_slot, slot_type* old_slot) { *new_slot = *old_slot; return {}; } static size_t space_used(const slot_type* slot) { if (slot == nullptr) return Policy::element_space_used(nullptr); return Policy::element_space_used(*slot); } static Reference element(slot_type* slot) { return **slot; } template <class T, class P = Policy> static auto value(T* elem) -> decltype(P::value(elem)) { return P::value(elem); } template <class... Ts, class P = Policy> static auto apply(Ts&&... ts) -> decltype(P::apply(std::forward<Ts>(ts)...)) { return P::apply(std::forward<Ts>(ts)...); } }; } ABSL_NAMESPACE_END } #endif
#include "absl/container/internal/node_slot_policy.h" #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/base/config.h" #include "absl/container/internal/hash_policy_traits.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace container_internal { namespace { using ::testing::Pointee; struct Policy : node_slot_policy<int&, Policy> { using key_type = int; using init_type = int; template <class Alloc> static int* new_element(Alloc* alloc, int value) { return new int(value); } template <class Alloc> static void delete_element(Alloc* alloc, int* elem) { delete elem; } }; using NodePolicy = hash_policy_traits<Policy>; struct NodeTest : ::testing::Test { std::allocator<int> alloc; int n = 53; int* a = &n; }; TEST_F(NodeTest, ConstructDestroy) { NodePolicy::construct(&alloc, &a, 42); EXPECT_THAT(a, Pointee(42)); NodePolicy::destroy(&alloc, &a); } TEST_F(NodeTest, transfer) { int s = 42; int* b = &s; NodePolicy::transfer(&alloc, &a, &b); EXPECT_EQ(&s, a); EXPECT_TRUE(NodePolicy::transfer_uses_memcpy()); } } } ABSL_NAMESPACE_END }
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/node_slot_policy.h
https://github.com/abseil/abseil-cpp/blob/03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4/absl/container/internal/node_slot_policy_test.cc
03b8d6ea3dc6a0b8c6bcf42503c2053754dab2e4